From: Florian Forster Date: Sun, 11 Nov 2012 11:43:52 +0000 (+0100) Subject: Merge branch 'collectd-5.0' into collectd-5.1 X-Git-Tag: collectd-5.1.1~1 X-Git-Url: https://git.verplant.org/?a=commitdiff_plain;h=1d7439282ad415e7d1630598becae3109c7d2735;hp=494386dffbab10af47c08846e6e3fec2b2ae5107;p=collectd.git Merge branch 'collectd-5.0' into collectd-5.1 Conflicts: ChangeLog version-gen.sh --- diff --git a/AUTHORS b/AUTHORS index 0e0a5fed..90560e34 100644 --- a/AUTHORS +++ b/AUTHORS @@ -15,6 +15,9 @@ Sebastian "tokkee" Harl Contributors (sorted alphabetically) ==================================== +Akkarit Sangpetch + - write_mongodb plugin. + Alessandro Iurlano - Initial filecount plugin. @@ -44,10 +47,16 @@ Bruno Prémont especially a nasty bug in the network plugin. - Wireshark dissector. +Chris Lundquist + - Improvements to the write_mongodb plugin. + Christophe Kalt - The version 3 `log' mode. - Many Solaris related hints and fixes. +Cyril Feraudet + - ethstat plugin. + Dan Berrange - uuid plugin. @@ -109,6 +118,9 @@ Marco Chiappero - ip6tables support in the iptables plugin. - openvpn plugin (support for more status file formats) +Michael Hanselmann + - md plugin. + Michael Stapelberg - OpenBSD port of the tcpconns plugin. @@ -169,6 +181,9 @@ Rodolphe Quiédeville Scott Garrett - tape plugin. +Scott Sanders + - Write-Graphite plugin. + Sebastien Pahl - AMQP plugin. diff --git a/ChangeLog b/ChangeLog index b412807f..4fab3107 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,56 @@ +2012-04-01, Version 5.1.0 + * Build system, iptables plugin: The shipped version of libiptc has + been removed. + * collectd-nagios: A list of value lists can now be queried using + "-n LIST". Thanks to Sebastian Harl for his patches. + * bind plugin: The "ParseTime" option has been added. It allows to use + the system time rather than the time reported by BIND. + * curl, memcachec, tail plugins: The "ExcludeRegexp" option has been + added. Thanks to Peter Warasin for his initial patch. + * ethstat plugin: The new "ethstat" plugin reads performance statistics + directly from ethernet cards. Thanks to Cyril Feraudet for his patch. + * GenericJMX plugin: Support for querying MBean "Operations" (in + addition to "Attributes") has been added. Thanks to Pierre-Yves + Ritschard for his patch. + * irq plugin: The selection / ignore code now uses the default + ignorelist infrastructure, providing the standard feature set, e.g. + regex matching. + * md plugin: The new "md" plugin reports the number of disks in various + states in Linux software RAID devices. Thanks to Michael Hanselmann + for his patch. + * modbus plugin: Support for signed integer register types has been + added. + * nfs plugin: Support for Solaris has been added. Thanks to Cosmin + Ioiart for his patch. + * numa plugin: The new "numa" plugin reports statistics of the + Non-Uniform Memory Access (NUMA) subsystem of Linux. + * processes plugin: Various fixes for the FreeBSD implementation. + Thanks to Phil Kulin for his patch. + * rrdcached plugin: Passing flushes to the caching daemon has been + added. + * sensors plugin: The initialization code has been improved. Thanks to + Henrique de Moraes Holschuh for his patch. + * swap plugin: The "ReportByDevice" option has been added. + * syslog plugin: Support for writing notifications has been added. + Thanks to Fabien Wernli for his patch. + * tcpconns plugin: Support for AIX has been added. Thanks to Manuel + Luis Sanmartín Rozada for his patch. + * threshold plugin: The "PersistOK" option has been added. Thanks to + Aaron Brady for his patch. + * varnish plugin: Support for Varnish 3.0 has been added. Thanks to + Jérôme Renard for his patches. + * write_mongodb plugin: The new "write_mongodb" plugin writes value + lists to MongoDB, a shema-less database. Thanks to Akkarit Sangpetch + and Chris Lundquist for their work. + * write_graphite plugin: The new "write_graphite" plugin writes value + lists to Carbon, the storage layer of the Graphite time-series + database. Thanks to Scott Sanders and Pierre-Yves Ritschard for their + work. + * zfs_arc plugin: Several new statistics have been added. Thanks to + Aurelien Rougemont for his patches. + * scale target: Support for scaling specific data sources only has been + added. Thanks to Gerrie Roos for his patch. + 2012-11-11, Version 5.0.5 * collectd: Create new directories with mode 0777 and let umask remove unwanted permission bits. @@ -196,7 +249,7 @@ technique of POWER CPUs. Thanks to Aurélien Reynaud for his code and patience. * modbus plugin: Support for libmodbus 2.9.2 has been added and the - license has been changes to LGPLv2.1. + license has been changed to LGPLv2.1. * mysql plugin: Backwards compatibility code has been removed. The data sets used have been improved. * network plugin: The default buffer size has been increased to diff --git a/README b/README index ac79ce50..67cac046 100644 --- a/README +++ b/README @@ -83,6 +83,9 @@ Features - entropy Amount of entropy available to the system. + - ethstat + Network interface card statistics. + - exec Values gathered by a custom program or script. See collectd-exec(5). @@ -140,6 +143,10 @@ Features Motherboard sensors: temperature, fanspeed and voltage information, using mbmon(1). + - md + Linux software-RAID device information (number of active, failed, spare + and missing disks). + - memcachec Query and parse data from a memcache daemon (memcached). @@ -192,6 +199,9 @@ Features Network UPS tools: UPS current, voltage, power, charge, utilisation, temperature, etc. See upsd(8). + - numa + Information about Non-Uniform Memory Access (NUMA). + - olsrd Queries routing information from the “Optimized Link State Routing” daemon. @@ -358,6 +368,9 @@ Features needed. Please read collectd-unixsock(5) for a description on how that's done. + - write_graphite + Sends data to Carbon, the storage layer of Graphite. + - write_http Sends the values collected by collectd to a web-server using HTTP POST requests. The transmitted data is either in a form understood by the diff --git a/bindings/java/org/collectd/java/GenericJMXConfValue.java b/bindings/java/org/collectd/java/GenericJMXConfValue.java index 0eb0d5f8..9fb0fc2e 100644 --- a/bindings/java/org/collectd/java/GenericJMXConfValue.java +++ b/bindings/java/org/collectd/java/GenericJMXConfValue.java @@ -312,7 +312,14 @@ class GenericJMXConfValue try { - value = conn.getAttribute (objName, key); + try + { + value = conn.getAttribute (objName, key); + } + catch (javax.management.AttributeNotFoundException e) + { + value = conn.invoke (objName, key, /* args = */ null, /* types = */ null); + } } catch (Exception e) { diff --git a/configure.in b/configure.in index 027bf9c3..eff8d611 100644 --- a/configure.in +++ b/configure.in @@ -1,5 +1,5 @@ dnl Process this file with autoconf to produce a configure script. -AC_INIT(collectd, m4_esyscmd(./version-gen.sh)) +AC_INIT(collectd, [m4_esyscmd(./version-gen.sh)]) AC_CONFIG_SRCDIR(src/collectd.c) AC_CONFIG_HEADERS(src/config.h) AC_CONFIG_AUX_DIR([libltdl/config]) @@ -300,6 +300,21 @@ fi # For hddtemp module AC_CHECK_HEADERS(linux/major.h libgen.h) +# For md module (Linux only) +if test "x$ac_system" = "xLinux" +then + AC_CHECK_HEADERS(linux/raid/md_u.h, + [have_linux_raid_md_u_h="yes"], + [have_linux_raid_md_u_h="no"], +[ +#include +#include +#include +]) +else + have_linux_raid_md_u_h="no" +fi + # For the battery plugin AC_CHECK_HEADERS(IOKit/ps/IOPowerSources.h, [], [], [ @@ -389,6 +404,33 @@ AC_CHECK_HEADERS(linux/netdevice.h, [], [], #endif ]) +# For ethstat module +AC_CHECK_HEADERS(linux/sockios.h, + [have_linux_sockios_h="yes"], + [have_linux_sockios_h="no"], + [ +#if HAVE_SYS_IOCTL_H +# include +#endif +#if HAVE_NET_IF_H +# include +#endif + ]) +AC_CHECK_HEADERS(linux/ethtool.h, + [have_linux_ethtool_h="yes"], + [have_linux_ethtool_h="no"], + [ +#if HAVE_SYS_IOCTL_H +# include +#endif +#if HAVE_NET_IF_H +# include +#endif +#if HAVE_LINUX_SOCKIOS_H +# include +#endif + ]) + # For ipvs module have_linux_ip_vs_h="no" have_net_ip_vs_h="no" @@ -1264,6 +1306,7 @@ AC_CHECK_MEMBERS([kstat_io_t.nwritten, kstat_io_t.writes, kstat_io_t.nwrites, ks # # Checks for libraries begin here # + with_libresolv="yes" AC_CHECK_LIB(resolv, res_search, [ @@ -2160,21 +2203,21 @@ then fi if test "x$with_libmodbus" = "xuse_pkgconfig" then - AC_MSG_NOTICE([Checking for modbus using $PKG_CONFIG]) - $PKG_CONFIG --exists 'modbus' 2>/dev/null + AC_MSG_NOTICE([Checking for libmodbus using $PKG_CONFIG]) + $PKG_CONFIG --exists 'libmodbus' 2>/dev/null if test $? -ne 0 then - with_libmodbus="no (pkg-config doesn't know modbus)" + with_libmodbus="no (pkg-config doesn't know libmodbus)" fi fi if test "x$with_libmodbus" = "xuse_pkgconfig" then - with_libmodbus_cflags="`$PKG_CONFIG --cflags 'modbus'`" + with_libmodbus_cflags="`$PKG_CONFIG --cflags 'libmodbus'`" if test $? -ne 0 then with_libmodbus="no ($PKG_CONFIG failed)" fi - with_libmodbus_libs="`$PKG_CONFIG --libs 'modbus'`" + with_libmodbus_libs="`$PKG_CONFIG --libs 'libmodbus'`" if test $? -ne 0 then with_libmodbus="no ($PKG_CONFIG failed)" @@ -2220,6 +2263,69 @@ then fi # }}} +# --with-libmongoc {{{ +AC_ARG_WITH(libmongoc, [AS_HELP_STRING([--with-libmongoc@<:@=PREFIX@:>@], [Path to libmongoc.])], +[ + if test "x$withval" = "xyes" + then + with_libmongoc="yes" + else if test "x$withval" = "xno" + then + with_libmongoc="no" + else + with_libmongoc="yes" + LIBMONGOC_CPPFLAGS="$LIBMONGOC_CPPFLAGS -I$withval/include" + LIBMONGOC_LDFLAGS="$LIBMONGOC_LDFLAGS -L$withval/lib" + fi; fi +], +[with_libmongoc="yes"]) + +SAVE_CPPFLAGS="$CPPFLAGS" +SAVE_LDFLAGS="$LDFLAGS" + +CPPFLAGS="$CPPFLAGS $LIBMONGOC_CPPFLAGS" +LDFLAGS="$LDFLAGS $LIBMONGOC_LDFLAGS" + +if test "x$with_libmongoc" = "xyes" +then + if test "x$LIBMONGOC_CPPFLAGS" != "x" + then + AC_MSG_NOTICE([libmongoc CPPFLAGS: $LIBMONGOC_CPPFLAGS]) + fi + AC_CHECK_HEADERS(mongo.h, + [with_libmongoc="yes"], + [with_libmongoc="no ('mongo.h' not found)"], +[#if HAVE_STDINT_H +# define MONGO_HAVE_STDINT 1 +#else +# define MONGO_USE_LONG_LONG_INT 1 +#endif +]) +fi +if test "x$with_libmongoc" = "xyes" +then + if test "x$LIBMONGOC_LDFLAGS" != "x" + then + AC_MSG_NOTICE([libmongoc LDFLAGS: $LIBMONGOC_LDFLAGS]) + fi + AC_CHECK_LIB(mongoc, mongo_run_command, + [with_libmongoc="yes"], + [with_libmongoc="no (symbol 'mongo_run_command' not found)"]) +fi + +CPPFLAGS="$SAVE_CPPFLAGS" +LDFLAGS="$SAVE_LDFLAGS" + +if test "x$with_libmongoc" = "xyes" +then + BUILD_WITH_LIBMONGOC_CPPFLAGS="$LIBMONGOC_CPPFLAGS" + BUILD_WITH_LIBMONGOC_LDFLAGS="$LIBMONGOC_LDFLAGS" + AC_SUBST(BUILD_WITH_LIBMONGOC_CPPFLAGS) + AC_SUBST(BUILD_WITH_LIBMONGOC_LDFLAGS) +fi +AM_CONDITIONAL(BUILD_WITH_LIBMONGOC, test "x$with_libmongoc" = "xyes") +# }}} + # --with-libmysql {{{ with_mysql_config="mysql_config" with_mysql_cflags="" @@ -4086,10 +4192,9 @@ then CPPFLAGS="$CPPFLAGS $with_libvarnish_cflags" #LDFLAGS="$LDFLAGS $with_libvarnish_libs" - AC_CHECK_LIB(varnishapi, VSL_OpenStats, - [with_libvarnish="yes"], - [with_libvarnish="no (symbol VSL_OpenStats not found)"], - [$with_libvarnish_libs]) + AC_CHECK_HEADERS(varnish/vsc.h, + [AC_DEFINE([HAVE_VARNISH_V3], [1], [Varnish 3 API support])], + [AC_DEFINE([HAVE_VARNISH_V2], [1], [Varnish 2 API support])]) CPPFLAGS="$SAVE_CPPFLAGS" #LDFLAGS="$SAVE_LDFLAGS" @@ -4447,6 +4552,8 @@ plugin_curl_xml="no" plugin_df="no" plugin_disk="no" plugin_entropy="no" +plugin_ethstat="no" +plugin_fscache="no" plugin_interface="no" plugin_ipmi="no" plugin_ipvs="no" @@ -4456,7 +4563,7 @@ plugin_load="no" plugin_memory="no" plugin_multimeter="no" plugin_nfs="no" -plugin_fscache="no" +plugin_numa="no" plugin_perl="no" plugin_processes="no" plugin_protocols="no" @@ -4483,12 +4590,13 @@ then plugin_cpufreq="yes" plugin_disk="yes" plugin_entropy="yes" + plugin_fscache="yes" plugin_interface="yes" plugin_irq="yes" plugin_load="yes" plugin_memory="yes" plugin_nfs="yes" - plugin_fscache="yes" + plugin_numa="yes" plugin_processes="yes" plugin_protocols="yes" plugin_serial="yes" @@ -4519,6 +4627,12 @@ then fi # AIX + +if test "x$ac_system" = "xAIX" +then + plugin_tcpconns="yes" +fi + if test "x$with_perfstat" = "xyes" then plugin_cpu="yes" @@ -4537,6 +4651,7 @@ fi # Solaris if test "x$with_kstat" = "xyes" then + plugin_nfs="yes" plugin_uptime="yes" plugin_zfs_arc="yes" fi @@ -4643,6 +4758,11 @@ then fi fi +if test "x$have_linux_sockios_h$have_linux_ethtool_h" = "xyesyes" +then + plugin_ethstat="yes" +fi + if test "x$have_getifaddrs" = "xyes" then plugin_interface="yes" @@ -4751,6 +4871,7 @@ AC_PLUGIN([disk], [$plugin_disk], [Disk usage statistics]) AC_PLUGIN([dns], [$with_libpcap], [DNS traffic analysis]) AC_PLUGIN([email], [yes], [EMail statistics]) AC_PLUGIN([entropy], [$plugin_entropy], [Entropy statistics]) +AC_PLUGIN([ethstat], [$plugin_ethstat], [Stats from NIC driver]) AC_PLUGIN([exec], [yes], [Execution of external programs]) AC_PLUGIN([filecount], [yes], [Count files in directories]) AC_PLUGIN([fscache], [$plugin_fscache], [fscache statistics]) @@ -4773,6 +4894,7 @@ AC_PLUGIN([match_regex], [yes], [The regex match]) AC_PLUGIN([match_timediff], [yes], [The timediff match]) AC_PLUGIN([match_value], [yes], [The value match]) AC_PLUGIN([mbmon], [yes], [Query mbmond]) +AC_PLUGIN([md], [$have_linux_raid_md_u_h], [md (Linux software RAID) devices]) AC_PLUGIN([memcachec], [$with_libmemcached], [memcachec statistics]) AC_PLUGIN([memcached], [yes], [memcached statistics]) AC_PLUGIN([memory], [$plugin_memory], [Memory usage]) @@ -4787,6 +4909,7 @@ AC_PLUGIN([nginx], [$with_libcurl], [nginx statistics]) AC_PLUGIN([notify_desktop], [$with_libnotify], [Desktop notifications]) AC_PLUGIN([notify_email], [$with_libesmtp], [Email notifier]) AC_PLUGIN([ntpd], [yes], [NTPd statistics]) +AC_PLUGIN([numa], [$plugin_numa], [NUMA virtual memory statistics]) AC_PLUGIN([nut], [$with_libupsclient], [Network UPS tools statistics]) AC_PLUGIN([olsrd], [yes], [olsrd statistics]) AC_PLUGIN([onewire], [$with_libowcapi], [OneWire sensor statistics]) @@ -4832,8 +4955,10 @@ AC_PLUGIN([varnish], [$with_libvarnish], [Varnish cache statistics]) AC_PLUGIN([vmem], [$plugin_vmem], [Virtual memory statistics]) AC_PLUGIN([vserver], [$plugin_vserver], [Linux VServer statistics]) AC_PLUGIN([wireless], [$plugin_wireless], [Wireless statistics]) +AC_PLUGIN([write_graphite], [yes], [Graphite / Carbon output plugin]) AC_PLUGIN([write_http], [$with_libcurl], [HTTP output plugin]) AC_PLUGIN([write_redis], [$with_libcredis], [Redis output plugin]) +AC_PLUGIN([write_mongodb], [$with_libmongoc], [MongoDB output plugin]) AC_PLUGIN([xmms], [$with_libxmms], [XMMS statistics]) AC_PLUGIN([zfs_arc], [$plugin_zfs_arc], [ZFS ARC statistics]) @@ -4976,7 +5101,7 @@ AC_SUBST(LCC_VERSION_STRING) AC_CONFIG_FILES(src/libcollectdclient/lcc_features.h) -AC_OUTPUT(Makefile src/Makefile src/collectd.conf src/owniptc/Makefile src/libcollectdclient/Makefile src/libcollectdclient/libcollectdclient.pc src/liboconfig/Makefile bindings/Makefile bindings/java/Makefile) +AC_OUTPUT(Makefile src/Makefile src/collectd.conf src/libcollectdclient/Makefile src/libcollectdclient/libcollectdclient.pc src/liboconfig/Makefile bindings/Makefile bindings/java/Makefile) if test "x$with_librrd" = "xyes" \ && test "x$librrd_threadsafe" != "xyes" @@ -5078,6 +5203,7 @@ Configuration: dns . . . . . . . . . $enable_dns email . . . . . . . . $enable_email entropy . . . . . . . $enable_entropy + ethstat . . . . . . . $enable_ethstat exec . . . . . . . . $enable_exec filecount . . . . . . $enable_filecount fscache . . . . . . . $enable_fscache @@ -5100,6 +5226,7 @@ Configuration: match_timediff . . . $enable_match_timediff match_value . . . . . $enable_match_value mbmon . . . . . . . . $enable_mbmon + md . . . . . . . . . $enable_md memcachec . . . . . . $enable_memcachec memcached . . . . . . $enable_memcached memory . . . . . . . $enable_memory @@ -5114,6 +5241,7 @@ Configuration: notify_desktop . . . $enable_notify_desktop notify_email . . . . $enable_notify_email ntpd . . . . . . . . $enable_ntpd + numa . . . . . . . . $enable_numa nut . . . . . . . . . $enable_nut olsrd . . . . . . . . $enable_olsrd onewire . . . . . . . $enable_onewire @@ -5158,8 +5286,10 @@ Configuration: vmem . . . . . . . . $enable_vmem vserver . . . . . . . $enable_vserver wireless . . . . . . $enable_wireless + write_graphite . . . $enable_write_graphite write_http . . . . . $enable_write_http write_redis . . . . . $enable_write_redis + write_mongodb . . . . $enable_write_mongodb xmms . . . . . . . . $enable_xmms zfs_arc . . . . . . . $enable_zfs_arc diff --git a/contrib/collection3/bin/graph.cgi b/contrib/collection3/bin/graph.cgi index 8a5bf85a..2b3f2fe1 100755 --- a/contrib/collection3/bin/graph.cgi +++ b/contrib/collection3/bin/graph.cgi @@ -1,14 +1,45 @@ #!/usr/bin/perl +# Copyright (C) 2008-2011 Florian Forster +# Copyright (C) 2011 noris network AG +# +# 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; only version 2 of the License is applicable. +# +# 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., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# Authors: +# Florian "octo" Forster + use strict; use warnings; -use lib ('../lib'); use utf8; +use vars (qw($BASE_DIR)); + +BEGIN +{ + if (defined $ENV{'SCRIPT_FILENAME'}) + { + if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$}) + { + $::BASE_DIR = $1; + unshift (@::INC, "$::BASE_DIR/lib"); + } + } +} -use FindBin ('$RealBin'); use Carp (qw(confess cluck)); use CGI (':cgi'); use RRDs (); +use File::Temp (':POSIX'); use Collectd::Graph::Config (qw(gc_read_config gc_get_scalar)); use Collectd::Graph::TypeLoader (qw(tl_load_type)); @@ -17,200 +48,287 @@ use Collectd::Graph::Common (qw(sanitize_type get_selected_files epoch_to_rfc1123 flush_files)); use Collectd::Graph::Type (); -our $Debug = param ('debug'); -our $Begin = param ('begin'); -our $End = param ('end'); -our $GraphWidth = param ('width'); -our $GraphHeight = param ('height'); -our $Index = param ('index') || 0; -our $OutputFormat = 'PNG'; -our $ContentType = 'image/png'; - -if (param ('format')) +sub base_dir { - my $temp = param ('format') || ''; - $temp = uc ($temp); + if (defined $::BASE_DIR) + { + return ($::BASE_DIR); + } - if ($temp =~ m/^(PNG|SVG|EPS|PDF)$/) + if (!defined ($ENV{'SCRIPT_FILENAME'})) { - $OutputFormat = $temp; + return; + } - if ($OutputFormat eq 'SVG') { $ContentType = 'image/svg+xml'; } - elsif ($OutputFormat eq 'EPS') { $ContentType = 'image/eps'; } - elsif ($OutputFormat eq 'PDF') { $ContentType = 'application/pdf'; } + if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$}) + { + $::BASE_DIR = $1; + return ($::BASE_DIR); } + + return; } -if ($Debug) +sub lib_dir { - print < 0) && ($Begin > $End)) + if ($GraphHeight) { - my $temp = $End; - $End = $Begin; - $Begin = $temp; + $GraphHeight =~ s/\D//g; } -} -my $type = param ('type') or die; -my $obj; + if (!$GraphHeight) + { + $GraphHeight = gc_get_scalar ('GraphHeight', 100); + } -$obj = tl_load_type ($type); -if (!$obj) -{ - confess ("tl_load_type ($type) failed"); -} + { # Sanitize begin and end times + $End ||= 0; + $Begin ||= 0; -$type = ucfirst (lc ($type)); -$type =~ s/_([A-Za-z])/\U$1\E/g; -$type = sanitize_type ($type); + if ($End =~ m/\D/) + { + $End = 0; + } -my $files = get_selected_files (); -if ($Debug) -{ - require Data::Dumper; - print STDOUT Data::Dumper->Dump ([$files], ['files']); -} -for (@$files) -{ - $obj->addFiles ($_); -} + if (!$Begin || !($Begin =~ m/^-?([1-9][0-9]*)$/)) + { + $Begin = -86400; + } -my $expires = time (); -# IF (End is `now') -# OR (Begin is before `now' AND End is after `now') -if (($End == 0) || (($Begin <= $expires) && ($End >= $expires))) -{ - # 400 == width in pixels - my $timespan; + if ($Begin < 0) + { + if ($End) + { + $Begin = $End + $Begin; + } + else + { + $Begin = time () + $Begin; + } + } + + if ($Begin < 0) + { + $Begin = time () - 86400; + } + + if (($End > 0) && ($Begin > $End)) + { + my $temp = $End; + $End = $Begin; + $Begin = $temp; + } + } - if ($End == 0) + my $type = param ('type') or die; + my $obj; + + $obj = tl_load_type ($type); + if (!$obj) { - $timespan = $expires - $Begin; + confess ("tl_load_type ($type) failed"); } - else + + $type = ucfirst (lc ($type)); + $type =~ s/_([A-Za-z])/\U$1\E/g; + $type = sanitize_type ($type); + + my $files = get_selected_files (); + if (param ('debug')) { - $timespan = $End - $Begin; + require Data::Dumper; + print Data::Dumper->Dump ([$files], ['files']); + } + for (@$files) + { + $obj->addFiles ($_); + } + + my $expires = time (); +# IF (End is `now') +# OR (Begin is before `now' AND End is after `now') + if (($End == 0) || (($Begin <= $expires) && ($End >= $expires))) + { + # 400 == width in pixels + my $timespan; + + if ($End == 0) + { + $timespan = $expires - $Begin; + } + else + { + $timespan = $End - $Begin; + } + $expires += int ($timespan / 400.0); } - $expires += int ($timespan / 400.0); -} # IF (End is not `now') # AND (End is before `now') # ==> Graph will never change again! -elsif (($End > 0) && ($End < $expires)) -{ - $expires += (366 * 86400); -} -elsif ($Begin > $expires) -{ - $expires = $Begin; -} + elsif (($End > 0) && ($End < $expires)) + { + $expires += (366 * 86400); + } + elsif ($Begin > $expires) + { + $expires = $Begin; + } # Send FLUSH command to the daemon if necessary and possible. -flush_files ($files, + flush_files ($files, begin => $Begin, end => $End, addr => gc_get_scalar ('UnixSockAddr', undef), interval => gc_get_scalar ('Interval', 10)); -print STDOUT header (-Content_type => $ContentType, - -Last_Modified => epoch_to_rfc1123 ($obj->getLastModified ()), - -Expires => epoch_to_rfc1123 ($expires)); - -if ($Debug) -{ - print "\$expires = $expires;\n"; -} + print header (-Content_type => $ContentType, + -Last_Modified => epoch_to_rfc1123 ($obj->getLastModified ()), + -Expires => epoch_to_rfc1123 ($expires)); -my $args = $obj->getRRDArgs (0 + $Index); - -if ($Debug) -{ - require Data::Dumper; - print STDOUT Data::Dumper->Dump ([$obj], ['obj']); - print STDOUT join (",\n", @$args) . "\n"; - print STDOUT "Last-Modified: " . epoch_to_rfc1123 ($obj->getLastModified ()) . "\n"; -} -else -{ - my @timesel = (); + if (param ('debug')) + { + print "\$expires = $expires;\n"; + } - if ($End) # $Begin is always true + my $args = $obj->getRRDArgs (0 + $Index); + if (param ('debug')) { - @timesel = ('-s', $Begin, '-e', $End); + require Data::Dumper; + print Data::Dumper->Dump ([$obj], ['obj']); + print join (",\n", @$args) . "\n"; + print "Last-Modified: " . epoch_to_rfc1123 ($obj->getLastModified ()) . "\n"; } else { - @timesel = ('-s', $Begin); # End is implicitely `now'. - } + my @timesel = (); + my $tmpfile = tmpnam (); + my $status; - $| = 1; - RRDs::graph ('-', '-a', $OutputFormat, '--width', $GraphWidth, '--height', $GraphHeight, @timesel, @$args); - if (my $err = RRDs::error ()) - { - print STDERR "RRDs::graph failed: $err\n"; - exit (1); + if ($End) # $Begin is always true + { + @timesel = ('-s', $Begin, '-e', $End); + } + else + { + @timesel = ('-s', $Begin); # End is implicitely `now'. + } + + if (-S "/var/run/rrdcached.sock" && -w "/var/run/rrdcached.sock") + { + $ENV{"RRDCACHED_ADDRESS"} = "/var/run/rrdcached.sock"; + } + unlink ($tmpfile); + RRDs::graph ($tmpfile, '-a', $OutputFormat, '--width', $GraphWidth, '--height', $GraphHeight, @timesel, @$args); + if (my $err = RRDs::error ()) + { + print STDERR "RRDs::graph failed: $err\n"; + exit (1); + } + + $status = open (IMG, '<', $tmpfile) or die ("open ($tmpfile): $!"); + if (!$status) + { + print STDERR "graph.cgi: Unable to open temporary file \"$tmpfile\" for reading: $!\n"; + } + else + { + local $/ = undef; + while (my $data = ) + { + print STDOUT $data; + } + + close (IMG); + unlink ($tmpfile); + } } -} +} # sub main -exit (0); +main (); # vim: set shiftwidth=2 softtabstop=2 tabstop=8 : diff --git a/contrib/collection3/bin/index.cgi b/contrib/collection3/bin/index.cgi index e28e9857..4723af96 100755 --- a/contrib/collection3/bin/index.cgi +++ b/contrib/collection3/bin/index.cgi @@ -1,6 +1,7 @@ #!/usr/bin/perl -# Copyright (C) 2008 Florian octo Forster +# Copyright (C) 2008-2011 Florian Forster +# Copyright (C) 2011 noris network AG # # 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 @@ -14,14 +15,28 @@ # 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., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# Authors: +# Florian "octo" Forster use strict; use warnings; -use lib ('../lib'); use utf8; +use vars (qw($BASE_DIR)); + +BEGIN +{ + if (defined $ENV{'SCRIPT_FILENAME'}) + { + if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$}) + { + $::BASE_DIR = $1; + unshift (@::INC, "$::BASE_DIR/lib"); + } + } +} use Carp (qw(cluck confess)); -use FindBin ('$RealBin'); use CGI (':cgi'); use CGI::Carp ('fatalsToBrowser'); use HTML::Entities ('encode_entities'); @@ -35,8 +50,6 @@ use Collectd::Graph::Common (qw(get_files_from_directory get_all_hosts get_plugin_selection flush_files)); use Collectd::Graph::Type (); -our $Debug = param ('debug') ? 1 : 0; - our $TimeSpans = { Hour => 3600, @@ -46,23 +59,90 @@ our $TimeSpans = Year => 366 * 86400 }; -my $action = param ('action') || 'list_hosts'; -our %Actions = +my %Actions = ( list_hosts => \&action_list_hosts, show_selection => \&action_show_selection ); -if (!exists ($Actions{$action})) +sub base_dir { - print STDERR "No such action: $action\n"; - exit 1; + if (defined $::BASE_DIR) + { + return ($::BASE_DIR); + } + + if (!defined ($ENV{'SCRIPT_FILENAME'})) + { + return; + } + + if ($ENV{'SCRIPT_FILENAME'} =~ m{^(/.+)/bin/[^/]+$}) + { + $::BASE_DIR = $1; + return ($::BASE_DIR); + } + + return; } -gc_read_config ("$RealBin/../etc/collection.conf"); +sub lib_dir +{ + my $base = base_dir (); -$Actions{$action}->(); -exit (0); + if ($base) + { + return "$base/lib"; + } + else + { + return "../lib"; + } +} + +sub sysconf_dir +{ + my $base = base_dir (); + + if ($base) + { + return "$base/etc"; + } + else + { + return "../etc"; + } +} + +sub init +{ + my $lib_dir = lib_dir (); + my $sysconf_dir = sysconf_dir (); + + if (!grep { $lib_dir eq $_ } (@::INC)) + { + unshift (@::INC, $lib_dir); + } + + gc_read_config ("$sysconf_dir/collection.conf"); +} + +sub main +{ + my $Debug = param ('debug') ? 1 : 0; + my $action = param ('action') || 'list_hosts'; + + if (!exists ($Actions{$action})) + { + print STDERR "No such action: $action\n"; + return (1); + } + + init (); + + $Actions{$action}->(); + return (1); +} # sub main sub can_handle_xhtml { @@ -104,7 +184,7 @@ sub can_handle_xhtml } } # can_handle_xhtml -{my $html_started; +my $html_started; sub start_html { return if ($html_started); @@ -119,9 +199,8 @@ sub start_html if (can_handle_xhtml ()) { + print header (-Content_Type => 'application/xhtml+xml; charset=UTF-8'); print < @@ -133,9 +212,8 @@ HTML } else { + print header (-Content_Type => 'text/html; charset=UTF-8'); print < @@ -151,7 +229,7 @@ HTML HTML $html_started = 1; -}} +} sub end_html { @@ -159,6 +237,7 @@ sub end_html HTML + $html_started = 0; } sub contains_invalid_chars @@ -308,7 +387,7 @@ sub action_show_selection $all_files = get_selected_files (); $timespan = get_timespan_selection (); - if ($Debug) + if (param ('debug')) { print "
", Data::Dumper->Dump ([$all_files], ['all_files']), "
\n"; } @@ -333,7 +412,7 @@ sub action_show_selection $types->{$type} = tl_load_type ($file->{'type'}); if (!$types->{$type}) { - cluck ("tl_load_type (" . $file->{'type'} . ") failed"); + warn ("tl_load_type (" . $file->{'type'} . ") failed"); next; } } @@ -346,6 +425,12 @@ sub action_show_selection for (sort (keys %$types)) { my $type = $_; + + if (!defined ($types->{$type})) + { + next; + } + my $graphs_num = $types->{$type}->getGraphsNum (); for (my $i = 0; $i < $graphs_num; $i++) @@ -400,6 +485,8 @@ EOF end_html (); } +main (); + =head1 SEE ALSO L diff --git a/contrib/collection3/lib/Collectd/Graph/Common.pm b/contrib/collection3/lib/Collectd/Graph/Common.pm index c6e25081..cc7e141f 100644 --- a/contrib/collection3/lib/Collectd/Graph/Common.pm +++ b/contrib/collection3/lib/Collectd/Graph/Common.pm @@ -1,5 +1,24 @@ package Collectd::Graph::Common; +# Copyright (C) 2008-2011 Florian Forster +# Copyright (C) 2011 noris network AG +# +# 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; only version 2 of the License is applicable. +# +# 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., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +# Authors: +# Florian "octo" Forster + use strict; use warnings; @@ -11,6 +30,8 @@ use CGI (':cgi'); use Exporter; use Collectd::Graph::Config (qw(gc_get_scalar)); +our $Cache = {}; + $ColorCanvas = 'FFFFFF'; $ColorFullBlue = '0000FF'; $ColorHalfBlue = 'B7B7F7'; @@ -191,22 +212,48 @@ sub ident_to_filename return ($ret); } # ident_to_filename +sub _part_to_string +{ + my $part = shift; + + if (!defined ($part)) + { + return ("(UNDEF)"); + } + if (ref ($part) eq 'ARRAY') + { + if (1 == @$part) + { + return ($part->[0]); + } + else + { + return ('(' . join (',', @$part) . ')'); + } + } + else + { + return ($part); + } +} # _part_to_string + sub ident_to_string { my $ident = shift; my $ret = ''; - $ret .= $ident->{'hostname'} . '/' . $ident->{'plugin'}; + $ret .= _part_to_string ($ident->{'hostname'}) + . '/' . _part_to_string ($ident->{'plugin'}); if (defined ($ident->{'plugin_instance'})) { - $ret .= '-' . $ident->{'plugin_instance'}; + $ret .= '-' . _part_to_string ($ident->{'plugin_instance'}); } - $ret .= '/' . $ident->{'type'}; + $ret .= '/' . _part_to_string ($ident->{'type'}); if (defined ($ident->{'type_instance'})) { - $ret .= '-' . $ident->{'type_instance'}; + $ret .= '-' . _part_to_string ($ident->{'type_instance'}); } return ($ret); @@ -258,27 +305,36 @@ sub get_files_from_directory sub get_all_hosts { - my $dh; - my @ret = (); - my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir); + my $ret = []; - opendir ($dh, "$data_dir") or confess ("opendir ($data_dir): $!"); - while (my $entry = readdir ($dh)) + if (defined ($Cache->{'get_all_hosts'})) { - next if ($entry =~ m/^\./); - next if (!-d "$data_dir/$entry"); - next if (!-r "$data_dir/$entry" or !-x "$data_dir/$entry"); - push (@ret, sanitize_hostname ($entry)); + $ret = $Cache->{'get_all_hosts'}; + } + else + { + my $dh; + my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir); + + opendir ($dh, "$data_dir") or confess ("opendir ($data_dir): $!"); + while (my $entry = readdir ($dh)) + { + next if ($entry =~ m/^\./); + next if (!-d "$data_dir/$entry"); + push (@$ret, sanitize_hostname ($entry)); + } + closedir ($dh); + + $Cache->{'get_all_hosts'} = $ret; } - closedir ($dh); if (wantarray ()) { - return (@ret); + return (@$ret); } - elsif (@ret) + elsif (@$ret) { - return (\@ret); + return ($ret); } else { @@ -292,12 +348,32 @@ sub get_all_plugins my $ret = {}; my $dh; my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir); + my $cache_key; - if (!@hosts) + if (@hosts) { + $cache_key = join (';', @hosts); + } + else + { + $cache_key = "/*/"; @hosts = get_all_hosts (); } + if (defined ($Cache->{'get_all_plugins'}{$cache_key})) + { + $ret = $Cache->{'get_all_plugins'}{$cache_key}; + + if (wantarray ()) + { + return (sort (keys %$ret)); + } + else + { + return ($ret); + } + } + for (@hosts) { my $host = $_; @@ -331,6 +407,7 @@ sub get_all_plugins closedir ($dh); } # for (@hosts) + $Cache->{'get_all_plugins'}{$cache_key} = $ret; if (wantarray ()) { return (sort (keys %$ret)); @@ -386,24 +463,44 @@ sub _filter_ident return (0); } # _filter_ident +sub _get_all_files +{ + my $ret; + + if (defined ($Cache->{'_get_all_files'})) + { + $ret = $Cache->{'_get_all_files'}; + } + else + { + my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir); + + $ret = get_files_from_directory ($data_dir, 3); + $Cache->{'_get_all_files'} = $ret; + } + + return ($ret); +} # _get_all_files + sub get_files_by_ident { my $ident = shift; my $all_files; my @ret = (); - my $data_dir = gc_get_scalar ('DataDir', $DefaultDataDir); - #if ($ident->{'hostname'}) - #{ - #$all_files = get_files_for_host ($ident->{'hostname'}); - #} - #else - #{ - $all_files = get_files_from_directory ($data_dir, 3); - #} + my $cache_key = ident_to_string ($ident); + if (defined ($Cache->{'get_files_by_ident'}{$cache_key})) + { + my $ret = $Cache->{'get_files_by_ident'}{$cache_key}; + + return ($ret) + } + + $all_files = _get_all_files (); @ret = grep { _filter_ident ($ident, $_) == 0 } (@$all_files); + $Cache->{'get_files_by_ident'}{$cache_key} = \@ret; return (\@ret); } # get_files_by_ident diff --git a/contrib/collection3/lib/Collectd/Graph/TypeLoader.pm b/contrib/collection3/lib/Collectd/Graph/TypeLoader.pm index 9078110b..5a0b522b 100644 --- a/contrib/collection3/lib/Collectd/Graph/TypeLoader.pm +++ b/contrib/collection3/lib/Collectd/Graph/TypeLoader.pm @@ -92,7 +92,8 @@ sub _load_module_from_config $obj = _create_object ($module); if (!$obj) { - cluck ("Creating an $module object failed"); + #cluck ("Creating an $module object failed"); + warn ("Creating an $module object failed"); return; } } diff --git a/contrib/exec-ksm.sh b/contrib/exec-ksm.sh new file mode 100755 index 00000000..a21aa1d6 --- /dev/null +++ b/contrib/exec-ksm.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +# collectd - contrib/exec-ksm.sh +# Copyright (C) 2011 Florian Forster +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, distribute, sublicense, +# and/or sell copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. +# +# Authors: +# Florian Forster + +HOSTNAME="${COLLECTD_HOSTNAME:-$(hostname -f)}" +INTERVAL="${COLLECTD_INTERVAL:-60}" + +function read_file() { + local type="$1" + local type_instance="$2" + local file_name="/sys/kernel/mm/ksm/$3" + local ident="$HOSTNAME/exec-ksm/vmpage_number-${type_instance}" + + echo "PUTVAL \"$ident\" interval=$INTERVAL N:$(< $file_name)" +} + +if [[ 0 -eq $(< /sys/kernel/mm/ksm/run) ]]; then + echo "$0: KSM not active." >&2 + exit 1 +fi + +while sleep "$INTERVAL" +do + read_file vmpage_number shared pages_shared + read_file vmpage_number saved pages_sharing + read_file vmpage_number unshared pages_unshared + read_file vmpage_number volatile pages_volatile + read_file total_operations scan full_scans +done + +exit 0 diff --git a/contrib/php-collection/definitions.php b/contrib/php-collection/definitions.php index c84aabea..7297d858 100644 --- a/contrib/php-collection/definitions.php +++ b/contrib/php-collection/definitions.php @@ -48,9 +48,9 @@ function load_graph_definitions($logarithmic = false, $tinylegend = false) { $GraphDefs = array(); $GraphDefs['apache_bytes'] = array( '-v', 'Bits/s', - 'DEF:min_raw={file}:count:MIN', - 'DEF:avg_raw={file}:count:AVERAGE', - 'DEF:max_raw={file}:count:MAX', + 'DEF:min_raw={file}:value:MIN', + 'DEF:avg_raw={file}:value:AVERAGE', + 'DEF:max_raw={file}:value:MAX', 'CDEF:min=min_raw,8,*', 'CDEF:avg=avg_raw,8,*', 'CDEF:max=max_raw,8,*', @@ -68,9 +68,9 @@ function load_graph_definitions($logarithmic = false, $tinylegend = false) { 'GPRINT:avg_sum:LAST:(ca. %5.1lf%sB Total)\l'); $GraphDefs['apache_requests'] = array( '-v', 'Requests/s', - 'DEF:min={file}:count:MIN', - 'DEF:avg={file}:count:AVERAGE', - 'DEF:max={file}:count:MAX', + 'DEF:min={file}:value:MIN', + 'DEF:avg={file}:value:AVERAGE', + 'DEF:max={file}:value:MAX', "AREA:max#$HalfBlue", "AREA:min#$Canvas", "LINE1:avg#$FullBlue:Requests/s", @@ -79,9 +79,9 @@ function load_graph_definitions($logarithmic = false, $tinylegend = false) { 'GPRINT:max:MAX:%6.2lf Max,', 'GPRINT:avg:LAST:%6.2lf Last'); $GraphDefs['apache_scoreboard'] = array( - 'DEF:min={file}:count:MIN', - 'DEF:avg={file}:count:AVERAGE', - 'DEF:max={file}:count:MAX', + 'DEF:min={file}:value:MIN', + 'DEF:avg={file}:value:AVERAGE', + 'DEF:max={file}:value:MAX', "AREA:max#$HalfBlue", "AREA:min#$Canvas", "LINE1:avg#$FullBlue:Processes", @@ -2024,7 +2024,7 @@ function meta_graph_apache_scoreboard($host, $plugin, $plugin_instance, $type, $ if ($file == '') continue; - $sources[] = array('name'=>$inst, 'file'=>$file, 'ds'=>'count'); + $sources[] = array('name'=>$inst, 'file'=>$file, 'ds'=>'value'); } return collectd_draw_meta_stack($opts, $sources); diff --git a/contrib/redhat/collectd.spec b/contrib/redhat/collectd.spec index 4617f6ca..6eefac9d 100644 --- a/contrib/redhat/collectd.spec +++ b/contrib/redhat/collectd.spec @@ -3,7 +3,7 @@ Summary: Statistics collection daemon for filling RRD files. Name: collectd -Version: 4.9.0 +Version: 5.0.1 Release: 1%{?dist} Source: http://collectd.org/files/%{name}-%{version}.tar.gz License: GPL @@ -147,6 +147,7 @@ exit 0 %attr(0755,root,root) /var/www/cgi-bin/collection.cgi %attr(0755,root,root) %{_sbindir}/collectd %attr(0755,root,root) %{_bindir}/collectd-nagios +%attr(0755,root,root) %{_bindir}/collectdctl %attr(0755,root,root) %{_sbindir}/collectdmon %attr(0644,root,root) %{_mandir}/man1/* %attr(0644,root,root) %{_mandir}/man5/* @@ -174,6 +175,7 @@ exit 0 %plugin_macro cpu %plugin_macro csv %plugin_macro curl +%plugin_macro curl_xml %plugin_macro df %plugin_macro disk %plugin_macro dns @@ -197,6 +199,7 @@ exit 0 %plugin_macro match_value %plugin_macro mbmon +%plugin_macro memcachec %plugin_macro memcached %plugin_macro memory %plugin_macro multimeter @@ -222,11 +225,14 @@ exit 0 %plugin_macro target_replace %plugin_macro target_scale %plugin_macro target_set +%plugin_macro target_v5upgrade %plugin_macro tcpconns %plugin_macro teamspeak2 %plugin_macro ted %plugin_macro thermal +%plugin_macro threshold + %plugin_macro unixsock %plugin_macro uptime %plugin_macro users @@ -243,6 +249,7 @@ exit 0 %attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd.pm %attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd/Unixsock.pm %attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd/Plugins/OpenVZ.pm +%attr(0644,root,root) /usr/lib/perl5/site_perl/5.8.8/Collectd/Plugins/Monitorus.pm %attr(0644,root,root) /usr/share/man/man3/Collectd::Unixsock.3pm.gz %exclude /usr/share/collectd/postgresql_default.conf @@ -251,8 +258,8 @@ exit 0 %if %with_java %files java -%attr(0644,root,root) /usr/share/%{name}/java/org/collectd/api/*.class -%attr(0644,root,root) /usr/share/%{name}/java/org/collectd/java/*.class +/usr/share/collectd/java/collectd-api.jar +/usr/share/collectd/java/generic-jmx.jar %plugin_macro java %endif @@ -283,6 +290,10 @@ exit 0 %plugin_macro snmp %changelog +* Tue Jan 03 2011 Monetate 5.0.1 +- New upstream version +- Changes to support 5.0.1 + * Tue Jan 04 2010 Rackspace 4.9.0 - New upstream version - Changes to support 4.9.0 @@ -299,7 +310,7 @@ exit 0 * Wed Jul 25 2007 Kjell Randa 4.0.5 - New major releas -- Changes to support 4.0.5 +- Changes to support 4.0.5 * Wed Jan 11 2007 Iain Lea 3.11.0-0 - fixed spec file to build correctly on fedora core diff --git a/src/Makefile.am b/src/Makefile.am index 45fd6f1a..1891f7a9 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,7 +1,4 @@ SUBDIRS = libcollectdclient -if BUILD_WITH_OWN_LIBIPTC -SUBDIRS += owniptc -endif if BUILD_WITH_OWN_LIBOCONFIG SUBDIRS += liboconfig endif @@ -380,6 +377,14 @@ collectd_LDADD += "-dlopen" exec.la collectd_DEPENDENCIES += exec.la endif +if BUILD_PLUGIN_ETHSTAT +pkglib_LTLIBRARIES += ethstat.la +ethstat_la_SOURCES = ethstat.c +ethstat_la_LDFLAGS = -module -avoid-version +collectd_LDADD += "-dlopen" ethstat.la +collectd_DEPENDENCIES += ethstat.la +endif + if BUILD_PLUGIN_FILECOUNT pkglib_LTLIBRARIES += filecount.la filecount_la_SOURCES = filecount.c @@ -439,12 +444,7 @@ pkglib_LTLIBRARIES += iptables.la iptables_la_SOURCES = iptables.c iptables_la_CPPFLAGS = $(AM_CPPFLAGS) $(BUILD_WITH_LIBIPTC_CPPFLAGS) iptables_la_LDFLAGS = -module -avoid-version $(BUILD_WITH_LIBIPTC_LDFLAGS) -if BUILD_WITH_OWN_LIBIPTC -iptables_la_LIBADD = owniptc/libiptc.la -iptables_la_DEPENDENCIES = owniptc/libiptc.la -else iptables_la_LIBADD = -liptc -endif collectd_LDADD += "-dlopen" iptables.la collectd_DEPENDENCIES += iptables.la endif @@ -594,6 +594,14 @@ collectd_LDADD += "-dlopen" mbmon.la collectd_DEPENDENCIES += mbmon.la endif +if BUILD_PLUGIN_MD +pkglib_LTLIBRARIES += md.la +md_la_SOURCES = md.c +md_la_LDFLAGS = -module -avoid-version +collectd_LDADD += "-dlopen" md.la +collectd_DEPENDENCIES += md.la +endif + if BUILD_PLUGIN_MEMCACHEC pkglib_LTLIBRARIES += memcachec.la memcachec_la_SOURCES = memcachec.c @@ -771,6 +779,14 @@ collectd_LDADD += "-dlopen" ntpd.la collectd_DEPENDENCIES += ntpd.la endif +if BUILD_PLUGIN_NUMA +pkglib_LTLIBRARIES += numa.la +numa_la_SOURCES = numa.c +numa_la_LDFLAGS = -module -avoid-version +collectd_LDADD += "-dlopen" numa.la +collectd_DEPENDENCIES += numa.la +endif + if BUILD_PLUGIN_NUT pkglib_LTLIBRARIES += nut.la nut_la_SOURCES = nut.c @@ -1237,6 +1253,15 @@ collectd_LDADD += "-dlopen" wireless.la collectd_DEPENDENCIES += wireless.la endif +if BUILD_PLUGIN_WRITE_GRAPHITE +pkglib_LTLIBRARIES += write_graphite.la +write_graphite_la_SOURCES = write_graphite.c \ + utils_format_json.c utils_format_json.h +write_graphite_la_LDFLAGS = -module -avoid-version +collectd_LDADD += "-dlopen" write_graphite.la +collectd_DEPENDENCIES += write_graphite.la +endif + if BUILD_PLUGIN_WRITE_HTTP pkglib_LTLIBRARIES += write_http.la write_http_la_SOURCES = write_http.c \ @@ -1252,6 +1277,16 @@ endif collectd_DEPENDENCIES += write_http.la endif +if BUILD_PLUGIN_WRITE_MONGODB +pkglib_LTLIBRARIES += write_mongodb.la +write_mongodb_la_SOURCES = write_mongodb.c +write_mongodb_la_CPPFLAGS = $(AM_CPPFLAGS) $(BUILD_WITH_LIBMONGOC_CPPFLAGS) +write_mongodb_la_LDFLAGS = -module -avoid-version $(BUILD_WITH_LIBMONGOC_LDFLAGS) +write_mongodb_la_LIBADD = -lmongoc +collectd_LDADD += "-dlopen" write_mongodb.la +collectd_DEPENDENCIES += write_mongodb.la +endif + if BUILD_PLUGIN_WRITE_REDIS pkglib_LTLIBRARIES += write_redis.la write_redis_la_SOURCES = write_redis.c diff --git a/src/bind.c b/src/bind.c index 38d4a27f..5b7d7a05 100644 --- a/src/bind.c +++ b/src/bind.c @@ -98,6 +98,10 @@ struct list_info_ptr_s }; typedef struct list_info_ptr_s list_info_ptr_t; +/* FIXME: Enabled by default for backwards compatibility. */ +/* TODO: Remove time parsing code. */ +static _Bool config_parse_time = 1; + static char *url = NULL; static int global_opcodes = 1; static int global_qtypes = 1; @@ -249,7 +253,8 @@ static void submit (time_t ts, const char *plugin_instance, /* {{{ */ vl.values = values; vl.values_len = 1; - vl.time = TIME_T_TO_CDTIME_T (ts); + if (config_parse_time) + vl.time = TIME_T_TO_CDTIME_T (ts); sstrncpy(vl.host, hostname_g, sizeof(vl.host)); sstrncpy(vl.plugin, "bind", sizeof(vl.plugin)); if (plugin_instance) { @@ -1364,6 +1369,8 @@ static int bind_config (oconfig_item_t *ci) /* {{{ */ bind_config_set_bool ("MemoryStats", &global_memory_stats, child); else if (strcasecmp ("View", child->key) == 0) bind_config_add_view (child); + else if (strcasecmp ("ParseTime", child->key) == 0) + cf_util_get_boolean (child, &config_parse_time); else { WARNING ("bind plugin: Unknown configuration option " diff --git a/src/collectd-nagios.c b/src/collectd-nagios.c index af8744de..88a53023 100644 --- a/src/collectd-nagios.c +++ b/src/collectd-nagios.c @@ -269,6 +269,67 @@ static void usage (const char *name) exit (1); } /* void usage */ +static int do_listval (lcc_connection_t *connection) +{ + lcc_identifier_t *ret_ident = NULL; + size_t ret_ident_num = 0; + + char *hostname = NULL; + + int status; + size_t i; + + status = lcc_listval (connection, &ret_ident, &ret_ident_num); + if (status != 0) { + printf ("UNKNOWN: %s\n", lcc_strerror (connection)); + if (ret_ident != NULL) + free (ret_ident); + return (RET_UNKNOWN); + } + + status = lcc_sort_identifiers (connection, ret_ident, ret_ident_num); + if (status != 0) { + printf ("UNKNOWN: %s\n", lcc_strerror (connection)); + if (ret_ident != NULL) + free (ret_ident); + return (RET_UNKNOWN); + } + + for (i = 0; i < ret_ident_num; ++i) { + char id[1024]; + + if ((hostname_g != NULL) && (strcasecmp (hostname_g, ret_ident[i].host))) + continue; + + if ((hostname == NULL) || strcasecmp (hostname, ret_ident[i].host)) + { + if (hostname != NULL) + free (hostname); + hostname = strdup (ret_ident[i].host); + printf ("Host: %s\n", hostname); + } + + /* empty hostname; not to be printed again */ + ret_ident[i].host[0] = '\0'; + + status = lcc_identifier_to_string (connection, + id, sizeof (id), ret_ident + i); + if (status != 0) { + printf ("ERROR: listval: Failed to convert returned " + "identifier to a string: %s\n", + lcc_strerror (connection)); + continue; + } + + /* skip over the (empty) hostname and following '/' */ + printf ("\t%s\n", id + 1); + } + + if (ret_ident != NULL) + free (ret_ident); + return (RET_OKAY); +} /* int do_listval */ + static int do_check_con_none (size_t values_num, double *values, char **values_names) { @@ -508,34 +569,20 @@ static int do_check_con_percentage (size_t values_num, return (status_code); } /* int do_check_con_percentage */ -static int do_check (void) +static int do_check (lcc_connection_t *connection) { - lcc_connection_t *connection; gauge_t *values; char **values_names; size_t values_num; - char address[1024]; char ident_str[1024]; lcc_identifier_t ident; size_t i; int status; - snprintf (address, sizeof (address), "unix:%s", socket_file_g); - address[sizeof (address) - 1] = 0; - snprintf (ident_str, sizeof (ident_str), "%s/%s", hostname_g, value_string_g); ident_str[sizeof (ident_str) - 1] = 0; - connection = NULL; - status = lcc_connect (address, &connection); - if (status != 0) - { - printf ("ERROR: Connecting to daemon at %s failed.\n", - socket_file_g); - return (RET_CRITICAL); - } - memset (&ident, 0, sizeof (ident)); status = lcc_string_to_identifier (connection, &ident, ident_str); if (status != 0) @@ -583,6 +630,11 @@ static int do_check (void) int main (int argc, char **argv) { + char address[1024]; + lcc_connection_t *connection; + + int status; + range_critical_g.min = NAN; range_critical_g.max = NAN; range_critical_g.invert = 0; @@ -664,11 +716,26 @@ int main (int argc, char **argv) } if ((socket_file_g == NULL) || (value_string_g == NULL) - || (hostname_g == NULL)) + || ((hostname_g == NULL) && (strcasecmp (value_string_g, "LIST")))) { fprintf (stderr, "Missing required arguments.\n"); usage (argv[0]); } - return (do_check ()); + snprintf (address, sizeof (address), "unix:%s", socket_file_g); + address[sizeof (address) - 1] = 0; + + connection = NULL; + status = lcc_connect (address, &connection); + if (status != 0) + { + printf ("ERROR: Connecting to daemon at %s failed.\n", + socket_file_g); + return (RET_CRITICAL); + } + + if (0 == strcasecmp (value_string_g, "LIST")) + return (do_listval (connection)); + + return (do_check (connection)); } /* int main */ diff --git a/src/collectd-threshold.pod b/src/collectd-threshold.pod index 5d1a645c..02e41b8b 100644 --- a/src/collectd-threshold.pod +++ b/src/collectd-threshold.pod @@ -154,6 +154,13 @@ This applies to missing values, too: If set to B a notification about a missing value is generated once every B seconds. If set to B only one such notification is generated until the value appears again. +=item B B|B + +Sets how OKAY notifications act. If set to B one notification will be +generated for each value that is in the acceptable range. If set to B +(the default) then a notification is only generated if a value is in range but +the previous value was not. + =item B B|B If set to B, the minimum and maximum values given are interpreted as diff --git a/src/collectd.conf.in b/src/collectd.conf.in index cd65fd27..f3ef6759 100644 --- a/src/collectd.conf.in +++ b/src/collectd.conf.in @@ -73,6 +73,7 @@ #@BUILD_PLUGIN_DNS_TRUE@LoadPlugin dns #@BUILD_PLUGIN_EMAIL_TRUE@LoadPlugin email #@BUILD_PLUGIN_ENTROPY_TRUE@LoadPlugin entropy +#@BUILD_PLUGIN_ETHSTAT_TRUE@LoadPlugin ethstat #@BUILD_PLUGIN_EXEC_TRUE@LoadPlugin exec #@BUILD_PLUGIN_FILECOUNT_TRUE@LoadPlugin filecount #@BUILD_PLUGIN_FSCACHE_TRUE@LoadPlugin fscache @@ -89,6 +90,7 @@ #@BUILD_PLUGIN_LPAR_TRUE@LoadPlugin lpar #@BUILD_PLUGIN_MADWIFI_TRUE@LoadPlugin madwifi #@BUILD_PLUGIN_MBMON_TRUE@LoadPlugin mbmon +#@BUILD_PLUGIN_MD_TRUE@LoadPlugin md #@BUILD_PLUGIN_MEMCACHEC_TRUE@LoadPlugin memcachec #@BUILD_PLUGIN_MEMCACHED_TRUE@LoadPlugin memcached @BUILD_PLUGIN_MEMORY_TRUE@@BUILD_PLUGIN_MEMORY_TRUE@LoadPlugin memory @@ -103,6 +105,7 @@ #@BUILD_PLUGIN_NOTIFY_DESKTOP_TRUE@LoadPlugin notify_desktop #@BUILD_PLUGIN_NOTIFY_EMAIL_TRUE@LoadPlugin notify_email #@BUILD_PLUGIN_NTPD_TRUE@LoadPlugin ntpd +#@BUILD_PLUGIN_NUMA_TRUE@LoadPlugin numa #@BUILD_PLUGIN_NUT_TRUE@LoadPlugin nut #@BUILD_PLUGIN_OLSRD_TRUE@LoadPlugin olsrd #@BUILD_PLUGIN_ONEWIRE_TRUE@LoadPlugin onewire @@ -144,8 +147,10 @@ #@BUILD_PLUGIN_VMEM_TRUE@LoadPlugin vmem #@BUILD_PLUGIN_VSERVER_TRUE@LoadPlugin vserver #@BUILD_PLUGIN_WIRELESS_TRUE@LoadPlugin wireless +#@BUILD_PLUGIN_WRITE_GRAPHITE_TRUE@LoadPlugin write_graphite #@BUILD_PLUGIN_WRITE_HTTP_TRUE@LoadPlugin write_http #@BUILD_PLUGIN_WRITE_REDIS_TRUE@LoadPlugin write_redis +#@BUILD_PLUGIN_WRITE_MONGODB_TRUE@LoadPlugin write_mongodb #@BUILD_PLUGIN_XMMS_TRUE@LoadPlugin xmms #@BUILD_PLUGIN_ZFS_ARC_TRUE@LoadPlugin zfs_arc @@ -193,6 +198,7 @@ # # URL "http://localhost:8053/" +# ParseTime false # OpCodes true # QTypes true # @@ -330,6 +336,13 @@ # MaxConns 5 # +# +# Interface "eth0" +# Map "rx_csum_offload_errors" "if_rx_errors" "checksum_offload" +# Map "multicast" "if_multicast" +# MappedOnly false +# + # # Exec "user:group" "/path/to/exec" # NotificationExec "user:group" "/path/to/exec" @@ -432,6 +445,11 @@ # Port "411" # +# +# Device "/dev/md0" +# IgnoreSelected false +# + # # # Server "localhost" @@ -798,6 +816,7 @@ # # +# SensorConfigFile "/etc/sensors.conf" # Sensor "it8712-isa-0290/temperature-temp1" # Sensor "it8712-isa-0290/fanspeed-fan3" # Sensor "it8712-isa-0290/voltage-in8" @@ -846,6 +865,10 @@ # # +# +# ReportByDevice false +# + # # # Instance "slabinfo" @@ -948,6 +971,18 @@ # Verbose false # +# +# +# Host "localhost" +# Port "2003" +# Prefix "collectd" +# Postfix "collectd" +# StoreRates false +# AlwaysAppendDS false +# EscapeCharacter "_" +# +# + # # # User "collectd" @@ -968,6 +1003,15 @@ # # +# +# +# Host "localhost" +# Port "27017" +# Timeout 1000 +# StoreRates false +# +# + ############################################################################## # Filter configuration # #----------------------------------------------------------------------------# diff --git a/src/collectd.conf.pod b/src/collectd.conf.pod index bee566cd..c025f949 100644 --- a/src/collectd.conf.pod +++ b/src/collectd.conf.pod @@ -493,6 +493,7 @@ Synopsis: URL "http://localhost:8053/" + ParseTime false OpCodes true QTypes true @@ -519,35 +520,44 @@ The bind plugin accepts the following configuration options: URL from which to retrieve the XML data. If not specified, C will be used. -=item B I|I +=item B B|B + +When set to B, the time provided by BIND will be parsed and used to +dispatch the values. When set to B, the local time source is queried. + +This setting is set to B by default for backwards compatibility; setting +this to B is I to avoid problems with timezones and +localization. + +=item B B|B When enabled, statistics about the I<"OpCodes">, for example the number of C packets, are collected. Default: Enabled. -=item B I|I +=item B B|B When enabled, the number of I queries by query types (for example C, C, C) is collected. Default: Enabled. -=item B I|I +=item B B|B Collect global server statistics, such as requests received over IPv4 and IPv6, successful queries, and failed updates. Default: Enabled. -=item B I|I +=item B B|B Collect zone maintenance statistics, mostly information about notifications (zone updates) and zone transfers. Default: Enabled. -=item B I|I +=item B B|B Collect resolver statistics, i.Ee. statistics about outgoing requests (e.Eg. queries over IPv4, lame servers). Since the global resolver @@ -576,21 +586,21 @@ configured, no detailed view statistics will be collected. =over 4 -=item B I|I +=item B B|B If enabled, the number of I queries by query type (e.Eg. C, C) is collected. Default: Enabled. -=item B I|I +=item B B|B Collect resolver statistics, i.Ee. statistics about outgoing requests (e.Eg. queries over IPv4, lame servers). Default: Enabled. -=item B I|I +=item B B|B If enabled, the number of entries (I<"RR sets">) in the view's cache by query type is collected. Negative entries (queries which resulted in an error, for @@ -1272,6 +1282,41 @@ at most B<16384> to prevent typos and dumb mistakes. =back +=head2 Plugin C + +The I collects information about network interface cards (NICs) +by talking directly with the underlying kernel driver using L. + +B + + + Interface "eth0" + Map "rx_csum_offload_errors" "if_rx_errors" "checksum_offload" + Map "multicast" "if_multicast" + + +B + +=over 4 + +=item B I + +Collect statistical information about interface I. + +=item B I I [I] + +By default, the plugin will submit values as type C and I set to I, the name of the metric as reported by the driver. If +an appropriate B option exists, the given I and, optionally, +I will be used. + +=item B B|B + +When set to B, only metrics that can be mapped to to a I will be +collected, all other metrics will be ignored. Defaults to B. + +=back + =head2 Plugin C Please make sure to read L before using this plugin. It @@ -1822,6 +1867,31 @@ TCP-Port to connect to. Defaults to B<411>. =back +=head2 Plugin C + +The C collects information from Linux Software-RAID devices (md). + +All reported values are of the type C. Reported type instances are +I, I (present but not operational), I (hot stand-by) and +I (physically absent) disks. + +=over 4 + +=item B I + +Select md devices based on device name. The I is the basename of +the device, i.e. the name of the block device without the leading C. +See B for more details. + +=item B B|B + +Invert device selection: If set to B, all md devices B those +listed using B are collected. If B (the default), only those +listed are collected. If no configuration is given, the B plugin will +collect data from all md devices. + +=back + =head2 Plugin C The C connects to a memcached server, queries one or more @@ -1943,11 +2013,11 @@ Configures the base register to read from the device. If the option B has been set to B or B, this and the next register will be read (the register number is increased by one). -=item B B|B|B +=item B B|B|B|B|B -Specifies what kind of data is returned by the device. If the type is B -or B, two 16Ebit registers will be read and the data is combined -into one value. Defaults to B. +Specifies what kind of data is returned by the device. If the type is B, +B or B, two 16Ebit registers will be read and the data is +combined into one value. Defaults to B. =item B I @@ -4178,6 +4248,11 @@ L. =over 4 +=item B I + +Read the I configuration from I. When unset (recommended), +the library's default will be used. + =item B I Selects the name of the sensor which you want to collect or ignore, depending @@ -4206,19 +4281,19 @@ L. Please see there for details. =head2 Plugin C The I collects information about used and available swap space. On -I, the following options are available: +I and I, the following options are available: =over 4 =item B B|B -Configures how to report physical swap devices. If set to B is used (the +Configures how to report physical swap devices. If set to B (the default), the summary over all swap devices is reported only, i.e. the globally used and available space over all devices. If B is configured, the used and available space of each device will be reported separately. -This option is only available if the I can use the L -mechanism under I. +This option is only available if the I can read C +(under Linux) or use the L mechanism (under I). =back @@ -4235,6 +4310,15 @@ syslog-daemon. Please note that B is only available if collectd has been compiled with debugging support. +=item B B|B|B + +Controls which notifications should be sent to syslog. The default behaviour is +not to send any. Less severe notifications always imply logging more severe +notifications: Setting this to B means all notifications will be sent to +syslog, setting this to B will send B and B +notifications but will dismiss B notifications. Setting this option to +B will only send failures to syslog. + =back =head2 Plugin C
@@ -4785,6 +4869,115 @@ traffic (e.Eg. due to headers and retransmission). If you want to collect on-wire traffic you could, for example, use the logging facilities of iptables to feed data for the guest IPs into the iptables plugin. +=head2 Plugin C + +The C plugin writes data to I, an open-source metrics +storage and graphing project. The plugin connects to I, the data layer +of I, and sends data via the "line based" protocol (per default using +portE2003). The data will be sent in blocks of at most 1428 bytes to +minimize the number of network packets. + +Synopsis: + + + + Host "localhost" + Port "2003" + Prefix "collectd" + + + +=over 4 + +=item B I
+ +Hostname or address to connect to. Defaults to C. + +=item B I + +Service name or port number to connect to. Defaults to C<2003>. + +=item B I + +When set, I is added in front of the host name. Dots and whitespace are +I escaped in this string (see B below). + +=item B I + +When set, I is appended to the host name. Dots and whitespace are +I escaped in this string (see B below). + +=item B I + +I uses the dot (C<.>) as escape character and doesn't allow whitespace +in the identifier. The B option determines which character +dots, whitespace and control characters are replaced with. Defaults to +underscore (C<_>). + +=item B B|B + +If set to B (the default), convert counter values to rates. If set to +B counter values are stored as is, i.Ee. as an increasing integer +number. + +=item B B|B + +If set to B, the plugin instance and type instance will be in their own +path component, for example C. If set to B (the +default), the plugin and plugin instance (and likewise the type and type +instance) are put into one component, for example C. + +=item B B|B + +If set the B, append the name of the I (DS) to the "metric" +identifier. If set to B (the default), this is only done when there is +more than one DS. + +=back + +=head2 Plugin C + +The I will send values to I, a schema-less +NoSQL database. + +B + + + + Host "localhost" + Port "27017" + Timeout 1000 + StoreRates true + + + +The plugin can send values to multiple instances of I by specifying +one B block for each instance. Within the B blocks, the following +options are available: + +=over 4 + +=item B I
+ +Hostname or address to connect to. Defaults to C. + +=item B I + +Service name or port number to connect to. Defaults to C<27017>. + +=item B I + +Set the timeout for each operation on I to I milliseconds. +Setting this option to zero means no timeout, which is the default. + +=item B B|B + +If set to B (the default), convert counter values to rates. If set to +B counter values are stored as is, i.e. as an increasing integer +number. + +=back + =head2 Plugin C This output plugin submits values to an http server by POST them using the @@ -5638,7 +5831,7 @@ convert counter values to rates. Please note that these placeholders are B! -=item B B<"FATAL">|B<"WARNING">|B<"OKAY"> +=item B B<"FAILURE">|B<"WARNING">|B<"OKAY"> Sets the severity of the message. If omitted, the severity B<"WARNING"> is used. diff --git a/src/configfile.c b/src/configfile.c index 7c8347b1..4fe50cc2 100644 --- a/src/configfile.c +++ b/src/configfile.c @@ -1094,6 +1094,54 @@ int cf_util_get_port_number (const oconfig_item_t *ci) /* {{{ */ return (tmp); } /* }}} int cf_util_get_port_number */ +int cf_util_get_service (const oconfig_item_t *ci, char **ret_string) /* {{{ */ +{ + int port; + char *service; + int status; + + if (ci->values_num != 1) + { + ERROR ("cf_util_get_service: The %s option requires exactly " + "one argument.", ci->key); + return (-1); + } + + if (ci->values[0].type == OCONFIG_TYPE_STRING) + return (cf_util_get_string (ci, ret_string)); + if (ci->values[0].type != OCONFIG_TYPE_NUMBER) + { + ERROR ("cf_util_get_service: The %s option requires " + "exactly one string or numeric argument.", + ci->key); + } + + port = 0; + status = cf_util_get_int (ci, &port); + if (status != 0) + return (status); + else if ((port < 1) || (port > 65535)) + { + ERROR ("cf_util_get_service: The port number given " + "for the %s option is out of " + "range (%i).", ci->key, port); + return (-1); + } + + service = malloc (6); + if (service == NULL) + { + ERROR ("cf_util_get_service: Out of memory."); + return (-1); + } + ssnprintf (service, 6, "%i", port); + + sfree (*ret_string); + *ret_string = service; + + return (0); +} /* }}} int cf_util_get_service */ + int cf_util_get_cdtime (const oconfig_item_t *ci, cdtime_t *ret_value) /* {{{ */ { if ((ci == NULL) || (ret_value == NULL)) diff --git a/src/configfile.h b/src/configfile.h index e63a0ea0..fbeafff8 100644 --- a/src/configfile.h +++ b/src/configfile.h @@ -116,6 +116,12 @@ int cf_util_get_flag (const oconfig_item_t *ci, * failure. */ int cf_util_get_port_number (const oconfig_item_t *ci); +/* Assures that the config option is either a service name (a string) or a port + * number (an integer in the appropriate range) and returns a newly allocated + * string. If ret_string points to a non-NULL pointer, it is freed before + * assigning a new value. */ +int cf_util_get_service (const oconfig_item_t *ci, char **ret_string); + int cf_util_get_cdtime (const oconfig_item_t *ci, cdtime_t *ret_value); #endif /* defined(CONFIGFILE_H) */ diff --git a/src/ethstat.c b/src/ethstat.c new file mode 100644 index 00000000..08381a82 --- /dev/null +++ b/src/ethstat.c @@ -0,0 +1,337 @@ +/** + * collectd - src/ethstat.c + * Copyright (C) 2011 Cyril Feraudet + * Copyright (C) 2012 Florian "octo" Forster + * + * 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., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Authors: + * Cyril Feraudet + * Florian "octo" Forster + **/ + +#include "collectd.h" +#include "common.h" +#include "plugin.h" +#include "configfile.h" +#include "utils_avltree.h" +#include "utils_complain.h" + +#if HAVE_SYS_IOCTL_H +# include +#endif +#if HAVE_NET_IF_H +# include +#endif +#if HAVE_LINUX_SOCKIOS_H +# include +#endif +#if HAVE_LINUX_ETHTOOL_H +# include +#endif + +struct value_map_s +{ + char type[DATA_MAX_NAME_LEN]; + char type_instance[DATA_MAX_NAME_LEN]; +}; +typedef struct value_map_s value_map_t; + +static char **interfaces = NULL; +static size_t interfaces_num = 0; + +static c_avl_tree_t *value_map = NULL; + +static _Bool collect_mapped_only = 0; + +static int ethstat_add_interface (const oconfig_item_t *ci) /* {{{ */ +{ + char **tmp; + int status; + + tmp = realloc (interfaces, + sizeof (*interfaces) * (interfaces_num + 1)); + if (tmp == NULL) + return (-1); + interfaces = tmp; + interfaces[interfaces_num] = NULL; + + status = cf_util_get_string (ci, interfaces + interfaces_num); + if (status != 0) + return (status); + + interfaces_num++; + INFO("ethstat plugin: Registred interface %s", + interfaces[interfaces_num - 1]); + + return (0); +} /* }}} int ethstat_add_interface */ + +static int ethstat_add_map (const oconfig_item_t *ci) /* {{{ */ +{ + value_map_t *map; + int status; + + if ((ci->values_num < 2) + || (ci->values_num > 3) + || (ci->values[0].type != OCONFIG_TYPE_STRING) + || (ci->values[1].type != OCONFIG_TYPE_STRING) + || ((ci->values_num == 3) + && (ci->values[2].type != OCONFIG_TYPE_STRING))) + { + ERROR ("ethstat plugin: The %s option requires " + "two or three string arguments.", ci->key); + return (-1); + } + + map = malloc (sizeof (*map)); + if (map == NULL) + { + ERROR ("ethstat plugin: malloc(3) failed."); + return (ENOMEM); + } + memset (map, 0, sizeof (*map)); + + sstrncpy (map->type, ci->values[1].value.string, sizeof (map->type)); + if (ci->values_num == 3) + sstrncpy (map->type_instance, ci->values[2].value.string, + sizeof (map->type_instance)); + + if (value_map == NULL) + { + value_map = c_avl_create ((void *) strcmp); + if (value_map == NULL) + { + sfree (map); + ERROR ("ethstat plugin: c_avl_create() failed."); + return (-1); + } + } + + status = c_avl_insert (value_map, + /* key = */ ci->values[0].value.string, + /* value = */ map); + if (status != 0) + { + sfree (map); + if (status > 0) + ERROR ("ethstat plugin: Multiple mappings for \"%s\".", + ci->values[0].value.string); + else + ERROR ("ethstat plugin: c_avl_insert(\"%s\") failed.", + ci->values[0].value.string); + return (-1); + } + + return (0); +} /* }}} int ethstat_add_map */ + +static int ethstat_config (oconfig_item_t *ci) /* {{{ */ +{ + int i; + + for (i = 0; i < ci->children_num; i++) + { + oconfig_item_t *child = ci->children + i; + + if (strcasecmp ("Interface", child->key) == 0) + ethstat_add_interface (child); + else if (strcasecmp ("Map", child->key) == 0) + ethstat_add_map (child); + else if (strcasecmp ("MappedOnly", child->key) == 0) + (void) cf_util_get_boolean (child, &collect_mapped_only); + else + WARNING ("ethstat plugin: The config option \"%s\" is unknown.", + child->key); + } + + return (0); +} /* }}} */ + +static void ethstat_submit_value (const char *device, + const char *type_instance, derive_t value) +{ + static c_complain_t complain_no_map = C_COMPLAIN_INIT_STATIC; + + value_t values[1]; + value_list_t vl = VALUE_LIST_INIT; + value_map_t *map = NULL; + + if (value_map != NULL) + c_avl_get (value_map, type_instance, (void *) &map); + + /* If the "MappedOnly" option is specified, ignore unmapped values. */ + if (collect_mapped_only && (map == NULL)) + { + if (value_map == NULL) + c_complain (LOG_WARNING, &complain_no_map, + "ethstat plugin: The \"MappedOnly\" option has been set to true, " + "but no mapping has been configured. All values will be ignored!"); + return; + } + + values[0].derive = value; + vl.values = values; + vl.values_len = 1; + + sstrncpy (vl.host, hostname_g, sizeof (vl.host)); + sstrncpy (vl.plugin, "ethstat", sizeof (vl.plugin)); + sstrncpy (vl.plugin_instance, device, sizeof (vl.plugin_instance)); + if (map != NULL) + { + sstrncpy (vl.type, map->type, sizeof (vl.type)); + sstrncpy (vl.type_instance, map->type_instance, + sizeof (vl.type_instance)); + } + else + { + sstrncpy (vl.type, "derive", sizeof (vl.type)); + sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); + } + + plugin_dispatch_values (&vl); +} + +static int ethstat_read_interface (char *device) +{ + int fd; + struct ifreq req; + struct ethtool_drvinfo drvinfo; + struct ethtool_gstrings *strings; + struct ethtool_stats *stats; + size_t n_stats; + size_t strings_size; + size_t stats_size; + size_t i; + int status; + + memset (&req, 0, sizeof (req)); + sstrncpy(req.ifr_name, device, sizeof (req.ifr_name)); + + fd = socket(AF_INET, SOCK_DGRAM, /* protocol = */ 0); + if (fd < 0) + { + char errbuf[1024]; + ERROR("ethstat plugin: Failed to open control socket: %s", + sstrerror (errno, errbuf, sizeof (errbuf))); + return 1; + } + + memset (&drvinfo, 0, sizeof (drvinfo)); + drvinfo.cmd = ETHTOOL_GDRVINFO; + req.ifr_data = (void *) &drvinfo; + status = ioctl (fd, SIOCETHTOOL, &req); + if (status < 0) + { + char errbuf[1024]; + close (fd); + ERROR ("ethstat plugin: Failed to get driver information " + "from %s: %s", device, + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + + n_stats = (size_t) drvinfo.n_stats; + if (n_stats < 1) + { + close (fd); + ERROR("ethstat plugin: No stats available for %s", device); + return (-1); + } + + strings_size = sizeof (struct ethtool_gstrings) + + (n_stats * ETH_GSTRING_LEN); + stats_size = sizeof (struct ethtool_stats) + + (n_stats * sizeof (uint64_t)); + + strings = malloc (strings_size); + stats = malloc (stats_size); + if ((strings == NULL) || (stats == NULL)) + { + close (fd); + sfree (strings); + sfree (stats); + ERROR("ethstat plugin: malloc(3) failed."); + return (-1); + } + + strings->cmd = ETHTOOL_GSTRINGS; + strings->string_set = ETH_SS_STATS; + strings->len = n_stats; + req.ifr_data = (void *) strings; + status = ioctl (fd, SIOCETHTOOL, &req); + if (status < 0) + { + char errbuf[1024]; + close (fd); + free (strings); + free (stats); + ERROR ("ethstat plugin: Cannot get strings from %s: %s", + device, + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + + stats->cmd = ETHTOOL_GSTATS; + stats->n_stats = n_stats; + req.ifr_data = (void *) stats; + status = ioctl (fd, SIOCETHTOOL, &req); + if (status < 0) + { + char errbuf[1024]; + close (fd); + free(strings); + free(stats); + ERROR("ethstat plugin: Reading statistics from %s failed: %s", + device, + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + + for (i = 0; i < n_stats; i++) + { + const char *stat_name; + + stat_name = (void *) &strings->data[i * ETH_GSTRING_LEN]; + DEBUG("ethstat plugin: device = \"%s\": %s = %"PRIu64, + device, stat_name, (uint64_t) stats->data[i]); + ethstat_submit_value (device, + stat_name, (derive_t) stats->data[i]); + } + + close (fd); + sfree (strings); + sfree (stats); + + return (0); +} /* }}} ethstat_read_interface */ + +static int ethstat_read(void) +{ + size_t i; + + for (i = 0; i < interfaces_num; i++) + ethstat_read_interface (interfaces[i]); + + return 0; +} + +void module_register (void) +{ + plugin_register_complex_config ("ethstat", ethstat_config); + plugin_register_read ("ethstat", ethstat_read); +} + +/* vim: set sw=2 sts=2 et fdm=marker : */ diff --git a/src/iptables.c b/src/iptables.c index c39aff8f..49454f05 100644 --- a/src/iptables.c +++ b/src/iptables.c @@ -31,16 +31,8 @@ #include -#if OWN_LIBIPTC -# include "owniptc/libiptc.h" -# include "owniptc/libip6tc.h" - -# define HAVE_IPTC_HANDLE_T 1 -# define HAVE_IP6TC_HANDLE_T 1 - -#else /* if !OWN_LIBIPTC */ -# include -# include +#include +#include /* * iptc_handle_t was available before libiptc was officially available as a @@ -54,13 +46,12 @@ * this is somewhat hacky, I didn't find better way to solve that :-/ * -tokkee */ -# ifndef HAVE_IPTC_HANDLE_T +#ifndef HAVE_IPTC_HANDLE_T typedef struct iptc_handle iptc_handle_t; -# endif -# ifndef HAVE_IP6TC_HANDLE_T +#endif +#ifndef HAVE_IP6TC_HANDLE_T typedef struct ip6tc_handle ip6tc_handle_t; -# endif -#endif /* !OWN_LIBIPTC */ +#endif /* * (Module-)Global variables diff --git a/src/irq.c b/src/irq.c index 7e738291..1168b979 100644 --- a/src/irq.c +++ b/src/irq.c @@ -1,6 +1,7 @@ /** * collectd - src/irq.c * Copyright (C) 2007 Peter Holik + * Copyright (C) 2011 Florian Forster * * 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 @@ -24,6 +25,7 @@ #include "common.h" #include "plugin.h" #include "configfile.h" +#include "utils_ignorelist.h" #if !KERNEL_LINUX # error "No applicable input method." @@ -39,71 +41,33 @@ static const char *config_keys[] = }; static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); -static char **irq_list; -static unsigned int irq_list_num = 0; +static ignorelist_t *ignorelist = NULL; -/* - * irq_list_action: - * 0 => default is to collect selected irqs - * 1 => ignore selcted irqs +/* + * Private functions */ -static int irq_list_action; - static int irq_config (const char *key, const char *value) { + if (ignorelist == NULL) + ignorelist = ignorelist_create (/* invert = */ 1); + if (strcasecmp (key, "Irq") == 0) { - char **temp; - - temp = realloc (irq_list, (irq_list_num + 1) * sizeof (*irq_list)); - if (temp == NULL) - { - fprintf (stderr, "irq plugin: Cannot allocate more memory.\n"); - ERROR ("irq plugin: Cannot allocate more memory."); - return (1); - } - irq_list = temp; - - irq_list[irq_list_num] = strdup (value); - if (irq_list[irq_list_num] == NULL) - { - ERROR ("irq plugin: strdup(3) failed."); - return (1); - } - - irq_list_num++; + ignorelist_add (ignorelist, value); } else if (strcasecmp (key, "IgnoreSelected") == 0) { + int invert = 1; if (IS_TRUE (value)) - irq_list_action = 1; - else - irq_list_action = 0; + invert = 0; + ignorelist_set_invert (ignorelist, invert); } else { return (-1); } - return (0); -} - -/* - * Check if this interface/instance should be ignored. This is called from - * both, `submit' and `write' to give client and server the ability to - * ignore certain stuff.. - */ -static int check_ignore_irq (const char *irq) -{ - unsigned int i; - - if (irq_list_num < 1) - return (0); - for (i = 0; i < irq_list_num; i++) - if (strcmp (irq, irq_list[i]) == 0) - return (irq_list_action); - - return (1 - irq_list_action); + return (0); } static void irq_submit (const char *irq_name, derive_t value) @@ -111,7 +75,7 @@ static void irq_submit (const char *irq_name, derive_t value) value_t values[1]; value_list_t vl = VALUE_LIST_INIT; - if (check_ignore_irq (irq_name)) + if (ignorelist_match (ignorelist, irq_name) != 0) return; values[0].derive = value; @@ -130,7 +94,16 @@ static int irq_read (void) { FILE *fh; char buffer[1024]; - + int cpu_count; + char *fields[256]; + + /* + * Example content: + * CPU0 CPU1 CPU2 CPU3 + * 0: 2574 1 3 2 IO-APIC-edge timer + * 1: 102553 158669 218062 70587 IO-APIC-edge i8042 + * 8: 0 0 0 1 IO-APIC-edge rtc0 + */ fh = fopen ("/proc/interrupts", "r"); if (fh == NULL) { @@ -140,20 +113,38 @@ static int irq_read (void) return (-1); } + /* Get CPU count from the first line */ + if(fgets (buffer, sizeof (buffer), fh) != NULL) { + cpu_count = strsplit (buffer, fields, + STATIC_ARRAY_SIZE (fields)); + } else { + ERROR ("irq plugin: unable to get CPU count from first line " + "of /proc/interrupts"); + return (-1); + } + while (fgets (buffer, sizeof (buffer), fh) != NULL) { char *irq_name; size_t irq_name_len; derive_t irq_value; int i; - - char *fields[64]; int fields_num; + int irq_values_to_parse; - fields_num = strsplit (buffer, fields, 64); + fields_num = strsplit (buffer, fields, + STATIC_ARRAY_SIZE (fields)); if (fields_num < 2) continue; + /* Parse this many numeric fields, skip the rest + * (+1 because first there is a name of irq in each line) */ + if (fields_num >= cpu_count + 1) + irq_values_to_parse = cpu_count; + else + irq_values_to_parse = fields_num - 1; + + /* First field is irq name and colon */ irq_name = fields[0]; irq_name_len = strlen (irq_name); if (irq_name_len < 2) @@ -168,7 +159,7 @@ static int irq_read (void) irq_name_len--; irq_value = 0; - for (i = 1; i < fields_num; i++) + for (i = 1; i <= irq_values_to_parse; i++) { /* Per-CPU value */ value_t v; diff --git a/src/libcollectdclient/client.c b/src/libcollectdclient/client.c index f5fe2049..2adf6d48 100644 --- a/src/libcollectdclient/client.c +++ b/src/libcollectdclient/client.c @@ -228,6 +228,53 @@ static void lcc_chomp (char *str) /* {{{ */ } } /* }}} void lcc_chomp */ +static int lcc_identifier_cmp (const void *a, const void *b) +{ + const lcc_identifier_t *ident_a, *ident_b; + + int status; + + ident_a = a; + ident_b = b; + + status = strcasecmp (ident_a->host, ident_b->host); + if (status != 0) + return (status); + + status = strcmp (ident_a->plugin, ident_b->plugin); + if (status != 0) + return (status); + + if ((*ident_a->plugin_instance != '\0') || (*ident_b->plugin_instance != '\0')) + { + if (*ident_a->plugin_instance == '\0') + return (-1); + else if (*ident_b->plugin_instance == '\0') + return (1); + + status = strcmp (ident_a->plugin_instance, ident_b->plugin_instance); + if (status != 0) + return (status); + } + + status = strcmp (ident_a->type, ident_b->type); + if (status != 0) + return (status); + + if ((*ident_a->type_instance != '\0') || (*ident_b->type_instance != '\0')) + { + if (*ident_a->type_instance == '\0') + return (-1); + else if (*ident_b->type_instance == '\0') + return (1); + + status = strcmp (ident_a->type_instance, ident_b->type_instance); + if (status != 0) + return (status); + } + return (0); +} /* }}} int lcc_identifier_cmp */ + static void lcc_response_free (lcc_response_t *res) /* {{{ */ { size_t i; @@ -1058,4 +1105,17 @@ int lcc_string_to_identifier (lcc_connection_t *c, /* {{{ */ return (0); } /* }}} int lcc_string_to_identifier */ +int lcc_sort_identifiers (lcc_connection_t *c, /* {{{ */ + lcc_identifier_t *idents, size_t idents_num) +{ + if (idents == NULL) + { + lcc_set_errno (c, EINVAL); + return (-1); + } + + qsort (idents, idents_num, sizeof (*idents), lcc_identifier_cmp); + return (0); +} /* }}} int lcc_sort_identifiers */ + /* vim: set sw=2 sts=2 et fdm=marker : */ diff --git a/src/libcollectdclient/client.h b/src/libcollectdclient/client.h index 99003538..36b1d4d2 100644 --- a/src/libcollectdclient/client.h +++ b/src/libcollectdclient/client.h @@ -116,6 +116,9 @@ int lcc_identifier_to_string (lcc_connection_t *c, int lcc_string_to_identifier (lcc_connection_t *c, lcc_identifier_t *ident, const char *string); +int lcc_sort_identifiers (lcc_connection_t *c, + lcc_identifier_t *idents, size_t idents_num); + LCC_END_DECLS /* vim: set sw=2 sts=2 et : */ diff --git a/src/logfile.c b/src/logfile.c index 60fb5d92..ded7732b 100644 --- a/src/logfile.c +++ b/src/logfile.c @@ -53,23 +53,8 @@ static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); static int logfile_config (const char *key, const char *value) { if (0 == strcasecmp (key, "LogLevel")) { - if ((0 == strcasecmp (value, "emerg")) - || (0 == strcasecmp (value, "alert")) - || (0 == strcasecmp (value, "crit")) - || (0 == strcasecmp (value, "err"))) - log_level = LOG_ERR; - else if (0 == strcasecmp (value, "warning")) - log_level = LOG_WARNING; - else if (0 == strcasecmp (value, "notice")) - log_level = LOG_NOTICE; - else if (0 == strcasecmp (value, "info")) - log_level = LOG_INFO; -#if COLLECT_DEBUG - else if (0 == strcasecmp (value, "debug")) - log_level = LOG_DEBUG; -#endif /* COLLECT_DEBUG */ - else - return 1; + log_level = parse_log_severity(value); + if (log_level == -1) return 1; /* to keep previous behaviour */ } else if (0 == strcasecmp (key, "File")) { sfree (log_file); diff --git a/src/md.c b/src/md.c new file mode 100644 index 00000000..3725f9a9 --- /dev/null +++ b/src/md.c @@ -0,0 +1,218 @@ +/** + * collectd - src/md.c + * Copyright (C) 2010,2011 Michael Hanselmann + * + * 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; only version 2 of the License is applicable. + * + * 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., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Michael Hanselmann + **/ + +#include "collectd.h" +#include "common.h" +#include "plugin.h" +#include "utils_ignorelist.h" + +#include + +#include +#include + +#define PROC_DISKSTATS "/proc/diskstats" +#define DEV_DIR "/dev" + +static const char *config_keys[] = +{ + "Device", + "IgnoreSelected" +}; +static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); + +static ignorelist_t *ignorelist = NULL; + +static int md_config (const char *key, const char *value) +{ + if (ignorelist == NULL) + ignorelist = ignorelist_create (/* invert = */ 1); + if (ignorelist == NULL) + return (1); + + if (strcasecmp (key, "Device") == 0) + { + ignorelist_add (ignorelist, value); + } + else if (strcasecmp (key, "IgnoreSelected") == 0) + { + ignorelist_set_invert (ignorelist, IS_TRUE (value) ? 0 : 1); + } + else + { + return (-1); + } + + return (0); +} + +static void md_submit (const int minor, const char *type_instance, + gauge_t value) +{ + value_t values[1]; + value_list_t vl = VALUE_LIST_INIT; + + values[0].gauge = value; + + vl.values = values; + vl.values_len = 1; + sstrncpy (vl.host, hostname_g, sizeof (vl.host)); + sstrncpy (vl.plugin, "md", sizeof (vl.plugin)); + ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance), + "%i", minor); + sstrncpy (vl.type, "md_disks", sizeof (vl.type)); + sstrncpy (vl.type_instance, type_instance, + sizeof (vl.type_instance)); + + plugin_dispatch_values (&vl); +} /* void md_submit */ + +static void md_process (const int minor, const char *path) +{ + char errbuf[1024]; + int fd; + struct stat st; + mdu_array_info_t array; + gauge_t disks_missing; + + fd = open (path, O_RDONLY); + if (fd < 0) + { + WARNING ("md: open(%s): %s", path, + sstrerror (errno, errbuf, sizeof (errbuf))); + return; + } + + if (fstat (fd, &st) < 0) + { + WARNING ("md: Unable to fstat file descriptor for %s: %s", path, + sstrerror (errno, errbuf, sizeof (errbuf))); + close (fd); + return; + } + + if (! S_ISBLK (st.st_mode)) + { + WARNING ("md: %s is no block device", path); + close (fd); + return; + } + + if (st.st_rdev != makedev (MD_MAJOR, minor)) + { + WARNING ("md: Major/minor of %s are %i:%i, should be %i:%i", + path, (int)major(st.st_rdev), (int)minor(st.st_rdev), + (int)MD_MAJOR, minor); + close (fd); + return; + } + + /* Retrieve md information */ + if (ioctl (fd, GET_ARRAY_INFO, &array) < 0) { + WARNING ("md: Unable to retrieve array info from %s: %s", path, + sstrerror (errno, errbuf, sizeof (errbuf))); + close (fd); + return; + } + + close (fd); + + /* + * The mdu_array_info_t structure contains numbers of disks in the array. + * However, disks are accounted for more than once: + * + * active: Number of active (in sync) disks. + * spare: Number of stand-by disks. + * working: Number of working disks. (active + sync) + * failed: Number of failed disks. + * nr: Number of physically present disks. (working + failed) + * raid: Number of disks in the RAID. This may be larger than "nr" if + * disks are missing and smaller than "nr" when spare disks are + * around. + */ + md_submit (minor, "active", (gauge_t) array.active_disks); + md_submit (minor, "failed", (gauge_t) array.failed_disks); + md_submit (minor, "spare", (gauge_t) array.spare_disks); + + disks_missing = 0.0; + if (array.raid_disks > array.nr_disks) + disks_missing = (gauge_t) (array.raid_disks - array.nr_disks); + md_submit (minor, "missing", disks_missing); +} /* void md_process */ + +static int md_read (void) +{ + FILE *fh; + char buffer[1024]; + + fh = fopen (PROC_DISKSTATS, "r"); + if (fh == NULL) { + char errbuf[1024]; + WARNING ("md: Unable to open %s: %s", + PROC_DISKSTATS , + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + + /* Iterate md devices */ + while (fgets (buffer, sizeof (buffer), fh) != NULL) + { + char path[PATH_MAX]; + char *fields[4]; + char *name; + int major, minor; + + /* Extract interesting fields */ + if (strsplit (buffer, fields, STATIC_ARRAY_SIZE(fields)) < 3) + continue; + + major = atoi (fields[0]); + + if (major != MD_MAJOR) + continue; + + minor = atoi (fields[1]); + name = fields[2]; + + if (ignorelist_match (ignorelist, name)) + continue; + + /* FIXME: Don't hardcode path. Walk /dev collecting major, + * minor and name, then use lookup table to find device. + * Alternatively create a temporary device file with correct + * major/minor, but that again can be tricky if the filesystem + * with the device file is mounted using the "nodev" option. + */ + ssnprintf (path, sizeof (path), "%s/%s", DEV_DIR, name); + + md_process (minor, path); + } + + fclose (fh); + + return (0); +} /* int md_read */ + +void module_register (void) +{ + plugin_register_config ("md", md_config, config_keys, config_keys_num); + plugin_register_read ("md", md_read); +} /* void module_register */ diff --git a/src/modbus.c b/src/modbus.c index cad4b2cf..19848b0b 100644 --- a/src/modbus.c +++ b/src/modbus.c @@ -1,6 +1,6 @@ /** * collectd - src/modbus.c - * Copyright (C) 2010 noris network AG + * Copyright (C) 2010,2011 noris network AG * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by @@ -69,6 +69,8 @@ */ enum mb_register_type_e /* {{{ */ { + REG_TYPE_INT16, + REG_TYPE_INT32, REG_TYPE_UINT16, REG_TYPE_UINT32, REG_TYPE_FLOAT @@ -411,6 +413,7 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */ } if ((ds->ds[0].type != DS_TYPE_GAUGE) + && (data->register_type != REG_TYPE_INT32) && (data->register_type != REG_TYPE_UINT32)) { NOTICE ("Modbus plugin: The data source of type \"%s\" is %s, not gauge. " @@ -419,7 +422,8 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */ } memset (values, 0, sizeof (values)); - if ((data->register_type == REG_TYPE_UINT32) + if ((data->register_type == REG_TYPE_INT32) + || (data->register_type == REG_TYPE_UINT32) || (data->register_type == REG_TYPE_FLOAT)) values_num = 2; else @@ -502,12 +506,47 @@ static int mb_read_data (mb_host_t *host, mb_slave_t *slave, /* {{{ */ CAST_TO_VALUE_T (ds, vt, float_value); mb_submit (host, slave, data, vt); } + else if (data->register_type == REG_TYPE_INT32) + { + union + { + uint32_t u32; + int32_t i32; + } v; + value_t vt; + + v.u32 = (((uint32_t) values[0]) << 16) + | ((uint32_t) values[1]); + DEBUG ("Modbus plugin: mb_read_data: " + "Returned int32 value is %"PRIi32, v.i32); + + CAST_TO_VALUE_T (ds, vt, v.i32); + mb_submit (host, slave, data, vt); + } + else if (data->register_type == REG_TYPE_INT16) + { + union + { + uint16_t u16; + int16_t i16; + } v; + value_t vt; + + v.u16 = values[0]; + + DEBUG ("Modbus plugin: mb_read_data: " + "Returned int16 value is %"PRIi16, v.i16); + + CAST_TO_VALUE_T (ds, vt, v.i16); + mb_submit (host, slave, data, vt); + } else if (data->register_type == REG_TYPE_UINT32) { uint32_t v32; value_t vt; - v32 = (values[0] << 16) | values[1]; + v32 = (((uint32_t) values[0]) << 16) + | ((uint32_t) values[1]); DEBUG ("Modbus plugin: mb_read_data: " "Returned uint32 value is %"PRIu32, v32); @@ -663,6 +702,10 @@ static int mb_config_add_data (oconfig_item_t *ci) /* {{{ */ status = cf_util_get_string_buffer (child, tmp, sizeof (tmp)); if (status != 0) /* do nothing */; + else if (strcasecmp ("Int16", tmp) == 0) + data.register_type = REG_TYPE_INT16; + else if (strcasecmp ("Int32", tmp) == 0) + data.register_type = REG_TYPE_INT32; else if (strcasecmp ("Uint16", tmp) == 0) data.register_type = REG_TYPE_UINT16; else if (strcasecmp ("Uint32", tmp) == 0) diff --git a/src/nfs.c b/src/nfs.c index f3c636ec..461e806f 100644 --- a/src/nfs.c +++ b/src/nfs.c @@ -18,14 +18,15 @@ * Authors: * Jason Pepas * Florian octo Forster + * Cosmin Ioiart **/ #include "collectd.h" #include "common.h" #include "plugin.h" -#if !KERNEL_LINUX -# error "No applicable input method." +#if HAVE_KSTAT_H +#include #endif /* @@ -92,10 +93,9 @@ static const char *nfs2_procedures_names[] = "mkdir", "rmdir", "readdir", - "fsstat", - NULL + "fsstat" }; -static int nfs2_procedures_names_num = 18; +static size_t nfs2_procedures_names_num = STATIC_ARRAY_SIZE (nfs2_procedures_names); static const char *nfs3_procedures_names[] = { @@ -120,12 +120,57 @@ static const char *nfs3_procedures_names[] = "fsstat", "fsinfo", "pathconf", + "commit" +}; +static size_t nfs3_procedures_names_num = STATIC_ARRAY_SIZE (nfs3_procedures_names); + +#if HAVE_LIBKSTAT +static const char *nfs4_procedures_names[] = +{ + "null", + "compound", + "reserved", + "access", + "close", "commit", - NULL + "create", + "delegpurge", + "delegreturn", + "getattr", + "getfh", + "link", + "lock", + "lockt", + "locku", + "lookup", + "lookupp", + "nverify", + "open", + "openattr", + "open_confirm", + "open_downgrade", + "putfh", + "putpubfh", + "putrootfh", + "read", + "readdir", + "readlink", + "remove", + "rename", + "renew", + "restorefh", + "savefh", + "secinfo", + "setattr", + "setclientid", + "setclientid_confirm", + "verify", + "write" }; -static int nfs3_procedures_names_num = 22; +static size_t nfs4_procedures_names_num = STATIC_ARRAY_SIZE (nfs4_procedures_names); +#endif -#if HAVE_LIBKSTAT && 0 +#if HAVE_LIBKSTAT extern kstat_ctl_t *kc; static kstat_t *nfs2_ksp_client; static kstat_t *nfs2_ksp_server; @@ -137,11 +182,17 @@ static kstat_t *nfs4_ksp_server; /* Possibly TODO: NFSv4 statistics */ -#if 0 +#if KERNEL_LINUX +static int nfs_init (void) +{ + return (0); +} +/* #endif KERNEL_LINUX */ + +#elif HAVE_LIBKSTAT static int nfs_init (void) { -#if HAVE_LIBKSTAT && 0 - kstat_t *ksp_chain; + kstat_t *ksp_chain = NULL; nfs2_ksp_client = NULL; nfs2_ksp_server = NULL; @@ -149,9 +200,9 @@ static int nfs_init (void) nfs3_ksp_server = NULL; nfs4_ksp_client = NULL; nfs4_ksp_server = NULL; - + if (kc == NULL) - return; + return (-1); for (ksp_chain = kc->kc_chain; ksp_chain != NULL; ksp_chain = ksp_chain->ks_next) @@ -171,192 +222,168 @@ static int nfs_init (void) else if (strncmp (ksp_chain->ks_name, "rfsreqcnt_v4", 12) == 0) nfs4_ksp_client = ksp_chain; } -#endif return (0); } /* int nfs_init */ #endif -#define BUFSIZE 1024 static void nfs_procedures_submit (const char *plugin_instance, - unsigned long long *val, const char **names, int len) + const char **type_instances, + value_t *values, size_t values_num) { - value_t values[1]; value_list_t vl = VALUE_LIST_INIT; - int i; + size_t i; - vl.values = values; vl.values_len = 1; sstrncpy (vl.host, hostname_g, sizeof (vl.host)); sstrncpy (vl.plugin, "nfs", sizeof (vl.plugin)); sstrncpy (vl.plugin_instance, plugin_instance, - sizeof (vl.plugin_instance)); + sizeof (vl.plugin_instance)); sstrncpy (vl.type, "nfs_procedure", sizeof (vl.type)); - for (i = 0; i < len; i++) + for (i = 0; i < values_num; i++) { - values[0].derive = val[i]; - sstrncpy (vl.type_instance, names[i], + vl.values = values + i; + sstrncpy (vl.type_instance, type_instances[i], sizeof (vl.type_instance)); - DEBUG ("%s-%s/nfs_procedure-%s = %llu", - vl.plugin, vl.plugin_instance, - vl.type_instance, val[i]); - plugin_dispatch_values (&vl); + plugin_dispatch_values_secure (&vl); } } /* void nfs_procedures_submit */ -static void nfs_read_stats_file (FILE *fh, char *inst) +#if KERNEL_LINUX +static int nfs_submit_fields (int nfs_version, const char *instance, + char **fields, size_t fields_num, + const char **proc_names, size_t proc_names_num) { - char buffer[BUFSIZE]; - char plugin_instance[DATA_MAX_NAME_LEN]; + value_t values[fields_num]; + size_t i; + + if (fields_num != proc_names_num) + { + WARNING ("nfs plugin: Wrong number of fields for " + "NFSv%i %s statistics. Expected %zu, got %zu.", + nfs_version, instance, + proc_names_num, fields_num); + return (EINVAL); + } + + ssnprintf (plugin_instance, sizeof (plugin_instance), "v%i%s", + nfs_version, instance); + + for (i = 0; i < proc_names_num; i++) + (void) parse_value (fields[i], &values[i], DS_TYPE_DERIVE); + + nfs_procedures_submit (plugin_instance, proc_names, values, + proc_names_num); + + return (0); +} + +static void nfs_read_linux (FILE *fh, char *inst) +{ + char buffer[1024]; char *fields[48]; - int numfields = 0; + int fields_num = 0; if (fh == NULL) return; - while (fgets (buffer, BUFSIZE, fh) != NULL) + while (fgets (buffer, sizeof (buffer), fh) != NULL) { - numfields = strsplit (buffer, fields, 48); + fields_num = strsplit (buffer, + fields, STATIC_ARRAY_SIZE (fields)); - if (((numfields - 2) != nfs2_procedures_names_num) - && ((numfields - 2) - != nfs3_procedures_names_num)) + if (fields_num < 3) continue; if (strcmp (fields[0], "proc2") == 0) { - int i; - unsigned long long *values; - - if ((numfields - 2) != nfs2_procedures_names_num) - { - WARNING ("nfs plugin: Wrong " - "number of fields (= %i) " - "for NFSv2 statistics.", - numfields - 2); - continue; - } - - ssnprintf (plugin_instance, sizeof (plugin_instance), - "v2%s", inst); - - values = (unsigned long long *) malloc (nfs2_procedures_names_num * sizeof (unsigned long long)); - if (values == NULL) - { - char errbuf[1024]; - ERROR ("nfs plugin: malloc " - "failed: %s", - sstrerror (errno, errbuf, sizeof (errbuf))); - continue; - } - - for (i = 0; i < nfs2_procedures_names_num; i++) - values[i] = atoll (fields[i + 2]); - - nfs_procedures_submit (plugin_instance, values, + nfs_submit_fields (/* version = */ 2, inst, + fields + 2, (size_t) (fields_num - 2), nfs2_procedures_names, nfs2_procedures_names_num); - - free (values); } else if (strncmp (fields[0], "proc3", 5) == 0) { - int i; - unsigned long long *values; - - if ((numfields - 2) != nfs3_procedures_names_num) - { - WARNING ("nfs plugin: Wrong " - "number of fields (= %i) " - "for NFSv3 statistics.", - numfields - 2); - continue; - } - - ssnprintf (plugin_instance, sizeof (plugin_instance), - "v3%s", inst); - - values = (unsigned long long *) malloc (nfs3_procedures_names_num * sizeof (unsigned long long)); - if (values == NULL) - { - char errbuf[1024]; - ERROR ("nfs plugin: malloc " - "failed: %s", - sstrerror (errno, errbuf, sizeof (errbuf))); - continue; - } - - for (i = 0; i < nfs3_procedures_names_num; i++) - values[i] = atoll (fields[i + 2]); - - nfs_procedures_submit (plugin_instance, values, + nfs_submit_fields (/* version = */ 3, inst, + fields + 2, (size_t) (fields_num - 2), nfs3_procedures_names, nfs3_procedures_names_num); - - free (values); } - } /* while (fgets (buffer, BUFSIZE, fh) != NULL) */ -} /* void nfs_read_stats_file */ -#undef BUFSIZE + } /* while (fgets) */ +} /* void nfs_read_linux */ +#endif /* KERNEL_LINUX */ -#if HAVE_LIBKSTAT && 0 -static void nfs2_read_kstat (kstat_t *ksp, char *inst) +#if HAVE_LIBKSTAT +static int nfs_read_kstat (kstat_t *ksp, int nfs_version, char *inst, + const char **proc_names, size_t proc_names_num) { - unsigned long long values[18]; - - values[0] = get_kstat_value (ksp, "null"); - values[1] = get_kstat_value (ksp, "getattr"); - values[2] = get_kstat_value (ksp, "setattr"); - values[3] = get_kstat_value (ksp, "root"); - values[4] = get_kstat_value (ksp, "lookup"); - values[5] = get_kstat_value (ksp, "readlink"); - values[6] = get_kstat_value (ksp, "read"); - values[7] = get_kstat_value (ksp, "wrcache"); - values[8] = get_kstat_value (ksp, "write"); - values[9] = get_kstat_value (ksp, "create"); - values[10] = get_kstat_value (ksp, "remove"); - values[11] = get_kstat_value (ksp, "rename"); - values[12] = get_kstat_value (ksp, "link"); - values[13] = get_kstat_value (ksp, "symlink"); - values[14] = get_kstat_value (ksp, "mkdir"); - values[15] = get_kstat_value (ksp, "rmdir"); - values[16] = get_kstat_value (ksp, "readdir"); - values[17] = get_kstat_value (ksp, "statfs"); - - nfs2_procedures_submit (values, inst); + char plugin_instance[DATA_MAX_NAME_LEN]; + value_t values[proc_names_num]; + size_t i; + + if (ksp == NULL) + return (EINVAL); + + ssnprintf (plugin_instance, sizeof (plugin_instance), "v%i%s", + nfs_version, inst); + + kstat_read(kc, ksp, NULL); + for (i = 0; i < proc_names_num; i++) + values[i].counter = (derive_t) get_kstat_value (ksp, + (char *)proc_names[i]); + + nfs_procedures_submit (plugin_instance, proc_names, values, + proc_names_num); + return (0); } #endif +#if KERNEL_LINUX static int nfs_read (void) { FILE *fh; if ((fh = fopen ("/proc/net/rpc/nfs", "r")) != NULL) { - nfs_read_stats_file (fh, "client"); + nfs_read_linux (fh, "client"); fclose (fh); } if ((fh = fopen ("/proc/net/rpc/nfsd", "r")) != NULL) { - nfs_read_stats_file (fh, "server"); + nfs_read_linux (fh, "server"); fclose (fh); } -#if HAVE_LIBKSTAT && 0 - if (nfs2_ksp_client != NULL) - nfs2_read_kstat (nfs2_ksp_client, "client"); - if (nfs2_ksp_server != NULL) - nfs2_read_kstat (nfs2_ksp_server, "server"); -#endif /* defined(HAVE_LIBKSTAT) */ + return (0); +} +/* #endif KERNEL_LINUX */ + +#elif HAVE_LIBKSTAT +static int nfs_read (void) +{ + nfs_read_kstat (nfs2_ksp_client, /* version = */ 2, "client", + nfs2_procedures_names, nfs2_procedures_names_num); + nfs_read_kstat (nfs2_ksp_server, /* version = */ 2, "server", + nfs2_procedures_names, nfs2_procedures_names_num); + nfs_read_kstat (nfs3_ksp_client, /* version = */ 3, "client", + nfs3_procedures_names, nfs3_procedures_names_num); + nfs_read_kstat (nfs3_ksp_server, /* version = */ 3, "server", + nfs3_procedures_names, nfs3_procedures_names_num); + nfs_read_kstat (nfs4_ksp_client, /* version = */ 4, "client", + nfs4_procedures_names, nfs4_procedures_names_num); + nfs_read_kstat (nfs4_ksp_server, /* version = */ 4, "server", + nfs4_procedures_names, nfs4_procedures_names_num); return (0); } +#endif /* HAVE_LIBKSTAT */ void module_register (void) { + plugin_register_init ("nfs", nfs_init); plugin_register_read ("nfs", nfs_read); } /* void module_register */ diff --git a/src/numa.c b/src/numa.c new file mode 100644 index 00000000..4b4ef208 --- /dev/null +++ b/src/numa.c @@ -0,0 +1,168 @@ +/** + * collectd - src/numa.c + * Copyright (C) 2012 Florian Forster + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Authors: + * Florian Forster + **/ + +#include "collectd.h" +#include "common.h" +#include "plugin.h" + +#if !KERNEL_LINUX +# error "No applicable input method." +#endif + +#ifndef NUMA_ROOT_DIR +# define NUMA_ROOT_DIR "/sys/devices/system/node" +#endif + +static int max_node = -1; + +static void numa_dispatch_value (int node, /* {{{ */ + const char *type_instance, value_t v) +{ + value_list_t vl = VALUE_LIST_INIT; + + vl.values = &v; + vl.values_len = 1; + + sstrncpy (vl.host, hostname_g, sizeof (vl.host)); + sstrncpy (vl.plugin, "numa", sizeof (vl.plugin)); + ssnprintf (vl.plugin_instance, sizeof (vl.plugin_instance), "node%i", node); + sstrncpy (vl.type, "vmpage_action", sizeof (vl.type)); + sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); + + plugin_dispatch_values (&vl); +} /* }}} void numa_dispatch_value */ + +static int numa_read_node (int node) /* {{{ */ +{ + char path[PATH_MAX]; + FILE *fh; + char buffer[128]; + int status; + int success; + + ssnprintf (path, sizeof (path), NUMA_ROOT_DIR "/node%i/numastat", node); + + fh = fopen (path, "r"); + if (fh == NULL) + { + char errbuf[1024]; + ERROR ("numa plugin: Reading node %i failed: open(%s): %s", + node, path, sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + + success = 0; + while (fgets (buffer, sizeof (buffer), fh) != NULL) + { + char *fields[4]; + value_t v; + + status = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields)); + if (status != 2) + { + WARNING ("numa plugin: Ignoring line with unexpected " + "number of fields (node %i).", node); + continue; + } + + v.derive = 0; + status = parse_value (fields[1], &v, DS_TYPE_DERIVE); + if (status != 0) + continue; + + numa_dispatch_value (node, fields[0], v); + success++; + } + + fclose (fh); + return (success ? 0 : -1); +} /* }}} int numa_read_node */ + +static int numa_read (void) /* {{{ */ +{ + int i; + int status; + int success; + + if (max_node < 0) + { + WARNING ("numa plugin: No NUMA nodes were detected."); + return (-1); + } + + success = 0; + for (i = 0; i <= max_node; i++) + { + status = numa_read_node (i); + if (status == 0) + success++; + } + + return (success ? 0 : -1); +} /* }}} int numa_read */ + +static int numa_init (void) /* {{{ */ +{ + /* Determine the number of nodes on this machine. */ + while (42) + { + char path[PATH_MAX]; + struct stat statbuf; + int status; + + ssnprintf (path, sizeof (path), NUMA_ROOT_DIR "/node%i", max_node + 1); + memset (&statbuf, 0, sizeof (statbuf)); + + status = stat (path, &statbuf); + if (status == 0) + { + max_node++; + continue; + } + else if (errno == ENOENT) + { + break; + } + else /* ((status != 0) && (errno != ENOENT)) */ + { + char errbuf[1024]; + ERROR ("numa plugin: stat(%s) failed: %s", path, + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + } + + DEBUG ("numa plugin: Found %i nodes.", max_node + 1); + return (0); +} /* }}} int numa_init */ + +void module_register (void) +{ + plugin_register_init ("numa", numa_init); + plugin_register_read ("numa", numa_read); +} /* void module_register */ + +/* vim: set sw=2 sts=2 et : */ diff --git a/src/owniptc/Makefile.am b/src/owniptc/Makefile.am deleted file mode 100644 index d51e9934..00000000 --- a/src/owniptc/Makefile.am +++ /dev/null @@ -1,14 +0,0 @@ -AUTOMAKE_OPTIONS = foreign no-dependencies - -EXTRA_DIST = libiptc.c README.collectd - -if COMPILER_IS_GCC -AM_CFLAGS = -Wall -Werror -endif - -noinst_LTLIBRARIES = libiptc.la - -libiptc_la_SOURCES = libip4tc.c libip6tc.c \ - ipt_kernel_headers.h libip6tc.h libiptc.h linux_list.h \ - xtables.h libxtc.h - diff --git a/src/owniptc/README.collectd b/src/owniptc/README.collectd deleted file mode 100644 index adb53b0b..00000000 --- a/src/owniptc/README.collectd +++ /dev/null @@ -1,25 +0,0 @@ - libiptc (IPTables Chains) in collectd -======================================= -http://netfilter.org/ -http://collectd.org/ - -About ------ - - This is libiptc taken from the iptables source distribution. As it is not - meant to be a public interface by upstream it is not shipped in some binary - distributions. Thus, collectd ships its own copy as a fall-back. - - The presently available version was imported from iptables 1.4.1.1. - -Changes to the iptables upstream sources: ------------------------------------------ - - * Added copyright headers mentioning the "Netfilter Core Team" as copyright - holder. - - * Changed "libiptc/*" includes to "*". - - * Use the shipped copy of "xtables.h" instead of the one possibly available - on the system. - diff --git a/src/owniptc/ipt_kernel_headers.h b/src/owniptc/ipt_kernel_headers.h deleted file mode 100644 index bf81f6e8..00000000 --- a/src/owniptc/ipt_kernel_headers.h +++ /dev/null @@ -1,45 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* This is the userspace/kernel interface for Generic IP Chains, - required for libc6. */ -#ifndef _FWCHAINS_KERNEL_HEADERS_H -#define _FWCHAINS_KERNEL_HEADERS_H - -#include - -#if defined(__GLIBC__) && __GLIBC__ == 2 -#include -#include -#include -#include -#include -#include -#include -#else /* libc5 */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif -#endif diff --git a/src/owniptc/libip4tc.c b/src/owniptc/libip4tc.c deleted file mode 100644 index bf7327cd..00000000 --- a/src/owniptc/libip4tc.c +++ /dev/null @@ -1,517 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* Library which manipulates firewall rules. Version 0.1. */ - -/* Architecture of firewall rules is as follows: - * - * Chains go INPUT, FORWARD, OUTPUT then user chains. - * Each user chain starts with an ERROR node. - * Every chain ends with an unconditional jump: a RETURN for user chains, - * and a POLICY for built-ins. - */ - -/* (C)1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See - COPYING for details). */ - -#include -#include -#include -#include -#include -#include - -#ifdef DEBUG_CONNTRACK -#define inline -#endif - -#if !defined(__GLIBC__) || (__GLIBC__ < 2) -typedef unsigned int socklen_t; -#endif - -#include "libiptc.h" - -#define IP_VERSION 4 -#define IP_OFFSET 0x1FFF - -#define HOOK_PRE_ROUTING NF_IP_PRE_ROUTING -#define HOOK_LOCAL_IN NF_IP_LOCAL_IN -#define HOOK_FORWARD NF_IP_FORWARD -#define HOOK_LOCAL_OUT NF_IP_LOCAL_OUT -#define HOOK_POST_ROUTING NF_IP_POST_ROUTING -#ifdef NF_IP_DROPPING -#define HOOK_DROPPING NF_IP_DROPPING -#endif - -#define STRUCT_ENTRY_TARGET struct ipt_entry_target -#define STRUCT_ENTRY struct ipt_entry -#define STRUCT_ENTRY_MATCH struct ipt_entry_match -#define STRUCT_GETINFO struct ipt_getinfo -#define STRUCT_GET_ENTRIES struct ipt_get_entries -#define STRUCT_COUNTERS struct ipt_counters -#define STRUCT_COUNTERS_INFO struct ipt_counters_info -#define STRUCT_STANDARD_TARGET struct ipt_standard_target -#define STRUCT_REPLACE struct ipt_replace - -#define STRUCT_TC_HANDLE struct iptc_handle -#define TC_HANDLE_T iptc_handle_t - -#define ENTRY_ITERATE IPT_ENTRY_ITERATE -#define TABLE_MAXNAMELEN IPT_TABLE_MAXNAMELEN -#define FUNCTION_MAXNAMELEN IPT_FUNCTION_MAXNAMELEN - -#define GET_TARGET ipt_get_target - -#define ERROR_TARGET IPT_ERROR_TARGET -#define NUMHOOKS NF_IP_NUMHOOKS - -#define IPT_CHAINLABEL ipt_chainlabel - -#define TC_DUMP_ENTRIES dump_entries -#define TC_IS_CHAIN iptc_is_chain -#define TC_FIRST_CHAIN iptc_first_chain -#define TC_NEXT_CHAIN iptc_next_chain -#define TC_FIRST_RULE iptc_first_rule -#define TC_NEXT_RULE iptc_next_rule -#define TC_GET_TARGET iptc_get_target -#define TC_BUILTIN iptc_builtin -#define TC_GET_POLICY iptc_get_policy -#define TC_INSERT_ENTRY iptc_insert_entry -#define TC_REPLACE_ENTRY iptc_replace_entry -#define TC_APPEND_ENTRY iptc_append_entry -#define TC_DELETE_ENTRY iptc_delete_entry -#define TC_DELETE_NUM_ENTRY iptc_delete_num_entry -#define TC_CHECK_PACKET iptc_check_packet -#define TC_FLUSH_ENTRIES iptc_flush_entries -#define TC_ZERO_ENTRIES iptc_zero_entries -#define TC_READ_COUNTER iptc_read_counter -#define TC_ZERO_COUNTER iptc_zero_counter -#define TC_SET_COUNTER iptc_set_counter -#define TC_CREATE_CHAIN iptc_create_chain -#define TC_GET_REFERENCES iptc_get_references -#define TC_DELETE_CHAIN iptc_delete_chain -#define TC_RENAME_CHAIN iptc_rename_chain -#define TC_SET_POLICY iptc_set_policy -#define TC_GET_RAW_SOCKET iptc_get_raw_socket -#define TC_INIT iptc_init -#define TC_FREE iptc_free -#define TC_COMMIT iptc_commit -#define TC_STRERROR iptc_strerror -#define TC_NUM_RULES iptc_num_rules -#define TC_GET_RULE iptc_get_rule - -#define TC_AF AF_INET -#define TC_IPPROTO IPPROTO_IP - -#define SO_SET_REPLACE IPT_SO_SET_REPLACE -#define SO_SET_ADD_COUNTERS IPT_SO_SET_ADD_COUNTERS -#define SO_GET_INFO IPT_SO_GET_INFO -#define SO_GET_ENTRIES IPT_SO_GET_ENTRIES -#define SO_GET_VERSION IPT_SO_GET_VERSION - -#define STANDARD_TARGET IPT_STANDARD_TARGET -#define LABEL_RETURN IPTC_LABEL_RETURN -#define LABEL_ACCEPT IPTC_LABEL_ACCEPT -#define LABEL_DROP IPTC_LABEL_DROP -#define LABEL_QUEUE IPTC_LABEL_QUEUE - -#define ALIGN IPT_ALIGN -#define RETURN IPT_RETURN - -#include "libiptc.c" - -#define IP_PARTS_NATIVE(n) \ -(unsigned int)((n)>>24)&0xFF, \ -(unsigned int)((n)>>16)&0xFF, \ -(unsigned int)((n)>>8)&0xFF, \ -(unsigned int)((n)&0xFF) - -#define IP_PARTS(n) IP_PARTS_NATIVE(ntohl(n)) - -int -dump_entry(STRUCT_ENTRY *e, const TC_HANDLE_T handle) -{ - size_t i; - STRUCT_ENTRY_TARGET *t; - - printf("Entry %u (%lu):\n", iptcb_entry2index(handle, e), - iptcb_entry2offset(handle, e)); - printf("SRC IP: %u.%u.%u.%u/%u.%u.%u.%u\n", - IP_PARTS(e->ip.src.s_addr),IP_PARTS(e->ip.smsk.s_addr)); - printf("DST IP: %u.%u.%u.%u/%u.%u.%u.%u\n", - IP_PARTS(e->ip.dst.s_addr),IP_PARTS(e->ip.dmsk.s_addr)); - printf("Interface: `%s'/", e->ip.iniface); - for (i = 0; i < IFNAMSIZ; i++) - printf("%c", e->ip.iniface_mask[i] ? 'X' : '.'); - printf("to `%s'/", e->ip.outiface); - for (i = 0; i < IFNAMSIZ; i++) - printf("%c", e->ip.outiface_mask[i] ? 'X' : '.'); - printf("\nProtocol: %u\n", e->ip.proto); - printf("Flags: %02X\n", e->ip.flags); - printf("Invflags: %02X\n", e->ip.invflags); - printf("Counters: %llu packets, %llu bytes\n", - (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt); - printf("Cache: %08X\n", e->nfcache); - - IPT_MATCH_ITERATE(e, print_match); - - t = GET_TARGET(e); - printf("Target name: `%s' [%u]\n", t->u.user.name, t->u.target_size); - if (strcmp(t->u.user.name, STANDARD_TARGET) == 0) { - const unsigned char *data = t->data; - int pos = *(const int *)data; - if (pos < 0) - printf("verdict=%s\n", - pos == -NF_ACCEPT-1 ? "NF_ACCEPT" - : pos == -NF_DROP-1 ? "NF_DROP" - : pos == -NF_QUEUE-1 ? "NF_QUEUE" - : pos == RETURN ? "RETURN" - : "UNKNOWN"); - else - printf("verdict=%u\n", pos); - } else if (strcmp(t->u.user.name, IPT_ERROR_TARGET) == 0) - printf("error=`%s'\n", t->data); - - printf("\n"); - return 0; -} - -static unsigned char * -is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b, unsigned char *matchmask) -{ - unsigned int i; - unsigned char *mptr; - - /* Always compare head structures: ignore mask here. */ - if (a->ip.src.s_addr != b->ip.src.s_addr - || a->ip.dst.s_addr != b->ip.dst.s_addr - || a->ip.smsk.s_addr != b->ip.smsk.s_addr - || a->ip.dmsk.s_addr != b->ip.dmsk.s_addr - || a->ip.proto != b->ip.proto - || a->ip.flags != b->ip.flags - || a->ip.invflags != b->ip.invflags) - return NULL; - - for (i = 0; i < IFNAMSIZ; i++) { - if (a->ip.iniface_mask[i] != b->ip.iniface_mask[i]) - return NULL; - if ((a->ip.iniface[i] & a->ip.iniface_mask[i]) - != (b->ip.iniface[i] & b->ip.iniface_mask[i])) - return NULL; - if (a->ip.outiface_mask[i] != b->ip.outiface_mask[i]) - return NULL; - if ((a->ip.outiface[i] & a->ip.outiface_mask[i]) - != (b->ip.outiface[i] & b->ip.outiface_mask[i])) - return NULL; - } - - if (a->target_offset != b->target_offset - || a->next_offset != b->next_offset) - return NULL; - - mptr = matchmask + sizeof(STRUCT_ENTRY); - if (IPT_MATCH_ITERATE(a, match_different, a->elems, b->elems, &mptr)) - return NULL; - mptr += IPT_ALIGN(sizeof(struct ipt_entry_target)); - - return mptr; -} - -#if 0 -/***************************** DEBUGGING ********************************/ -static inline int -unconditional(const struct ipt_ip *ip) -{ - unsigned int i; - - for (i = 0; i < sizeof(*ip)/sizeof(u_int32_t); i++) - if (((u_int32_t *)ip)[i]) - return 0; - - return 1; -} - -static inline int -check_match(const STRUCT_ENTRY_MATCH *m, unsigned int *off) -{ - assert(m->u.match_size >= sizeof(STRUCT_ENTRY_MATCH)); - assert(ALIGN(m->u.match_size) == m->u.match_size); - - (*off) += m->u.match_size; - return 0; -} - -static inline int -check_entry(const STRUCT_ENTRY *e, unsigned int *i, unsigned int *off, - unsigned int user_offset, int *was_return, - TC_HANDLE_T h) -{ - unsigned int toff; - STRUCT_STANDARD_TARGET *t; - - assert(e->target_offset >= sizeof(STRUCT_ENTRY)); - assert(e->next_offset >= e->target_offset - + sizeof(STRUCT_ENTRY_TARGET)); - toff = sizeof(STRUCT_ENTRY); - IPT_MATCH_ITERATE(e, check_match, &toff); - - assert(toff == e->target_offset); - - t = (STRUCT_STANDARD_TARGET *) - GET_TARGET((STRUCT_ENTRY *)e); - /* next_offset will have to be multiple of entry alignment. */ - assert(e->next_offset == ALIGN(e->next_offset)); - assert(e->target_offset == ALIGN(e->target_offset)); - assert(t->target.u.target_size == ALIGN(t->target.u.target_size)); - assert(!TC_IS_CHAIN(t->target.u.user.name, h)); - - if (strcmp(t->target.u.user.name, STANDARD_TARGET) == 0) { - assert(t->target.u.target_size - == ALIGN(sizeof(STRUCT_STANDARD_TARGET))); - - assert(t->verdict == -NF_DROP-1 - || t->verdict == -NF_ACCEPT-1 - || t->verdict == RETURN - || t->verdict < (int)h->entries->size); - - if (t->verdict >= 0) { - STRUCT_ENTRY *te = get_entry(h, t->verdict); - int idx; - - idx = iptcb_entry2index(h, te); - assert(strcmp(GET_TARGET(te)->u.user.name, - IPT_ERROR_TARGET) - != 0); - assert(te != e); - - /* Prior node must be error node, or this node. */ - assert(t->verdict == iptcb_entry2offset(h, e)+e->next_offset - || strcmp(GET_TARGET(index2entry(h, idx-1)) - ->u.user.name, IPT_ERROR_TARGET) - == 0); - } - - if (t->verdict == RETURN - && unconditional(&e->ip) - && e->target_offset == sizeof(*e)) - *was_return = 1; - else - *was_return = 0; - } else if (strcmp(t->target.u.user.name, IPT_ERROR_TARGET) == 0) { - assert(t->target.u.target_size - == ALIGN(sizeof(struct ipt_error_target))); - - /* If this is in user area, previous must have been return */ - if (*off > user_offset) - assert(*was_return); - - *was_return = 0; - } - else *was_return = 0; - - if (*off == user_offset) - assert(strcmp(t->target.u.user.name, IPT_ERROR_TARGET) == 0); - - (*off) += e->next_offset; - (*i)++; - return 0; -} - -#ifdef IPTC_DEBUG -/* Do every conceivable sanity check on the handle */ -static void -do_check(TC_HANDLE_T h, unsigned int line) -{ - unsigned int i, n; - unsigned int user_offset; /* Offset of first user chain */ - int was_return; - - assert(h->changed == 0 || h->changed == 1); - if (strcmp(h->info.name, "filter") == 0) { - assert(h->info.valid_hooks - == (1 << NF_IP_LOCAL_IN - | 1 << NF_IP_FORWARD - | 1 << NF_IP_LOCAL_OUT)); - - /* Hooks should be first three */ - assert(h->info.hook_entry[NF_IP_LOCAL_IN] == 0); - - n = get_chain_end(h, 0); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_FORWARD] == n); - - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); - - user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; - } else if (strcmp(h->info.name, "nat") == 0) { - assert((h->info.valid_hooks - == (1 << NF_IP_PRE_ROUTING - | 1 << NF_IP_POST_ROUTING - | 1 << NF_IP_LOCAL_OUT)) || - (h->info.valid_hooks - == (1 << NF_IP_PRE_ROUTING - | 1 << NF_IP_LOCAL_IN - | 1 << NF_IP_POST_ROUTING - | 1 << NF_IP_LOCAL_OUT))); - - assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0); - - n = get_chain_end(h, 0); - - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_POST_ROUTING] == n); - n = get_chain_end(h, n); - - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); - user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; - - if (h->info.valid_hooks & (1 << NF_IP_LOCAL_IN)) { - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_LOCAL_IN] == n); - user_offset = h->info.hook_entry[NF_IP_LOCAL_IN]; - } - - } else if (strcmp(h->info.name, "mangle") == 0) { - /* This code is getting ugly because linux < 2.4.18-pre6 had - * two mangle hooks, linux >= 2.4.18-pre6 has five mangle hooks - * */ - assert((h->info.valid_hooks - == (1 << NF_IP_PRE_ROUTING - | 1 << NF_IP_LOCAL_OUT)) || - (h->info.valid_hooks - == (1 << NF_IP_PRE_ROUTING - | 1 << NF_IP_LOCAL_IN - | 1 << NF_IP_FORWARD - | 1 << NF_IP_LOCAL_OUT - | 1 << NF_IP_POST_ROUTING))); - - /* Hooks should be first five */ - assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0); - - n = get_chain_end(h, 0); - - if (h->info.valid_hooks & (1 << NF_IP_LOCAL_IN)) { - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_LOCAL_IN] == n); - n = get_chain_end(h, n); - } - - if (h->info.valid_hooks & (1 << NF_IP_FORWARD)) { - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_FORWARD] == n); - n = get_chain_end(h, n); - } - - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); - user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; - - if (h->info.valid_hooks & (1 << NF_IP_POST_ROUTING)) { - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_POST_ROUTING] == n); - user_offset = h->info.hook_entry[NF_IP_POST_ROUTING]; - } - } else if (strcmp(h->info.name, "raw") == 0) { - assert(h->info.valid_hooks - == (1 << NF_IP_PRE_ROUTING - | 1 << NF_IP_LOCAL_OUT)); - - /* Hooks should be first three */ - assert(h->info.hook_entry[NF_IP_PRE_ROUTING] == 0); - - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP_LOCAL_OUT] == n); - - user_offset = h->info.hook_entry[NF_IP_LOCAL_OUT]; - -#ifdef NF_IP_DROPPING - } else if (strcmp(h->info.name, "drop") == 0) { - assert(h->info.valid_hooks == (1 << NF_IP_DROPPING)); - - /* Hook should be first */ - assert(h->info.hook_entry[NF_IP_DROPPING] == 0); - user_offset = 0; -#endif - } else { - fprintf(stderr, "Unknown table `%s'\n", h->info.name); - abort(); - } - - /* User chain == end of last builtin + policy entry */ - user_offset = get_chain_end(h, user_offset); - user_offset += get_entry(h, user_offset)->next_offset; - - /* Overflows should be end of entry chains, and unconditional - policy nodes. */ - for (i = 0; i < NUMHOOKS; i++) { - STRUCT_ENTRY *e; - STRUCT_STANDARD_TARGET *t; - - if (!(h->info.valid_hooks & (1 << i))) - continue; - assert(h->info.underflow[i] - == get_chain_end(h, h->info.hook_entry[i])); - - e = get_entry(h, get_chain_end(h, h->info.hook_entry[i])); - assert(unconditional(&e->ip)); - assert(e->target_offset == sizeof(*e)); - t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); - assert(t->target.u.target_size == ALIGN(sizeof(*t))); - assert(e->next_offset == sizeof(*e) + ALIGN(sizeof(*t))); - - assert(strcmp(t->target.u.user.name, STANDARD_TARGET)==0); - assert(t->verdict == -NF_DROP-1 || t->verdict == -NF_ACCEPT-1); - - /* Hooks and underflows must be valid entries */ - entry2index(h, get_entry(h, h->info.hook_entry[i])); - entry2index(h, get_entry(h, h->info.underflow[i])); - } - - assert(h->info.size - >= h->info.num_entries * (sizeof(STRUCT_ENTRY) - +sizeof(STRUCT_STANDARD_TARGET))); - - assert(h->entries.size - >= (h->new_number - * (sizeof(STRUCT_ENTRY) - + sizeof(STRUCT_STANDARD_TARGET)))); - assert(strcmp(h->info.name, h->entries.name) == 0); - - i = 0; n = 0; - was_return = 0; - /* Check all the entries. */ - ENTRY_ITERATE(h->entries.entrytable, h->entries.size, - check_entry, &i, &n, user_offset, &was_return, h); - - assert(i == h->new_number); - assert(n == h->entries.size); - - /* Final entry must be error node */ - assert(strcmp(GET_TARGET(index2entry(h, h->new_number-1)) - ->u.user.name, - ERROR_TARGET) == 0); -} -#endif /*IPTC_DEBUG*/ - -#endif diff --git a/src/owniptc/libip6tc.c b/src/owniptc/libip6tc.c deleted file mode 100644 index 672dae12..00000000 --- a/src/owniptc/libip6tc.c +++ /dev/null @@ -1,456 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* Library which manipulates firewall rules. Version 0.1. */ - -/* Architecture of firewall rules is as follows: - * - * Chains go INPUT, FORWARD, OUTPUT then user chains. - * Each user chain starts with an ERROR node. - * Every chain ends with an unconditional jump: a RETURN for user chains, - * and a POLICY for built-ins. - */ - -/* (C)1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See - COPYING for details). */ - -#include -#include -#include -#include -#include -#include -#include - -#ifdef DEBUG_CONNTRACK -#define inline -#endif - -#if !defined(__GLIBC__) || (__GLIBC__ < 2) -typedef unsigned int socklen_t; -#endif - -#include "libip6tc.h" - -#define HOOK_PRE_ROUTING NF_IP6_PRE_ROUTING -#define HOOK_LOCAL_IN NF_IP6_LOCAL_IN -#define HOOK_FORWARD NF_IP6_FORWARD -#define HOOK_LOCAL_OUT NF_IP6_LOCAL_OUT -#define HOOK_POST_ROUTING NF_IP6_POST_ROUTING - -#define STRUCT_ENTRY_TARGET struct ip6t_entry_target -#define STRUCT_ENTRY struct ip6t_entry -#define STRUCT_ENTRY_MATCH struct ip6t_entry_match -#define STRUCT_GETINFO struct ip6t_getinfo -#define STRUCT_GET_ENTRIES struct ip6t_get_entries -#define STRUCT_COUNTERS struct ip6t_counters -#define STRUCT_COUNTERS_INFO struct ip6t_counters_info -#define STRUCT_STANDARD_TARGET struct ip6t_standard_target -#define STRUCT_REPLACE struct ip6t_replace - -#define STRUCT_TC_HANDLE struct ip6tc_handle -#define TC_HANDLE_T ip6tc_handle_t - -#define ENTRY_ITERATE IP6T_ENTRY_ITERATE -#define TABLE_MAXNAMELEN IP6T_TABLE_MAXNAMELEN -#define FUNCTION_MAXNAMELEN IP6T_FUNCTION_MAXNAMELEN - -#define GET_TARGET ip6t_get_target - -#define ERROR_TARGET IP6T_ERROR_TARGET -#define NUMHOOKS NF_IP6_NUMHOOKS - -#define IPT_CHAINLABEL ip6t_chainlabel - -#define TC_DUMP_ENTRIES dump_entries6 -#define TC_IS_CHAIN ip6tc_is_chain -#define TC_FIRST_CHAIN ip6tc_first_chain -#define TC_NEXT_CHAIN ip6tc_next_chain -#define TC_FIRST_RULE ip6tc_first_rule -#define TC_NEXT_RULE ip6tc_next_rule -#define TC_GET_TARGET ip6tc_get_target -#define TC_BUILTIN ip6tc_builtin -#define TC_GET_POLICY ip6tc_get_policy -#define TC_INSERT_ENTRY ip6tc_insert_entry -#define TC_REPLACE_ENTRY ip6tc_replace_entry -#define TC_APPEND_ENTRY ip6tc_append_entry -#define TC_DELETE_ENTRY ip6tc_delete_entry -#define TC_DELETE_NUM_ENTRY ip6tc_delete_num_entry -#define TC_CHECK_PACKET ip6tc_check_packet -#define TC_FLUSH_ENTRIES ip6tc_flush_entries -#define TC_ZERO_ENTRIES ip6tc_zero_entries -#define TC_ZERO_COUNTER ip6tc_zero_counter -#define TC_READ_COUNTER ip6tc_read_counter -#define TC_SET_COUNTER ip6tc_set_counter -#define TC_CREATE_CHAIN ip6tc_create_chain -#define TC_GET_REFERENCES ip6tc_get_references -#define TC_DELETE_CHAIN ip6tc_delete_chain -#define TC_RENAME_CHAIN ip6tc_rename_chain -#define TC_SET_POLICY ip6tc_set_policy -#define TC_GET_RAW_SOCKET ip6tc_get_raw_socket -#define TC_INIT ip6tc_init -#define TC_FREE ip6tc_free -#define TC_COMMIT ip6tc_commit -#define TC_STRERROR ip6tc_strerror -#define TC_NUM_RULES ip6tc_num_rules -#define TC_GET_RULE ip6tc_get_rule - -#define TC_AF AF_INET6 -#define TC_IPPROTO IPPROTO_IPV6 - -#define SO_SET_REPLACE IP6T_SO_SET_REPLACE -#define SO_SET_ADD_COUNTERS IP6T_SO_SET_ADD_COUNTERS -#define SO_GET_INFO IP6T_SO_GET_INFO -#define SO_GET_ENTRIES IP6T_SO_GET_ENTRIES -#define SO_GET_VERSION IP6T_SO_GET_VERSION - -#define STANDARD_TARGET IP6T_STANDARD_TARGET -#define LABEL_RETURN IP6TC_LABEL_RETURN -#define LABEL_ACCEPT IP6TC_LABEL_ACCEPT -#define LABEL_DROP IP6TC_LABEL_DROP -#define LABEL_QUEUE IP6TC_LABEL_QUEUE - -#define ALIGN IP6T_ALIGN -#define RETURN IP6T_RETURN - -#include "libiptc.c" - -#define BIT6(a, l) \ - ((ntohl(a->s6_addr32[(l) / 32]) >> (31 - ((l) & 31))) & 1) - -int -ipv6_prefix_length(const struct in6_addr *a) -{ - int l, i; - for (l = 0; l < 128; l++) { - if (BIT6(a, l) == 0) - break; - } - for (i = l + 1; i < 128; i++) { - if (BIT6(a, i) == 1) - return -1; - } - return l; -} - -static int -dump_entry(struct ip6t_entry *e, const ip6tc_handle_t handle) -{ - size_t i; - char buf[40]; - int len; - struct ip6t_entry_target *t; - - printf("Entry %u (%lu):\n", iptcb_entry2index(handle, e), - iptcb_entry2offset(handle, e)); - puts("SRC IP: "); - inet_ntop(AF_INET6, &e->ipv6.src, buf, sizeof buf); - puts(buf); - putchar('/'); - len = ipv6_prefix_length(&e->ipv6.smsk); - if (len != -1) - printf("%d", len); - else { - inet_ntop(AF_INET6, &e->ipv6.smsk, buf, sizeof buf); - puts(buf); - } - putchar('\n'); - - puts("DST IP: "); - inet_ntop(AF_INET6, &e->ipv6.dst, buf, sizeof buf); - puts(buf); - putchar('/'); - len = ipv6_prefix_length(&e->ipv6.dmsk); - if (len != -1) - printf("%d", len); - else { - inet_ntop(AF_INET6, &e->ipv6.dmsk, buf, sizeof buf); - puts(buf); - } - putchar('\n'); - - printf("Interface: `%s'/", e->ipv6.iniface); - for (i = 0; i < IFNAMSIZ; i++) - printf("%c", e->ipv6.iniface_mask[i] ? 'X' : '.'); - printf("to `%s'/", e->ipv6.outiface); - for (i = 0; i < IFNAMSIZ; i++) - printf("%c", e->ipv6.outiface_mask[i] ? 'X' : '.'); - printf("\nProtocol: %u\n", e->ipv6.proto); - if (e->ipv6.flags & IP6T_F_TOS) - printf("TOS: %u\n", e->ipv6.tos); - printf("Flags: %02X\n", e->ipv6.flags); - printf("Invflags: %02X\n", e->ipv6.invflags); - printf("Counters: %llu packets, %llu bytes\n", - (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt); - printf("Cache: %08X\n", e->nfcache); - - IP6T_MATCH_ITERATE(e, print_match); - - t = ip6t_get_target(e); - printf("Target name: `%s' [%u]\n", t->u.user.name, t->u.target_size); - if (strcmp(t->u.user.name, IP6T_STANDARD_TARGET) == 0) { - const unsigned char *data = t->data; - int pos = *(const int *)data; - if (pos < 0) - printf("verdict=%s\n", - pos == -NF_ACCEPT-1 ? "NF_ACCEPT" - : pos == -NF_DROP-1 ? "NF_DROP" - : pos == IP6T_RETURN ? "RETURN" - : "UNKNOWN"); - else - printf("verdict=%u\n", pos); - } else if (strcmp(t->u.user.name, IP6T_ERROR_TARGET) == 0) - printf("error=`%s'\n", t->data); - - printf("\n"); - return 0; -} - -static unsigned char * -is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b, - unsigned char *matchmask) -{ - unsigned int i; - unsigned char *mptr; - - /* Always compare head structures: ignore mask here. */ - if (memcmp(&a->ipv6.src, &b->ipv6.src, sizeof(struct in6_addr)) - || memcmp(&a->ipv6.dst, &b->ipv6.dst, sizeof(struct in6_addr)) - || memcmp(&a->ipv6.smsk, &b->ipv6.smsk, sizeof(struct in6_addr)) - || memcmp(&a->ipv6.dmsk, &b->ipv6.dmsk, sizeof(struct in6_addr)) - || a->ipv6.proto != b->ipv6.proto - || a->ipv6.tos != b->ipv6.tos - || a->ipv6.flags != b->ipv6.flags - || a->ipv6.invflags != b->ipv6.invflags) - return NULL; - - for (i = 0; i < IFNAMSIZ; i++) { - if (a->ipv6.iniface_mask[i] != b->ipv6.iniface_mask[i]) - return NULL; - if ((a->ipv6.iniface[i] & a->ipv6.iniface_mask[i]) - != (b->ipv6.iniface[i] & b->ipv6.iniface_mask[i])) - return NULL; - if (a->ipv6.outiface_mask[i] != b->ipv6.outiface_mask[i]) - return NULL; - if ((a->ipv6.outiface[i] & a->ipv6.outiface_mask[i]) - != (b->ipv6.outiface[i] & b->ipv6.outiface_mask[i])) - return NULL; - } - - if (a->target_offset != b->target_offset - || a->next_offset != b->next_offset) - return NULL; - - mptr = matchmask + sizeof(STRUCT_ENTRY); - if (IP6T_MATCH_ITERATE(a, match_different, a->elems, b->elems, &mptr)) - return NULL; - mptr += IP6T_ALIGN(sizeof(struct ip6t_entry_target)); - - return mptr; -} - -/* All zeroes == unconditional rule. */ -static inline int -unconditional(const struct ip6t_ip6 *ipv6) -{ - unsigned int i; - - for (i = 0; i < sizeof(*ipv6); i++) - if (((char *)ipv6)[i]) - break; - - return (i == sizeof(*ipv6)); -} - -#ifdef IPTC_DEBUG -/* Do every conceivable sanity check on the handle */ -static void -do_check(TC_HANDLE_T h, unsigned int line) -{ - unsigned int i, n; - unsigned int user_offset; /* Offset of first user chain */ - int was_return; - - assert(h->changed == 0 || h->changed == 1); - if (strcmp(h->info.name, "filter") == 0) { - assert(h->info.valid_hooks - == (1 << NF_IP6_LOCAL_IN - | 1 << NF_IP6_FORWARD - | 1 << NF_IP6_LOCAL_OUT)); - - /* Hooks should be first three */ - assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == 0); - - n = get_chain_end(h, 0); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_FORWARD] == n); - - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); - - user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; - } else if (strcmp(h->info.name, "nat") == 0) { - assert((h->info.valid_hooks - == (1 << NF_IP6_PRE_ROUTING - | 1 << NF_IP6_LOCAL_OUT - | 1 << NF_IP6_POST_ROUTING)) || - (h->info.valid_hooks - == (1 << NF_IP6_PRE_ROUTING - | 1 << NF_IP6_LOCAL_IN - | 1 << NF_IP6_LOCAL_OUT - | 1 << NF_IP6_POST_ROUTING))); - - assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0); - - n = get_chain_end(h, 0); - - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_POST_ROUTING] == n); - n = get_chain_end(h, n); - - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); - user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; - - if (h->info.valid_hooks & (1 << NF_IP6_LOCAL_IN)) { - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == n); - user_offset = h->info.hook_entry[NF_IP6_LOCAL_IN]; - } - - } else if (strcmp(h->info.name, "mangle") == 0) { - /* This code is getting ugly because linux < 2.4.18-pre6 had - * two mangle hooks, linux >= 2.4.18-pre6 has five mangle hooks - * */ - assert((h->info.valid_hooks - == (1 << NF_IP6_PRE_ROUTING - | 1 << NF_IP6_LOCAL_OUT)) || - (h->info.valid_hooks - == (1 << NF_IP6_PRE_ROUTING - | 1 << NF_IP6_LOCAL_IN - | 1 << NF_IP6_FORWARD - | 1 << NF_IP6_LOCAL_OUT - | 1 << NF_IP6_POST_ROUTING))); - - /* Hooks should be first five */ - assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0); - - n = get_chain_end(h, 0); - - if (h->info.valid_hooks & (1 << NF_IP6_LOCAL_IN)) { - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_LOCAL_IN] == n); - n = get_chain_end(h, n); - } - - if (h->info.valid_hooks & (1 << NF_IP6_FORWARD)) { - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_FORWARD] == n); - n = get_chain_end(h, n); - } - - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); - user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; - - if (h->info.valid_hooks & (1 << NF_IP6_POST_ROUTING)) { - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_POST_ROUTING] == n); - user_offset = h->info.hook_entry[NF_IP6_POST_ROUTING]; - } - } else if (strcmp(h->info.name, "raw") == 0) { - assert(h->info.valid_hooks - == (1 << NF_IP6_PRE_ROUTING - | 1 << NF_IP6_LOCAL_OUT)); - - /* Hooks should be first three */ - assert(h->info.hook_entry[NF_IP6_PRE_ROUTING] == 0); - - n = get_chain_end(h, n); - n += get_entry(h, n)->next_offset; - assert(h->info.hook_entry[NF_IP6_LOCAL_OUT] == n); - - user_offset = h->info.hook_entry[NF_IP6_LOCAL_OUT]; - } else { - fprintf(stderr, "Unknown table `%s'\n", h->info.name); - abort(); - } - - /* User chain == end of last builtin + policy entry */ - user_offset = get_chain_end(h, user_offset); - user_offset += get_entry(h, user_offset)->next_offset; - - /* Overflows should be end of entry chains, and unconditional - policy nodes. */ - for (i = 0; i < NUMHOOKS; i++) { - STRUCT_ENTRY *e; - STRUCT_STANDARD_TARGET *t; - - if (!(h->info.valid_hooks & (1 << i))) - continue; - assert(h->info.underflow[i] - == get_chain_end(h, h->info.hook_entry[i])); - - e = get_entry(h, get_chain_end(h, h->info.hook_entry[i])); - assert(unconditional(&e->ipv6)); - assert(e->target_offset == sizeof(*e)); - t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); - printf("target_size=%u, align=%u\n", - t->target.u.target_size, ALIGN(sizeof(*t))); - assert(t->target.u.target_size == ALIGN(sizeof(*t))); - assert(e->next_offset == sizeof(*e) + ALIGN(sizeof(*t))); - - assert(strcmp(t->target.u.user.name, STANDARD_TARGET)==0); - assert(t->verdict == -NF_DROP-1 || t->verdict == -NF_ACCEPT-1); - - /* Hooks and underflows must be valid entries */ - iptcb_entry2index(h, get_entry(h, h->info.hook_entry[i])); - iptcb_entry2index(h, get_entry(h, h->info.underflow[i])); - } - - assert(h->info.size - >= h->info.num_entries * (sizeof(STRUCT_ENTRY) - +sizeof(STRUCT_STANDARD_TARGET))); - - assert(h->entries.size - >= (h->new_number - * (sizeof(STRUCT_ENTRY) - + sizeof(STRUCT_STANDARD_TARGET)))); - assert(strcmp(h->info.name, h->entries.name) == 0); - - i = 0; n = 0; - was_return = 0; - -#if 0 - /* Check all the entries. */ - ENTRY_ITERATE(h->entries.entrytable, h->entries.size, - check_entry, &i, &n, user_offset, &was_return, h); - - assert(i == h->new_number); - assert(n == h->entries.size); - - /* Final entry must be error node */ - assert(strcmp(GET_TARGET(index2entry(h, h->new_number-1)) - ->u.user.name, - ERROR_TARGET) == 0); -#endif -} -#endif /*IPTC_DEBUG*/ diff --git a/src/owniptc/libip6tc.h b/src/owniptc/libip6tc.h deleted file mode 100644 index 9253e11f..00000000 --- a/src/owniptc/libip6tc.h +++ /dev/null @@ -1,175 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef _LIBIP6TC_H -#define _LIBIP6TC_H -/* Library which manipulates firewall rules. Version 0.2. */ - -#include -#include "ipt_kernel_headers.h" -#include - -#ifndef IP6T_MIN_ALIGN -#define IP6T_MIN_ALIGN (__alignof__(struct ip6t_entry)) -#endif -#define IP6T_ALIGN(s) (((s) + (IP6T_MIN_ALIGN-1)) & ~(IP6T_MIN_ALIGN-1)) - -typedef char ip6t_chainlabel[32]; - -#define IP6TC_LABEL_ACCEPT "ACCEPT" -#define IP6TC_LABEL_DROP "DROP" -#define IP6TC_LABEL_QUEUE "QUEUE" -#define IP6TC_LABEL_RETURN "RETURN" - -/* Transparent handle type. */ -typedef struct ip6tc_handle *ip6tc_handle_t; - -/* Does this chain exist? */ -int ip6tc_is_chain(const char *chain, const ip6tc_handle_t handle); - -/* Take a snapshot of the rules. Returns NULL on error. */ -ip6tc_handle_t ip6tc_init(const char *tablename); - -/* Cleanup after ip6tc_init(). */ -void ip6tc_free(ip6tc_handle_t *h); - -/* Iterator functions to run through the chains. Returns NULL at end. */ -const char *ip6tc_first_chain(ip6tc_handle_t *handle); -const char *ip6tc_next_chain(ip6tc_handle_t *handle); - -/* Get first rule in the given chain: NULL for empty chain. */ -const struct ip6t_entry *ip6tc_first_rule(const char *chain, - ip6tc_handle_t *handle); - -/* Returns NULL when rules run out. */ -const struct ip6t_entry *ip6tc_next_rule(const struct ip6t_entry *prev, - ip6tc_handle_t *handle); - -/* Returns a pointer to the target name of this position. */ -const char *ip6tc_get_target(const struct ip6t_entry *e, - ip6tc_handle_t *handle); - -/* Is this a built-in chain? */ -int ip6tc_builtin(const char *chain, const ip6tc_handle_t handle); - -/* Get the policy of a given built-in chain */ -const char *ip6tc_get_policy(const char *chain, - struct ip6t_counters *counters, - ip6tc_handle_t *handle); - -/* These functions return TRUE for OK or 0 and set errno. If errno == - 0, it means there was a version error (ie. upgrade libiptc). */ -/* Rule numbers start at 1 for the first rule. */ - -/* Insert the entry `fw' in chain `chain' into position `rulenum'. */ -int ip6tc_insert_entry(const ip6t_chainlabel chain, - const struct ip6t_entry *e, - unsigned int rulenum, - ip6tc_handle_t *handle); - -/* Atomically replace rule `rulenum' in `chain' with `fw'. */ -int ip6tc_replace_entry(const ip6t_chainlabel chain, - const struct ip6t_entry *e, - unsigned int rulenum, - ip6tc_handle_t *handle); - -/* Append entry `fw' to chain `chain'. Equivalent to insert with - rulenum = length of chain. */ -int ip6tc_append_entry(const ip6t_chainlabel chain, - const struct ip6t_entry *e, - ip6tc_handle_t *handle); - -/* Delete the first rule in `chain' which matches `fw'. */ -int ip6tc_delete_entry(const ip6t_chainlabel chain, - const struct ip6t_entry *origfw, - unsigned char *matchmask, - ip6tc_handle_t *handle); - -/* Delete the rule in position `rulenum' in `chain'. */ -int ip6tc_delete_num_entry(const ip6t_chainlabel chain, - unsigned int rulenum, - ip6tc_handle_t *handle); - -/* Check the packet `fw' on chain `chain'. Returns the verdict, or - NULL and sets errno. */ -const char *ip6tc_check_packet(const ip6t_chainlabel chain, - struct ip6t_entry *, - ip6tc_handle_t *handle); - -/* Flushes the entries in the given chain (ie. empties chain). */ -int ip6tc_flush_entries(const ip6t_chainlabel chain, - ip6tc_handle_t *handle); - -/* Zeroes the counters in a chain. */ -int ip6tc_zero_entries(const ip6t_chainlabel chain, - ip6tc_handle_t *handle); - -/* Creates a new chain. */ -int ip6tc_create_chain(const ip6t_chainlabel chain, - ip6tc_handle_t *handle); - -/* Deletes a chain. */ -int ip6tc_delete_chain(const ip6t_chainlabel chain, - ip6tc_handle_t *handle); - -/* Renames a chain. */ -int ip6tc_rename_chain(const ip6t_chainlabel oldname, - const ip6t_chainlabel newname, - ip6tc_handle_t *handle); - -/* Sets the policy on a built-in chain. */ -int ip6tc_set_policy(const ip6t_chainlabel chain, - const ip6t_chainlabel policy, - struct ip6t_counters *counters, - ip6tc_handle_t *handle); - -/* Get the number of references to this chain */ -int ip6tc_get_references(unsigned int *ref, const ip6t_chainlabel chain, - ip6tc_handle_t *handle); - -/* read packet and byte counters for a specific rule */ -struct ip6t_counters *ip6tc_read_counter(const ip6t_chainlabel chain, - unsigned int rulenum, - ip6tc_handle_t *handle); - -/* zero packet and byte counters for a specific rule */ -int ip6tc_zero_counter(const ip6t_chainlabel chain, - unsigned int rulenum, - ip6tc_handle_t *handle); - -/* set packet and byte counters for a specific rule */ -int ip6tc_set_counter(const ip6t_chainlabel chain, - unsigned int rulenum, - struct ip6t_counters *counters, - ip6tc_handle_t *handle); - -/* Makes the actual changes. */ -int ip6tc_commit(ip6tc_handle_t *handle); - -/* Get raw socket. */ -int ip6tc_get_raw_socket(void); - -/* Translates errno numbers into more human-readable form than strerror. */ -const char *ip6tc_strerror(int err); - -/* Return prefix length, or -1 if not contiguous */ -int ipv6_prefix_length(const struct in6_addr *a); - -extern void dump_entries6(const ip6tc_handle_t); - -#endif /* _LIBIP6TC_H */ diff --git a/src/owniptc/libiptc.c b/src/owniptc/libiptc.c deleted file mode 100644 index 7e48e182..00000000 --- a/src/owniptc/libiptc.c +++ /dev/null @@ -1,2714 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -/* Library which manipulates firewall rules. Version $Revision: 7138 $ */ - -/* Architecture of firewall rules is as follows: - * - * Chains go INPUT, FORWARD, OUTPUT then user chains. - * Each user chain starts with an ERROR node. - * Every chain ends with an unconditional jump: a RETURN for user chains, - * and a POLICY for built-ins. - */ - -/* (C) 1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See - * COPYING for details). - * (C) 2000-2004 by the Netfilter Core Team - * - * 2003-Jun-20: Harald Welte : - * - Reimplementation of chain cache to use offsets instead of entries - * 2003-Jun-23: Harald Welte : - * - performance optimization, sponsored by Astaro AG (http://www.astaro.com/) - * don't rebuild the chain cache after every operation, instead fix it - * up after a ruleset change. - * 2004-Aug-18: Harald Welte : - * - futher performance work: total reimplementation of libiptc. - * - libiptc now has a real internal (linked-list) represntation of the - * ruleset and a parser/compiler from/to this internal representation - * - again sponsored by Astaro AG (http://www.astaro.com/) - */ -#include -#include -#include "xtables.h" - -#include "linux_list.h" - -//#define IPTC_DEBUG2 1 - -#ifdef IPTC_DEBUG2 -#include -#define DEBUGP(x, args...) fprintf(stderr, "%s: " x, __FUNCTION__, ## args) -#define DEBUGP_C(x, args...) fprintf(stderr, x, ## args) -#else -#define DEBUGP(x, args...) -#define DEBUGP_C(x, args...) -#endif - -#ifdef DEBUG -#define debug(x, args...) fprintf(stderr, x, ## args) -#else -#define debug(x, args...) -#endif - -static int sockfd = -1; -static int sockfd_use = 0; -static void *iptc_fn = NULL; - -static const char *hooknames[] = { - [HOOK_PRE_ROUTING] = "PREROUTING", - [HOOK_LOCAL_IN] = "INPUT", - [HOOK_FORWARD] = "FORWARD", - [HOOK_LOCAL_OUT] = "OUTPUT", - [HOOK_POST_ROUTING] = "POSTROUTING", -#ifdef HOOK_DROPPING - [HOOK_DROPPING] = "DROPPING" -#endif -}; - -/* Convenience structures */ -struct ipt_error_target -{ - STRUCT_ENTRY_TARGET t; - char error[TABLE_MAXNAMELEN]; -}; - -struct chain_head; -struct rule_head; - -struct counter_map -{ - enum { - COUNTER_MAP_NOMAP, - COUNTER_MAP_NORMAL_MAP, - COUNTER_MAP_ZEROED, - COUNTER_MAP_SET - } maptype; - unsigned int mappos; -}; - -enum iptcc_rule_type { - IPTCC_R_STANDARD, /* standard target (ACCEPT, ...) */ - IPTCC_R_MODULE, /* extension module (SNAT, ...) */ - IPTCC_R_FALLTHROUGH, /* fallthrough rule */ - IPTCC_R_JUMP, /* jump to other chain */ -}; - -struct rule_head -{ - struct list_head list; - struct chain_head *chain; - struct counter_map counter_map; - - unsigned int index; /* index (needed for counter_map) */ - unsigned int offset; /* offset in rule blob */ - - enum iptcc_rule_type type; - struct chain_head *jump; /* jump target, if IPTCC_R_JUMP */ - - unsigned int size; /* size of entry data */ - STRUCT_ENTRY entry[0]; -}; - -struct chain_head -{ - struct list_head list; - char name[TABLE_MAXNAMELEN]; - unsigned int hooknum; /* hook number+1 if builtin */ - unsigned int references; /* how many jumps reference us */ - int verdict; /* verdict if builtin */ - - STRUCT_COUNTERS counters; /* per-chain counters */ - struct counter_map counter_map; - - unsigned int num_rules; /* number of rules in list */ - struct list_head rules; /* list of rules */ - - unsigned int index; /* index (needed for jump resolval) */ - unsigned int head_offset; /* offset in rule blob */ - unsigned int foot_index; /* index (needed for counter_map) */ - unsigned int foot_offset; /* offset in rule blob */ -}; - -STRUCT_TC_HANDLE -{ - int changed; /* Have changes been made? */ - - struct list_head chains; - - struct chain_head *chain_iterator_cur; - struct rule_head *rule_iterator_cur; - - unsigned int num_chains; /* number of user defined chains */ - - struct chain_head **chain_index; /* array for fast chain list access*/ - unsigned int chain_index_sz;/* size of chain index array */ - - STRUCT_GETINFO info; - STRUCT_GET_ENTRIES *entries; -}; - -/* allocate a new chain head for the cache */ -static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum) -{ - struct chain_head *c = malloc(sizeof(*c)); - if (!c) - return NULL; - memset(c, 0, sizeof(*c)); - - strncpy(c->name, name, TABLE_MAXNAMELEN); - c->hooknum = hooknum; - INIT_LIST_HEAD(&c->rules); - - return c; -} - -/* allocate and initialize a new rule for the cache */ -static struct rule_head *iptcc_alloc_rule(struct chain_head *c, unsigned int size) -{ - struct rule_head *r = malloc(sizeof(*r)+size); - if (!r) - return NULL; - memset(r, 0, sizeof(*r)); - - r->chain = c; - r->size = size; - - return r; -} - -/* notify us that the ruleset has been modified by the user */ -static inline void -set_changed(TC_HANDLE_T h) -{ - h->changed = 1; -} - -#ifdef IPTC_DEBUG -static void do_check(TC_HANDLE_T h, unsigned int line); -#define CHECK(h) do { if (!getenv("IPTC_NO_CHECK")) do_check((h), __LINE__); } while(0) -#else -#define CHECK(h) -#endif - - -/********************************************************************** - * iptc blob utility functions (iptcb_*) - **********************************************************************/ - -static inline int -iptcb_get_number(const STRUCT_ENTRY *i, - const STRUCT_ENTRY *seek, - unsigned int *pos) -{ - if (i == seek) - return 1; - (*pos)++; - return 0; -} - -static inline int -iptcb_get_entry_n(STRUCT_ENTRY *i, - unsigned int number, - unsigned int *pos, - STRUCT_ENTRY **pe) -{ - if (*pos == number) { - *pe = i; - return 1; - } - (*pos)++; - return 0; -} - -static inline STRUCT_ENTRY * -iptcb_get_entry(TC_HANDLE_T h, unsigned int offset) -{ - return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset); -} - -static unsigned int -iptcb_entry2index(const TC_HANDLE_T h, const STRUCT_ENTRY *seek) -{ - unsigned int pos = 0; - - if (ENTRY_ITERATE(h->entries->entrytable, h->entries->size, - iptcb_get_number, seek, &pos) == 0) { - fprintf(stderr, "ERROR: offset %u not an entry!\n", - (unsigned int)((char *)seek - (char *)h->entries->entrytable)); - abort(); - } - return pos; -} - -static inline STRUCT_ENTRY * -iptcb_offset2entry(TC_HANDLE_T h, unsigned int offset) -{ - return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset); -} - - -static inline unsigned long -iptcb_entry2offset(const TC_HANDLE_T h, const STRUCT_ENTRY *e) -{ - return (void *)e - (void *)h->entries->entrytable; -} - -static inline unsigned int -iptcb_offset2index(const TC_HANDLE_T h, unsigned int offset) -{ - return iptcb_entry2index(h, iptcb_offset2entry(h, offset)); -} - -/* Returns 0 if not hook entry, else hooknumber + 1 */ -static inline unsigned int -iptcb_ent_is_hook_entry(STRUCT_ENTRY *e, TC_HANDLE_T h) -{ - unsigned int i; - - for (i = 0; i < NUMHOOKS; i++) { - if ((h->info.valid_hooks & (1 << i)) - && iptcb_get_entry(h, h->info.hook_entry[i]) == e) - return i+1; - } - return 0; -} - - -/********************************************************************** - * Chain index (cache utility) functions - ********************************************************************** - * The chain index is an array with pointers into the chain list, with - * CHAIN_INDEX_BUCKET_LEN spacing. This facilitates the ability to - * speedup chain list searching, by find a more optimal starting - * points when searching the linked list. - * - * The starting point can be found fast by using a binary search of - * the chain index. Thus, reducing the previous search complexity of - * O(n) to O(log(n/k) + k) where k is CHAIN_INDEX_BUCKET_LEN. - * - * A nice property of the chain index, is that the "bucket" list - * length is max CHAIN_INDEX_BUCKET_LEN (when just build, inserts will - * change this). Oppose to hashing, where the "bucket" list length can - * vary a lot. - */ -#ifndef CHAIN_INDEX_BUCKET_LEN -#define CHAIN_INDEX_BUCKET_LEN 40 -#endif - -/* Another nice property of the chain index is that inserting/creating - * chains in chain list don't change the correctness of the chain - * index, it only causes longer lists in the buckets. - * - * To mitigate the performance penalty of longer bucket lists and the - * penalty of rebuilding, the chain index is rebuild only when - * CHAIN_INDEX_INSERT_MAX chains has been added. - */ -#ifndef CHAIN_INDEX_INSERT_MAX -#define CHAIN_INDEX_INSERT_MAX 355 -#endif - -static inline unsigned int iptcc_is_builtin(struct chain_head *c); - - -/* Use binary search in the chain index array, to find a chain_head - * pointer closest to the place of the searched name element. - * - * Notes that, binary search (obviously) requires that the chain list - * is sorted by name. - */ -static struct list_head * -iptcc_bsearch_chain_index(const char *name, unsigned int *idx, TC_HANDLE_T handle) -{ - unsigned int pos, end; - int res; - - struct list_head *list_pos; - list_pos=&handle->chains; - - /* Check for empty array, e.g. no user defined chains */ - if (handle->chain_index_sz == 0) { - debug("WARNING: handle->chain_index_sz == 0\n"); - return list_pos; - } - - /* Init */ - end = handle->chain_index_sz; - pos = end / 2; - - debug("bsearch Find chain:%s (pos:%d end:%d)\n", name, pos, end); - - /* Loop */ - loop: - if (!handle->chain_index[pos]) { - fprintf(stderr, "ERROR: NULL pointer chain_index[%d]\n", pos); - return &handle->chains; /* Be safe, return orig start pos */ - } - - res = strcmp(name, handle->chain_index[pos]->name); - list_pos = &handle->chain_index[pos]->list; - *idx = pos; - - debug("bsearch Index[%d] name:%s res:%d ", - pos, handle->chain_index[pos]->name, res); - - if (res == 0) { /* Found element, by direct hit */ - debug("[found] Direct hit pos:%d end:%d\n", pos, end); - return list_pos; - } else if (res < 0) { /* Too far, jump back */ - end = pos; - pos = pos / 2; - - /* Exit case: First element of array */ - if (end == 0) { - debug("[found] Reached first array elem (end%d)\n",end); - return list_pos; - } - debug("jump back to pos:%d (end:%d)\n", pos, end); - goto loop; - } else if (res > 0 ){ /* Not far enough, jump forward */ - - /* Exit case: Last element of array */ - if (pos == handle->chain_index_sz-1) { - debug("[found] Last array elem (end:%d)\n", end); - return list_pos; - } - - /* Exit case: Next index less, thus elem in this list section */ - res = strcmp(name, handle->chain_index[pos+1]->name); - if (res < 0) { - debug("[found] closest list (end:%d)\n", end); - return list_pos; - } - - pos = (pos+end)/2; - debug("jump forward to pos:%d (end:%d)\n", pos, end); - goto loop; - } - - return list_pos; -} - -#ifdef DEBUG -/* Trivial linear search of chain index. Function used for verifying - the output of bsearch function */ -static struct list_head * -iptcc_linearly_search_chain_index(const char *name, TC_HANDLE_T handle) -{ - unsigned int i=0; - int res=0; - - struct list_head *list_pos; - list_pos = &handle->chains; - - if (handle->chain_index_sz) - list_pos = &handle->chain_index[0]->list; - - /* Linearly walk of chain index array */ - - for (i=0; i < handle->chain_index_sz; i++) { - if (handle->chain_index[i]) { - res = strcmp(handle->chain_index[i]->name, name); - if (res > 0) - break; // One step too far - list_pos = &handle->chain_index[i]->list; - if (res == 0) - break; // Direct hit - } - } - - return list_pos; -} -#endif - -static int iptcc_chain_index_alloc(TC_HANDLE_T h) -{ - unsigned int list_length = CHAIN_INDEX_BUCKET_LEN; - unsigned int array_elems; - unsigned int array_mem; - - /* Allocate memory for the chain index array */ - array_elems = (h->num_chains / list_length) + - (h->num_chains % list_length ? 1 : 0); - array_mem = sizeof(h->chain_index) * array_elems; - - debug("Alloc Chain index, elems:%d mem:%d bytes\n", - array_elems, array_mem); - - h->chain_index = malloc(array_mem); - if (!h->chain_index) { - h->chain_index_sz = 0; - return -ENOMEM; - } - memset(h->chain_index, 0, array_mem); - h->chain_index_sz = array_elems; - - return 1; -} - -static void iptcc_chain_index_free(TC_HANDLE_T h) -{ - h->chain_index_sz = 0; - free(h->chain_index); -} - - -#ifdef DEBUG -static void iptcc_chain_index_dump(TC_HANDLE_T h) -{ - unsigned int i = 0; - - /* Dump: contents of chain index array */ - for (i=0; i < h->chain_index_sz; i++) { - if (h->chain_index[i]) { - fprintf(stderr, "Chain index[%d].name: %s\n", - i, h->chain_index[i]->name); - } - } -} -#endif - -/* Build the chain index */ -static int iptcc_chain_index_build(TC_HANDLE_T h) -{ - unsigned int list_length = CHAIN_INDEX_BUCKET_LEN; - unsigned int chains = 0; - unsigned int cindex = 0; - struct chain_head *c; - - /* Build up the chain index array here */ - debug("Building chain index\n"); - - debug("Number of user defined chains:%d bucket_sz:%d array_sz:%d\n", - h->num_chains, list_length, h->chain_index_sz); - - if (h->chain_index_sz == 0) - return 0; - - list_for_each_entry(c, &h->chains, list) { - - /* Issue: The index array needs to start after the - * builtin chains, as they are not sorted */ - if (!iptcc_is_builtin(c)) { - cindex=chains / list_length; - - /* Safe guard, break out on array limit, this - * is useful if chains are added and array is - * rebuild, without realloc of memory. */ - if (cindex >= h->chain_index_sz) - break; - - if ((chains % list_length)== 0) { - debug("\nIndex[%d] Chains:", cindex); - h->chain_index[cindex] = c; - } - chains++; - } - debug("%s, ", c->name); - } - debug("\n"); - - return 1; -} - -static int iptcc_chain_index_rebuild(TC_HANDLE_T h) -{ - debug("REBUILD chain index array\n"); - iptcc_chain_index_free(h); - if ((iptcc_chain_index_alloc(h)) < 0) - return -ENOMEM; - iptcc_chain_index_build(h); - return 1; -} - -/* Delete chain (pointer) from index array. Removing an element from - * the chain list only affects the chain index array, if the chain - * index points-to/uses that list pointer. - * - * There are different strategies, the simple and safe is to rebuild - * the chain index every time. The more advanced is to update the - * array index to point to the next element, but that requires some - * house keeping and boundry checks. The advanced is implemented, as - * the simple approach behaves badly when all chains are deleted - * because list_for_each processing will always hit the first chain - * index, thus causing a rebuild for every chain. - */ -static int iptcc_chain_index_delete_chain(struct chain_head *c, TC_HANDLE_T h) -{ - struct list_head *index_ptr, *next; - struct chain_head *c2; - unsigned int idx, idx2; - - index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h); - - debug("Del chain[%s] c->list:%p index_ptr:%p\n", - c->name, &c->list, index_ptr); - - /* Save the next pointer */ - next = c->list.next; - list_del(&c->list); - - if (index_ptr == &c->list) { /* Chain used as index ptr */ - - /* See if its possible to avoid a rebuild, by shifting - * to next pointer. Its possible if the next pointer - * is located in the same index bucket. - */ - c2 = list_entry(next, struct chain_head, list); - iptcc_bsearch_chain_index(c2->name, &idx2, h); - if (idx != idx2) { - /* Rebuild needed */ - return iptcc_chain_index_rebuild(h); - } else { - /* Avoiding rebuild */ - debug("Update cindex[%d] with next ptr name:[%s]\n", - idx, c2->name); - h->chain_index[idx]=c2; - return 0; - } - } - return 0; -} - - -/********************************************************************** - * iptc cache utility functions (iptcc_*) - **********************************************************************/ - -/* Is the given chain builtin (1) or user-defined (0) */ -static inline unsigned int iptcc_is_builtin(struct chain_head *c) -{ - return (c->hooknum ? 1 : 0); -} - -/* Get a specific rule within a chain */ -static struct rule_head *iptcc_get_rule_num(struct chain_head *c, - unsigned int rulenum) -{ - struct rule_head *r; - unsigned int num = 0; - - list_for_each_entry(r, &c->rules, list) { - num++; - if (num == rulenum) - return r; - } - return NULL; -} - -/* Get a specific rule within a chain backwards */ -static struct rule_head *iptcc_get_rule_num_reverse(struct chain_head *c, - unsigned int rulenum) -{ - struct rule_head *r; - unsigned int num = 0; - - list_for_each_entry_reverse(r, &c->rules, list) { - num++; - if (num == rulenum) - return r; - } - return NULL; -} - -/* Returns chain head if found, otherwise NULL. */ -static struct chain_head * -iptcc_find_chain_by_offset(TC_HANDLE_T handle, unsigned int offset) -{ - struct list_head *pos; - - if (list_empty(&handle->chains)) - return NULL; - - list_for_each(pos, &handle->chains) { - struct chain_head *c = list_entry(pos, struct chain_head, list); - if (offset >= c->head_offset && offset <= c->foot_offset) - return c; - } - - return NULL; -} - -/* Returns chain head if found, otherwise NULL. */ -static struct chain_head * -iptcc_find_label(const char *name, TC_HANDLE_T handle) -{ - struct list_head *pos; - struct list_head *list_start_pos; - unsigned int i=0; - int res; - - if (list_empty(&handle->chains)) - return NULL; - - /* First look at builtin chains */ - list_for_each(pos, &handle->chains) { - struct chain_head *c = list_entry(pos, struct chain_head, list); - if (!iptcc_is_builtin(c)) - break; - if (!strcmp(c->name, name)) - return c; - } - - /* Find a smart place to start the search via chain index */ - //list_start_pos = iptcc_linearly_search_chain_index(name, handle); - list_start_pos = iptcc_bsearch_chain_index(name, &i, handle); - - /* Handel if bsearch bails out early */ - if (list_start_pos == &handle->chains) { - list_start_pos = pos; - } -#ifdef DEBUG - else { - /* Verify result of bsearch against linearly index search */ - struct list_head *test_pos; - struct chain_head *test_c, *tmp_c; - test_pos = iptcc_linearly_search_chain_index(name, handle); - if (list_start_pos != test_pos) { - debug("BUG in chain_index search\n"); - test_c=list_entry(test_pos, struct chain_head,list); - tmp_c =list_entry(list_start_pos,struct chain_head,list); - debug("Verify search found:\n"); - debug(" Chain:%s\n", test_c->name); - debug("BSearch found:\n"); - debug(" Chain:%s\n", tmp_c->name); - exit(42); - } - } -#endif - - /* Initial/special case, no user defined chains */ - if (handle->num_chains == 0) - return NULL; - - /* Start searching through the chain list */ - list_for_each(pos, list_start_pos->prev) { - struct chain_head *c = list_entry(pos, struct chain_head, list); - res = strcmp(c->name, name); - debug("List search name:%s == %s res:%d\n", name, c->name, res); - if (res==0) - return c; - - /* We can stop earlier as we know list is sorted */ - if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/ - debug(" Not in list, walked too far, sorted list\n"); - return NULL; - } - - /* Stop on wrap around, if list head is reached */ - if (pos == &handle->chains) { - debug("Stop, list head reached\n"); - return NULL; - } - } - - debug("List search NOT found name:%s\n", name); - return NULL; -} - -/* called when rule is to be removed from cache */ -static void iptcc_delete_rule(struct rule_head *r) -{ - DEBUGP("deleting rule %p (offset %u)\n", r, r->offset); - /* clean up reference count of called chain */ - if (r->type == IPTCC_R_JUMP - && r->jump) - r->jump->references--; - - list_del(&r->list); - free(r); -} - - -/********************************************************************** - * RULESET PARSER (blob -> cache) - **********************************************************************/ - -/* Delete policy rule of previous chain, since cache doesn't contain - * chain policy rules. - * WARNING: This function has ugly design and relies on a lot of context, only - * to be called from specific places within the parser */ -static int __iptcc_p_del_policy(TC_HANDLE_T h, unsigned int num) -{ - const unsigned char *data; - - if (h->chain_iterator_cur) { - /* policy rule is last rule */ - struct rule_head *pr = (struct rule_head *) - h->chain_iterator_cur->rules.prev; - - /* save verdict */ - data = GET_TARGET(pr->entry)->data; - h->chain_iterator_cur->verdict = *(const int *)data; - - /* save counter and counter_map information */ - h->chain_iterator_cur->counter_map.maptype = - COUNTER_MAP_NORMAL_MAP; - h->chain_iterator_cur->counter_map.mappos = num-1; - memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters, - sizeof(h->chain_iterator_cur->counters)); - - /* foot_offset points to verdict rule */ - h->chain_iterator_cur->foot_index = num; - h->chain_iterator_cur->foot_offset = pr->offset; - - /* delete rule from cache */ - iptcc_delete_rule(pr); - h->chain_iterator_cur->num_rules--; - - return 1; - } - return 0; -} - -/* alphabetically insert a chain into the list */ -static inline void iptc_insert_chain(TC_HANDLE_T h, struct chain_head *c) -{ - struct chain_head *tmp; - struct list_head *list_start_pos; - unsigned int i=1; - - /* Find a smart place to start the insert search */ - list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h); - - /* Handle the case, where chain.name is smaller than index[0] */ - if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) { - h->chain_index[0] = c; /* Update chain index head */ - list_start_pos = h->chains.next; - debug("Update chain_index[0] with %s\n", c->name); - } - - /* Handel if bsearch bails out early */ - if (list_start_pos == &h->chains) { - list_start_pos = h->chains.next; - } - - /* sort only user defined chains */ - if (!c->hooknum) { - list_for_each_entry(tmp, list_start_pos->prev, list) { - if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) { - list_add(&c->list, tmp->list.prev); - return; - } - - /* Stop if list head is reached */ - if (&tmp->list == &h->chains) { - debug("Insert, list head reached add to tail\n"); - break; - } - } - } - - /* survived till end of list: add at tail */ - list_add_tail(&c->list, &h->chains); -} - -/* Another ugly helper function split out of cache_add_entry to make it less - * spaghetti code */ -static void __iptcc_p_add_chain(TC_HANDLE_T h, struct chain_head *c, - unsigned int offset, unsigned int *num) -{ - struct list_head *tail = h->chains.prev; - struct chain_head *ctail; - - __iptcc_p_del_policy(h, *num); - - c->head_offset = offset; - c->index = *num; - - /* Chains from kernel are already sorted, as they are inserted - * sorted. But there exists an issue when shifting to 1.4.0 - * from an older version, as old versions allow last created - * chain to be unsorted. - */ - if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/ - list_add_tail(&c->list, &h->chains); - else { - ctail = list_entry(tail, struct chain_head, list); - if (strcmp(c->name, ctail->name) > 0) - list_add_tail(&c->list, &h->chains);/* Already sorted*/ - else - iptc_insert_chain(h, c);/* Was not sorted */ - } - - h->chain_iterator_cur = c; -} - -/* main parser function: add an entry from the blob to the cache */ -static int cache_add_entry(STRUCT_ENTRY *e, - TC_HANDLE_T h, - STRUCT_ENTRY **prev, - unsigned int *num) -{ - unsigned int builtin; - unsigned int offset = (char *)e - (char *)h->entries->entrytable; - - DEBUGP("entering..."); - - /* Last entry ("policy rule"). End it.*/ - if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) { - /* This is the ERROR node at the end of the chain */ - DEBUGP_C("%u:%u: end of table:\n", *num, offset); - - __iptcc_p_del_policy(h, *num); - - h->chain_iterator_cur = NULL; - goto out_inc; - } - - /* We know this is the start of a new chain if it's an ERROR - * target, or a hook entry point */ - - if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) { - struct chain_head *c = - iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0); - DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset, - (char *)c->name, c); - if (!c) { - errno = -ENOMEM; - return -1; - } - h->num_chains++; /* New user defined chain */ - - __iptcc_p_add_chain(h, c, offset, num); - - } else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) { - struct chain_head *c = - iptcc_alloc_chain_head((char *)hooknames[builtin-1], - builtin); - DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n", - *num, offset, c, &c->rules); - if (!c) { - errno = -ENOMEM; - return -1; - } - - c->hooknum = builtin; - - __iptcc_p_add_chain(h, c, offset, num); - - /* FIXME: this is ugly. */ - goto new_rule; - } else { - /* has to be normal rule */ - struct rule_head *r; -new_rule: - - if (!(r = iptcc_alloc_rule(h->chain_iterator_cur, - e->next_offset))) { - errno = ENOMEM; - return -1; - } - DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r); - - r->index = *num; - r->offset = offset; - memcpy(r->entry, e, e->next_offset); - r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP; - r->counter_map.mappos = r->index; - - /* handling of jumps, etc. */ - if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) { - STRUCT_STANDARD_TARGET *t; - - t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); - if (t->target.u.target_size - != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) { - errno = EINVAL; - return -1; - } - - if (t->verdict < 0) { - DEBUGP_C("standard, verdict=%d\n", t->verdict); - r->type = IPTCC_R_STANDARD; - } else if (t->verdict == r->offset+e->next_offset) { - DEBUGP_C("fallthrough\n"); - r->type = IPTCC_R_FALLTHROUGH; - } else { - DEBUGP_C("jump, target=%u\n", t->verdict); - r->type = IPTCC_R_JUMP; - /* Jump target fixup has to be deferred - * until second pass, since we migh not - * yet have parsed the target */ - } - } else { - DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name); - r->type = IPTCC_R_MODULE; - } - - list_add_tail(&r->list, &h->chain_iterator_cur->rules); - h->chain_iterator_cur->num_rules++; - } -out_inc: - (*num)++; - return 0; -} - - -/* parse an iptables blob into it's pieces */ -static int parse_table(TC_HANDLE_T h) -{ - STRUCT_ENTRY *prev; - unsigned int num = 0; - struct chain_head *c; - - /* First pass: over ruleset blob */ - ENTRY_ITERATE(h->entries->entrytable, h->entries->size, - cache_add_entry, h, &prev, &num); - - /* Build the chain index, used for chain list search speedup */ - if ((iptcc_chain_index_alloc(h)) < 0) - return -ENOMEM; - iptcc_chain_index_build(h); - - /* Second pass: fixup parsed data from first pass */ - list_for_each_entry(c, &h->chains, list) { - struct rule_head *r; - list_for_each_entry(r, &c->rules, list) { - struct chain_head *lc; - STRUCT_STANDARD_TARGET *t; - - if (r->type != IPTCC_R_JUMP) - continue; - - t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); - lc = iptcc_find_chain_by_offset(h, t->verdict); - if (!lc) - return -1; - r->jump = lc; - lc->references++; - } - } - - /* FIXME: sort chains */ - - return 1; -} - - -/********************************************************************** - * RULESET COMPILATION (cache -> blob) - **********************************************************************/ - -/* Convenience structures */ -struct iptcb_chain_start{ - STRUCT_ENTRY e; - struct ipt_error_target name; -}; -#define IPTCB_CHAIN_START_SIZE (sizeof(STRUCT_ENTRY) + \ - ALIGN(sizeof(struct ipt_error_target))) - -struct iptcb_chain_foot { - STRUCT_ENTRY e; - STRUCT_STANDARD_TARGET target; -}; -#define IPTCB_CHAIN_FOOT_SIZE (sizeof(STRUCT_ENTRY) + \ - ALIGN(sizeof(STRUCT_STANDARD_TARGET))) - -struct iptcb_chain_error { - STRUCT_ENTRY entry; - struct ipt_error_target target; -}; -#define IPTCB_CHAIN_ERROR_SIZE (sizeof(STRUCT_ENTRY) + \ - ALIGN(sizeof(struct ipt_error_target))) - - - -/* compile rule from cache into blob */ -static inline int iptcc_compile_rule (TC_HANDLE_T h, STRUCT_REPLACE *repl, struct rule_head *r) -{ - /* handle jumps */ - if (r->type == IPTCC_R_JUMP) { - STRUCT_STANDARD_TARGET *t; - t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); - /* memset for memcmp convenience on delete/replace */ - memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN); - strcpy(t->target.u.user.name, STANDARD_TARGET); - /* Jumps can only happen to builtin chains, so we - * can safely assume that they always have a header */ - t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE; - } else if (r->type == IPTCC_R_FALLTHROUGH) { - STRUCT_STANDARD_TARGET *t; - t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); - t->verdict = r->offset + r->size; - } - - /* copy entry from cache to blob */ - memcpy((char *)repl->entries+r->offset, r->entry, r->size); - - return 1; -} - -/* compile chain from cache into blob */ -static int iptcc_compile_chain(TC_HANDLE_T h, STRUCT_REPLACE *repl, struct chain_head *c) -{ - int ret; - struct rule_head *r; - struct iptcb_chain_start *head; - struct iptcb_chain_foot *foot; - - /* only user-defined chains have heaer */ - if (!iptcc_is_builtin(c)) { - /* put chain header in place */ - head = (void *)repl->entries + c->head_offset; - head->e.target_offset = sizeof(STRUCT_ENTRY); - head->e.next_offset = IPTCB_CHAIN_START_SIZE; - strcpy(head->name.t.u.user.name, ERROR_TARGET); - head->name.t.u.target_size = - ALIGN(sizeof(struct ipt_error_target)); - strcpy(head->name.error, c->name); - } else { - repl->hook_entry[c->hooknum-1] = c->head_offset; - repl->underflow[c->hooknum-1] = c->foot_offset; - } - - /* iterate over rules */ - list_for_each_entry(r, &c->rules, list) { - ret = iptcc_compile_rule(h, repl, r); - if (ret < 0) - return ret; - } - - /* put chain footer in place */ - foot = (void *)repl->entries + c->foot_offset; - foot->e.target_offset = sizeof(STRUCT_ENTRY); - foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE; - strcpy(foot->target.target.u.user.name, STANDARD_TARGET); - foot->target.target.u.target_size = - ALIGN(sizeof(STRUCT_STANDARD_TARGET)); - /* builtin targets have verdict, others return */ - if (iptcc_is_builtin(c)) - foot->target.verdict = c->verdict; - else - foot->target.verdict = RETURN; - /* set policy-counters */ - memcpy(&foot->e.counters, &c->counters, sizeof(STRUCT_COUNTERS)); - - return 0; -} - -/* calculate offset and number for every rule in the cache */ -static int iptcc_compile_chain_offsets(TC_HANDLE_T h, struct chain_head *c, - unsigned int *offset, unsigned int *num) -{ - struct rule_head *r; - - c->head_offset = *offset; - DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset); - - if (!iptcc_is_builtin(c)) { - /* Chain has header */ - *offset += sizeof(STRUCT_ENTRY) - + ALIGN(sizeof(struct ipt_error_target)); - (*num)++; - } - - list_for_each_entry(r, &c->rules, list) { - DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num); - r->offset = *offset; - r->index = *num; - *offset += r->size; - (*num)++; - } - - DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num, - *offset, *num); - c->foot_offset = *offset; - c->foot_index = *num; - *offset += sizeof(STRUCT_ENTRY) - + ALIGN(sizeof(STRUCT_STANDARD_TARGET)); - (*num)++; - - return 1; -} - -/* put the pieces back together again */ -static int iptcc_compile_table_prep(TC_HANDLE_T h, unsigned int *size) -{ - struct chain_head *c; - unsigned int offset = 0, num = 0; - int ret = 0; - - /* First pass: calculate offset for every rule */ - list_for_each_entry(c, &h->chains, list) { - ret = iptcc_compile_chain_offsets(h, c, &offset, &num); - if (ret < 0) - return ret; - } - - /* Append one error rule at end of chain */ - num++; - offset += sizeof(STRUCT_ENTRY) - + ALIGN(sizeof(struct ipt_error_target)); - - /* ruleset size is now in offset */ - *size = offset; - return num; -} - -static int iptcc_compile_table(TC_HANDLE_T h, STRUCT_REPLACE *repl) -{ - struct chain_head *c; - struct iptcb_chain_error *error; - - /* Second pass: copy from cache to offsets, fill in jumps */ - list_for_each_entry(c, &h->chains, list) { - int ret = iptcc_compile_chain(h, repl, c); - if (ret < 0) - return ret; - } - - /* Append error rule at end of chain */ - error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE; - error->entry.target_offset = sizeof(STRUCT_ENTRY); - error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE; - error->target.t.u.user.target_size = - ALIGN(sizeof(struct ipt_error_target)); - strcpy((char *)&error->target.t.u.user.name, ERROR_TARGET); - strcpy((char *)&error->target.error, "ERROR"); - - return 1; -} - -/********************************************************************** - * EXTERNAL API (operates on cache only) - **********************************************************************/ - -/* Allocate handle of given size */ -static TC_HANDLE_T -alloc_handle(const char *tablename, unsigned int size, unsigned int num_rules) -{ - TC_HANDLE_T h; - - - h = malloc(sizeof(STRUCT_TC_HANDLE)); - if (!h) { - errno = ENOMEM; - return NULL; - } - memset(h, 0, sizeof(*h)); - INIT_LIST_HEAD(&h->chains); - strcpy(h->info.name, tablename); - - h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + size); - if (!h->entries) - goto out_free_handle; - - strcpy(h->entries->name, tablename); - h->entries->size = size; - - return h; - -out_free_handle: - free(h); - - return NULL; -} - - -TC_HANDLE_T -TC_INIT(const char *tablename) -{ - TC_HANDLE_T h; - STRUCT_GETINFO info; - unsigned int tmp; - socklen_t s; - - iptc_fn = TC_INIT; - - if (strlen(tablename) >= TABLE_MAXNAMELEN) { - errno = EINVAL; - return NULL; - } - - if (sockfd_use == 0) { - sockfd = socket(TC_AF, SOCK_RAW, IPPROTO_RAW); - if (sockfd < 0) - return NULL; - } - sockfd_use++; -retry: - s = sizeof(info); - - strcpy(info.name, tablename); - if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) { - if (--sockfd_use == 0) { - close(sockfd); - sockfd = -1; - } - return NULL; - } - - DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n", - info.valid_hooks, info.num_entries, info.size); - - if ((h = alloc_handle(info.name, info.size, info.num_entries)) - == NULL) { - if (--sockfd_use == 0) { - close(sockfd); - sockfd = -1; - } - return NULL; - } - - /* Initialize current state */ - h->info = info; - - h->entries->size = h->info.size; - - tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size; - - if (getsockopt(sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries, - &tmp) < 0) - goto error; - -#ifdef IPTC_DEBUG2 - { - int fd = open("/tmp/libiptc-so_get_entries.blob", - O_CREAT|O_WRONLY); - if (fd >= 0) { - write(fd, h->entries, tmp); - close(fd); - } - } -#endif - - if (parse_table(h) < 0) - goto error; - - CHECK(h); - return h; -error: - TC_FREE(&h); - /* A different process changed the ruleset size, retry */ - if (errno == EAGAIN) - goto retry; - return NULL; -} - -void -TC_FREE(TC_HANDLE_T *h) -{ - struct chain_head *c, *tmp; - - iptc_fn = TC_FREE; - if (--sockfd_use == 0) { - close(sockfd); - sockfd = -1; - } - - list_for_each_entry_safe(c, tmp, &(*h)->chains, list) { - struct rule_head *r, *rtmp; - - list_for_each_entry_safe(r, rtmp, &c->rules, list) { - free(r); - } - - free(c); - } - - iptcc_chain_index_free(*h); - - free((*h)->entries); - free(*h); - - *h = NULL; -} - -static inline int -print_match(const STRUCT_ENTRY_MATCH *m) -{ - printf("Match name: `%s'\n", m->u.user.name); - return 0; -} - -static int dump_entry(STRUCT_ENTRY *e, const TC_HANDLE_T handle); - -void -TC_DUMP_ENTRIES(const TC_HANDLE_T handle) -{ - iptc_fn = TC_DUMP_ENTRIES; - CHECK(handle); - - printf("libiptc v%s. %u bytes.\n", - XTABLES_VERSION, handle->entries->size); - printf("Table `%s'\n", handle->info.name); - printf("Hooks: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n", - handle->info.hook_entry[HOOK_PRE_ROUTING], - handle->info.hook_entry[HOOK_LOCAL_IN], - handle->info.hook_entry[HOOK_FORWARD], - handle->info.hook_entry[HOOK_LOCAL_OUT], - handle->info.hook_entry[HOOK_POST_ROUTING]); - printf("Underflows: pre/in/fwd/out/post = %u/%u/%u/%u/%u\n", - handle->info.underflow[HOOK_PRE_ROUTING], - handle->info.underflow[HOOK_LOCAL_IN], - handle->info.underflow[HOOK_FORWARD], - handle->info.underflow[HOOK_LOCAL_OUT], - handle->info.underflow[HOOK_POST_ROUTING]); - - ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size, - dump_entry, handle); -} - -/* Does this chain exist? */ -int TC_IS_CHAIN(const char *chain, const TC_HANDLE_T handle) -{ - iptc_fn = TC_IS_CHAIN; - return iptcc_find_label(chain, handle) != NULL; -} - -static void iptcc_chain_iterator_advance(TC_HANDLE_T handle) -{ - struct chain_head *c = handle->chain_iterator_cur; - - if (c->list.next == &handle->chains) - handle->chain_iterator_cur = NULL; - else - handle->chain_iterator_cur = - list_entry(c->list.next, struct chain_head, list); -} - -/* Iterator functions to run through the chains. */ -const char * -TC_FIRST_CHAIN(TC_HANDLE_T *handle) -{ - struct chain_head *c = list_entry((*handle)->chains.next, - struct chain_head, list); - - iptc_fn = TC_FIRST_CHAIN; - - - if (list_empty(&(*handle)->chains)) { - DEBUGP(": no chains\n"); - return NULL; - } - - (*handle)->chain_iterator_cur = c; - iptcc_chain_iterator_advance(*handle); - - DEBUGP(": returning `%s'\n", c->name); - return c->name; -} - -/* Iterator functions to run through the chains. Returns NULL at end. */ -const char * -TC_NEXT_CHAIN(TC_HANDLE_T *handle) -{ - struct chain_head *c = (*handle)->chain_iterator_cur; - - iptc_fn = TC_NEXT_CHAIN; - - if (!c) { - DEBUGP(": no more chains\n"); - return NULL; - } - - iptcc_chain_iterator_advance(*handle); - - DEBUGP(": returning `%s'\n", c->name); - return c->name; -} - -/* Get first rule in the given chain: NULL for empty chain. */ -const STRUCT_ENTRY * -TC_FIRST_RULE(const char *chain, TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - - iptc_fn = TC_FIRST_RULE; - - DEBUGP("first rule(%s): ", chain); - - c = iptcc_find_label(chain, *handle); - if (!c) { - errno = ENOENT; - return NULL; - } - - /* Empty chain: single return/policy rule */ - if (list_empty(&c->rules)) { - DEBUGP_C("no rules, returning NULL\n"); - return NULL; - } - - r = list_entry(c->rules.next, struct rule_head, list); - (*handle)->rule_iterator_cur = r; - DEBUGP_C("%p\n", r); - - return r->entry; -} - -/* Returns NULL when rules run out. */ -const STRUCT_ENTRY * -TC_NEXT_RULE(const STRUCT_ENTRY *prev, TC_HANDLE_T *handle) -{ - struct rule_head *r; - - iptc_fn = TC_NEXT_RULE; - DEBUGP("rule_iterator_cur=%p...", (*handle)->rule_iterator_cur); - - if (!(*handle)->rule_iterator_cur) { - DEBUGP_C("returning NULL\n"); - return NULL; - } - - r = list_entry((*handle)->rule_iterator_cur->list.next, - struct rule_head, list); - - iptc_fn = TC_NEXT_RULE; - - DEBUGP_C("next=%p, head=%p...", &r->list, - &(*handle)->rule_iterator_cur->chain->rules); - - if (&r->list == &(*handle)->rule_iterator_cur->chain->rules) { - (*handle)->rule_iterator_cur = NULL; - DEBUGP_C("finished, returning NULL\n"); - return NULL; - } - - (*handle)->rule_iterator_cur = r; - - /* NOTE: prev is without any influence ! */ - DEBUGP_C("returning rule %p\n", r); - return r->entry; -} - -/* How many rules in this chain? */ -#if 0 -static unsigned int -TC_NUM_RULES(const char *chain, TC_HANDLE_T *handle) -{ - struct chain_head *c; - iptc_fn = TC_NUM_RULES; - CHECK(*handle); - - c = iptcc_find_label(chain, *handle); - if (!c) { - errno = ENOENT; - return (unsigned int)-1; - } - - return c->num_rules; -} -#endif - -#if 0 -static const STRUCT_ENTRY * -TC_GET_RULE(const char *chain, unsigned int n, TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - - iptc_fn = TC_GET_RULE; - - CHECK(*handle); - - c = iptcc_find_label(chain, *handle); - if (!c) { - errno = ENOENT; - return NULL; - } - - r = iptcc_get_rule_num(c, n); - if (!r) - return NULL; - return r->entry; -} -#endif - -/* Returns a pointer to the target name of this position. */ -static const char *standard_target_map(int verdict) -{ - switch (verdict) { - case RETURN: - return LABEL_RETURN; - break; - case -NF_ACCEPT-1: - return LABEL_ACCEPT; - break; - case -NF_DROP-1: - return LABEL_DROP; - break; - case -NF_QUEUE-1: - return LABEL_QUEUE; - break; - default: - fprintf(stderr, "ERROR: %d not a valid target)\n", - verdict); - abort(); - break; - } - /* not reached */ - return NULL; -} - -/* Returns a pointer to the target name of this position. */ -const char *TC_GET_TARGET(const STRUCT_ENTRY *ce, - TC_HANDLE_T *handle) -{ - STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce; - struct rule_head *r = container_of(e, struct rule_head, entry[0]); - const unsigned char *data; - - iptc_fn = TC_GET_TARGET; - - switch(r->type) { - int spos; - case IPTCC_R_FALLTHROUGH: - return ""; - break; - case IPTCC_R_JUMP: - DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name); - return r->jump->name; - break; - case IPTCC_R_STANDARD: - data = GET_TARGET(e)->data; - spos = *(const int *)data; - DEBUGP("r=%p, spos=%d'\n", r, spos); - return standard_target_map(spos); - break; - case IPTCC_R_MODULE: - return GET_TARGET(e)->u.user.name; - break; - } - return NULL; -} -/* Is this a built-in chain? Actually returns hook + 1. */ -int -TC_BUILTIN(const char *chain, const TC_HANDLE_T handle) -{ - struct chain_head *c; - - iptc_fn = TC_BUILTIN; - - c = iptcc_find_label(chain, handle); - if (!c) { - errno = ENOENT; - return 0; - } - - return iptcc_is_builtin(c); -} - -/* Get the policy of a given built-in chain */ -const char * -TC_GET_POLICY(const char *chain, - STRUCT_COUNTERS *counters, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - - iptc_fn = TC_GET_POLICY; - - DEBUGP("called for chain %s\n", chain); - - c = iptcc_find_label(chain, *handle); - if (!c) { - errno = ENOENT; - return NULL; - } - - if (!iptcc_is_builtin(c)) - return NULL; - - *counters = c->counters; - - return standard_target_map(c->verdict); -} - -static int -iptcc_standard_map(struct rule_head *r, int verdict) -{ - STRUCT_ENTRY *e = r->entry; - STRUCT_STANDARD_TARGET *t; - - t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); - - if (t->target.u.target_size - != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) { - errno = EINVAL; - return 0; - } - /* memset for memcmp convenience on delete/replace */ - memset(t->target.u.user.name, 0, FUNCTION_MAXNAMELEN); - strcpy(t->target.u.user.name, STANDARD_TARGET); - t->verdict = verdict; - - r->type = IPTCC_R_STANDARD; - - return 1; -} - -static int -iptcc_map_target(const TC_HANDLE_T handle, - struct rule_head *r) -{ - STRUCT_ENTRY *e = r->entry; - STRUCT_ENTRY_TARGET *t = GET_TARGET(e); - - /* Maybe it's empty (=> fall through) */ - if (strcmp(t->u.user.name, "") == 0) { - r->type = IPTCC_R_FALLTHROUGH; - return 1; - } - /* Maybe it's a standard target name... */ - else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0) - return iptcc_standard_map(r, -NF_ACCEPT - 1); - else if (strcmp(t->u.user.name, LABEL_DROP) == 0) - return iptcc_standard_map(r, -NF_DROP - 1); - else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0) - return iptcc_standard_map(r, -NF_QUEUE - 1); - else if (strcmp(t->u.user.name, LABEL_RETURN) == 0) - return iptcc_standard_map(r, RETURN); - else if (TC_BUILTIN(t->u.user.name, handle)) { - /* Can't jump to builtins. */ - errno = EINVAL; - return 0; - } else { - /* Maybe it's an existing chain name. */ - struct chain_head *c; - DEBUGP("trying to find chain `%s': ", t->u.user.name); - - c = iptcc_find_label(t->u.user.name, handle); - if (c) { - DEBUGP_C("found!\n"); - r->type = IPTCC_R_JUMP; - r->jump = c; - c->references++; - return 1; - } - DEBUGP_C("not found :(\n"); - } - - /* Must be a module? If not, kernel will reject... */ - /* memset to all 0 for your memcmp convenience: don't clear version */ - memset(t->u.user.name + strlen(t->u.user.name), - 0, - FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name)); - r->type = IPTCC_R_MODULE; - set_changed(handle); - return 1; -} - -/* Insert the entry `fw' in chain `chain' into position `rulenum'. */ -int -TC_INSERT_ENTRY(const IPT_CHAINLABEL chain, - const STRUCT_ENTRY *e, - unsigned int rulenum, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - struct list_head *prev; - - iptc_fn = TC_INSERT_ENTRY; - - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - /* first rulenum index = 0 - first c->num_rules index = 1 */ - if (rulenum > c->num_rules) { - errno = E2BIG; - return 0; - } - - /* If we are inserting at the end just take advantage of the - double linked list, insert will happen before the entry - prev points to. */ - if (rulenum == c->num_rules) { - prev = &c->rules; - } else if (rulenum + 1 <= c->num_rules/2) { - r = iptcc_get_rule_num(c, rulenum + 1); - prev = &r->list; - } else { - r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); - prev = &r->list; - } - - if (!(r = iptcc_alloc_rule(c, e->next_offset))) { - errno = ENOMEM; - return 0; - } - - memcpy(r->entry, e, e->next_offset); - r->counter_map.maptype = COUNTER_MAP_SET; - - if (!iptcc_map_target(*handle, r)) { - free(r); - return 0; - } - - list_add_tail(&r->list, prev); - c->num_rules++; - - set_changed(*handle); - - return 1; -} - -/* Atomically replace rule `rulenum' in `chain' with `fw'. */ -int -TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain, - const STRUCT_ENTRY *e, - unsigned int rulenum, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r, *old; - - iptc_fn = TC_REPLACE_ENTRY; - - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - if (rulenum >= c->num_rules) { - errno = E2BIG; - return 0; - } - - /* Take advantage of the double linked list if possible. */ - if (rulenum + 1 <= c->num_rules/2) { - old = iptcc_get_rule_num(c, rulenum + 1); - } else { - old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); - } - - if (!(r = iptcc_alloc_rule(c, e->next_offset))) { - errno = ENOMEM; - return 0; - } - - memcpy(r->entry, e, e->next_offset); - r->counter_map.maptype = COUNTER_MAP_SET; - - if (!iptcc_map_target(*handle, r)) { - free(r); - return 0; - } - - list_add(&r->list, &old->list); - iptcc_delete_rule(old); - - set_changed(*handle); - - return 1; -} - -/* Append entry `fw' to chain `chain'. Equivalent to insert with - rulenum = length of chain. */ -int -TC_APPEND_ENTRY(const IPT_CHAINLABEL chain, - const STRUCT_ENTRY *e, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - - iptc_fn = TC_APPEND_ENTRY; - if (!(c = iptcc_find_label(chain, *handle))) { - DEBUGP("unable to find chain `%s'\n", chain); - errno = ENOENT; - return 0; - } - - if (!(r = iptcc_alloc_rule(c, e->next_offset))) { - DEBUGP("unable to allocate rule for chain `%s'\n", chain); - errno = ENOMEM; - return 0; - } - - memcpy(r->entry, e, e->next_offset); - r->counter_map.maptype = COUNTER_MAP_SET; - - if (!iptcc_map_target(*handle, r)) { - DEBUGP("unable to map target of rule for chain `%s'\n", chain); - free(r); - return 0; - } - - list_add_tail(&r->list, &c->rules); - c->num_rules++; - - set_changed(*handle); - - return 1; -} - -static inline int -match_different(const STRUCT_ENTRY_MATCH *a, - const unsigned char *a_elems, - const unsigned char *b_elems, - unsigned char **maskptr) -{ - const STRUCT_ENTRY_MATCH *b; - unsigned int i; - - /* Offset of b is the same as a. */ - b = (void *)b_elems + ((unsigned char *)a - a_elems); - - if (a->u.match_size != b->u.match_size) - return 1; - - if (strcmp(a->u.user.name, b->u.user.name) != 0) - return 1; - - *maskptr += ALIGN(sizeof(*a)); - - for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++) - if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0) - return 1; - *maskptr += i; - return 0; -} - -static inline int -target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask) -{ - unsigned int i; - STRUCT_ENTRY_TARGET *ta, *tb; - - if (a->type != b->type) - return 0; - - ta = GET_TARGET(a->entry); - tb = GET_TARGET(b->entry); - - switch (a->type) { - case IPTCC_R_FALLTHROUGH: - return 1; - case IPTCC_R_JUMP: - return a->jump == b->jump; - case IPTCC_R_STANDARD: - return ((STRUCT_STANDARD_TARGET *)ta)->verdict - == ((STRUCT_STANDARD_TARGET *)tb)->verdict; - case IPTCC_R_MODULE: - if (ta->u.target_size != tb->u.target_size) - return 0; - if (strcmp(ta->u.user.name, tb->u.user.name) != 0) - return 0; - - for (i = 0; i < ta->u.target_size - sizeof(*ta); i++) - if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0) - return 0; - return 1; - default: - fprintf(stderr, "ERROR: bad type %i\n", a->type); - abort(); - } -} - -static unsigned char * -is_same(const STRUCT_ENTRY *a, - const STRUCT_ENTRY *b, - unsigned char *matchmask); - -/* Delete the first rule in `chain' which matches `fw'. */ -int -TC_DELETE_ENTRY(const IPT_CHAINLABEL chain, - const STRUCT_ENTRY *origfw, - unsigned char *matchmask, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r, *i; - - iptc_fn = TC_DELETE_ENTRY; - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - /* Create a rule_head from origfw. */ - r = iptcc_alloc_rule(c, origfw->next_offset); - if (!r) { - errno = ENOMEM; - return 0; - } - - memcpy(r->entry, origfw, origfw->next_offset); - r->counter_map.maptype = COUNTER_MAP_NOMAP; - if (!iptcc_map_target(*handle, r)) { - DEBUGP("unable to map target of rule for chain `%s'\n", chain); - free(r); - return 0; - } else { - /* iptcc_map_target increment target chain references - * since this is a fake rule only used for matching - * the chain references count is decremented again. - */ - if (r->type == IPTCC_R_JUMP - && r->jump) - r->jump->references--; - } - - list_for_each_entry(i, &c->rules, list) { - unsigned char *mask; - - mask = is_same(r->entry, i->entry, matchmask); - if (!mask) - continue; - - if (!target_same(r, i, mask)) - continue; - - /* If we are about to delete the rule that is the - * current iterator, move rule iterator back. next - * pointer will then point to real next node */ - if (i == (*handle)->rule_iterator_cur) { - (*handle)->rule_iterator_cur = - list_entry((*handle)->rule_iterator_cur->list.prev, - struct rule_head, list); - } - - c->num_rules--; - iptcc_delete_rule(i); - - set_changed(*handle); - free(r); - return 1; - } - - free(r); - errno = ENOENT; - return 0; -} - - -/* Delete the rule in position `rulenum' in `chain'. */ -int -TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain, - unsigned int rulenum, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - - iptc_fn = TC_DELETE_NUM_ENTRY; - - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - if (rulenum >= c->num_rules) { - errno = E2BIG; - return 0; - } - - /* Take advantage of the double linked list if possible. */ - if (rulenum + 1 <= c->num_rules/2) { - r = iptcc_get_rule_num(c, rulenum + 1); - } else { - r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); - } - - /* If we are about to delete the rule that is the current - * iterator, move rule iterator back. next pointer will then - * point to real next node */ - if (r == (*handle)->rule_iterator_cur) { - (*handle)->rule_iterator_cur = - list_entry((*handle)->rule_iterator_cur->list.prev, - struct rule_head, list); - } - - c->num_rules--; - iptcc_delete_rule(r); - - set_changed(*handle); - - return 1; -} - -/* Check the packet `fw' on chain `chain'. Returns the verdict, or - NULL and sets errno. */ -const char * -TC_CHECK_PACKET(const IPT_CHAINLABEL chain, - STRUCT_ENTRY *entry, - TC_HANDLE_T *handle) -{ - iptc_fn = TC_CHECK_PACKET; - errno = ENOSYS; - return NULL; -} - -/* Flushes the entries in the given chain (ie. empties chain). */ -int -TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r, *tmp; - - iptc_fn = TC_FLUSH_ENTRIES; - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - list_for_each_entry_safe(r, tmp, &c->rules, list) { - iptcc_delete_rule(r); - } - - c->num_rules = 0; - - set_changed(*handle); - - return 1; -} - -/* Zeroes the counters in a chain. */ -int -TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - - iptc_fn = TC_ZERO_ENTRIES; - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) - c->counter_map.maptype = COUNTER_MAP_ZEROED; - - list_for_each_entry(r, &c->rules, list) { - if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) - r->counter_map.maptype = COUNTER_MAP_ZEROED; - } - - set_changed(*handle); - - return 1; -} - -STRUCT_COUNTERS * -TC_READ_COUNTER(const IPT_CHAINLABEL chain, - unsigned int rulenum, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - - iptc_fn = TC_READ_COUNTER; - CHECK(*handle); - - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return NULL; - } - - if (!(r = iptcc_get_rule_num(c, rulenum))) { - errno = E2BIG; - return NULL; - } - - return &r->entry[0].counters; -} - -int -TC_ZERO_COUNTER(const IPT_CHAINLABEL chain, - unsigned int rulenum, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - - iptc_fn = TC_ZERO_COUNTER; - CHECK(*handle); - - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - if (!(r = iptcc_get_rule_num(c, rulenum))) { - errno = E2BIG; - return 0; - } - - if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) - r->counter_map.maptype = COUNTER_MAP_ZEROED; - - set_changed(*handle); - - return 1; -} - -int -TC_SET_COUNTER(const IPT_CHAINLABEL chain, - unsigned int rulenum, - STRUCT_COUNTERS *counters, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - struct rule_head *r; - STRUCT_ENTRY *e; - - iptc_fn = TC_SET_COUNTER; - CHECK(*handle); - - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - if (!(r = iptcc_get_rule_num(c, rulenum))) { - errno = E2BIG; - return 0; - } - - e = r->entry; - r->counter_map.maptype = COUNTER_MAP_SET; - - memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS)); - - set_changed(*handle); - - return 1; -} - -/* Creates a new chain. */ -/* To create a chain, create two rules: error node and unconditional - * return. */ -int -TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle) -{ - static struct chain_head *c; - int capacity; - int exceeded; - - iptc_fn = TC_CREATE_CHAIN; - - /* find_label doesn't cover built-in targets: DROP, ACCEPT, - QUEUE, RETURN. */ - if (iptcc_find_label(chain, *handle) - || strcmp(chain, LABEL_DROP) == 0 - || strcmp(chain, LABEL_ACCEPT) == 0 - || strcmp(chain, LABEL_QUEUE) == 0 - || strcmp(chain, LABEL_RETURN) == 0) { - DEBUGP("Chain `%s' already exists\n", chain); - errno = EEXIST; - return 0; - } - - if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) { - DEBUGP("Chain name `%s' too long\n", chain); - errno = EINVAL; - return 0; - } - - c = iptcc_alloc_chain_head(chain, 0); - if (!c) { - DEBUGP("Cannot allocate memory for chain `%s'\n", chain); - errno = ENOMEM; - return 0; - - } - (*handle)->num_chains++; /* New user defined chain */ - - DEBUGP("Creating chain `%s'\n", chain); - iptc_insert_chain(*handle, c); /* Insert sorted */ - - /* Inserting chains don't change the correctness of the chain - * index (except if its smaller than index[0], but that - * handled by iptc_insert_chain). It only causes longer lists - * in the buckets. Thus, only rebuild chain index when the - * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains. - */ - capacity = (*handle)->chain_index_sz * CHAIN_INDEX_BUCKET_LEN; - exceeded = ((((*handle)->num_chains)-capacity)); - if (exceeded > CHAIN_INDEX_INSERT_MAX) { - debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n", - capacity, exceeded, (*handle)->num_chains); - iptcc_chain_index_rebuild(*handle); - } - - set_changed(*handle); - - return 1; -} - -/* Get the number of references to this chain. */ -int -TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - - iptc_fn = TC_GET_REFERENCES; - if (!(c = iptcc_find_label(chain, *handle))) { - errno = ENOENT; - return 0; - } - - *ref = c->references; - - return 1; -} - -/* Deletes a chain. */ -int -TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, TC_HANDLE_T *handle) -{ - unsigned int references; - struct chain_head *c; - - iptc_fn = TC_DELETE_CHAIN; - - if (!(c = iptcc_find_label(chain, *handle))) { - DEBUGP("cannot find chain `%s'\n", chain); - errno = ENOENT; - return 0; - } - - if (TC_BUILTIN(chain, *handle)) { - DEBUGP("cannot remove builtin chain `%s'\n", chain); - errno = EINVAL; - return 0; - } - - if (!TC_GET_REFERENCES(&references, chain, handle)) { - DEBUGP("cannot get references on chain `%s'\n", chain); - return 0; - } - - if (references > 0) { - DEBUGP("chain `%s' still has references\n", chain); - errno = EMLINK; - return 0; - } - - if (c->num_rules) { - DEBUGP("chain `%s' is not empty\n", chain); - errno = ENOTEMPTY; - return 0; - } - - /* If we are about to delete the chain that is the current - * iterator, move chain iterator forward. */ - if (c == (*handle)->chain_iterator_cur) - iptcc_chain_iterator_advance(*handle); - - (*handle)->num_chains--; /* One user defined chain deleted */ - - //list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */ - iptcc_chain_index_delete_chain(c, *handle); - free(c); - - DEBUGP("chain `%s' deleted\n", chain); - - set_changed(*handle); - - return 1; -} - -/* Renames a chain. */ -int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname, - const IPT_CHAINLABEL newname, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - iptc_fn = TC_RENAME_CHAIN; - - /* find_label doesn't cover built-in targets: DROP, ACCEPT, - QUEUE, RETURN. */ - if (iptcc_find_label(newname, *handle) - || strcmp(newname, LABEL_DROP) == 0 - || strcmp(newname, LABEL_ACCEPT) == 0 - || strcmp(newname, LABEL_QUEUE) == 0 - || strcmp(newname, LABEL_RETURN) == 0) { - errno = EEXIST; - return 0; - } - - if (!(c = iptcc_find_label(oldname, *handle)) - || TC_BUILTIN(oldname, *handle)) { - errno = ENOENT; - return 0; - } - - if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) { - errno = EINVAL; - return 0; - } - - strncpy(c->name, newname, sizeof(IPT_CHAINLABEL)); - - set_changed(*handle); - - return 1; -} - -/* Sets the policy on a built-in chain. */ -int -TC_SET_POLICY(const IPT_CHAINLABEL chain, - const IPT_CHAINLABEL policy, - STRUCT_COUNTERS *counters, - TC_HANDLE_T *handle) -{ - struct chain_head *c; - - iptc_fn = TC_SET_POLICY; - - if (!(c = iptcc_find_label(chain, *handle))) { - DEBUGP("cannot find chain `%s'\n", chain); - errno = ENOENT; - return 0; - } - - if (!iptcc_is_builtin(c)) { - DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain); - errno = ENOENT; - return 0; - } - - if (strcmp(policy, LABEL_ACCEPT) == 0) - c->verdict = -NF_ACCEPT - 1; - else if (strcmp(policy, LABEL_DROP) == 0) - c->verdict = -NF_DROP - 1; - else { - errno = EINVAL; - return 0; - } - - if (counters) { - /* set byte and packet counters */ - memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS)); - c->counter_map.maptype = COUNTER_MAP_SET; - } else { - c->counter_map.maptype = COUNTER_MAP_NOMAP; - } - - set_changed(*handle); - - return 1; -} - -/* Without this, on gcc 2.7.2.3, we get: - libiptc.c: In function `TC_COMMIT': - libiptc.c:833: fixed or forbidden register was spilled. - This may be due to a compiler bug or to impossible asm - statements or clauses. -*/ -static void -subtract_counters(STRUCT_COUNTERS *answer, - const STRUCT_COUNTERS *a, - const STRUCT_COUNTERS *b) -{ - answer->pcnt = a->pcnt - b->pcnt; - answer->bcnt = a->bcnt - b->bcnt; -} - - -static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx) -{ - newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0}); - DEBUGP_C("NOMAP => zero\n"); -} - -static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters, - STRUCT_REPLACE *repl, unsigned int idx, - unsigned int mappos) -{ - /* Original read: X. - * Atomic read on replacement: X + Y. - * Currently in kernel: Z. - * Want in kernel: X + Y + Z. - * => Add in X + Y - * => Add in replacement read. - */ - newcounters->counters[idx] = repl->counters[mappos]; - DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos); -} - -static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters, - STRUCT_REPLACE *repl, unsigned int idx, - unsigned int mappos, STRUCT_COUNTERS *counters) -{ - /* Original read: X. - * Atomic read on replacement: X + Y. - * Currently in kernel: Z. - * Want in kernel: Y + Z. - * => Add in Y. - * => Add in (replacement read - original read). - */ - subtract_counters(&newcounters->counters[idx], - &repl->counters[mappos], - counters); - DEBUGP_C("ZEROED => mappos %u\n", mappos); -} - -static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters, - unsigned int idx, STRUCT_COUNTERS *counters) -{ - /* Want to set counter (iptables-restore) */ - - memcpy(&newcounters->counters[idx], counters, - sizeof(STRUCT_COUNTERS)); - - DEBUGP_C("SET\n"); -} - - -int -TC_COMMIT(TC_HANDLE_T *handle) -{ - /* Replace, then map back the counters. */ - STRUCT_REPLACE *repl; - STRUCT_COUNTERS_INFO *newcounters; - struct chain_head *c; - int ret; - size_t counterlen; - int new_number; - unsigned int new_size; - - iptc_fn = TC_COMMIT; - CHECK(*handle); - - /* Don't commit if nothing changed. */ - if (!(*handle)->changed) - goto finished; - - new_number = iptcc_compile_table_prep(*handle, &new_size); - if (new_number < 0) { - errno = ENOMEM; - goto out_zero; - } - - repl = malloc(sizeof(*repl) + new_size); - if (!repl) { - errno = ENOMEM; - goto out_zero; - } - memset(repl, 0, sizeof(*repl) + new_size); - -#if 0 - TC_DUMP_ENTRIES(*handle); -#endif - - counterlen = sizeof(STRUCT_COUNTERS_INFO) - + sizeof(STRUCT_COUNTERS) * new_number; - - /* These are the old counters we will get from kernel */ - repl->counters = malloc(sizeof(STRUCT_COUNTERS) - * (*handle)->info.num_entries); - if (!repl->counters) { - errno = ENOMEM; - goto out_free_repl; - } - /* These are the counters we're going to put back, later. */ - newcounters = malloc(counterlen); - if (!newcounters) { - errno = ENOMEM; - goto out_free_repl_counters; - } - memset(newcounters, 0, counterlen); - - strcpy(repl->name, (*handle)->info.name); - repl->num_entries = new_number; - repl->size = new_size; - - repl->num_counters = (*handle)->info.num_entries; - repl->valid_hooks = (*handle)->info.valid_hooks; - - DEBUGP("num_entries=%u, size=%u, num_counters=%u\n", - repl->num_entries, repl->size, repl->num_counters); - - ret = iptcc_compile_table(*handle, repl); - if (ret < 0) { - errno = ret; - goto out_free_newcounters; - } - - -#ifdef IPTC_DEBUG2 - { - int fd = open("/tmp/libiptc-so_set_replace.blob", - O_CREAT|O_WRONLY); - if (fd >= 0) { - write(fd, repl, sizeof(*repl) + repl->size); - close(fd); - } - } -#endif - - ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_REPLACE, repl, - sizeof(*repl) + repl->size); - if (ret < 0) - goto out_free_newcounters; - - /* Put counters back. */ - strcpy(newcounters->name, (*handle)->info.name); - newcounters->num_counters = new_number; - - list_for_each_entry(c, &(*handle)->chains, list) { - struct rule_head *r; - - /* Builtin chains have their own counters */ - if (iptcc_is_builtin(c)) { - DEBUGP("counter for chain-index %u: ", c->foot_index); - switch(c->counter_map.maptype) { - case COUNTER_MAP_NOMAP: - counters_nomap(newcounters, c->foot_index); - break; - case COUNTER_MAP_NORMAL_MAP: - counters_normal_map(newcounters, repl, - c->foot_index, - c->counter_map.mappos); - break; - case COUNTER_MAP_ZEROED: - counters_map_zeroed(newcounters, repl, - c->foot_index, - c->counter_map.mappos, - &c->counters); - break; - case COUNTER_MAP_SET: - counters_map_set(newcounters, c->foot_index, - &c->counters); - break; - } - } - - list_for_each_entry(r, &c->rules, list) { - DEBUGP("counter for index %u: ", r->index); - switch (r->counter_map.maptype) { - case COUNTER_MAP_NOMAP: - counters_nomap(newcounters, r->index); - break; - - case COUNTER_MAP_NORMAL_MAP: - counters_normal_map(newcounters, repl, - r->index, - r->counter_map.mappos); - break; - - case COUNTER_MAP_ZEROED: - counters_map_zeroed(newcounters, repl, - r->index, - r->counter_map.mappos, - &r->entry->counters); - break; - - case COUNTER_MAP_SET: - counters_map_set(newcounters, r->index, - &r->entry->counters); - break; - } - } - } - -#ifdef IPTC_DEBUG2 - { - int fd = open("/tmp/libiptc-so_set_add_counters.blob", - O_CREAT|O_WRONLY); - if (fd >= 0) { - write(fd, newcounters, counterlen); - close(fd); - } - } -#endif - - ret = setsockopt(sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS, - newcounters, counterlen); - if (ret < 0) - goto out_free_newcounters; - - free(repl->counters); - free(repl); - free(newcounters); - -finished: - TC_FREE(handle); - return 1; - -out_free_newcounters: - free(newcounters); -out_free_repl_counters: - free(repl->counters); -out_free_repl: - free(repl); -out_zero: - return 0; -} - -/* Get raw socket. */ -int -TC_GET_RAW_SOCKET(void) -{ - return sockfd; -} - -/* Translates errno numbers into more human-readable form than strerror. */ -const char * -TC_STRERROR(int err) -{ - unsigned int i; - struct table_struct { - void *fn; - int err; - const char *message; - } table [] = - { { TC_INIT, EPERM, "Permission denied (you must be root)" }, - { TC_INIT, EINVAL, "Module is wrong version" }, - { TC_INIT, ENOENT, - "Table does not exist (do you need to insmod?)" }, - { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" }, - { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" }, - { TC_DELETE_CHAIN, EMLINK, - "Can't delete chain with references left" }, - { TC_CREATE_CHAIN, EEXIST, "Chain already exists" }, - { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" }, - { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" }, - { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" }, - { TC_READ_COUNTER, E2BIG, "Index of counter too big" }, - { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" }, - { TC_INSERT_ENTRY, ELOOP, "Loop found in table" }, - { TC_INSERT_ENTRY, EINVAL, "Target problem" }, - /* EINVAL for CHECK probably means bad interface. */ - { TC_CHECK_PACKET, EINVAL, - "Bad arguments (does that interface exist?)" }, - { TC_CHECK_PACKET, ENOSYS, - "Checking will most likely never get implemented" }, - /* ENOENT for DELETE probably means no matching rule */ - { TC_DELETE_ENTRY, ENOENT, - "Bad rule (does a matching rule exist in that chain?)" }, - { TC_SET_POLICY, ENOENT, - "Bad built-in chain name" }, - { TC_SET_POLICY, EINVAL, - "Bad policy name" }, - - { NULL, 0, "Incompatible with this kernel" }, - { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" }, - { NULL, ENOSYS, "Will be implemented real soon. I promise ;)" }, - { NULL, ENOMEM, "Memory allocation problem" }, - { NULL, ENOENT, "No chain/target/match by that name" }, - }; - - for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) { - if ((!table[i].fn || table[i].fn == iptc_fn) - && table[i].err == err) - return table[i].message; - } - - return strerror(err); -} diff --git a/src/owniptc/libiptc.h b/src/owniptc/libiptc.h deleted file mode 100644 index 3fc25b6f..00000000 --- a/src/owniptc/libiptc.h +++ /dev/null @@ -1,187 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef _LIBIPTC_H -#define _LIBIPTC_H -/* Library which manipulates filtering rules. */ - -#include -#include "ipt_kernel_headers.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef IPT_MIN_ALIGN -/* ipt_entry has pointers and u_int64_t's in it, so if you align to - it, you'll also align to any crazy matches and targets someone - might write */ -#define IPT_MIN_ALIGN (__alignof__(struct ipt_entry)) -#endif - -#define IPT_ALIGN(s) (((s) + ((IPT_MIN_ALIGN)-1)) & ~((IPT_MIN_ALIGN)-1)) - -typedef char ipt_chainlabel[32]; - -#define IPTC_LABEL_ACCEPT "ACCEPT" -#define IPTC_LABEL_DROP "DROP" -#define IPTC_LABEL_QUEUE "QUEUE" -#define IPTC_LABEL_RETURN "RETURN" - -/* Transparent handle type. */ -typedef struct iptc_handle *iptc_handle_t; - -/* Does this chain exist? */ -int iptc_is_chain(const char *chain, const iptc_handle_t handle); - -/* Take a snapshot of the rules. Returns NULL on error. */ -iptc_handle_t iptc_init(const char *tablename); - -/* Cleanup after iptc_init(). */ -void iptc_free(iptc_handle_t *h); - -/* Iterator functions to run through the chains. Returns NULL at end. */ -const char *iptc_first_chain(iptc_handle_t *handle); -const char *iptc_next_chain(iptc_handle_t *handle); - -/* Get first rule in the given chain: NULL for empty chain. */ -const struct ipt_entry *iptc_first_rule(const char *chain, - iptc_handle_t *handle); - -/* Returns NULL when rules run out. */ -const struct ipt_entry *iptc_next_rule(const struct ipt_entry *prev, - iptc_handle_t *handle); - -/* Returns a pointer to the target name of this entry. */ -const char *iptc_get_target(const struct ipt_entry *e, - iptc_handle_t *handle); - -/* Is this a built-in chain? */ -int iptc_builtin(const char *chain, const iptc_handle_t handle); - -/* Get the policy of a given built-in chain */ -const char *iptc_get_policy(const char *chain, - struct ipt_counters *counter, - iptc_handle_t *handle); - -/* These functions return TRUE for OK or 0 and set errno. If errno == - 0, it means there was a version error (ie. upgrade libiptc). */ -/* Rule numbers start at 1 for the first rule. */ - -/* Insert the entry `e' in chain `chain' into position `rulenum'. */ -int iptc_insert_entry(const ipt_chainlabel chain, - const struct ipt_entry *e, - unsigned int rulenum, - iptc_handle_t *handle); - -/* Atomically replace rule `rulenum' in `chain' with `e'. */ -int iptc_replace_entry(const ipt_chainlabel chain, - const struct ipt_entry *e, - unsigned int rulenum, - iptc_handle_t *handle); - -/* Append entry `e' to chain `chain'. Equivalent to insert with - rulenum = length of chain. */ -int iptc_append_entry(const ipt_chainlabel chain, - const struct ipt_entry *e, - iptc_handle_t *handle); - -/* Delete the first rule in `chain' which matches `e', subject to - matchmask (array of length == origfw) */ -int iptc_delete_entry(const ipt_chainlabel chain, - const struct ipt_entry *origfw, - unsigned char *matchmask, - iptc_handle_t *handle); - -/* Delete the rule in position `rulenum' in `chain'. */ -int iptc_delete_num_entry(const ipt_chainlabel chain, - unsigned int rulenum, - iptc_handle_t *handle); - -/* Check the packet `e' on chain `chain'. Returns the verdict, or - NULL and sets errno. */ -const char *iptc_check_packet(const ipt_chainlabel chain, - struct ipt_entry *entry, - iptc_handle_t *handle); - -/* Flushes the entries in the given chain (ie. empties chain). */ -int iptc_flush_entries(const ipt_chainlabel chain, - iptc_handle_t *handle); - -/* Zeroes the counters in a chain. */ -int iptc_zero_entries(const ipt_chainlabel chain, - iptc_handle_t *handle); - -/* Creates a new chain. */ -int iptc_create_chain(const ipt_chainlabel chain, - iptc_handle_t *handle); - -/* Deletes a chain. */ -int iptc_delete_chain(const ipt_chainlabel chain, - iptc_handle_t *handle); - -/* Renames a chain. */ -int iptc_rename_chain(const ipt_chainlabel oldname, - const ipt_chainlabel newname, - iptc_handle_t *handle); - -/* Sets the policy on a built-in chain. */ -int iptc_set_policy(const ipt_chainlabel chain, - const ipt_chainlabel policy, - struct ipt_counters *counters, - iptc_handle_t *handle); - -/* Get the number of references to this chain */ -int iptc_get_references(unsigned int *ref, - const ipt_chainlabel chain, - iptc_handle_t *handle); - -/* read packet and byte counters for a specific rule */ -struct ipt_counters *iptc_read_counter(const ipt_chainlabel chain, - unsigned int rulenum, - iptc_handle_t *handle); - -/* zero packet and byte counters for a specific rule */ -int iptc_zero_counter(const ipt_chainlabel chain, - unsigned int rulenum, - iptc_handle_t *handle); - -/* set packet and byte counters for a specific rule */ -int iptc_set_counter(const ipt_chainlabel chain, - unsigned int rulenum, - struct ipt_counters *counters, - iptc_handle_t *handle); - -/* Makes the actual changes. */ -int iptc_commit(iptc_handle_t *handle); - -/* Get raw socket. */ -int iptc_get_raw_socket(void); - -/* Translates errno numbers into more human-readable form than strerror. */ -const char *iptc_strerror(int err); - -extern void dump_entries(const iptc_handle_t); - -#ifdef __cplusplus -} -#endif - - -#endif /* _LIBIPTC_H */ diff --git a/src/owniptc/libxtc.h b/src/owniptc/libxtc.h deleted file mode 100644 index 2ed03f4c..00000000 --- a/src/owniptc/libxtc.h +++ /dev/null @@ -1,53 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef _LIBXTC_H -#define _LIBXTC_H -/* Library which manipulates filtering rules. */ - -#include "ipt_kernel_headers.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef XT_MIN_ALIGN -/* xt_entry has pointers and u_int64_t's in it, so if you align to - it, you'll also align to any crazy matches and targets someone - might write */ -#define XT_MIN_ALIGN (__alignof__(struct xt_entry)) -#endif - -#ifndef XT_ALIGN -#define XT_ALIGN(s) (((s) + ((XT_MIN_ALIGN)-1)) & ~((XT_MIN_ALIGN)-1)) -#endif - -typedef char xt_chainlabel[32]; - -#define XTC_LABEL_ACCEPT "ACCEPT" -#define XTC_LABEL_DROP "DROP" -#define XTC_LABEL_QUEUE "QUEUE" -#define XTC_LABEL_RETURN "RETURN" - - -#ifdef __cplusplus -} -#endif - -#endif /* _LIBXTC_H */ diff --git a/src/owniptc/linux_list.h b/src/owniptc/linux_list.h deleted file mode 100644 index 56d9a26e..00000000 --- a/src/owniptc/linux_list.h +++ /dev/null @@ -1,741 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef _LINUX_LIST_H -#define _LINUX_LIST_H - -#undef offsetof -#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) - -/** - * container_of - cast a member of a structure out to the containing structure - * - * @ptr: the pointer to the member. - * @type: the type of the container struct this is embedded in. - * @member: the name of the member within the struct. - * - */ -#define container_of(ptr, type, member) ({ \ - const typeof( ((type *)0)->member ) *__mptr = (ptr); \ - (type *)( (char *)__mptr - offsetof(type,member) );}) - -/* - * Check at compile time that something is of a particular type. - * Always evaluates to 1 so you may use it easily in comparisons. - */ -#define typecheck(type,x) \ -({ type __dummy; \ - typeof(x) __dummy2; \ - (void)(&__dummy == &__dummy2); \ - 1; \ -}) - -#define prefetch(x) 1 - -/* empty define to make this work in userspace -HW */ -#define smp_wmb() - -/* - * These are non-NULL pointers that will result in page faults - * under normal circumstances, used to verify that nobody uses - * non-initialized list entries. - */ -#define LIST_POISON1 ((void *) 0x00100100) -#define LIST_POISON2 ((void *) 0x00200200) - -/* - * Simple doubly linked list implementation. - * - * Some of the internal functions ("__xxx") are useful when - * manipulating whole lists rather than single entries, as - * sometimes we already know the next/prev entries and we can - * generate better code by using them directly rather than - * using the generic single-entry routines. - */ - -struct list_head { - struct list_head *next, *prev; -}; - -#define LIST_HEAD_INIT(name) { &(name), &(name) } - -#define LIST_HEAD(name) \ - struct list_head name = LIST_HEAD_INIT(name) - -#define INIT_LIST_HEAD(ptr) do { \ - (ptr)->next = (ptr); (ptr)->prev = (ptr); \ -} while (0) - -/* - * Insert a new entry between two known consecutive entries. - * - * This is only for internal list manipulation where we know - * the prev/next entries already! - */ -static inline void __list_add(struct list_head *new, - struct list_head *prev, - struct list_head *next) -{ - next->prev = new; - new->next = next; - new->prev = prev; - prev->next = new; -} - -/** - * list_add - add a new entry - * @new: new entry to be added - * @head: list head to add it after - * - * Insert a new entry after the specified head. - * This is good for implementing stacks. - */ -static inline void list_add(struct list_head *new, struct list_head *head) -{ - __list_add(new, head, head->next); -} - -/** - * list_add_tail - add a new entry - * @new: new entry to be added - * @head: list head to add it before - * - * Insert a new entry before the specified head. - * This is useful for implementing queues. - */ -static inline void list_add_tail(struct list_head *new, struct list_head *head) -{ - __list_add(new, head->prev, head); -} - -/* - * Insert a new entry between two known consecutive entries. - * - * This is only for internal list manipulation where we know - * the prev/next entries already! - */ -static inline void __list_add_rcu(struct list_head * new, - struct list_head * prev, struct list_head * next) -{ - new->next = next; - new->prev = prev; - smp_wmb(); - next->prev = new; - prev->next = new; -} - -/** - * list_add_rcu - add a new entry to rcu-protected list - * @new: new entry to be added - * @head: list head to add it after - * - * Insert a new entry after the specified head. - * This is good for implementing stacks. - * - * The caller must take whatever precautions are necessary - * (such as holding appropriate locks) to avoid racing - * with another list-mutation primitive, such as list_add_rcu() - * or list_del_rcu(), running on this same list. - * However, it is perfectly legal to run concurrently with - * the _rcu list-traversal primitives, such as - * list_for_each_entry_rcu(). - */ -static inline void list_add_rcu(struct list_head *new, struct list_head *head) -{ - __list_add_rcu(new, head, head->next); -} - -/** - * list_add_tail_rcu - add a new entry to rcu-protected list - * @new: new entry to be added - * @head: list head to add it before - * - * Insert a new entry before the specified head. - * This is useful for implementing queues. - * - * The caller must take whatever precautions are necessary - * (such as holding appropriate locks) to avoid racing - * with another list-mutation primitive, such as list_add_tail_rcu() - * or list_del_rcu(), running on this same list. - * However, it is perfectly legal to run concurrently with - * the _rcu list-traversal primitives, such as - * list_for_each_entry_rcu(). - */ -static inline void list_add_tail_rcu(struct list_head *new, - struct list_head *head) -{ - __list_add_rcu(new, head->prev, head); -} - -/* - * Delete a list entry by making the prev/next entries - * point to each other. - * - * This is only for internal list manipulation where we know - * the prev/next entries already! - */ -static inline void __list_del(struct list_head * prev, struct list_head * next) -{ - next->prev = prev; - prev->next = next; -} - -/** - * list_del - deletes entry from list. - * @entry: the element to delete from the list. - * Note: list_empty on entry does not return true after this, the entry is - * in an undefined state. - */ -static inline void list_del(struct list_head *entry) -{ - __list_del(entry->prev, entry->next); - entry->next = LIST_POISON1; - entry->prev = LIST_POISON2; -} - -/** - * list_del_rcu - deletes entry from list without re-initialization - * @entry: the element to delete from the list. - * - * Note: list_empty on entry does not return true after this, - * the entry is in an undefined state. It is useful for RCU based - * lockfree traversal. - * - * In particular, it means that we can not poison the forward - * pointers that may still be used for walking the list. - * - * The caller must take whatever precautions are necessary - * (such as holding appropriate locks) to avoid racing - * with another list-mutation primitive, such as list_del_rcu() - * or list_add_rcu(), running on this same list. - * However, it is perfectly legal to run concurrently with - * the _rcu list-traversal primitives, such as - * list_for_each_entry_rcu(). - * - * Note that the caller is not permitted to immediately free - * the newly deleted entry. Instead, either synchronize_kernel() - * or call_rcu() must be used to defer freeing until an RCU - * grace period has elapsed. - */ -static inline void list_del_rcu(struct list_head *entry) -{ - __list_del(entry->prev, entry->next); - entry->prev = LIST_POISON2; -} - -/** - * list_del_init - deletes entry from list and reinitialize it. - * @entry: the element to delete from the list. - */ -static inline void list_del_init(struct list_head *entry) -{ - __list_del(entry->prev, entry->next); - INIT_LIST_HEAD(entry); -} - -/** - * list_move - delete from one list and add as another's head - * @list: the entry to move - * @head: the head that will precede our entry - */ -static inline void list_move(struct list_head *list, struct list_head *head) -{ - __list_del(list->prev, list->next); - list_add(list, head); -} - -/** - * list_move_tail - delete from one list and add as another's tail - * @list: the entry to move - * @head: the head that will follow our entry - */ -static inline void list_move_tail(struct list_head *list, - struct list_head *head) -{ - __list_del(list->prev, list->next); - list_add_tail(list, head); -} - -/** - * list_empty - tests whether a list is empty - * @head: the list to test. - */ -static inline int list_empty(const struct list_head *head) -{ - return head->next == head; -} - -/** - * list_empty_careful - tests whether a list is - * empty _and_ checks that no other CPU might be - * in the process of still modifying either member - * - * NOTE: using list_empty_careful() without synchronization - * can only be safe if the only activity that can happen - * to the list entry is list_del_init(). Eg. it cannot be used - * if another CPU could re-list_add() it. - * - * @head: the list to test. - */ -static inline int list_empty_careful(const struct list_head *head) -{ - struct list_head *next = head->next; - return (next == head) && (next == head->prev); -} - -static inline void __list_splice(struct list_head *list, - struct list_head *head) -{ - struct list_head *first = list->next; - struct list_head *last = list->prev; - struct list_head *at = head->next; - - first->prev = head; - head->next = first; - - last->next = at; - at->prev = last; -} - -/** - * list_splice - join two lists - * @list: the new list to add. - * @head: the place to add it in the first list. - */ -static inline void list_splice(struct list_head *list, struct list_head *head) -{ - if (!list_empty(list)) - __list_splice(list, head); -} - -/** - * list_splice_init - join two lists and reinitialise the emptied list. - * @list: the new list to add. - * @head: the place to add it in the first list. - * - * The list at @list is reinitialised - */ -static inline void list_splice_init(struct list_head *list, - struct list_head *head) -{ - if (!list_empty(list)) { - __list_splice(list, head); - INIT_LIST_HEAD(list); - } -} - -/** - * list_entry - get the struct for this entry - * @ptr: the &struct list_head pointer. - * @type: the type of the struct this is embedded in. - * @member: the name of the list_struct within the struct. - */ -#define list_entry(ptr, type, member) \ - container_of(ptr, type, member) - -/** - * list_for_each - iterate over a list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - */ -#define list_for_each(pos, head) \ - for (pos = (head)->next, prefetch(pos->next); pos != (head); \ - pos = pos->next, prefetch(pos->next)) - -/** - * __list_for_each - iterate over a list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - * - * This variant differs from list_for_each() in that it's the - * simplest possible list iteration code, no prefetching is done. - * Use this for code that knows the list to be very short (empty - * or 1 entry) most of the time. - */ -#define __list_for_each(pos, head) \ - for (pos = (head)->next; pos != (head); pos = pos->next) - -/** - * list_for_each_prev - iterate over a list backwards - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - */ -#define list_for_each_prev(pos, head) \ - for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \ - pos = pos->prev, prefetch(pos->prev)) - -/** - * list_for_each_safe - iterate over a list safe against removal of list entry - * @pos: the &struct list_head to use as a loop counter. - * @n: another &struct list_head to use as temporary storage - * @head: the head for your list. - */ -#define list_for_each_safe(pos, n, head) \ - for (pos = (head)->next, n = pos->next; pos != (head); \ - pos = n, n = pos->next) - -/** - * list_for_each_entry - iterate over list of given type - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - prefetch(pos->member.next); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, typeof(*pos), member), \ - prefetch(pos->member.next)) - -/** - * list_for_each_entry_reverse - iterate backwards over list of given type. - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry_reverse(pos, head, member) \ - for (pos = list_entry((head)->prev, typeof(*pos), member), \ - prefetch(pos->member.prev); \ - &pos->member != (head); \ - pos = list_entry(pos->member.prev, typeof(*pos), member), \ - prefetch(pos->member.prev)) - -/** - * list_prepare_entry - prepare a pos entry for use as a start point in - * list_for_each_entry_continue - * @pos: the type * to use as a start point - * @head: the head of the list - * @member: the name of the list_struct within the struct. - */ -#define list_prepare_entry(pos, head, member) \ - ((pos) ? : list_entry(head, typeof(*pos), member)) - -/** - * list_for_each_entry_continue - iterate over list of given type - * continuing after existing point - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry_continue(pos, head, member) \ - for (pos = list_entry(pos->member.next, typeof(*pos), member), \ - prefetch(pos->member.next); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, typeof(*pos), member), \ - prefetch(pos->member.next)) - -/** - * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry - * @pos: the type * to use as a loop counter. - * @n: another type * to use as temporary storage - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - */ -#define list_for_each_entry_safe(pos, n, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - n = list_entry(pos->member.next, typeof(*pos), member); \ - &pos->member != (head); \ - pos = n, n = list_entry(n->member.next, typeof(*n), member)) - -/** - * list_for_each_rcu - iterate over an rcu-protected list - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - * - * This list-traversal primitive may safely run concurrently with - * the _rcu list-mutation primitives such as list_add_rcu() - * as long as the traversal is guarded by rcu_read_lock(). - */ -#define list_for_each_rcu(pos, head) \ - for (pos = (head)->next, prefetch(pos->next); pos != (head); \ - pos = pos->next, ({ smp_read_barrier_depends(); 0;}), prefetch(pos->next)) - -#define __list_for_each_rcu(pos, head) \ - for (pos = (head)->next; pos != (head); \ - pos = pos->next, ({ smp_read_barrier_depends(); 0;})) - -/** - * list_for_each_safe_rcu - iterate over an rcu-protected list safe - * against removal of list entry - * @pos: the &struct list_head to use as a loop counter. - * @n: another &struct list_head to use as temporary storage - * @head: the head for your list. - * - * This list-traversal primitive may safely run concurrently with - * the _rcu list-mutation primitives such as list_add_rcu() - * as long as the traversal is guarded by rcu_read_lock(). - */ -#define list_for_each_safe_rcu(pos, n, head) \ - for (pos = (head)->next, n = pos->next; pos != (head); \ - pos = n, ({ smp_read_barrier_depends(); 0;}), n = pos->next) - -/** - * list_for_each_entry_rcu - iterate over rcu list of given type - * @pos: the type * to use as a loop counter. - * @head: the head for your list. - * @member: the name of the list_struct within the struct. - * - * This list-traversal primitive may safely run concurrently with - * the _rcu list-mutation primitives such as list_add_rcu() - * as long as the traversal is guarded by rcu_read_lock(). - */ -#define list_for_each_entry_rcu(pos, head, member) \ - for (pos = list_entry((head)->next, typeof(*pos), member), \ - prefetch(pos->member.next); \ - &pos->member != (head); \ - pos = list_entry(pos->member.next, typeof(*pos), member), \ - ({ smp_read_barrier_depends(); 0;}), \ - prefetch(pos->member.next)) - - -/** - * list_for_each_continue_rcu - iterate over an rcu-protected list - * continuing after existing point. - * @pos: the &struct list_head to use as a loop counter. - * @head: the head for your list. - * - * This list-traversal primitive may safely run concurrently with - * the _rcu list-mutation primitives such as list_add_rcu() - * as long as the traversal is guarded by rcu_read_lock(). - */ -#define list_for_each_continue_rcu(pos, head) \ - for ((pos) = (pos)->next, prefetch((pos)->next); (pos) != (head); \ - (pos) = (pos)->next, ({ smp_read_barrier_depends(); 0;}), prefetch((pos)->next)) - -/* - * Double linked lists with a single pointer list head. - * Mostly useful for hash tables where the two pointer list head is - * too wasteful. - * You lose the ability to access the tail in O(1). - */ - -struct hlist_head { - struct hlist_node *first; -}; - -struct hlist_node { - struct hlist_node *next, **pprev; -}; - -#define HLIST_HEAD_INIT { .first = NULL } -#define HLIST_HEAD(name) struct hlist_head name = { .first = NULL } -#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL) -#define INIT_HLIST_NODE(ptr) ((ptr)->next = NULL, (ptr)->pprev = NULL) - -static inline int hlist_unhashed(const struct hlist_node *h) -{ - return !h->pprev; -} - -static inline int hlist_empty(const struct hlist_head *h) -{ - return !h->first; -} - -static inline void __hlist_del(struct hlist_node *n) -{ - struct hlist_node *next = n->next; - struct hlist_node **pprev = n->pprev; - *pprev = next; - if (next) - next->pprev = pprev; -} - -static inline void hlist_del(struct hlist_node *n) -{ - __hlist_del(n); - n->next = LIST_POISON1; - n->pprev = LIST_POISON2; -} - -/** - * hlist_del_rcu - deletes entry from hash list without re-initialization - * @n: the element to delete from the hash list. - * - * Note: list_unhashed() on entry does not return true after this, - * the entry is in an undefined state. It is useful for RCU based - * lockfree traversal. - * - * In particular, it means that we can not poison the forward - * pointers that may still be used for walking the hash list. - * - * The caller must take whatever precautions are necessary - * (such as holding appropriate locks) to avoid racing - * with another list-mutation primitive, such as hlist_add_head_rcu() - * or hlist_del_rcu(), running on this same list. - * However, it is perfectly legal to run concurrently with - * the _rcu list-traversal primitives, such as - * hlist_for_each_entry(). - */ -static inline void hlist_del_rcu(struct hlist_node *n) -{ - __hlist_del(n); - n->pprev = LIST_POISON2; -} - -static inline void hlist_del_init(struct hlist_node *n) -{ - if (n->pprev) { - __hlist_del(n); - INIT_HLIST_NODE(n); - } -} - -#define hlist_del_rcu_init hlist_del_init - -static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) -{ - struct hlist_node *first = h->first; - n->next = first; - if (first) - first->pprev = &n->next; - h->first = n; - n->pprev = &h->first; -} - - -/** - * hlist_add_head_rcu - adds the specified element to the specified hlist, - * while permitting racing traversals. - * @n: the element to add to the hash list. - * @h: the list to add to. - * - * The caller must take whatever precautions are necessary - * (such as holding appropriate locks) to avoid racing - * with another list-mutation primitive, such as hlist_add_head_rcu() - * or hlist_del_rcu(), running on this same list. - * However, it is perfectly legal to run concurrently with - * the _rcu list-traversal primitives, such as - * hlist_for_each_entry(), but only if smp_read_barrier_depends() - * is used to prevent memory-consistency problems on Alpha CPUs. - * Regardless of the type of CPU, the list-traversal primitive - * must be guarded by rcu_read_lock(). - * - * OK, so why don't we have an hlist_for_each_entry_rcu()??? - */ -static inline void hlist_add_head_rcu(struct hlist_node *n, - struct hlist_head *h) -{ - struct hlist_node *first = h->first; - n->next = first; - n->pprev = &h->first; - smp_wmb(); - if (first) - first->pprev = &n->next; - h->first = n; -} - -/* next must be != NULL */ -static inline void hlist_add_before(struct hlist_node *n, - struct hlist_node *next) -{ - n->pprev = next->pprev; - n->next = next; - next->pprev = &n->next; - *(n->pprev) = n; -} - -static inline void hlist_add_after(struct hlist_node *n, - struct hlist_node *next) -{ - next->next = n->next; - n->next = next; - next->pprev = &n->next; - - if(next->next) - next->next->pprev = &next->next; -} - -#define hlist_entry(ptr, type, member) container_of(ptr,type,member) - -#define hlist_for_each(pos, head) \ - for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \ - pos = pos->next) - -#define hlist_for_each_safe(pos, n, head) \ - for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \ - pos = n) - -/** - * hlist_for_each_entry - iterate over list of given type - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @head: the head for your list. - * @member: the name of the hlist_node within the struct. - */ -#define hlist_for_each_entry(tpos, pos, head, member) \ - for (pos = (head)->first; \ - pos && ({ prefetch(pos->next); 1;}) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = pos->next) - -/** - * hlist_for_each_entry_continue - iterate over a hlist continuing after existing point - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @member: the name of the hlist_node within the struct. - */ -#define hlist_for_each_entry_continue(tpos, pos, member) \ - for (pos = (pos)->next; \ - pos && ({ prefetch(pos->next); 1;}) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = pos->next) - -/** - * hlist_for_each_entry_from - iterate over a hlist continuing from existing point - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @member: the name of the hlist_node within the struct. - */ -#define hlist_for_each_entry_from(tpos, pos, member) \ - for (; pos && ({ prefetch(pos->next); 1;}) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = pos->next) - -/** - * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry - * @tpos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @n: another &struct hlist_node to use as temporary storage - * @head: the head for your list. - * @member: the name of the hlist_node within the struct. - */ -#define hlist_for_each_entry_safe(tpos, pos, n, head, member) \ - for (pos = (head)->first; \ - pos && ({ n = pos->next; 1; }) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = n) - -/** - * hlist_for_each_entry_rcu - iterate over rcu list of given type - * @pos: the type * to use as a loop counter. - * @pos: the &struct hlist_node to use as a loop counter. - * @head: the head for your list. - * @member: the name of the hlist_node within the struct. - * - * This list-traversal primitive may safely run concurrently with - * the _rcu list-mutation primitives such as hlist_add_rcu() - * as long as the traversal is guarded by rcu_read_lock(). - */ -#define hlist_for_each_entry_rcu(tpos, pos, head, member) \ - for (pos = (head)->first; \ - pos && ({ prefetch(pos->next); 1;}) && \ - ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ - pos = pos->next, ({ smp_read_barrier_depends(); 0; }) ) - -#endif diff --git a/src/owniptc/xtables.h b/src/owniptc/xtables.h deleted file mode 100644 index 47e47dc7..00000000 --- a/src/owniptc/xtables.h +++ /dev/null @@ -1,239 +0,0 @@ -/** - * This file was imported from the iptables sources. - * Copyright (C) 1999-2008 Netfilter Core Team - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; only version 2 of the License is applicable. - * - * 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., - * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef _XTABLES_H -#define _XTABLES_H - -#include -#include -#include -#include "libxtc.h" -#include - -#ifndef IPPROTO_SCTP -#define IPPROTO_SCTP 132 -#endif -#ifndef IPPROTO_DCCP -#define IPPROTO_DCCP 33 -#endif -#ifndef IPPROTO_UDPLITE -#define IPPROTO_UDPLITE 136 -#endif - -#define XTABLES_VERSION "1.4.1.1" -#define XTABLES_VERSION_CODE (0x10000 * 1 + 0x100 * 4 + 1) - -#define XTABLES_API_VERSION(x,y,z) (0x10000*(x) + 0x100*(y) + z) - -/* Include file for additions: new matches and targets. */ -struct xtables_match -{ - struct xtables_match *next; - - xt_chainlabel name; - - /* Revision of match (0 by default). */ - u_int8_t revision; - - u_int16_t family; - - const char *version; - - /* Size of match data. */ - size_t size; - - /* Size of match data relevent for userspace comparison purposes */ - size_t userspacesize; - - /* Function which prints out usage message. */ - void (*help)(void); - - /* Initialize the match. */ - void (*init)(struct xt_entry_match *m); - - /* Function which parses command options; returns true if it - ate an option */ - /* entry is struct ipt_entry for example */ - int (*parse)(int c, char **argv, int invert, unsigned int *flags, - const void *entry, - struct xt_entry_match **match); - - /* Final check; exit if not ok. */ - void (*final_check)(unsigned int flags); - - /* Prints out the match iff non-NULL: put space at end */ - /* ip is struct ipt_ip * for example */ - void (*print)(const void *ip, - const struct xt_entry_match *match, int numeric); - - /* Saves the match info in parsable form to stdout. */ - /* ip is struct ipt_ip * for example */ - void (*save)(const void *ip, const struct xt_entry_match *match); - - /* Pointer to list of extra command-line options */ - const struct option *extra_opts; - - /* Ignore these men behind the curtain: */ - unsigned int option_offset; - struct xt_entry_match *m; - unsigned int mflags; -#ifdef NO_SHARED_LIBS - unsigned int loaded; /* simulate loading so options are merged properly */ -#endif -}; - -struct xtables_target -{ - struct xtables_target *next; - - xt_chainlabel name; - - /* Revision of target (0 by default). */ - u_int8_t revision; - - u_int16_t family; - - const char *version; - - /* Size of target data. */ - size_t size; - - /* Size of target data relevent for userspace comparison purposes */ - size_t userspacesize; - - /* Function which prints out usage message. */ - void (*help)(void); - - /* Initialize the target. */ - void (*init)(struct xt_entry_target *t); - - /* Function which parses command options; returns true if it - ate an option */ - /* entry is struct ipt_entry for example */ - int (*parse)(int c, char **argv, int invert, unsigned int *flags, - const void *entry, - struct xt_entry_target **targetinfo); - - /* Final check; exit if not ok. */ - void (*final_check)(unsigned int flags); - - /* Prints out the target iff non-NULL: put space at end */ - void (*print)(const void *ip, - const struct xt_entry_target *target, int numeric); - - /* Saves the targinfo in parsable form to stdout. */ - void (*save)(const void *ip, - const struct xt_entry_target *target); - - /* Pointer to list of extra command-line options */ - const struct option *extra_opts; - - /* Ignore these men behind the curtain: */ - unsigned int option_offset; - struct xt_entry_target *t; - unsigned int tflags; - unsigned int used; -#ifdef NO_SHARED_LIBS - unsigned int loaded; /* simulate loading so options are merged properly */ -#endif -}; - -/* Your shared library should call one of these. */ -extern void xtables_register_match(struct xtables_match *me); -extern void xtables_register_target(struct xtables_target *me); - -extern int string_to_number_ll(const char *s, - unsigned long long min, - unsigned long long max, - unsigned long long *ret); -extern int string_to_number_l(const char *s, - unsigned long min, - unsigned long max, - unsigned long *ret); -extern int string_to_number(const char *s, - unsigned int min, - unsigned int max, - unsigned int *ret); -extern bool strtonuml(const char *, char **, unsigned long *, - unsigned long, unsigned long); -extern bool strtonum(const char *, char **, unsigned int *, - unsigned int, unsigned int); -extern int service_to_port(const char *name, const char *proto); -extern u_int16_t parse_port(const char *port, const char *proto); -extern void -parse_interface(const char *arg, char *vianame, unsigned char *mask); - -enum exittype { - OTHER_PROBLEM = 1, - PARAMETER_PROBLEM, - VERSION_PROBLEM, - RESOURCE_PROBLEM, - P_ONLY_ONCE, - P_NO_INVERT, - P_BAD_VALUE, - P_ONE_ACTION, -}; - -/* this is a special 64bit data type that is 8-byte aligned */ -#define aligned_u64 u_int64_t __attribute__((aligned(8))) - -int check_inverse(const char option[], int *invert, int *my_optind, int argc); -void exit_error(enum exittype, const char *, ...)__attribute__((noreturn, - format(printf,2,3))); -extern void param_act(unsigned int, const char *, ...); -extern const char *program_name, *program_version; - -extern const char *ipaddr_to_numeric(const struct in_addr *); -extern const char *ipaddr_to_anyname(const struct in_addr *); -extern const char *ipmask_to_numeric(const struct in_addr *); -extern struct in_addr *numeric_to_ipaddr(const char *); -extern struct in_addr *numeric_to_ipmask(const char *); -extern void ipparse_hostnetworkmask(const char *, struct in_addr **, - struct in_addr *, unsigned int *); - -extern struct in6_addr *numeric_to_ip6addr(const char *); -extern const char *ip6addr_to_numeric(const struct in6_addr *); -extern const char *ip6addr_to_anyname(const struct in6_addr *); -extern const char *ip6mask_to_numeric(const struct in6_addr *); -extern void ip6parse_hostnetworkmask(const char *, struct in6_addr **, - struct in6_addr *, unsigned int *); - -/** - * Print the specified value to standard output, quoting dangerous - * characters if required. - */ -extern void save_string(const char *value); - -#ifdef NO_SHARED_LIBS -# ifdef _INIT -# undef _init -# define _init _INIT -# endif - extern void init_extensions(void); -#else -# define _init __attribute__((constructor)) _INIT -#endif - -/* Present in both iptables.c and ip6tables.c */ -extern u_int16_t parse_protocol(const char *s); - -#ifdef XTABLES_INTERNAL -# include -#endif - -#endif /* _XTABLES_H */ diff --git a/src/pinba.c b/src/pinba.c index a6fd06fe..26aa539b 100644 --- a/src/pinba.c +++ b/src/pinba.c @@ -617,7 +617,7 @@ static int plugin_config (oconfig_item_t *ci) /* {{{ */ if (strcasecmp ("Address", child->key) == 0) cf_util_get_string (child, &conf_node); else if (strcasecmp ("Port", child->key) == 0) - cf_util_get_string (child, &conf_service); + cf_util_get_service (child, &conf_service); else if (strcasecmp ("View", child->key) == 0) pinba_config_view (child); else diff --git a/src/plugin.c b/src/plugin.c index 91c40b6b..cdd56bd7 100644 --- a/src/plugin.c +++ b/src/plugin.c @@ -1706,6 +1706,44 @@ void plugin_log (int level, const char *format, ...) } } /* void plugin_log */ +int parse_log_severity (const char *severity) +{ + int log_level = -1; + + if ((0 == strcasecmp (severity, "emerg")) + || (0 == strcasecmp (severity, "alert")) + || (0 == strcasecmp (severity, "crit")) + || (0 == strcasecmp (severity, "err"))) + log_level = LOG_ERR; + else if (0 == strcasecmp (severity, "warning")) + log_level = LOG_WARNING; + else if (0 == strcasecmp (severity, "notice")) + log_level = LOG_NOTICE; + else if (0 == strcasecmp (severity, "info")) + log_level = LOG_INFO; +#if COLLECT_DEBUG + else if (0 == strcasecmp (severity, "debug")) + log_level = LOG_DEBUG; +#endif /* COLLECT_DEBUG */ + + return (log_level); +} /* int parse_log_severity */ + +int parse_notif_severity (const char *severity) +{ + int notif_severity = -1; + + if (strcasecmp (severity, "FAILURE") == 0) + notif_severity = NOTIF_FAILURE; + else if (strcmp (severity, "OKAY") == 0) + notif_severity = NOTIF_OKAY; + else if ((strcmp (severity, "WARNING") == 0) + || (strcmp (severity, "WARN") == 0)) + notif_severity = NOTIF_WARNING; + + return (notif_severity); +} /* int parse_notif_severity */ + const data_set_t *plugin_get_ds (const char *name) { data_set_t *ds; diff --git a/src/plugin.h b/src/plugin.h index 86d40340..dd65b598 100644 --- a/src/plugin.h +++ b/src/plugin.h @@ -326,6 +326,10 @@ int plugin_dispatch_notification (const notification_t *notif); void plugin_log (int level, const char *format, ...) __attribute__ ((format(printf,2,3))); +/* These functions return the parsed severity or less than zero on failure. */ +int parse_log_severity (const char *severity); +int parse_notif_severity (const char *severity); + #define ERROR(...) plugin_log (LOG_ERR, __VA_ARGS__) #define WARNING(...) plugin_log (LOG_WARNING, __VA_ARGS__) #define NOTICE(...) plugin_log (LOG_NOTICE, __VA_ARGS__) diff --git a/src/postgresql.c b/src/postgresql.c index a8812e21..0a5e66c2 100644 --- a/src/postgresql.c +++ b/src/postgresql.c @@ -523,19 +523,6 @@ static int c_psql_shutdown (void) return 0; } /* c_psql_shutdown */ -static int config_set_s (char *name, char **var, const oconfig_item_t *ci) -{ - if ((0 != ci->children_num) || (1 != ci->values_num) - || (OCONFIG_TYPE_STRING != ci->values[0].type)) { - log_err ("%s expects a single string argument.", name); - return 1; - } - - sfree (*var); - *var = sstrdup (ci->values[0].value.string); - return 0; -} /* config_set_s */ - static int config_query_param_add (udb_query_t *q, oconfig_item_t *ci) { c_psql_user_data_t *data; @@ -618,19 +605,19 @@ static int c_psql_config_database (oconfig_item_t *ci) oconfig_item_t *c = ci->children + i; if (0 == strcasecmp (c->key, "Host")) - config_set_s ("Host", &db->host, c); + cf_util_get_string (c, &db->host); else if (0 == strcasecmp (c->key, "Port")) - config_set_s ("Port", &db->port, c); + cf_util_get_service (c, &db->port); else if (0 == strcasecmp (c->key, "User")) - config_set_s ("User", &db->user, c); + cf_util_get_string (c, &db->user); else if (0 == strcasecmp (c->key, "Password")) - config_set_s ("Password", &db->password, c); + cf_util_get_string (c, &db->password); else if (0 == strcasecmp (c->key, "SSLMode")) - config_set_s ("SSLMode", &db->sslmode, c); + cf_util_get_string (c, &db->sslmode); else if (0 == strcasecmp (c->key, "KRBSrvName")) - config_set_s ("KRBSrvName", &db->krbsrvname, c); + cf_util_get_string (c, &db->krbsrvname); else if (0 == strcasecmp (c->key, "Service")) - config_set_s ("Service", &db->service, c); + cf_util_get_string (c, &db->service); else if (0 == strcasecmp (c->key, "Query")) udb_query_pick_from_list (c, queries, queries_num, &db->queries, &db->queries_num); diff --git a/src/processes.c b/src/processes.c index 8a1436e1..66237dc3 100644 --- a/src/processes.c +++ b/src/processes.c @@ -200,7 +200,7 @@ static long pagesize_g; /* #endif KERNEL_LINUX */ #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD -/* no global variables */ +static int pagesize; /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */ #elif HAVE_PROCINFO_H @@ -609,7 +609,7 @@ static int ps_init (void) /* #endif KERNEL_LINUX */ #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD -/* no initialization */ + pagesize = getpagesize(); /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */ #elif HAVE_PROCINFO_H @@ -790,7 +790,7 @@ static procstat_t *ps_read_vmem (int pid, procstat_t *ps) tmp = strtoll (fields[1], &endptr, /* base = */ 10); if ((errno == 0) && (endptr != fields[1])) { - if (strncmp (buffer, "VmData", 6) == 0) + if (strncmp (buffer, "VmData", 6) == 0) { data = tmp; } @@ -1605,10 +1605,8 @@ static int ps_read (void) kvm_t *kd; char errbuf[1024]; - char cmdline[ARG_MAX]; - char *cmdline_ptr; struct kinfo_proc *procs; /* array of processes */ - char **argv; + struct kinfo_proc *proc_ptr = NULL; int count; /* returns number of processes */ int i; @@ -1639,64 +1637,80 @@ static int ps_read (void) /* Iterate through the processes in kinfo_proc */ for (i = 0; i < count; i++) { - /* retrieve the arguments */ - cmdline[0] = 0; - cmdline_ptr = NULL; - - argv = kvm_getargv (kd, (const struct kinfo_proc *) &(procs[i]), 0); - if (argv != NULL) + /* Create only one process list entry per _process_, i.e. + * filter out threads (duplicate PID entries). */ + if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) { - int status; - int argc; - - argc = 0; - while (argv[argc] != NULL) - argc++; + char cmdline[ARG_MAX] = ""; + _Bool have_cmdline = 0; - status = strjoin (cmdline, sizeof (cmdline), - argv, argc, " "); - - if (status < 0) - { - WARNING ("processes plugin: Command line did " - "not fit into buffer."); - } - else + proc_ptr = &(procs[i]); + /* Don't probe system processes and processes without arguments */ + if (((procs[i].ki_flag & P_SYSTEM) == 0) + && (procs[i].ki_args != NULL)) { - cmdline_ptr = &cmdline[0]; - } - } + char **argv; + int argc; + int status; + + /* retrieve the arguments */ + argv = kvm_getargv (kd, proc_ptr, /* nchr = */ 0); + argc = 0; + if ((argv != NULL) && (argv[0] != NULL)) + { + while (argv[argc] != NULL) + argc++; + + status = strjoin (cmdline, sizeof (cmdline), argv, argc, " "); + if (status < 0) + WARNING ("processes plugin: Command line did not fit into buffer."); + else + have_cmdline = 1; + } + } /* if (process has argument list) */ - pse.id = procs[i].ki_pid; - pse.age = 0; + pse.id = procs[i].ki_pid; + pse.age = 0; - pse.num_proc = 1; - pse.num_lwp = procs[i].ki_numthreads; + pse.num_proc = 1; + pse.num_lwp = procs[i].ki_numthreads; - pse.vmem_size = procs[i].ki_size; - pse.vmem_rss = procs[i].ki_rssize * getpagesize(); - pse.vmem_data = procs[i].ki_dsize * getpagesize(); - pse.vmem_code = procs[i].ki_tsize * getpagesize(); - pse.stack_size = procs[i].ki_ssize * getpagesize(); - pse.vmem_minflt = 0; - pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt; - pse.vmem_majflt = 0; - pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt; + pse.vmem_size = procs[i].ki_size; + pse.vmem_rss = procs[i].ki_rssize * pagesize; + pse.vmem_data = procs[i].ki_dsize * pagesize; + pse.vmem_code = procs[i].ki_tsize * pagesize; + pse.stack_size = procs[i].ki_ssize * pagesize; + pse.vmem_minflt = 0; + pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt; + pse.vmem_majflt = 0; + pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt; - pse.cpu_user = 0; - pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_sec - * 1000 - + procs[i].ki_rusage.ru_utime.tv_usec; - pse.cpu_system = 0; - pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_sec - * 1000 - + procs[i].ki_rusage.ru_stime.tv_usec; + pse.cpu_user = 0; + pse.cpu_system = 0; + pse.cpu_user_counter = 0; + pse.cpu_system_counter = 0; + /* + * The u-area might be swapped out, and we can't get + * at it because we have a crashdump and no swap. + * If it's here fill in these fields, otherwise, just + * leave them 0. + */ + if (procs[i].ki_flag & P_INMEM) + { + pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_usec + + (1000000lu * procs[i].ki_rusage.ru_utime.tv_sec); + pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_usec + + (1000000lu * procs[i].ki_rusage.ru_stime.tv_sec); + } - /* no io data */ - pse.io_rchar = -1; - pse.io_wchar = -1; - pse.io_syscr = -1; - pse.io_syscw = -1; + /* no I/O data */ + pse.io_rchar = -1; + pse.io_wchar = -1; + pse.io_syscr = -1; + pse.io_syscw = -1; + + ps_list_add (procs[i].ki_comm, have_cmdline ? cmdline : NULL, &pse); + } /* if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) */ switch (procs[i].ki_stat) { @@ -1708,8 +1722,6 @@ static int ps_read (void) case SLOCK: blocked++; break; case SZOMB: zombies++; break; } - - ps_list_add (procs[i].ki_comm, cmdline_ptr, &pse); } kvm_close(kd); diff --git a/src/routeros.c b/src/routeros.c index d61ffe98..2ade3bb9 100644 --- a/src/routeros.c +++ b/src/routeros.c @@ -341,7 +341,7 @@ static int cr_config_router (oconfig_item_t *ci) /* {{{ */ if (strcasecmp ("Host", child->key) == 0) status = cf_util_get_string (child, &router_data->node); else if (strcasecmp ("Port", child->key) == 0) - status = cf_util_get_string (child, &router_data->service); + status = cf_util_get_service (child, &router_data->service); else if (strcasecmp ("User", child->key) == 0) status = cf_util_get_string (child, &router_data->username); else if (strcasecmp ("Password", child->key) == 0) diff --git a/src/rrdcached.c b/src/rrdcached.c index fb7eb79e..11c1c6a7 100644 --- a/src/rrdcached.c +++ b/src/rrdcached.c @@ -31,15 +31,6 @@ /* * Private variables */ -static const char *config_keys[] = -{ - "DaemonAddress", - "DataDir", - "CreateFiles", - "CollectStatistics" -}; -static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); - static char *datadir = NULL; static char *daemon_address = NULL; static int config_create_files = 1; @@ -58,6 +49,14 @@ static rrdcreate_config_t rrdcreate_config = /* consolidation_functions_num = */ 0 }; +/* + * Prototypes. + */ +static int rc_write (const data_set_t *ds, const value_list_t *vl, + user_data_t __attribute__((unused)) *user_data); +static int rc_flush (__attribute__((unused)) cdtime_t timeout, + const char *identifier, __attribute__((unused)) user_data_t *ud); + static int value_list_to_string (char *buffer, int buffer_len, const data_set_t *ds, const value_list_t *vl) { @@ -162,55 +161,91 @@ static int value_list_to_filename (char *buffer, int buffer_len, return (0); } /* int value_list_to_filename */ -static int rc_config (const char *key, const char *value) +static const char *config_get_string (oconfig_item_t *ci) { - if (strcasecmp ("DataDir", key) == 0) + if ((ci->children_num != 0) || (ci->values_num != 1) + || ((ci->values[0].type != OCONFIG_TYPE_STRING) + && (ci->values[0].type != OCONFIG_TYPE_BOOLEAN))) { - if (datadir != NULL) - free (datadir); - datadir = strdup (value); - if (datadir != NULL) + ERROR ("rrdcached plugin: %s expects a single string argument.", + ci->key); + return (NULL); + } + + if (ci->values[0].type == OCONFIG_TYPE_BOOLEAN) { + if (ci->values[0].value.boolean) + return "true"; + else + return "false"; + } + return (ci->values[0].value.string); +} /* const char *config_get_string */ + +static int rc_config (oconfig_item_t *ci) +{ + int i; + + for (i = 0; i < ci->children_num; ++i) { + const char *key = ci->children[i].key; + const char *value = config_get_string (ci->children + i); + + if (value == NULL) /* config_get_strings prints error message */ + continue; + + if (strcasecmp ("DataDir", key) == 0) { - int len = strlen (datadir); - while ((len > 0) && (datadir[len - 1] == '/')) + if (datadir != NULL) + free (datadir); + datadir = strdup (value); + if (datadir != NULL) { - len--; - datadir[len] = '\0'; + int len = strlen (datadir); + while ((len > 0) && (datadir[len - 1] == '/')) + { + len--; + datadir[len] = '\0'; + } + if (len <= 0) + { + free (datadir); + datadir = NULL; + } } - if (len <= 0) + } + else if (strcasecmp ("DaemonAddress", key) == 0) + { + sfree (daemon_address); + daemon_address = strdup (value); + if (daemon_address == NULL) { - free (datadir); - datadir = NULL; + ERROR ("rrdcached plugin: strdup failed."); + continue; } } - } - else if (strcasecmp ("DaemonAddress", key) == 0) - { - sfree (daemon_address); - daemon_address = strdup (value); - if (daemon_address == NULL) + else if (strcasecmp ("CreateFiles", key) == 0) { - ERROR ("rrdcached plugin: strdup failed."); - return (1); + if (IS_FALSE (value)) + config_create_files = 0; + else + config_create_files = 1; + } + else if (strcasecmp ("CollectStatistics", key) == 0) + { + if (IS_FALSE (value)) + config_collect_stats = 0; + else + config_collect_stats = 1; } - } - else if (strcasecmp ("CreateFiles", key) == 0) - { - if (IS_FALSE (value)) - config_create_files = 0; - else - config_create_files = 1; - } - else if (strcasecmp ("CollectStatistics", key) == 0) - { - if (IS_FALSE (value)) - config_collect_stats = 0; else - config_collect_stats = 1; + { + WARNING ("rrdcached plugin: Ignoring invalid option %s.", key); + continue; + } } - else - { - return (-1); + + if (daemon_address != NULL) { + plugin_register_write ("rrdcached", rc_write, /* user_data = */ NULL); + plugin_register_flush ("rrdcached", rc_flush, /* user_data = */ NULL); } return (0); } /* int rc_config */ @@ -328,7 +363,7 @@ static int rc_init (void) static int rc_write (const data_set_t *ds, const value_list_t *vl, user_data_t __attribute__((unused)) *user_data) { - char filename[512]; + char filename[PATH_MAX]; char values[512]; char *values_array[2]; int status; @@ -406,6 +441,41 @@ static int rc_write (const data_set_t *ds, const value_list_t *vl, return (0); } /* int rc_write */ +static int rc_flush (__attribute__((unused)) cdtime_t timeout, /* {{{ */ + const char *identifier, + __attribute__((unused)) user_data_t *ud) +{ + char filename[PATH_MAX + 1]; + int status; + + if (identifier == NULL) + return (EINVAL); + + if (datadir != NULL) + ssnprintf (filename, sizeof (filename), "%s/%s.rrd", datadir, identifier); + else + ssnprintf (filename, sizeof (filename), "%s.rrd", identifier); + + status = rrdc_connect (daemon_address); + if (status != 0) + { + ERROR ("rrdcached plugin: rrdc_connect (%s) failed with status %i.", + daemon_address, status); + return (-1); + } + + status = rrdc_flush (filename); + if (status != 0) + { + ERROR ("rrdcached plugin: rrdc_flush (%s) failed with status %i.", + filename, status); + return (-1); + } + DEBUG ("rrdcached plugin: rrdc_flush (%s): Success.", filename); + + return (0); +} /* }}} int rc_flush */ + static int rc_shutdown (void) { rrdc_disconnect (); @@ -414,10 +484,8 @@ static int rc_shutdown (void) void module_register (void) { - plugin_register_config ("rrdcached", rc_config, - config_keys, config_keys_num); + plugin_register_complex_config ("rrdcached", rc_config); plugin_register_init ("rrdcached", rc_init); - plugin_register_write ("rrdcached", rc_write, /* user_data = */ NULL); plugin_register_shutdown ("rrdcached", rc_shutdown); } /* void module_register */ diff --git a/src/sensors.c b/src/sensors.c index 8391346b..209482e0 100644 --- a/src/sensors.c +++ b/src/sensors.c @@ -27,6 +27,10 @@ * - honor sensors.conf's ignored * - config Sensor option * - config IgnoreSelected option + * + * Henrique de Moraes Holschuh + * - use default libsensors config file on API 0x400 + * - config SensorConfigFile option **/ #include "collectd.h" @@ -132,7 +136,8 @@ static int known_features_num = STATIC_ARRAY_SIZE (known_features); static const char *config_keys[] = { "Sensor", - "IgnoreSelected" + "IgnoreSelected", + "SensorConfigFile" }; static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); @@ -148,6 +153,7 @@ typedef struct featurelist # ifndef SENSORS_CONF_PATH # define SENSORS_CONF_PATH "/etc/sensors.conf" # endif +static char *conffile = SENSORS_CONF_PATH; /* #endif SENSORS_API_VERSION < 0x400 */ #elif (SENSORS_API_VERSION >= 0x400) && (SENSORS_API_VERSION < 0x500) @@ -159,9 +165,7 @@ typedef struct featurelist struct featurelist *next; } featurelist_t; -# ifndef SENSORS_CONF_PATH -# define SENSORS_CONF_PATH "/etc/sensors3.conf" -# endif +static char *conffile = NULL; /* #endif (SENSORS_API_VERSION >= 0x400) && (SENSORS_API_VERSION < 0x500) */ #else /* if SENSORS_API_VERSION >= 0x500 */ @@ -169,10 +173,8 @@ typedef struct featurelist "as bug." #endif -static const char *conffile = SENSORS_CONF_PATH; featurelist_t *first_feature = NULL; static ignorelist_t *sensor_list; -static time_t sensors_config_mtime = 0; #if SENSORS_API_VERSION < 0x400 /* full chip name logic borrowed from lm_sensors */ @@ -225,7 +227,19 @@ static int sensors_config (const char *key, const char *value) if (sensor_list == NULL) sensor_list = ignorelist_create (1); - if (strcasecmp (key, "Sensor") == 0) + /* TODO: This setting exists for compatibility with old versions of + * lm-sensors. Remove support for those ancient versions in the next + * major release. */ + if (strcasecmp (key, "SensorConfigFile") == 0) + { + char *tmp = strdup (value); + if (tmp != NULL) + { + sfree (conffile); + conffile = tmp; + } + } + else if (strcasecmp (key, "Sensor") == 0) { if (ignorelist_add (sensor_list, value)) { @@ -268,47 +282,37 @@ void sensors_free_features (void) static int sensors_load_conf (void) { - FILE *fh; + static int call_once = 0; + + FILE *fh = NULL; featurelist_t *last_feature = NULL; const sensors_chip_name *chip; int chip_num; - struct stat statbuf; int status; - - status = stat (conffile, &statbuf); - if (status != 0) - { - char errbuf[1024]; - ERROR ("sensors plugin: stat (%s) failed: %s", conffile, - sstrerror (errno, errbuf, sizeof (errbuf))); - sensors_config_mtime = 0; - } - if ((sensors_config_mtime != 0) - && (sensors_config_mtime == statbuf.st_mtime)) - return (0); + if (call_once) + return 0; - if (sensors_config_mtime != 0) - { - NOTICE ("sensors plugin: Reloading config from %s", - conffile); - sensors_free_features (); - sensors_config_mtime = 0; - } + call_once = 1; - fh = fopen (conffile, "r"); - if (fh == NULL) + if (conffile != NULL) { - char errbuf[1024]; - ERROR ("sensors plugin: fopen(%s) failed: %s", conffile, - sstrerror (errno, errbuf, sizeof (errbuf))); - return (-1); + fh = fopen (conffile, "r"); + if (fh == NULL) + { + char errbuf[1024]; + ERROR ("sensors plugin: fopen(%s) failed: %s", conffile, + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } } status = sensors_init (fh); - fclose (fh); + if (fh) + fclose (fh); + if (status != 0) { ERROR ("sensors plugin: Cannot initialize sensors. " @@ -316,8 +320,6 @@ static int sensors_load_conf (void) return (-1); } - sensors_config_mtime = statbuf.st_mtime; - #if SENSORS_API_VERSION < 0x400 chip_num = 0; while ((chip = sensors_get_detected_chips (&chip_num)) != NULL) diff --git a/src/snmp.c b/src/snmp.c index b8bbee44..f4966694 100644 --- a/src/snmp.c +++ b/src/snmp.c @@ -751,7 +751,8 @@ static void csnmp_host_open_session (host_definition_t *host) /* TODO: Check if negative values wrap around. Problem: negative temperatures. */ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type, - double scale, double shift) + double scale, double shift, + const char *host_name, const char *data_name) { value_t ret; uint64_t tmp_unsigned = 0; @@ -803,8 +804,11 @@ static value_t csnmp_value_list_to_value (struct variable_list *vl, int type, oid_buffer); else #endif - WARNING ("snmp plugin: I don't know the ASN type \"%i\" (OID: %s)", - (int) vl->type, oid_buffer); + WARNING ("snmp plugin: I don't know the ASN type #%i " + "(OID: \"%s\", data block \"%s\", host block \"%s\")", + (int) vl->type, oid_buffer, + (data_name != NULL) ? data_name : "UNKNOWN", + (host_name != NULL) ? host_name : "UNKNOWN"); defined = 0; } @@ -1025,8 +1029,8 @@ static int csnmp_strvbcopy (char *dst, /* {{{ */ static int csnmp_instance_list_add (csnmp_list_instances_t **head, csnmp_list_instances_t **tail, - struct snmp_pdu const *res, - oid_t const *root) + const struct snmp_pdu *res, + const host_definition_t *hd, const data_definition_t *dd) { csnmp_list_instances_t *il; struct variable_list *vb; @@ -1052,7 +1056,7 @@ static int csnmp_instance_list_add (csnmp_list_instances_t **head, memset (il, 0, sizeof (*il)); il->next = NULL; - status = csnmp_oid_suffix (&il->suffix, &vb_name, root); + status = csnmp_oid_suffix (&il->suffix, &vb_name, &dd->instance.oid); if (status != 0) { sfree (il); @@ -1077,7 +1081,8 @@ static int csnmp_instance_list_add (csnmp_list_instances_t **head, } else { - value_t val = csnmp_value_list_to_value (vb, DS_TYPE_COUNTER, 1.0, 0.0); + value_t val = csnmp_value_list_to_value (vb, DS_TYPE_COUNTER, + /* scale = */ 1.0, /* shift = */ 0.0, hd->name, dd->name); ssnprintf (il->instance, sizeof (il->instance), "%llu", val.counter); } @@ -1392,7 +1397,7 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data) /* Allocate a new `csnmp_list_instances_t', insert the instance name and * add it to the list */ if (csnmp_instance_list_add (&instance_list_head, &instance_list_tail, - res, &data->instance.oid) != 0) + res, host, data) != 0) { ERROR ("snmp plugin: csnmp_instance_list_add failed."); status = -1; @@ -1460,7 +1465,7 @@ static int csnmp_read_table (host_definition_t *host, data_definition_t *data) memset (vt, 0, sizeof (*vt)); vt->value = csnmp_value_list_to_value (vb, ds->ds[i].type, - data->scale, data->shift); + data->scale, data->shift, host->name, data->name); memcpy (&vt->suffix, &suffix, sizeof (vt->suffix)); vt->next = NULL; @@ -1612,7 +1617,7 @@ static int csnmp_read_value (host_definition_t *host, data_definition_t *data) if (snmp_oid_compare (data->values[i].oid, data->values[i].oid_len, vb->name, vb->name_length) == 0) vl.values[i] = csnmp_value_list_to_value (vb, ds->ds[i].type, - data->scale, data->shift); + data->scale, data->shift, host->name, data->name); } /* for (res->variables) */ if (res != NULL) diff --git a/src/swap.c b/src/swap.c index 30daa4b1..397969ef 100644 --- a/src/swap.c +++ b/src/swap.c @@ -70,19 +70,13 @@ #define MAX(x,y) ((x) > (y) ? (x) : (y)) #if KERNEL_LINUX +# define SWAP_HAVE_CONFIG 1 /* No global variables */ /* #endif KERNEL_LINUX */ #elif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS +# define SWAP_HAVE_CONFIG 1 static derive_t pagesize; - -static const char *config_keys[] = -{ - "ReportByDevice" -}; -static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); - -static _Bool report_by_device = 0; /* #endif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS */ #elif defined(VM_SWAPUSAGE) @@ -107,7 +101,34 @@ static perfstat_memory_total_t pmemory; # error "No applicable input method." #endif /* HAVE_LIBSTATGRAB */ -static int swap_init (void) +#if SWAP_HAVE_CONFIG +static const char *config_keys[] = +{ + "ReportByDevice" +}; +static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); + +static _Bool report_by_device = 0; + +static int swap_config (const char *key, const char *value) /* {{{ */ +{ + if (strcasecmp ("ReportByDevice", key) == 0) + { + if (IS_TRUE (value)) + report_by_device = 1; + else + report_by_device = 0; + } + else + { + return (-1); + } + + return (0); +} /* }}} int swap_config */ +#endif /* SWAP_HAVE_CONFIG */ + +static int swap_init (void) /* {{{ */ { #if KERNEL_LINUX /* No init stuff */ @@ -152,102 +173,188 @@ static int swap_init (void) #endif /* HAVE_PERFSTAT */ return (0); -} +} /* }}} int swap_init */ -static void swap_submit_inst (const char *plugin_instance, /* {{{ */ - const char *type_instance, derive_t value, unsigned type) +static void swap_submit (const char *plugin_instance, /* {{{ */ + const char *type, const char *type_instance, + value_t value) { - value_t values[1]; value_list_t vl = VALUE_LIST_INIT; - switch (type) - { - case DS_TYPE_GAUGE: - values[0].gauge = (gauge_t) value; - sstrncpy (vl.type, "swap", sizeof (vl.type)); - break; - case DS_TYPE_DERIVE: - values[0].derive = value; - sstrncpy (vl.type, "swap_io", sizeof (vl.type)); - break; - default: - ERROR ("swap plugin: swap_submit called with wrong" - " type"); - } + assert (type != NULL); - vl.values = values; + vl.values = &value; vl.values_len = 1; sstrncpy (vl.host, hostname_g, sizeof (vl.host)); sstrncpy (vl.plugin, "swap", sizeof (vl.plugin)); if (plugin_instance != NULL) sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); - sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); + sstrncpy (vl.type, type, sizeof (vl.type)); + if (type_instance != NULL) + sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); plugin_dispatch_values (&vl); } /* }}} void swap_submit_inst */ -static void swap_submit (const char *type_instance, derive_t value, unsigned type) +static void swap_submit_gauge (const char *plugin_instance, /* {{{ */ + const char *type_instance, gauge_t value) { - swap_submit_inst (/* plugin instance = */ NULL, - type_instance, value, type); -} + value_t v; + + v.gauge = value; + swap_submit (plugin_instance, "swap", type_instance, v); +} /* }}} void swap_submit_gauge */ #if KERNEL_LINUX -static int swap_read (void) /* {{{ */ +static void swap_submit_derive (const char *plugin_instance, /* {{{ */ + const char *type_instance, derive_t value) +{ + value_t v; + + v.derive = value; + swap_submit (plugin_instance, "swap_io", type_instance, v); +} /* }}} void swap_submit_derive */ + +static int swap_read_separate (void) /* {{{ */ { FILE *fh; char buffer[1024]; - char *fields[8]; - int numfields; + fh = fopen ("/proc/swaps", "r"); + if (fh == NULL) + { + char errbuf[1024]; + WARNING ("swap plugin: fopen (/proc/swaps) failed: %s", + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + + while (fgets (buffer, sizeof (buffer), fh) != NULL) + { + char *fields[8]; + int numfields; + char *endptr; + + char path[PATH_MAX]; + gauge_t size; + gauge_t used; + gauge_t free; + + numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields)); + if (numfields != 5) + continue; + + sstrncpy (path, fields[0], sizeof (path)); + escape_slashes (path, sizeof (path)); + + errno = 0; + endptr = NULL; + size = strtod (fields[2], &endptr); + if ((endptr == fields[2]) || (errno != 0)) + continue; + + errno = 0; + endptr = NULL; + used = strtod (fields[3], &endptr); + if ((endptr == fields[3]) || (errno != 0)) + continue; + + if (size < used) + continue; + + free = size - used; + + swap_submit_gauge (path, "used", used); + swap_submit_gauge (path, "free", free); + } + + fclose (fh); - _Bool old_kernel=0; + return (0); +} /* }}} int swap_read_separate */ + +static int swap_read_combined (void) /* {{{ */ +{ + FILE *fh; + char buffer[1024]; - derive_t swap_used = 0; - derive_t swap_cached = 0; - derive_t swap_free = 0; - derive_t swap_total = 0; - derive_t swap_in = 0; - derive_t swap_out = 0; + uint8_t have_data = 0; + gauge_t swap_used = 0.0; + gauge_t swap_cached = 0.0; + gauge_t swap_free = 0.0; + gauge_t swap_total = 0.0; - if ((fh = fopen ("/proc/meminfo", "r")) == NULL) + fh = fopen ("/proc/meminfo", "r"); + if (fh == NULL) { char errbuf[1024]; - WARNING ("memory: fopen: %s", + WARNING ("swap plugin: fopen (/proc/meminfo) failed: %s", sstrerror (errno, errbuf, sizeof (errbuf))); return (-1); } while (fgets (buffer, sizeof (buffer), fh) != NULL) { + char *fields[8]; + int numfields; + numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields)); if (numfields < 2) continue; if (strcasecmp (fields[0], "SwapTotal:") == 0) - strtoderive (fields[1], &swap_total); + { + swap_total = strtod (fields[1], /* endptr = */ NULL); + have_data |= 0x01; + } else if (strcasecmp (fields[0], "SwapFree:") == 0) - strtoderive (fields[1], &swap_free); + { + swap_free = strtod (fields[1], /* endptr = */ NULL); + have_data |= 0x02; + } else if (strcasecmp (fields[0], "SwapCached:") == 0) - strtoderive (fields[1], &swap_cached); + { + swap_cached = strtod (fields[1], /* endptr = */ NULL); + have_data |= 0x04; + } } - if (fclose (fh)) - { - char errbuf[1024]; - WARNING ("memory: fclose: %s", - sstrerror (errno, errbuf, sizeof (errbuf))); - } + fclose (fh); - if ((swap_free + swap_cached) > swap_total) - return (-1); + if (have_data != 0x07) + return (ENOENT); + + if (isnan (swap_total) + || (swap_total <= 0.0) + || ((swap_free + swap_cached) > swap_total)) + return (EINVAL); swap_used = swap_total - (swap_free + swap_cached); - if ((fh = fopen ("/proc/vmstat", "r")) == NULL) + swap_submit_gauge (NULL, "used", 1024.0 * swap_used); + swap_submit_gauge (NULL, "free", 1024.0 * swap_free); + swap_submit_gauge (NULL, "cached", 1024.0 * swap_cached); + + return (0); +} /* }}} int swap_read_combined */ + +static int swap_read_io (void) /* {{{ */ +{ + FILE *fh; + char buffer[1024]; + + _Bool old_kernel = 0; + + uint8_t have_data = 0; + derive_t swap_in = 0; + derive_t swap_out = 0; + + fh = fopen ("/proc/vmstat", "r"); + if (fh == NULL) { - // /proc/vmstat does not exist in kernels <2.6 - if ((fh = fopen ("/proc/stat", "r")) == NULL ) + /* /proc/vmstat does not exist in kernels <2.6 */ + fh = fopen ("/proc/stat", "r"); + if (fh == NULL) { char errbuf[1024]; WARNING ("swap: fopen: %s", @@ -260,6 +367,9 @@ static int swap_read (void) /* {{{ */ while (fgets (buffer, sizeof (buffer), fh) != NULL) { + char *fields[8]; + int numfields; + numfields = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields)); if (!old_kernel) @@ -268,9 +378,15 @@ static int swap_read (void) /* {{{ */ continue; if (strcasecmp ("pswpin", fields[0]) == 0) + { strtoderive (fields[1], &swap_in); + have_data |= 0x01; + } else if (strcasecmp ("pswpout", fields[0]) == 0) + { strtoderive (fields[1], &swap_out); + have_data |= 0x02; + } } else /* if (old_kernel) */ { @@ -285,18 +401,25 @@ static int swap_read (void) /* {{{ */ } } /* while (fgets) */ - if (fclose (fh)) - { - char errbuf[1024]; - WARNING ("swap: fclose: %s", - sstrerror (errno, errbuf, sizeof (errbuf))); - } + fclose (fh); + + if (have_data != 0x03) + return (ENOENT); + + swap_submit_derive (NULL, "in", swap_in); + swap_submit_derive (NULL, "out", swap_out); + + return (0); +} /* }}} int swap_read_io */ - swap_submit ("used", 1024 * swap_used, DS_TYPE_GAUGE); - swap_submit ("free", 1024 * swap_free, DS_TYPE_GAUGE); - swap_submit ("cached", 1024 * swap_cached, DS_TYPE_GAUGE); - swap_submit ("in", swap_in, DS_TYPE_DERIVE); - swap_submit ("out", swap_out, DS_TYPE_DERIVE); +static int swap_read (void) /* {{{ */ +{ + if (report_by_device) + swap_read_separate (); + else + swap_read_combined (); + + swap_read_io (); return (0); } /* }}} int swap_read */ @@ -355,9 +478,9 @@ static int swap_read_kstat (void) /* {{{ */ * pagesize); swap_avail = (derive_t) ((ai.ani_max - ai.ani_resv) * pagesize); - swap_submit ("used", swap_alloc, DS_TYPE_GAUGE); - swap_submit ("free", swap_avail, DS_TYPE_GAUGE); - swap_submit ("reserved", swap_resv, DS_TYPE_GAUGE); + swap_submit_gauge (NULL, "used", swap_alloc); + swap_submit_gauge (NULL, "free", swap_avail); + swap_submit_gauge (NULL, "reserved", swap_resv); return (0); } /* }}} int swap_read_kstat */ @@ -454,25 +577,11 @@ static int swap_read (void) /* {{{ */ continue; } - /* Okay, using "/" as swap device would be super-weird, but - * we'll handle it anyway to cover all cases. */ - if (strcmp ("/", s->swt_ent[i].ste_path) == 0) - sstrncpy (path, "root", sizeof (path)); - else - { - int j; - - s->swt_ent[i].ste_path[PATH_MAX - 1] = 0; - /* Don't copy the leading slash */ - sstrncpy (path, &s->swt_ent[i].ste_path[1], sizeof (path)); - /* Convert slashes to dashes, just like the "df" plugin. */ - for (j = 0; path[j] != 0; j++) - if (path[j] == '/') - path[j] = '-'; - } + sstrncpy (path, s->swt_ent[i].ste_path, sizeof (path)); + escape_slashes (path, sizeof (path)); - swap_submit_inst (path, "used", this_total - this_avail, DS_TYPE_GAUGE); - swap_submit_inst (path, "free", this_avail, DS_TYPE_GAUGE); + swap_submit_gauge (path, "used", (gauge_t) (this_total - this_avail)); + swap_submit_gauge (path, "free", (gauge_t) this_avail); } /* for (swap_num) */ if (total < avail) @@ -489,32 +598,14 @@ static int swap_read (void) /* {{{ */ * values have already been dispatched from within the loop. */ if (!report_by_device) { - swap_submit ("used", total - avail, DS_TYPE_GAUGE); - swap_submit ("free", avail, DS_TYPE_GAUGE); + swap_submit_gauge (NULL, "used", (gauge_t) (total - avail)); + swap_submit_gauge (NULL, "free", (gauge_t) avail); } sfree (s_paths); sfree (s); return (0); } /* }}} int swap_read */ - -/* Configuration: Present when swapctl or both methods are available. */ -static int swap_config (const char *key, const char *value) /* {{{ */ -{ - if (strcasecmp ("ReportByDevice", key) == 0) - { - if (IS_TRUE (value)) - report_by_device = 1; - else - report_by_device = 0; - } - else - { - return (-1); - } - - return (0); -} /* }}} int swap_config */ /* #endif HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS */ #elif HAVE_SWAPCTL && HAVE_SWAPCTL_THREE_ARGS @@ -579,8 +670,8 @@ static int swap_read (void) /* {{{ */ return (-1); } - swap_submit ("used", used, DS_TYPE_GAUGE); - swap_submit ("free", total - used, DS_TYPE_GAUGE); + swap_submit_gauge (NULL, "used", (gauge_t) used); + swap_submit_gauge (NULL, "free", (gauge_t) (total - used)); sfree (swap_entries); @@ -606,8 +697,8 @@ static int swap_read (void) /* {{{ */ return (-1); /* The returned values are bytes. */ - swap_submit ("used", (derive_t) sw_usage.xsu_used, DS_TYPE_GAUGE); - swap_submit ("free", (derive_t) sw_usage.xsu_avail, DS_TYPE_GAUGE); + swap_submit_gauge (NULL, "used", (gauge_t) sw_usage.xsu_used); + swap_submit_gauge (NULL, "free", (gauge_t) sw_usage.xsu_avail); return (0); } /* }}} int swap_read */ @@ -639,8 +730,8 @@ static int swap_read (void) /* {{{ */ free = total - used; - swap_submit ("used", used, DS_TYPE_GAUGE); - swap_submit ("free", free, DS_TYPE_GAUGE); + swap_submit_gauge (NULL, "used", (gauge_t) used); + swap_submit_gauge (NULL, "free", (gauge_t) free); return (0); } /* }}} int swap_read */ @@ -656,8 +747,8 @@ static int swap_read (void) /* {{{ */ if (swap == NULL) return (-1); - swap_submit ("used", (derive_t) swap->used, DS_TYPE_GAUGE); - swap_submit ("free", (derive_t) swap->free, DS_TYPE_GAUGE); + swap_submit_gauge (NULL, "used", (gauge_t) swap->used); + swap_submit_gauge (NULL, "free", (gauge_t) swap->free); return (0); } /* }}} int swap_read */ @@ -673,8 +764,8 @@ static int swap_read (void) /* {{{ */ sstrerror (errno, errbuf, sizeof (errbuf))); return (-1); } - swap_submit ("used", (derive_t) (pmemory.pgsp_total - pmemory.pgsp_free) * pagesize, DS_TYPE_GAUGE); - swap_submit ("free", (derive_t) pmemory.pgsp_free * pagesize , DS_TYPE_GAUGE); + swap_submit_gauge (NULL, "used", (gauge_t) (pmemory.pgsp_total - pmemory.pgsp_free) * pagesize); + swap_submit_gauge (NULL, "free", (gauge_t) pmemory.pgsp_free * pagesize ); return (0); } /* }}} int swap_read */ @@ -682,7 +773,7 @@ static int swap_read (void) /* {{{ */ void module_register (void) { -#if HAVE_SWAPCTL && HAVE_SWAPCTL_TWO_ARGS +#if SWAP_HAVE_CONFIG plugin_register_config ("swap", swap_config, config_keys, config_keys_num); #endif plugin_register_init ("swap", swap_init); diff --git a/src/syslog.c b/src/syslog.c index ace9dc6f..4f5d0c4a 100644 --- a/src/syslog.c +++ b/src/syslog.c @@ -33,10 +33,12 @@ static int log_level = LOG_DEBUG; #else static int log_level = LOG_INFO; #endif /* COLLECT_DEBUG */ +static int notif_severity = 0; static const char *config_keys[] = { - "LogLevel" + "LogLevel", + "NotifyLevel", }; static int config_keys_num = STATIC_ARRAY_SIZE(config_keys); @@ -44,26 +46,16 @@ static int sl_config (const char *key, const char *value) { if (strcasecmp (key, "LogLevel") == 0) { - if ((strcasecmp (value, "emerg") == 0) - || (strcasecmp (value, "alert") == 0) - || (strcasecmp (value, "crit") == 0) - || (strcasecmp (value, "err") == 0)) - log_level = LOG_ERR; - else if (strcasecmp (value, "warning") == 0) - log_level = LOG_WARNING; - else if (strcasecmp (value, "notice") == 0) - log_level = LOG_NOTICE; - else if (strcasecmp (value, "info") == 0) - log_level = LOG_INFO; -#if COLLECT_DEBUG - else if (strcasecmp (value, "debug") == 0) - log_level = LOG_DEBUG; -#endif - else + log_level = parse_log_severity (value); + if (log_level < 0) + return (1); + } + else if (strcasecmp (key, "NotifyLevel") == 0) + { + notif_severity = parse_notif_severity (value); + if (notif_severity < 0) return (1); } - else - return (-1); return (0); } /* int sl_config */ @@ -84,11 +76,77 @@ static int sl_shutdown (void) return (0); } +static int sl_notification (const notification_t *n, + user_data_t __attribute__((unused)) *user_data) +{ + char buf[1024] = ""; + size_t offset = 0; + int log_severity; + char *severity_string; + int status; + + if (n->severity > notif_severity) + return (0); + + switch (n->severity) + { + case NOTIF_FAILURE: + severity_string = "FAILURE"; + log_severity = LOG_ERR; + break; + case NOTIF_WARNING: + severity_string = "WARNING"; + log_severity = LOG_WARNING; + break; + case NOTIF_OKAY: + severity_string = "OKAY"; + log_severity = LOG_NOTICE; + break; + default: + severity_string = "UNKNOWN"; + log_severity = LOG_ERR; + } + +#define BUFFER_ADD(...) do { \ + status = ssnprintf (&buf[offset], sizeof (buf) - offset, \ + __VA_ARGS__); \ + if (status < 1) \ + return (-1); \ + else if (((size_t) status) >= (sizeof (buf) - offset)) \ + return (-ENOMEM); \ + else \ + offset += ((size_t) status); \ +} while (0) + +#define BUFFER_ADD_FIELD(field) do { \ + if (n->field[0]) \ + BUFFER_ADD (", " #field " = %s", n->field); \ +} while (0) + + BUFFER_ADD ("Notification: severity = %s", severity_string); + BUFFER_ADD_FIELD (host); + BUFFER_ADD_FIELD (plugin); + BUFFER_ADD_FIELD (plugin_instance); + BUFFER_ADD_FIELD (type); + BUFFER_ADD_FIELD (type_instance); + BUFFER_ADD_FIELD (message); + +#undef BUFFER_ADD_FIELD +#undef BUFFER_ADD + + buf[sizeof (buf) - 1] = '\0'; + + sl_log (log_severity, buf, NULL); + + return (0); +} /* int sl_notification */ + void module_register (void) { openlog ("collectd", LOG_CONS | LOG_PID, LOG_DAEMON); plugin_register_config ("syslog", sl_config, config_keys, config_keys_num); plugin_register_log ("syslog", sl_log, /* user_data = */ NULL); + plugin_register_notification ("syslog", sl_notification, NULL); plugin_register_shutdown ("syslog", sl_shutdown); } /* void module_register(void) */ diff --git a/src/target_scale.c b/src/target_scale.c index af224f10..bef03e58 100644 --- a/src/target_scale.c +++ b/src/target_scale.c @@ -29,6 +29,9 @@ struct ts_data_s { double factor; double offset; + + char **data_sources; + size_t data_sources_num; }; typedef struct ts_data_s ts_data_t; @@ -300,17 +303,86 @@ static int ts_config_set_double (double *ret, oconfig_item_t *ci) /* {{{ */ return (0); } /* }}} int ts_config_set_double */ +static int ts_config_add_data_source(ts_data_t *data, /* {{{ */ + oconfig_item_t *ci) +{ + size_t new_data_sources_num; + char **temp; + int i; + + /* Check number of arbuments. */ + if (ci->values_num < 1) + { + ERROR ("`value' match: `%s' needs at least one argument.", + ci->key); + return (-1); + } + + /* Check type of arguments */ + for (i = 0; i < ci->values_num; i++) + { + if (ci->values[i].type == OCONFIG_TYPE_STRING) + continue; + + ERROR ("`value' match: `%s' accepts only string arguments " + "(argument %i is a %s).", + ci->key, i + 1, + (ci->values[i].type == OCONFIG_TYPE_BOOLEAN) + ? "truth value" : "number"); + return (-1); + } + + /* Allocate space for the char pointers */ + new_data_sources_num = data->data_sources_num + ((size_t) ci->values_num); + temp = (char **) realloc (data->data_sources, + new_data_sources_num * sizeof (char *)); + if (temp == NULL) + { + ERROR ("`value' match: realloc failed."); + return (-1); + } + data->data_sources = temp; + + /* Copy the strings, allocating memory as needed. */ + for (i = 0; i < ci->values_num; i++) + { + size_t j; + + /* If we get here, there better be memory for us to write to. */ + assert (data->data_sources_num < new_data_sources_num); + + j = data->data_sources_num; + data->data_sources[j] = sstrdup (ci->values[i].value.string); + if (data->data_sources[j] == NULL) + { + ERROR ("`value' match: sstrdup failed."); + continue; + } + data->data_sources_num++; + } + + return (0); +} /* }}} int ts_config_add_data_source */ + static int ts_destroy (void **user_data) /* {{{ */ { - ts_data_t **data; + ts_data_t *data; if (user_data == NULL) return (-EINVAL); - data = (ts_data_t **) user_data; + data = (ts_data_t *) *user_data; - free (*data); - *data = NULL; + if ((data != NULL) && (data->data_sources != NULL)) + { + size_t i; + for (i = 0; i < data->data_sources_num; i++) + sfree (data->data_sources[i]); + sfree (data->data_sources); + } + + sfree (data); + *user_data = NULL; return (0); } /* }}} int ts_destroy */ @@ -341,6 +413,8 @@ static int ts_create (const oconfig_item_t *ci, void **user_data) /* {{{ */ status = ts_config_set_double (&data->factor, child); else if (strcasecmp ("Offset", child->key) == 0) status = ts_config_set_double (&data->offset, child); + else if (strcasecmp ("DataSource", child->key) == 0) + status = ts_config_add_data_source(data, child); else { ERROR ("Target `scale': The `%s' configuration option is not understood " @@ -393,6 +467,18 @@ static int ts_invoke (const data_set_t *ds, value_list_t *vl, /* {{{ */ for (i = 0; i < ds->ds_num; i++) { + /* If we've got a list of data sources, is it in the list? */ + if (data->data_sources) { + size_t j; + for (j = 0; j < data->data_sources_num; j++) + if (strcasecmp(ds->ds[i].name, data->data_sources[j]) == 0) + break; + + /* No match, ignore */ + if (j >= data->data_sources_num) + continue; + } + if (ds->ds[i].type == DS_TYPE_COUNTER) ts_invoke_counter (ds, vl, data, i); else if (ds->ds[i].type == DS_TYPE_GAUGE) diff --git a/src/tcpconns.c b/src/tcpconns.c index 78c337b7..3c8fc728 100644 --- a/src/tcpconns.c +++ b/src/tcpconns.c @@ -65,7 +65,7 @@ #undef HAVE_SYSCTLBYNAME /* force HAVE_LIBKVM_NLIST path */ #endif -#if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST +#if !KERNEL_LINUX && !HAVE_SYSCTLBYNAME && !HAVE_LIBKVM_NLIST && !KERNEL_AIX # error "No applicable input method." #endif @@ -122,7 +122,12 @@ # include # endif # include -#endif /* HAVE_LIBKVM_NLIST */ +/* #endif HAVE_LIBKVM_NLIST */ + +#elif KERNEL_AIX +# include +# include +#endif /* KERNEL_AIX */ #if KERNEL_LINUX static const char *tcp_state[] = @@ -190,7 +195,49 @@ struct inpcbtable *inpcbtable_ptr = NULL; # define TCP_STATE_LISTEN 1 # define TCP_STATE_MIN 1 # define TCP_STATE_MAX 10 -#endif /* HAVE_LIBKVM_NLIST */ +/* #endif HAVE_LIBKVM_NLIST */ + +#elif KERNEL_AIX +static const char *tcp_state[] = +{ + "CLOSED", + "LISTEN", + "SYN_SENT", + "SYN_RCVD", + "ESTABLISHED", + "CLOSE_WAIT", + "FIN_WAIT_1", + "CLOSING", + "LAST_ACK", + "FIN_WAIT_2", + "TIME_WAIT" +}; + +# define TCP_STATE_LISTEN 1 +# define TCP_STATE_MIN 0 +# define TCP_STATE_MAX 10 + +struct netinfo_conn { + uint32_t unknow1[2]; + uint16_t dstport; + uint16_t unknow2; + struct in6_addr dstaddr; + uint16_t srcport; + uint16_t unknow3; + struct in6_addr srcaddr; + uint32_t unknow4[36]; + uint16_t tcp_state; + uint16_t unknow5[7]; +}; + +struct netinfo_header { + unsigned int proto; + unsigned int size; +}; + +# define NETINFO_TCP 3 +extern int netinfo (int proto, void *data, int *size, int n); +#endif /* KERNEL_AIX */ #define PORT_COLLECT_LOCAL 0x01 #define PORT_COLLECT_REMOTE 0x02 @@ -710,7 +757,67 @@ static int conn_read (void) return (0); } -#endif /* HAVE_LIBKVM_NLIST */ +/* #endif HAVE_LIBKVM_NLIST */ + +#elif KERNEL_AIX + +static int conn_read (void) +{ + int size; + int i; + int nconn; + void *data; + struct netinfo_header *header; + struct netinfo_conn *conn; + + conn_reset_port_entry (); + + size = netinfo(NETINFO_TCP, 0, 0, 0); + if (size < 0) + { + ERROR ("tcpconns plugin: netinfo failed return: %i", size); + return (-1); + } + + if (size == 0) + return (0); + + if ((size - sizeof (struct netinfo_header)) % sizeof (struct netinfo_conn)) + { + ERROR ("tcpconns plugin: invalid buffer size"); + return (-1); + } + + data = malloc(size); + if (data == NULL) + { + ERROR ("tcpconns plugin: malloc failed"); + return (-1); + } + + if (netinfo(NETINFO_TCP, data, &size, 0) < 0) + { + ERROR ("tcpconns plugin: netinfo failed"); + free(data); + return (-1); + } + + header = (struct netinfo_header *)data; + nconn = header->size; + conn = (struct netinfo_conn *)(data + sizeof(struct netinfo_header)); + + for (i=0; i < nconn; conn++, i++) + { + conn_handle_ports (conn->srcport, conn->dstport, conn->tcp_state); + } + + free(data); + + conn_submit_all (); + + return (0); +} +#endif /* KERNEL_AIX */ void module_register (void) { @@ -722,6 +829,8 @@ void module_register (void) /* no initialization */ #elif HAVE_LIBKVM_NLIST plugin_register_init ("tcpconns", conn_init); +#elif KERNEL_AIX + /* no initialization */ #endif plugin_register_read ("tcpconns", conn_read); } /* void module_register */ diff --git a/src/threshold.c b/src/threshold.c index 7bbc59ef..d4cfd6ea 100644 --- a/src/threshold.c +++ b/src/threshold.c @@ -39,6 +39,7 @@ #define UT_FLAG_PERSIST 0x02 #define UT_FLAG_PERCENTAGE 0x04 #define UT_FLAG_INTERESTING 0x08 +#define UT_FLAG_PERSIST_OK 0x10 typedef struct threshold_s { char host[DATA_MAX_NAME_LEN]; @@ -378,6 +379,8 @@ static int ut_config_type (const threshold_t *th_orig, oconfig_item_t *ci) status = cf_util_get_flag (option, &th.flags, UT_FLAG_INVERT); else if (strcasecmp ("Persist", option->key) == 0) status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERSIST); + else if (strcasecmp ("PersistOK", option->key) == 0) + status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERSIST_OK); else if (strcasecmp ("Percentage", option->key) == 0) status = cf_util_get_flag (option, &th.flags, UT_FLAG_PERCENTAGE); else if (strcasecmp ("Hits", option->key) == 0) @@ -512,57 +515,6 @@ static int ut_config_host (const threshold_t *th_orig, oconfig_item_t *ci) return (status); } /* int ut_config_host */ - -int ut_config (oconfig_item_t *ci) -{ - int i; - int status = 0; - - threshold_t th; - - if (threshold_tree == NULL) - { - threshold_tree = c_avl_create ((void *) strcmp); - if (threshold_tree == NULL) - { - ERROR ("ut_config: c_avl_create failed."); - return (-1); - } - } - - memset (&th, '\0', sizeof (th)); - th.warning_min = NAN; - th.warning_max = NAN; - th.failure_min = NAN; - th.failure_max = NAN; - - th.hits = 0; - th.hysteresis = 0; - th.flags = UT_FLAG_INTERESTING; /* interesting by default */ - - for (i = 0; i < ci->children_num; i++) - { - oconfig_item_t *option = ci->children + i; - status = 0; - - if (strcasecmp ("Type", option->key) == 0) - status = ut_config_type (&th, option); - else if (strcasecmp ("Plugin", option->key) == 0) - status = ut_config_plugin (&th, option); - else if (strcasecmp ("Host", option->key) == 0) - status = ut_config_host (&th, option); - else - { - WARNING ("threshold values: Option `%s' not allowed here.", option->key); - status = -1; - } - - if (status != 0) - break; - } - - return (status); -} /* int um_config */ /* * End of the functions used to configure threshold values. */ @@ -594,8 +546,9 @@ static int ut_report_state (const data_set_t *ds, if ( (th->hits != 0) ) { int hits = uc_get_hits(ds,vl); - /* The STATE_OKAY always reset hits, or if hits reaise the limit */ - if ( (state == STATE_OKAY) || (hits > th->hits) ) + /* STATE_OKAY resets hits unless PERSIST_OK flag is set. Hits resets if + * threshold is hit. */ + if ( ( (state == STATE_OKAY) && ((th->flags & UT_FLAG_PERSIST_OK) == 0) ) || (hits > th->hits) ) { DEBUG("ut_report_state: reset uc_get_hits = 0"); uc_set_hits(ds,vl,0); /* reset hit counter and notify */ @@ -608,13 +561,13 @@ static int ut_report_state (const data_set_t *ds, state_old = uc_get_state (ds, vl); - /* If the state didn't change, only report if `persistent' is specified and - * the state is not `okay'. */ + /* If the state didn't change, report if `persistent' is specified. If the + * state is `okay', then only report if `persist_ok` flag is set. */ if (state == state_old) { if ((th->flags & UT_FLAG_PERSIST) == 0) return (0); - else if (state == STATE_OKAY) + else if ( (state == STATE_OKAY) && ((th->flags & UT_FLAG_PERSIST_OK) == 0) ) return (0); } @@ -990,6 +943,10 @@ static int ut_missing (const value_list_t *vl, char identifier[6 * DATA_MAX_NAME_LEN]; notification_t n; + /* dispatch notifications for "interesting" values only */ + if (threshold_tree == NULL) + return (0); + th = threshold_search (vl); if (th == NULL) return (0); @@ -1007,13 +964,67 @@ static int ut_missing (const value_list_t *vl, return (0); } /* }}} int ut_missing */ +int ut_config (oconfig_item_t *ci) +{ /* {{{ */ + int i; + int status = 0; + + threshold_t th; + + if (threshold_tree == NULL) + { + threshold_tree = c_avl_create ((void *) strcmp); + if (threshold_tree == NULL) + { + ERROR ("ut_config: c_avl_create failed."); + return (-1); + } + } + + memset (&th, '\0', sizeof (th)); + th.warning_min = NAN; + th.warning_max = NAN; + th.failure_min = NAN; + th.failure_max = NAN; + + th.hits = 0; + th.hysteresis = 0; + th.flags = UT_FLAG_INTERESTING; /* interesting by default */ + + for (i = 0; i < ci->children_num; i++) + { + oconfig_item_t *option = ci->children + i; + status = 0; + + if (strcasecmp ("Type", option->key) == 0) + status = ut_config_type (&th, option); + else if (strcasecmp ("Plugin", option->key) == 0) + status = ut_config_plugin (&th, option); + else if (strcasecmp ("Host", option->key) == 0) + status = ut_config_host (&th, option); + else + { + WARNING ("threshold values: Option `%s' not allowed here.", option->key); + status = -1; + } + + if (status != 0) + break; + } + + if (c_avl_size (threshold_tree) > 0) { + plugin_register_missing ("threshold", ut_missing, + /* user data = */ NULL); + plugin_register_write ("threshold", ut_check_threshold, + /* user data = */ NULL); + } + + return (status); +} /* }}} int um_config */ + void module_register (void) { plugin_register_complex_config ("threshold", ut_config); - plugin_register_missing ("threshold", ut_missing, - /* user data = */ NULL); - plugin_register_write ("threshold", ut_check_threshold, - /* user data = */ NULL); } /* vim: set sw=2 ts=8 sts=2 tw=78 et fdm=marker : */ diff --git a/src/types.db b/src/types.db index e6345ab6..ed27b785 100644 --- a/src/types.db +++ b/src/types.db @@ -8,6 +8,7 @@ ath_nodes value:GAUGE:0:65535 ath_stat value:DERIVE:0:U bitrate value:GAUGE:0:4294967295 bytes value:GAUGE:0:U +cache_eviction value:DERIVE:0:U cache_operation value:DERIVE:0:U cache_ratio value:GAUGE:0:100 cache_result value:DERIVE:0:U @@ -63,6 +64,7 @@ frequency value:GAUGE:0:U frequency_offset value:GAUGE:-1000000:1000000 fscache_stat value:DERIVE:0:U gauge value:GAUGE:U:U +hash_collisions value:DERIVE:0:U http_request_methods value:DERIVE:0:U http_requests value:DERIVE:0:U http_response_codes value:DERIVE:0:U @@ -84,6 +86,7 @@ irq value:DERIVE:0:U latency value:GAUGE:0:65535 links value:GAUGE:0:U load shortterm:GAUGE:0:100, midterm:GAUGE:0:100, longterm:GAUGE:0:100 +md_disks value:GAUGE:0:U memcached_command value:DERIVE:0:U memcached_connections value:GAUGE:0:U memcached_items value:GAUGE:0:U @@ -91,6 +94,7 @@ memcached_octets rx:DERIVE:0:U, tx:DERIVE:0:U memcached_ops value:DERIVE:0:U memory value:GAUGE:0:281474976710656 multimeter value:GAUGE:U:U +mutex_operations value:DERIVE:0:U mysql_commands value:DERIVE:0:U mysql_handler value:DERIVE:0:U mysql_locks value:DERIVE:0:U diff --git a/src/utils_avltree.c b/src/utils_avltree.c index 12310d3f..f71b1fd6 100644 --- a/src/utils_avltree.c +++ b/src/utils_avltree.c @@ -51,6 +51,7 @@ struct c_avl_tree_s { c_avl_node_t *root; int (*compare) (const void *, const void *); + int size; }; struct c_avl_iterator_s @@ -479,6 +480,7 @@ c_avl_tree_t *c_avl_create (int (*compare) (const void *, const void *)) t->root = NULL; t->compare = compare; + t->size = 0; return (t); } @@ -510,6 +512,7 @@ int c_avl_insert (c_avl_tree_t *t, void *key, void *value) { new->parent = NULL; t->root = new; + t->size = 1; return (0); } @@ -555,6 +558,7 @@ int c_avl_insert (c_avl_tree_t *t, void *key, void *value) } /* while (42) */ verify_tree (t->root); + ++t->size; return (0); } /* int c_avl_insert */ @@ -576,6 +580,7 @@ int c_avl_remove (c_avl_tree_t *t, const void *key, void **rkey, void **rvalue) status = _remove (t, n); verify_tree (t->root); + --t->size; return (status); } /* void *c_avl_remove */ @@ -712,3 +717,10 @@ void c_avl_iterator_destroy (c_avl_iterator_t *iter) { free (iter); } + +int c_avl_size (c_avl_tree_t *t) +{ + if (t == NULL) + return (0); + return (t->size); +} diff --git a/src/utils_avltree.h b/src/utils_avltree.h index 355ced24..10fb5cbe 100644 --- a/src/utils_avltree.h +++ b/src/utils_avltree.h @@ -148,4 +148,19 @@ int c_avl_iterator_next (c_avl_iterator_t *iter, void **key, void **value); int c_avl_iterator_prev (c_avl_iterator_t *iter, void **key, void **value); void c_avl_iterator_destroy (c_avl_iterator_t *iter); +/* + * NAME + * c_avl_size + * + * DESCRIPTION + * Return the size (number of nodes) of the specified tree. + * + * PARAMETERS + * `t' AVL-tree to get the size of. + * + * RETURN VALUE + * Number of nodes in the tree, 0 if the tree is empty or NULL. + */ +int c_avl_size (c_avl_tree_t *t); + #endif /* UTILS_AVLTREE_H */ diff --git a/src/varnish.c b/src/varnish.c index 37fd4bb3..de60e39c 100644 --- a/src/varnish.c +++ b/src/varnish.c @@ -134,6 +134,15 @@ #include +#if HAVE_VARNISH_V3 +# include +typedef struct VSC_C_main c_varnish_stats_t; +#endif + +#if HAVE_VARNISH_V2 +typedef struct varnish_stats c_varnish_stats_t; +#endif + /* {{{ user_config_s */ struct user_config_s { char *instance; @@ -145,9 +154,11 @@ struct user_config_s { _Bool collect_fetch; _Bool collect_hcb; _Bool collect_shm; - _Bool collect_sma; _Bool collect_sms; +#if HAVE_VARNISH_V2 _Bool collect_sm; + _Bool collect_sma; +#endif _Bool collect_totals; _Bool collect_workers; }; @@ -204,182 +215,194 @@ static int varnish_submit_derive (const char *plugin_instance, /* {{{ */ return (varnish_submit (plugin_instance, category, type, type_instance, value)); } /* }}} int varnish_submit_derive */ -static void varnish_monitor (const user_config_t *conf, struct varnish_stats *VSL_stats) /* {{{ */ +static void varnish_monitor (const user_config_t *conf, /* {{{ */ + const c_varnish_stats_t *stats) { if (conf->collect_cache) { /* Cache hits */ - varnish_submit_derive (conf->instance, "cache", "cache_result", "hit", VSL_stats->cache_hit); + varnish_submit_derive (conf->instance, "cache", "cache_result", "hit", stats->cache_hit); /* Cache misses */ - varnish_submit_derive (conf->instance, "cache", "cache_result", "miss", VSL_stats->cache_miss); + varnish_submit_derive (conf->instance, "cache", "cache_result", "miss", stats->cache_miss); /* Cache hits for pass */ - varnish_submit_derive (conf->instance, "cache", "cache_result", "hitpass", VSL_stats->cache_hitpass); + varnish_submit_derive (conf->instance, "cache", "cache_result", "hitpass", stats->cache_hitpass); } if (conf->collect_connections) { /* Client connections accepted */ - varnish_submit_derive (conf->instance, "connections", "connections", "accepted", VSL_stats->client_conn); + varnish_submit_derive (conf->instance, "connections", "connections", "accepted", stats->client_conn); /* Connection dropped, no sess */ - varnish_submit_derive (conf->instance, "connections", "connections", "dropped" , VSL_stats->client_drop); + varnish_submit_derive (conf->instance, "connections", "connections", "dropped" , stats->client_drop); /* Client requests received */ - varnish_submit_derive (conf->instance, "connections", "connections", "received", VSL_stats->client_req); + varnish_submit_derive (conf->instance, "connections", "connections", "received", stats->client_req); } if (conf->collect_esi) { - /* Objects ESI parsed (unlock) */ - varnish_submit_derive (conf->instance, "esi", "total_operations", "parsed", VSL_stats->esi_parse); /* ESI parse errors (unlock) */ - varnish_submit_derive (conf->instance, "esi", "total_operations", "error", VSL_stats->esi_errors); + varnish_submit_derive (conf->instance, "esi", "total_operations", "error", stats->esi_errors); +#if HAVE_VARNISH_V2 + /* Objects ESI parsed (unlock) */ + varnish_submit_derive (conf->instance, "esi", "total_operations", "parsed", stats->esi_parse); +#endif } if (conf->collect_backend) { /* Backend conn. success */ - varnish_submit_derive (conf->instance, "backend", "connections", "success" , VSL_stats->backend_conn); + varnish_submit_derive (conf->instance, "backend", "connections", "success" , stats->backend_conn); /* Backend conn. not attempted */ - varnish_submit_derive (conf->instance, "backend", "connections", "not-attempted", VSL_stats->backend_unhealthy); + varnish_submit_derive (conf->instance, "backend", "connections", "not-attempted", stats->backend_unhealthy); /* Backend conn. too many */ - varnish_submit_derive (conf->instance, "backend", "connections", "too-many" , VSL_stats->backend_busy); + varnish_submit_derive (conf->instance, "backend", "connections", "too-many" , stats->backend_busy); /* Backend conn. failures */ - varnish_submit_derive (conf->instance, "backend", "connections", "failures" , VSL_stats->backend_fail); + varnish_submit_derive (conf->instance, "backend", "connections", "failures" , stats->backend_fail); /* Backend conn. reuses */ - varnish_submit_derive (conf->instance, "backend", "connections", "reuses" , VSL_stats->backend_reuse); + varnish_submit_derive (conf->instance, "backend", "connections", "reuses" , stats->backend_reuse); /* Backend conn. was closed */ - varnish_submit_derive (conf->instance, "backend", "connections", "was-closed" , VSL_stats->backend_toolate); + varnish_submit_derive (conf->instance, "backend", "connections", "was-closed" , stats->backend_toolate); /* Backend conn. recycles */ - varnish_submit_derive (conf->instance, "backend", "connections", "recycled" , VSL_stats->backend_recycle); + varnish_submit_derive (conf->instance, "backend", "connections", "recycled" , stats->backend_recycle); +#if HAVE_VARNISH_V2 /* Backend conn. unused */ - varnish_submit_derive (conf->instance, "backend", "connections", "unused" , VSL_stats->backend_unused); + varnish_submit_derive (conf->instance, "backend", "connections", "unused" , stats->backend_unused); +#endif } if (conf->collect_fetch) { /* Fetch head */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "head" , VSL_stats->fetch_head); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "head" , stats->fetch_head); /* Fetch with length */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "length" , VSL_stats->fetch_length); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "length" , stats->fetch_length); /* Fetch chunked */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "chunked" , VSL_stats->fetch_chunked); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "chunked" , stats->fetch_chunked); /* Fetch EOF */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "eof" , VSL_stats->fetch_eof); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "eof" , stats->fetch_eof); /* Fetch bad headers */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "bad_headers", VSL_stats->fetch_bad); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "bad_headers", stats->fetch_bad); /* Fetch wanted close */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "close" , VSL_stats->fetch_close); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "close" , stats->fetch_close); /* Fetch pre HTTP/1.1 closed */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "oldhttp" , VSL_stats->fetch_oldhttp); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "oldhttp" , stats->fetch_oldhttp); /* Fetch zero len */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "zero" , VSL_stats->fetch_zero); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "zero" , stats->fetch_zero); /* Fetch failed */ - varnish_submit_derive (conf->instance, "fetch", "http_requests", "failed" , VSL_stats->fetch_failed); + varnish_submit_derive (conf->instance, "fetch", "http_requests", "failed" , stats->fetch_failed); } if (conf->collect_hcb) { /* HCB Lookups without lock */ - varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_nolock", VSL_stats->hcb_nolock); + varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_nolock", stats->hcb_nolock); /* HCB Lookups with lock */ - varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_lock", VSL_stats->hcb_lock); + varnish_submit_derive (conf->instance, "hcb", "cache_operation", "lookup_lock", stats->hcb_lock); /* HCB Inserts */ - varnish_submit_derive (conf->instance, "hcb", "cache_operation", "insert", VSL_stats->hcb_insert); + varnish_submit_derive (conf->instance, "hcb", "cache_operation", "insert", stats->hcb_insert); } if (conf->collect_shm) { /* SHM records */ - varnish_submit_derive (conf->instance, "shm", "total_operations", "records" , VSL_stats->shm_records); + varnish_submit_derive (conf->instance, "shm", "total_operations", "records" , stats->shm_records); /* SHM writes */ - varnish_submit_derive (conf->instance, "shm", "total_operations", "writes" , VSL_stats->shm_writes); + varnish_submit_derive (conf->instance, "shm", "total_operations", "writes" , stats->shm_writes); /* SHM flushes due to overflow */ - varnish_submit_derive (conf->instance, "shm", "total_operations", "flushes" , VSL_stats->shm_flushes); + varnish_submit_derive (conf->instance, "shm", "total_operations", "flushes" , stats->shm_flushes); /* SHM MTX contention */ - varnish_submit_derive (conf->instance, "shm", "total_operations", "contention", VSL_stats->shm_cont); + varnish_submit_derive (conf->instance, "shm", "total_operations", "contention", stats->shm_cont); /* SHM cycles through buffer */ - varnish_submit_derive (conf->instance, "shm", "total_operations", "cycles" , VSL_stats->shm_cycles); + varnish_submit_derive (conf->instance, "shm", "total_operations", "cycles" , stats->shm_cycles); } +#if HAVE_VARNISH_V2 if (conf->collect_sm) { /* allocator requests */ - varnish_submit_derive (conf->instance, "sm", "total_requests", "nreq", VSL_stats->sm_nreq); + varnish_submit_derive (conf->instance, "sm", "total_requests", "nreq", stats->sm_nreq); /* outstanding allocations */ - varnish_submit_gauge (conf->instance, "sm", "requests", "outstanding", VSL_stats->sm_nobj); + varnish_submit_gauge (conf->instance, "sm", "requests", "outstanding", stats->sm_nobj); /* bytes allocated */ - varnish_submit_derive (conf->instance, "sm", "total_bytes", "allocated", VSL_stats->sm_balloc); + varnish_submit_derive (conf->instance, "sm", "total_bytes", "allocated", stats->sm_balloc); /* bytes free */ - varnish_submit_derive (conf->instance, "sm", "total_bytes", "free", VSL_stats->sm_bfree); + varnish_submit_derive (conf->instance, "sm", "total_bytes", "free", stats->sm_bfree); } if (conf->collect_sma) { /* SMA allocator requests */ - varnish_submit_derive (conf->instance, "sma", "total_requests", "nreq", VSL_stats->sma_nreq); + varnish_submit_derive (conf->instance, "sma", "total_requests", "nreq", stats->sma_nreq); /* SMA outstanding allocations */ - varnish_submit_gauge (conf->instance, "sma", "requests", "outstanding", VSL_stats->sma_nobj); + varnish_submit_gauge (conf->instance, "sma", "requests", "outstanding", stats->sma_nobj); /* SMA outstanding bytes */ - varnish_submit_gauge (conf->instance, "sma", "bytes", "outstanding", VSL_stats->sma_nbytes); + varnish_submit_gauge (conf->instance, "sma", "bytes", "outstanding", stats->sma_nbytes); /* SMA bytes allocated */ - varnish_submit_derive (conf->instance, "sma", "total_bytes", "allocated", VSL_stats->sma_balloc); + varnish_submit_derive (conf->instance, "sma", "total_bytes", "allocated", stats->sma_balloc); /* SMA bytes free */ - varnish_submit_derive (conf->instance, "sma", "total_bytes", "free" , VSL_stats->sma_bfree); + varnish_submit_derive (conf->instance, "sma", "total_bytes", "free" , stats->sma_bfree); } +#endif if (conf->collect_sms) { /* SMS allocator requests */ - varnish_submit_derive (conf->instance, "sms", "total_requests", "allocator", VSL_stats->sms_nreq); + varnish_submit_derive (conf->instance, "sms", "total_requests", "allocator", stats->sms_nreq); /* SMS outstanding allocations */ - varnish_submit_gauge (conf->instance, "sms", "requests", "outstanding", VSL_stats->sms_nobj); + varnish_submit_gauge (conf->instance, "sms", "requests", "outstanding", stats->sms_nobj); /* SMS outstanding bytes */ - varnish_submit_gauge (conf->instance, "sms", "bytes", "outstanding", VSL_stats->sms_nbytes); + varnish_submit_gauge (conf->instance, "sms", "bytes", "outstanding", stats->sms_nbytes); /* SMS bytes allocated */ - varnish_submit_derive (conf->instance, "sms", "total_bytes", "allocated", VSL_stats->sms_balloc); + varnish_submit_derive (conf->instance, "sms", "total_bytes", "allocated", stats->sms_balloc); /* SMS bytes freed */ - varnish_submit_derive (conf->instance, "sms", "total_bytes", "free", VSL_stats->sms_bfree); + varnish_submit_derive (conf->instance, "sms", "total_bytes", "free", stats->sms_bfree); } if (conf->collect_totals) { /* Total Sessions */ - varnish_submit_derive (conf->instance, "totals", "total_sessions", "sessions", VSL_stats->s_sess); + varnish_submit_derive (conf->instance, "totals", "total_sessions", "sessions", stats->s_sess); /* Total Requests */ - varnish_submit_derive (conf->instance, "totals", "total_requests", "requests", VSL_stats->s_req); + varnish_submit_derive (conf->instance, "totals", "total_requests", "requests", stats->s_req); /* Total pipe */ - varnish_submit_derive (conf->instance, "totals", "total_operations", "pipe", VSL_stats->s_pipe); + varnish_submit_derive (conf->instance, "totals", "total_operations", "pipe", stats->s_pipe); /* Total pass */ - varnish_submit_derive (conf->instance, "totals", "total_operations", "pass", VSL_stats->s_pass); + varnish_submit_derive (conf->instance, "totals", "total_operations", "pass", stats->s_pass); /* Total fetch */ - varnish_submit_derive (conf->instance, "totals", "total_operations", "fetches", VSL_stats->s_fetch); + varnish_submit_derive (conf->instance, "totals", "total_operations", "fetches", stats->s_fetch); /* Total header bytes */ - varnish_submit_derive (conf->instance, "totals", "total_bytes", "header-bytes", VSL_stats->s_hdrbytes); + varnish_submit_derive (conf->instance, "totals", "total_bytes", "header-bytes", stats->s_hdrbytes); /* Total body byte */ - varnish_submit_derive (conf->instance, "totals", "total_bytes", "body-bytes", VSL_stats->s_bodybytes); + varnish_submit_derive (conf->instance, "totals", "total_bytes", "body-bytes", stats->s_bodybytes); } if (conf->collect_workers) { /* worker threads */ - varnish_submit_gauge (conf->instance, "workers", "threads", "worker", VSL_stats->n_wrk); + varnish_submit_gauge (conf->instance, "workers", "threads", "worker", stats->n_wrk); /* worker threads created */ - varnish_submit_derive (conf->instance, "workers", "total_threads", "created", VSL_stats->n_wrk_create); + varnish_submit_derive (conf->instance, "workers", "total_threads", "created", stats->n_wrk_create); /* worker threads not created */ - varnish_submit_derive (conf->instance, "workers", "total_threads", "failed", VSL_stats->n_wrk_failed); + varnish_submit_derive (conf->instance, "workers", "total_threads", "failed", stats->n_wrk_failed); /* worker threads limited */ - varnish_submit_derive (conf->instance, "workers", "total_threads", "limited", VSL_stats->n_wrk_max); + varnish_submit_derive (conf->instance, "workers", "total_threads", "limited", stats->n_wrk_max); + /* dropped work requests */ + varnish_submit_derive (conf->instance, "workers", "total_requests", "dropped", stats->n_wrk_drop); +#ifdef HAVE_VARNISH_V2 /* queued work requests */ - varnish_submit_derive (conf->instance, "workers", "total_requests", "queued", VSL_stats->n_wrk_queue); + varnish_submit_derive (conf->instance, "workers", "total_requests", "queued", stats->n_wrk_queue); /* overflowed work requests */ - varnish_submit_derive (conf->instance, "workers", "total_requests", "overflowed", VSL_stats->n_wrk_overflow); - /* dropped work requests */ - varnish_submit_derive (conf->instance, "workers", "total_requests", "dropped", VSL_stats->n_wrk_drop); + varnish_submit_derive (conf->instance, "workers", "total_requests", "overflowed", stats->n_wrk_overflow); +#endif } } /* }}} void varnish_monitor */ +#if HAVE_VARNISH_V3 static int varnish_read (user_data_t *ud) /* {{{ */ { - struct varnish_stats *VSL_stats; + struct VSM_data *vd; + const c_varnish_stats_t *stats; + user_config_t *conf; if ((ud == NULL) || (ud->data == NULL)) @@ -387,18 +410,52 @@ static int varnish_read (user_data_t *ud) /* {{{ */ conf = ud->data; - VSL_stats = VSL_OpenStats (conf->instance); - if (VSL_stats == NULL) + vd = VSM_New(); + VSC_Setup(vd); + if (VSM_n_Arg(vd, conf->instance) == -1) + { + ERROR ("Varnish plugin : unable to load statistics from instance"); + return (-1); + } + if (VSC_Open (vd, /* diag = */ 1)) + { + ERROR ("varnish plugin: Unable to load statistics."); + + return (-1); + } + + stats = VSC_Main(vd); + + varnish_monitor (conf, stats); + VSM_Close (vd); + + return (0); +} /* }}} */ +#else /* if HAVE_VARNISH_V2 */ +static int varnish_read (user_data_t *ud) /* {{{ */ +{ + const c_varnish_stats_t *stats; + + user_config_t *conf; + + if ((ud == NULL) || (ud->data == NULL)) + return (EINVAL); + + conf = ud->data; + + stats = VSL_OpenStats (conf->instance); + if (stats == NULL) { ERROR ("Varnish plugin : unable to load statistics"); return (-1); } - varnish_monitor (conf, VSL_stats); + varnish_monitor (conf, stats); - return (0); + return (0); } /* }}} */ +#endif static void varnish_config_free (void *ptr) /* {{{ */ { @@ -423,11 +480,13 @@ static int varnish_config_apply_default (user_config_t *conf) /* {{{ */ conf->collect_fetch = 0; conf->collect_hcb = 0; conf->collect_shm = 1; +#if HAVE_VARNISH_V2 conf->collect_sm = 0; conf->collect_sma = 0; +#endif conf->collect_sms = 0; conf->collect_totals = 0; - + return (0); } /* }}} int varnish_config_apply_default */ @@ -519,12 +578,14 @@ static int varnish_config_instance (const oconfig_item_t *ci) /* {{{ */ cf_util_get_boolean (child, &conf->collect_hcb); else if (strcasecmp ("CollectSHM", child->key) == 0) cf_util_get_boolean (child, &conf->collect_shm); - else if (strcasecmp ("CollectSMA", child->key) == 0) - cf_util_get_boolean (child, &conf->collect_sma); else if (strcasecmp ("CollectSMS", child->key) == 0) cf_util_get_boolean (child, &conf->collect_sms); +#if HAVE_VARNISH_V2 + else if (strcasecmp ("CollectSMA", child->key) == 0) + cf_util_get_boolean (child, &conf->collect_sma); else if (strcasecmp ("CollectSM", child->key) == 0) cf_util_get_boolean (child, &conf->collect_sm); +#endif else if (strcasecmp ("CollectTotals", child->key) == 0) cf_util_get_boolean (child, &conf->collect_totals); else if (strcasecmp ("CollectWorkers", child->key) == 0) @@ -544,9 +605,11 @@ static int varnish_config_instance (const oconfig_item_t *ci) /* {{{ */ && !conf->collect_fetch && !conf->collect_hcb && !conf->collect_shm - && !conf->collect_sma && !conf->collect_sms +#if HAVE_VARNISH_V2 + && !conf->collect_sma && !conf->collect_sm +#endif && !conf->collect_totals && !conf->collect_workers) { diff --git a/src/write_graphite.c b/src/write_graphite.c new file mode 100644 index 00000000..d6583a75 --- /dev/null +++ b/src/write_graphite.c @@ -0,0 +1,695 @@ +/** + * collectd - src/write_graphite.c + * Copyright (C) 2012 Pierre-Yves Ritschard + * Copyright (C) 2011 Scott Sanders + * Copyright (C) 2009 Paul Sadauskas + * Copyright (C) 2009 Doug MacEachern + * Copyright (C) 2007-2012 Florian octo Forster + * + * 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; only version 2 of the License is applicable. + * + * 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., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Authors: + * Florian octo Forster + * Doug MacEachern + * Paul Sadauskas + * Scott Sanders + * Pierre-Yves Ritschard + * + * Based on the write_http plugin. + **/ + + /* write_graphite plugin configuation example + * + * + * + * Host "localhost" + * Port "2003" + * Prefix "collectd" + * + * + */ + +#include "collectd.h" +#include "common.h" +#include "plugin.h" +#include "configfile.h" + +#include "utils_cache.h" +#include "utils_parse_option.h" + +/* Folks without pthread will need to disable this plugin. */ +#include + +#include +#include + +#ifndef WG_DEFAULT_NODE +# define WG_DEFAULT_NODE "localhost" +#endif + +#ifndef WG_DEFAULT_SERVICE +# define WG_DEFAULT_SERVICE "2003" +#endif + +#ifndef WG_DEFAULT_ESCAPE +# define WG_DEFAULT_ESCAPE '_' +#endif + +/* Ethernet - (IPv6 + TCP) = 1500 - (40 + 32) = 1428 */ +#ifndef WG_SEND_BUF_SIZE +# define WG_SEND_BUF_SIZE 1428 +#endif + +/* + * Private variables + */ +struct wg_callback +{ + int sock_fd; + + char *node; + char *service; + char *prefix; + char *postfix; + char escape_char; + + _Bool store_rates; + _Bool separate_instances; + _Bool always_append_ds; + + char send_buf[WG_SEND_BUF_SIZE]; + size_t send_buf_free; + size_t send_buf_fill; + cdtime_t send_buf_init_time; + + pthread_mutex_t send_lock; +}; + + +/* + * Functions + */ +static void wg_reset_buffer (struct wg_callback *cb) +{ + memset (cb->send_buf, 0, sizeof (cb->send_buf)); + cb->send_buf_free = sizeof (cb->send_buf); + cb->send_buf_fill = 0; + cb->send_buf_init_time = cdtime (); +} + +static int wg_send_buffer (struct wg_callback *cb) +{ + ssize_t status = 0; + + status = swrite (cb->sock_fd, cb->send_buf, strlen (cb->send_buf)); + if (status < 0) + { + char errbuf[1024]; + ERROR ("write_graphite plugin: send failed with status %zi (%s)", + status, sstrerror (errno, errbuf, sizeof (errbuf))); + + + close (cb->sock_fd); + cb->sock_fd = -1; + + return (-1); + } + + return (0); +} + +/* NOTE: You must hold cb->send_lock when calling this function! */ +static int wg_flush_nolock (cdtime_t timeout, struct wg_callback *cb) +{ + int status; + + DEBUG ("write_graphite plugin: wg_flush_nolock: timeout = %.3f; " + "send_buf_fill = %zu;", + (double)timeout, + cb->send_buf_fill); + + /* timeout == 0 => flush unconditionally */ + if (timeout > 0) + { + cdtime_t now; + + now = cdtime (); + if ((cb->send_buf_init_time + timeout) > now) + return (0); + } + + if (cb->send_buf_fill <= 0) + { + cb->send_buf_init_time = cdtime (); + return (0); + } + + status = wg_send_buffer (cb); + wg_reset_buffer (cb); + + return (status); +} + +static int wg_callback_init (struct wg_callback *cb) +{ + struct addrinfo ai_hints; + struct addrinfo *ai_list; + struct addrinfo *ai_ptr; + int status; + + const char *node = cb->node ? cb->node : WG_DEFAULT_NODE; + const char *service = cb->service ? cb->service : WG_DEFAULT_SERVICE; + + if (cb->sock_fd > 0) + return (0); + + memset (&ai_hints, 0, sizeof (ai_hints)); +#ifdef AI_ADDRCONFIG + ai_hints.ai_flags |= AI_ADDRCONFIG; +#endif + ai_hints.ai_family = AF_UNSPEC; + ai_hints.ai_socktype = SOCK_STREAM; + + ai_list = NULL; + + status = getaddrinfo (node, service, &ai_hints, &ai_list); + if (status != 0) + { + ERROR ("write_graphite plugin: getaddrinfo (%s, %s) failed: %s", + node, service, gai_strerror (status)); + return (-1); + } + + assert (ai_list != NULL); + for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) + { + cb->sock_fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, + ai_ptr->ai_protocol); + if (cb->sock_fd < 0) + continue; + + status = connect (cb->sock_fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen); + if (status != 0) + { + close (cb->sock_fd); + cb->sock_fd = -1; + continue; + } + + break; + } + + freeaddrinfo (ai_list); + + if (cb->sock_fd < 0) + { + char errbuf[1024]; + ERROR ("write_graphite plugin: Connecting to %s:%s failed. " + "The last error was: %s", node, service, + sstrerror (errno, errbuf, sizeof (errbuf))); + close (cb->sock_fd); + return (-1); + } + + wg_reset_buffer (cb); + + return (0); +} + +static void wg_callback_free (void *data) +{ + struct wg_callback *cb; + + if (data == NULL) + return; + + cb = data; + + pthread_mutex_lock (&cb->send_lock); + + wg_flush_nolock (/* timeout = */ 0, cb); + + close(cb->sock_fd); + cb->sock_fd = -1; + + sfree(cb->node); + sfree(cb->service); + sfree(cb->prefix); + sfree(cb->postfix); + + pthread_mutex_destroy (&cb->send_lock); + + sfree(cb); +} + +static int wg_flush (cdtime_t timeout, + const char *identifier __attribute__((unused)), + user_data_t *user_data) +{ + struct wg_callback *cb; + int status; + + if (user_data == NULL) + return (-EINVAL); + + cb = user_data->data; + + pthread_mutex_lock (&cb->send_lock); + + if (cb->sock_fd < 0) + { + status = wg_callback_init (cb); + if (status != 0) + { + ERROR ("write_graphite plugin: wg_callback_init failed."); + pthread_mutex_unlock (&cb->send_lock); + return (-1); + } + } + + status = wg_flush_nolock (timeout, cb); + pthread_mutex_unlock (&cb->send_lock); + + return (status); +} + +static int wg_format_values (char *ret, size_t ret_len, + int ds_num, const data_set_t *ds, const value_list_t *vl, + _Bool store_rates) +{ + size_t offset = 0; + int status; + gauge_t *rates = NULL; + + assert (0 == strcmp (ds->type, vl->type)); + + memset (ret, 0, ret_len); + +#define BUFFER_ADD(...) do { \ + status = ssnprintf (ret + offset, ret_len - offset, \ + __VA_ARGS__); \ + if (status < 1) \ + { \ + sfree (rates); \ + return (-1); \ + } \ + else if (((size_t) status) >= (ret_len - offset)) \ + { \ + sfree (rates); \ + return (-1); \ + } \ + else \ + offset += ((size_t) status); \ +} while (0) + + if (ds->ds[ds_num].type == DS_TYPE_GAUGE) + BUFFER_ADD ("%f", vl->values[ds_num].gauge); + else if (store_rates) + { + if (rates == NULL) + rates = uc_get_rate (ds, vl); + if (rates == NULL) + { + WARNING ("format_values: " + "uc_get_rate failed."); + return (-1); + } + BUFFER_ADD ("%g", rates[ds_num]); + } + else if (ds->ds[ds_num].type == DS_TYPE_COUNTER) + BUFFER_ADD ("%llu", vl->values[ds_num].counter); + else if (ds->ds[ds_num].type == DS_TYPE_DERIVE) + BUFFER_ADD ("%"PRIi64, vl->values[ds_num].derive); + else if (ds->ds[ds_num].type == DS_TYPE_ABSOLUTE) + BUFFER_ADD ("%"PRIu64, vl->values[ds_num].absolute); + else + { + ERROR ("format_values plugin: Unknown data source type: %i", + ds->ds[ds_num].type); + sfree (rates); + return (-1); + } + +#undef BUFFER_ADD + + sfree (rates); + return (0); +} + +static void wg_copy_escape_part (char *dst, const char *src, size_t dst_len, + char escape_char) +{ + size_t i; + + memset (dst, 0, dst_len); + + if (src == NULL) + return; + + for (i = 0; i < dst_len; i++) + { + if (src[i] == 0) + { + dst[i] = 0; + break; + } + + if ((src[i] == '.') + || isspace ((int) src[i]) + || iscntrl ((int) src[i])) + dst[i] = escape_char; + else + dst[i] = src[i]; + } +} + +static int wg_format_name (char *ret, int ret_len, + const value_list_t *vl, + const struct wg_callback *cb, + const char *ds_name) +{ + char n_host[DATA_MAX_NAME_LEN]; + char n_plugin[DATA_MAX_NAME_LEN]; + char n_plugin_instance[DATA_MAX_NAME_LEN]; + char n_type[DATA_MAX_NAME_LEN]; + char n_type_instance[DATA_MAX_NAME_LEN]; + + char *prefix; + char *postfix; + + char tmp_plugin[2 * DATA_MAX_NAME_LEN + 1]; + char tmp_type[2 * DATA_MAX_NAME_LEN + 1]; + + prefix = cb->prefix; + if (prefix == NULL) + prefix = ""; + + postfix = cb->postfix; + if (postfix == NULL) + postfix = ""; + + wg_copy_escape_part (n_host, vl->host, + sizeof (n_host), cb->escape_char); + wg_copy_escape_part (n_plugin, vl->plugin, + sizeof (n_plugin), cb->escape_char); + wg_copy_escape_part (n_plugin_instance, vl->plugin_instance, + sizeof (n_plugin_instance), cb->escape_char); + wg_copy_escape_part (n_type, vl->type, + sizeof (n_type), cb->escape_char); + wg_copy_escape_part (n_type_instance, vl->type_instance, + sizeof (n_type_instance), cb->escape_char); + + if (n_plugin_instance[0] != '\0') + ssnprintf (tmp_plugin, sizeof (tmp_plugin), "%s%c%s", + n_plugin, + cb->separate_instances ? '.' : '-', + n_plugin_instance); + else + sstrncpy (tmp_plugin, n_plugin, sizeof (tmp_plugin)); + + if (n_type_instance[0] != '\0') + ssnprintf (tmp_type, sizeof (tmp_type), "%s%c%s", + n_type, + cb->separate_instances ? '.' : '-', + n_type_instance); + else + sstrncpy (tmp_type, n_type, sizeof (tmp_type)); + + if (ds_name != NULL) + ssnprintf (ret, ret_len, "%s%s%s.%s.%s.%s", + prefix, n_host, postfix, tmp_plugin, tmp_type, ds_name); + else + ssnprintf (ret, ret_len, "%s%s%s.%s.%s", + prefix, n_host, postfix, tmp_plugin, tmp_type); + + return (0); +} + +static int wg_send_message (const char* key, const char* value, + cdtime_t time, struct wg_callback *cb) +{ + int status; + size_t message_len; + char message[1024]; + + message_len = (size_t) ssnprintf (message, sizeof (message), + "%s %s %u\r\n", + key, + value, + (unsigned int) CDTIME_T_TO_TIME_T (time)); + if (message_len >= sizeof (message)) { + ERROR ("write_graphite plugin: message buffer too small: " + "Need %zu bytes.", message_len + 1); + return (-1); + } + + pthread_mutex_lock (&cb->send_lock); + + if (cb->sock_fd < 0) + { + status = wg_callback_init (cb); + if (status != 0) + { + ERROR ("write_graphite plugin: wg_callback_init failed."); + pthread_mutex_unlock (&cb->send_lock); + return (-1); + } + } + + if (message_len >= cb->send_buf_free) + { + status = wg_flush_nolock (/* timeout = */ 0, cb); + if (status != 0) + { + pthread_mutex_unlock (&cb->send_lock); + return (status); + } + } + + /* Assert that we have enough space for this message. */ + assert (message_len < cb->send_buf_free); + + /* `message_len + 1' because `message_len' does not include the + * trailing null byte. Neither does `send_buffer_fill'. */ + memcpy (cb->send_buf + cb->send_buf_fill, + message, message_len + 1); + cb->send_buf_fill += message_len; + cb->send_buf_free -= message_len; + + DEBUG ("write_graphite plugin: [%s]:%s buf %zu/%zu (%.1f %%) \"%s\"", + cb->node, + cb->service, + cb->send_buf_fill, sizeof (cb->send_buf), + 100.0 * ((double) cb->send_buf_fill) / ((double) sizeof (cb->send_buf)), + message); + + pthread_mutex_unlock (&cb->send_lock); + + return (0); +} + +static int wg_write_messages (const data_set_t *ds, const value_list_t *vl, + struct wg_callback *cb) +{ + char key[10*DATA_MAX_NAME_LEN]; + char values[512]; + + int status, i; + + if (0 != strcmp (ds->type, vl->type)) + { + ERROR ("write_graphite plugin: DS type does not match " + "value list type"); + return -1; + } + + for (i = 0; i < ds->ds_num; i++) + { + const char *ds_name = NULL; + + if (cb->always_append_ds || (ds->ds_num > 1)) + ds_name = ds->ds[i].name; + + /* Copy the identifier to `key' and escape it. */ + status = wg_format_name (key, sizeof (key), vl, cb, ds_name); + if (status != 0) + { + ERROR ("write_graphite plugin: error with format_name"); + return (status); + } + + escape_string (key, sizeof (key)); + /* Convert the values to an ASCII representation and put that into + * `values'. */ + status = wg_format_values (values, sizeof (values), i, ds, vl, + cb->store_rates); + if (status != 0) + { + ERROR ("write_graphite plugin: error with " + "wg_format_values"); + return (status); + } + + /* Send the message to graphite */ + status = wg_send_message (key, values, vl->time, cb); + if (status != 0) + { + ERROR ("write_graphite plugin: error with " + "wg_send_message"); + return (status); + } + } + + return (0); +} + +static int wg_write (const data_set_t *ds, const value_list_t *vl, + user_data_t *user_data) +{ + struct wg_callback *cb; + int status; + + if (user_data == NULL) + return (EINVAL); + + cb = user_data->data; + + status = wg_write_messages (ds, vl, cb); + + return (status); +} + +static int config_set_char (char *dest, + oconfig_item_t *ci) +{ + char buffer[4]; + int status; + + memset (buffer, 0, sizeof (buffer)); + + status = cf_util_get_string_buffer (ci, buffer, sizeof (buffer)); + if (status != 0) + return (status); + + if (buffer[0] == 0) + { + ERROR ("write_graphite plugin: Cannot use an empty string for the " + "\"EscapeCharacter\" option."); + return (-1); + } + + if (buffer[1] != 0) + { + WARNING ("write_graphite plugin: Only the first character of the " + "\"EscapeCharacter\" option ('%c') will be used.", + (int) buffer[0]); + } + + *dest = buffer[0]; + + return (0); +} + +static int wg_config_carbon (oconfig_item_t *ci) +{ + struct wg_callback *cb; + user_data_t user_data; + char callback_name[DATA_MAX_NAME_LEN]; + int i; + + cb = malloc (sizeof (*cb)); + if (cb == NULL) + { + ERROR ("write_graphite plugin: malloc failed."); + return (-1); + } + memset (cb, 0, sizeof (*cb)); + cb->sock_fd = -1; + cb->node = NULL; + cb->service = NULL; + cb->prefix = NULL; + cb->postfix = NULL; + cb->escape_char = WG_DEFAULT_ESCAPE; + cb->store_rates = 1; + + pthread_mutex_init (&cb->send_lock, /* attr = */ NULL); + + for (i = 0; i < ci->children_num; i++) + { + oconfig_item_t *child = ci->children + i; + + if (strcasecmp ("Host", child->key) == 0) + cf_util_get_string (child, &cb->node); + else if (strcasecmp ("Port", child->key) == 0) + cf_util_get_service (child, &cb->service); + else if (strcasecmp ("Prefix", child->key) == 0) + cf_util_get_string (child, &cb->prefix); + else if (strcasecmp ("Postfix", child->key) == 0) + cf_util_get_string (child, &cb->postfix); + else if (strcasecmp ("StoreRates", child->key) == 0) + cf_util_get_boolean (child, &cb->store_rates); + else if (strcasecmp ("SeparateInstances", child->key) == 0) + cf_util_get_boolean (child, &cb->separate_instances); + else if (strcasecmp ("AlwaysAppendDS", child->key) == 0) + cf_util_get_boolean (child, &cb->always_append_ds); + else if (strcasecmp ("EscapeCharacter", child->key) == 0) + config_set_char (&cb->escape_char, child); + else + { + ERROR ("write_graphite plugin: Invalid configuration " + "option: %s.", child->key); + } + } + + ssnprintf (callback_name, sizeof (callback_name), "write_graphite/%s/%s", + cb->node != NULL ? cb->node : WG_DEFAULT_NODE, + cb->service != NULL ? cb->service : WG_DEFAULT_SERVICE); + + memset (&user_data, 0, sizeof (user_data)); + user_data.data = cb; + user_data.free_func = wg_callback_free; + plugin_register_write (callback_name, wg_write, &user_data); + + user_data.free_func = NULL; + plugin_register_flush (callback_name, wg_flush, &user_data); + + return (0); +} + +static int wg_config (oconfig_item_t *ci) +{ + int i; + + for (i = 0; i < ci->children_num; i++) + { + oconfig_item_t *child = ci->children + i; + + if (strcasecmp ("Carbon", child->key) == 0) + wg_config_carbon (child); + else + { + ERROR ("write_graphite plugin: Invalid configuration " + "option: %s.", child->key); + } + } + + return (0); +} + +void module_register (void) +{ + plugin_register_complex_config ("write_graphite", wg_config); +} + +/* vim: set sw=4 ts=4 sts=4 tw=78 et : */ diff --git a/src/write_mongodb.c b/src/write_mongodb.c new file mode 100644 index 00000000..c7b76820 --- /dev/null +++ b/src/write_mongodb.c @@ -0,0 +1,335 @@ +/** + * collectd - src/write_mongodb.c + * Copyright (C) 2010-2012 Florian Forster + * Copyright (C) 2010 Akkarit Sangpetch + * Copyright (C) 2012 Chris Lundquist + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Authors: + * Florian Forster + * Akkarit Sangpetch + * Chris Lundquist + **/ + +#include "collectd.h" +#include "plugin.h" +#include "common.h" +#include "configfile.h" +#include "utils_cache.h" + +#include + +#if HAVE_STDINT_H +# define MONGO_HAVE_STDINT 1 +#else +# define MONGO_USE_LONG_LONG_INT 1 +#endif +#include + +struct wm_node_s +{ + char name[DATA_MAX_NAME_LEN]; + + char *host; + int port; + int timeout; + + _Bool store_rates; + + mongo conn[1]; + pthread_mutex_t lock; +}; +typedef struct wm_node_s wm_node_t; + +/* + * Functions + */ +static bson *wm_create_bson (const data_set_t *ds, /* {{{ */ + const value_list_t *vl, + _Bool store_rates) +{ + bson *ret; + gauge_t *rates; + int i; + + ret = bson_create (); + if (ret == NULL) + { + ERROR ("write_mongodb plugin: bson_create failed."); + return (NULL); + } + + if (store_rates) + { + rates = uc_get_rate (ds, vl); + if (rates == NULL) + { + ERROR ("write_mongodb plugin: uc_get_rate() failed."); + return (NULL); + } + } + else + { + rates = NULL; + } + + bson_init (ret); + bson_append_date (ret, "time", (bson_date_t) CDTIME_T_TO_MS (vl->time)); + bson_append_string (ret, "host", vl->host); + bson_append_string (ret, "plugin", vl->plugin); + bson_append_string (ret, "plugin_instance", vl->plugin_instance); + bson_append_string (ret, "type", vl->type); + bson_append_string (ret, "type_instance", vl->type_instance); + + bson_append_start_array (ret, "values"); /* {{{ */ + for (i = 0; i < ds->ds_num; i++) + { + char key[16]; + + ssnprintf (key, sizeof (key), "%i", i); + + if (ds->ds[i].type == DS_TYPE_GAUGE) + bson_append_double(ret, key, vl->values[i].gauge); + else if (store_rates) + bson_append_double(ret, key, (double) rates[i]); + else if (ds->ds[i].type == DS_TYPE_COUNTER) + bson_append_long(ret, key, vl->values[i].counter); + else if (ds->ds[i].type == DS_TYPE_DERIVE) + bson_append_long(ret, key, vl->values[i].derive); + else if (ds->ds[i].type == DS_TYPE_ABSOLUTE) + bson_append_long(ret, key, vl->values[i].absolute); + else + assert (23 == 42); + } + bson_append_finish_array (ret); /* }}} values */ + + bson_append_start_array (ret, "dstypes"); /* {{{ */ + for (i = 0; i < ds->ds_num; i++) + { + char key[16]; + + ssnprintf (key, sizeof (key), "%i", i); + + if (store_rates) + bson_append_string (ret, key, "gauge"); + else + bson_append_string (ret, key, DS_TYPE_TO_STRING (ds->ds[i].type)); + } + bson_append_finish_array (ret); /* }}} dstypes */ + + bson_append_start_array (ret, "dsnames"); /* {{{ */ + for (i = 0; i < ds->ds_num; i++) + { + char key[16]; + + ssnprintf (key, sizeof (key), "%i", i); + bson_append_string (ret, key, ds->ds[i].name); + } + bson_append_finish_array (ret); /* }}} dsnames */ + + bson_finish (ret); + + sfree (rates); + return (ret); +} /* }}} bson *wm_create_bson */ + +static int wm_write (const data_set_t *ds, /* {{{ */ + const value_list_t *vl, + user_data_t *ud) +{ + wm_node_t *node = ud->data; + char collection_name[512]; + bson *bson_record; + int status; + + ssnprintf (collection_name, sizeof (collection_name), "collectd.%s", + vl->plugin); + + bson_record = wm_create_bson (ds, vl, node->store_rates); + if (bson_record == NULL) + return (ENOMEM); + + pthread_mutex_lock (&node->lock); + + if (!mongo_is_connected (node->conn)) + { + INFO ("write_mongodb plugin: Connecting to [%s]:%i", + (node->host != NULL) ? node->host : "localhost", + (node->port != 0) ? node->port : MONGO_DEFAULT_PORT); + status = mongo_connect (node->conn, node->host, node->port); + if (status != MONGO_OK) { + ERROR ("write_mongodb plugin: Connecting to [%s]:%i failed.", + (node->host != NULL) ? node->host : "localhost", + (node->port != 0) ? node->port : MONGO_DEFAULT_PORT); + mongo_destroy (node->conn); + pthread_mutex_unlock (&node->lock); + return (-1); + } + + if (node->timeout > 0) { + status = mongo_set_op_timeout (node->conn, node->timeout); + if (status != MONGO_OK) { + WARNING ("write_mongodb plugin: mongo_set_op_timeout(%i) failed: %s", + node->timeout, node->conn->errstr); + } + } + } + + /* Assert if the connection has been established */ + assert (mongo_is_connected (node->conn)); + + #if MONGO_MINOR >= 6 + /* There was an API change in 0.6.0 as linked below */ + /* https://github.com/mongodb/mongo-c-driver/blob/master/HISTORY.md */ + status = mongo_insert (node->conn, collection_name, bson_record, NULL); + #else + status = mongo_insert (node->conn, collection_name, bson_record); + #endif + + if(status != MONGO_OK) + { + ERROR ( "write_mongodb plugin: error inserting record: %d", node->conn->err); + if (node->conn->err != MONGO_BSON_INVALID) + ERROR ("write_mongodb plugin: %s", node->conn->errstr); + else if (bson_record->err) + ERROR ("write_mongodb plugin: %s", bson_record->errstr); + + /* Disconnect except on data errors. */ + if ((node->conn->err != MONGO_BSON_INVALID) + && (node->conn->err != MONGO_BSON_NOT_FINISHED)) + mongo_destroy (node->conn); + } + + pthread_mutex_unlock (&node->lock); + + /* free our resource as not to leak memory */ + bson_dispose (bson_record); + + return (0); +} /* }}} int wm_write */ + +static void wm_config_free (void *ptr) /* {{{ */ +{ + wm_node_t *node = ptr; + + if (node == NULL) + return; + + if (mongo_is_connected (node->conn)) + mongo_destroy (node->conn); + + sfree (node->host); + sfree (node); +} /* }}} void wm_config_free */ + +static int wm_config_node (oconfig_item_t *ci) /* {{{ */ +{ + wm_node_t *node; + int status; + int i; + + node = malloc (sizeof (*node)); + if (node == NULL) + return (ENOMEM); + memset (node, 0, sizeof (*node)); + mongo_init (node->conn); + node->host = NULL; + node->store_rates = 1; + pthread_mutex_init (&node->lock, /* attr = */ NULL); + + status = cf_util_get_string_buffer (ci, node->name, sizeof (node->name)); + + if (status != 0) + { + sfree (node); + return (status); + } + + for (i = 0; i < ci->children_num; i++) + { + oconfig_item_t *child = ci->children + i; + + if (strcasecmp ("Host", child->key) == 0) + status = cf_util_get_string (child, &node->host); + else if (strcasecmp ("Port", child->key) == 0) + { + status = cf_util_get_port_number (child); + if (status > 0) + { + node->port = status; + status = 0; + } + } + else if (strcasecmp ("Timeout", child->key) == 0) + status = cf_util_get_int (child, &node->timeout); + else if (strcasecmp ("StoreRates", child->key) == 0) + status = cf_util_get_boolean (child, &node->store_rates); + else + WARNING ("write_mongodb plugin: Ignoring unknown config option \"%s\".", + child->key); + + if (status != 0) + break; + } /* for (i = 0; i < ci->children_num; i++) */ + + if (status == 0) + { + char cb_name[DATA_MAX_NAME_LEN]; + user_data_t ud; + + ssnprintf (cb_name, sizeof (cb_name), "write_mongodb/%s", node->name); + + ud.data = node; + ud.free_func = wm_config_free; + + status = plugin_register_write (cb_name, wm_write, &ud); + INFO ("write_mongodb plugin: registered write plugin %s %d",cb_name,status); + } + + if (status != 0) + wm_config_free (node); + + return (status); +} /* }}} int wm_config_node */ + +static int wm_config (oconfig_item_t *ci) /* {{{ */ +{ + int i; + + for (i = 0; i < ci->children_num; i++) + { + oconfig_item_t *child = ci->children + i; + + if (strcasecmp ("Node", child->key) == 0) + wm_config_node (child); + else + WARNING ("write_mongodb plugin: Ignoring unknown " + "configuration option \"%s\" at top level.", child->key); + } + + return (0); +} /* }}} int wm_config */ + +void module_register (void) +{ + plugin_register_complex_config ("write_mongodb", wm_config); +} + +/* vim: set sw=2 sts=2 tw=78 et fdm=marker : */ diff --git a/src/zfs_arc.c b/src/zfs_arc.c index f886c86a..046b7b02 100644 --- a/src/zfs_arc.c +++ b/src/zfs_arc.c @@ -1,6 +1,7 @@ /** * collectd - src/zfs_arc.c * Copyright (C) 2009 Anthony Dewhurst + * Copyright (C) 2012 Aurelien Rougemont * * 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 @@ -17,6 +18,7 @@ * * Authors: * Anthony Dewhurst + * Aurelien Rougemont **/ #include "collectd.h" @@ -52,12 +54,40 @@ static void za_submit_gauge (const char* type, const char* type_instance, gauge_ za_submit (type, type_instance, &vv, 1); } -static void za_submit_derive (const char* type, const char* type_instance, derive_t dv) +static int za_read_derive (kstat_t *ksp, const char *kstat_value, + const char *type, const char *type_instance) { - value_t vv; + long long tmp; + value_t v; + + tmp = get_kstat_value (ksp, (char *)kstat_value); + if (tmp == -1LL) + { + ERROR ("zfs_arc plugin: Reading kstat value \"%s\" failed.", kstat_value); + return (-1); + } + + v.derive = (derive_t) tmp; + za_submit (type, type_instance, /* values = */ &v, /* values_num = */ 1); + return (0); +} - vv.derive = dv; - za_submit (type, type_instance, &vv, 1); +static int za_read_gauge (kstat_t *ksp, const char *kstat_value, + const char *type, const char *type_instance) +{ + long long tmp; + value_t v; + + tmp = get_kstat_value (ksp, (char *)kstat_value); + if (tmp == -1LL) + { + ERROR ("zfs_arc plugin: Reading kstat value \"%s\" failed.", kstat_value); + return (-1); + } + + v.gauge = (gauge_t) tmp; + za_submit (type, type_instance, /* values = */ &v, /* values_num = */ 1); + return (0); } static void za_submit_ratio (const char* type_instance, gauge_t hits, gauge_t misses) @@ -77,15 +107,6 @@ static void za_submit_ratio (const char* type_instance, gauge_t hits, gauge_t mi static int za_read (void) { - gauge_t arc_size, l2_size; - derive_t demand_data_hits, - demand_metadata_hits, - prefetch_data_hits, - prefetch_metadata_hits, - demand_data_misses, - demand_metadata_misses, - prefetch_data_misses, - prefetch_metadata_misses; gauge_t arc_hits, arc_misses, l2_hits, l2_misses; value_t l2_io[2]; kstat_t *ksp = NULL; @@ -98,32 +119,32 @@ static int za_read (void) } /* Sizes */ - arc_size = get_kstat_value(ksp, "size"); - l2_size = get_kstat_value(ksp, "l2_size"); - - za_submit_gauge ("cache_size", "arc", arc_size); - za_submit_gauge ("cache_size", "L2", l2_size); + za_read_gauge (ksp, "size", "cache_size", "arc"); + za_read_gauge (ksp, "l2_size", "cache_size", "L2"); + + /* Operations */ + za_read_derive (ksp, "allocated","cache_operation", "allocated"); + za_read_derive (ksp, "deleted", "cache_operation", "deleted"); + za_read_derive (ksp, "stolen", "cache_operation", "stolen"); + + /* Issue indicators */ + za_read_derive (ksp, "mutex_miss", "mutex_operation", "miss"); + za_read_derive (ksp, "hash_collisions", "hash_collisions", ""); + + /* Evictions */ + za_read_derive (ksp, "evict_l2_cached", "cache_eviction", "cached"); + za_read_derive (ksp, "evict_l2_eligible", "cache_eviction", "eligible"); + za_read_derive (ksp, "evict_l2_ineligible", "cache_eviction", "ineligible"); /* Hits / misses */ - demand_data_hits = get_kstat_value(ksp, "demand_data_hits"); - demand_metadata_hits = get_kstat_value(ksp, "demand_metadata_hits"); - prefetch_data_hits = get_kstat_value(ksp, "prefetch_data_hits"); - prefetch_metadata_hits = get_kstat_value(ksp, "prefetch_metadata_hits"); - - demand_data_misses = get_kstat_value(ksp, "demand_data_misses"); - demand_metadata_misses = get_kstat_value(ksp, "demand_metadata_misses"); - prefetch_data_misses = get_kstat_value(ksp, "prefetch_data_misses"); - prefetch_metadata_misses = get_kstat_value(ksp, "prefetch_metadata_misses"); - - za_submit_derive ("cache_result", "demand_data-hit", demand_data_hits); - za_submit_derive ("cache_result", "demand_metadata-hit", demand_metadata_hits); - za_submit_derive ("cache_result", "prefetch_data-hit", prefetch_data_hits); - za_submit_derive ("cache_result", "prefetch_metadata-hit", prefetch_metadata_hits); - - za_submit_derive ("cache_result", "demand_data-miss", demand_data_misses); - za_submit_derive ("cache_result", "demand_metadata-miss", demand_metadata_misses); - za_submit_derive ("cache_result", "prefetch_data-miss", prefetch_data_misses); - za_submit_derive ("cache_result", "prefetch_metadata-miss", prefetch_metadata_misses); + za_read_derive (ksp, "demand_data_hits", "cache_result", "demand_data-hit"); + za_read_derive (ksp, "demand_metadata_hits", "cache_result", "demand_metadata-hit"); + za_read_derive (ksp, "prefetch_data_hits", "cache_result", "prefetch_data-hit"); + za_read_derive (ksp, "prefetch_metadata_hits", "cache_result", "prefetch_metadata-hit"); + za_read_derive (ksp, "demand_data_misses", "cache_result", "demand_data-miss"); + za_read_derive (ksp, "demand_metadata_misses", "cache_result", "demand_metadata-miss"); + za_read_derive (ksp, "prefetch_data_misses", "cache_result", "prefetch_data-miss"); + za_read_derive (ksp, "prefetch_metadata_misses", "cache_result", "prefetch_metadata-miss"); /* Ratios */ arc_hits = (gauge_t) get_kstat_value(ksp, "hits"); diff --git a/version-gen.sh b/version-gen.sh index 6a91b40f..d6d7bb20 100755 --- a/version-gen.sh +++ b/version-gen.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash -DEFAULT_VERSION="5.0.5.git" +DEFAULT_VERSION="5.1.0.git" VERSION="`git describe 2> /dev/null | sed -e 's/^collectd-//'`" @@ -10,8 +10,4 @@ fi VERSION="`echo \"$VERSION\" | sed -e 's/-/./g'`" -if test "x`uname -s`" = "xAIX" || test "x`uname -s`" = "xSunOS" ; then - echo "$VERSION\c" -else - echo -n "$VERSION" -fi +echo -n "$VERSION"