#!/bin/sh
# -*- sh -*-
#
# Wildcard-plugin to monitor IP addresses through iptables. To monitor an
# IP, link ip_<ipaddress> to this file. E.g.
#
#    ln -s /usr/share/node/node/plugins-auto/ip_ /etc/munin/node.d/ip_192.168.0.1
#
# ...will monitor the IP 192.168.0.1.
#
# Aditionally, you need these iptables rules as the first rules (they don't do anything, just make packet counts)
#
#    iptables -A INPUT -d 192.168.0.1
#    iptables -A OUTPUT -s 192.168.0.1
#
# If the IP number contains a ":" anywhere it is assumed to be a ip6 IP
# number and ip6tables are used instead of iptables.
#
# Furthermore, this plugin needs to be run as root for iptables to work
#
# This plugin is based on the if_ plugin.
#
# Parameters
#     env.input <input chain name>
#     env.output <output chain name>
#
# Magic markers (optional - used by munin-config and some installation
# scripts):
#
#%# family=auto
#%# capabilities=autoconf suggest


IP=${0##*/ip_}
INPUT=${input:-INPUT}
OUTPUT=${output:-OUTPUT}

case $IP in
    *:*) # I know this! This is IPv6!
	# This is a fun hack to make the plugin ip6 compatible.
	# Suggested in ticket #439 by "jodal".
	eval 'function iptables() {
	    /sbin/ip6tables "$@"
	}'
	;;
esac

if [ "$1" = "autoconf" ]; then
	if [ -r /proc/net/dev ]; then
		iptables -L ${INPUT} -v -n -x >/dev/null 2>/dev/null
		if [ $? -gt 0 ]; then
			echo "no (could not run iptables as user `whoami`)"
			exit 1
		else
			echo yes
			exit 0
		fi
	else
		echo "no (/proc/net/dev not found)"
		exit 1
	fi
fi

if [ "$1" = "suggest" ]; then
	iptables -L ${INPUT} -v -n -x 2>/dev/null | awk '$8 ~ /[0-9]/ { if (done[$8]!=1) {print $8; done[$8]=1;}}'
	exit 0
fi

if [ "$1" = "config" ]; then

        echo "graph_order out in"
        echo "graph_title $IP traffic"
        echo 'graph_args --base 1000'
        echo 'graph_vlabel bits per ${graph_period}'
	echo 'graph_category network'
        echo 'out.label sent'
        echo 'out.type DERIVE'
        echo 'out.min 0'
        echo 'out.cdef out,8,*'
        echo 'in.label received'
        echo 'in.type DERIVE'
        echo 'in.min 0'
        echo 'in.cdef in,8,*' 
        exit 0
fi;

iptables -L ${INPUT} -v -n -x | grep -m1 $IP | awk "{ print \"in.value \" \$2 }"
iptables -L ${OUTPUT} -v -n -x | grep -m1 $IP | awk "{ print \"out.value \" \$2 }"

