#!/usr/bin/perl
#
# (c) Feb 2008 - Matteo Vitturi <matteo_vitturi@virgilio.it>
#
# A script to parse ip xfrm output - NETKEY version of "ipsec look"

open(IPSXP,"ip -s x p|");

$dir = '';
$remotegw = '';
$spi = '';
while(<IPSXP>) {

    if ( m/src (.+) dst (.+) uid/ ) { ($src,$dst) = ($2,$1) };
    if ( m/dir (.+) action/ ) { $dir = $1 }
    if ( m/index (.+) prio/ ) { $spi = $1 }
    if ( m/tmpl src (.+) dst (.+)/ and $remotegw eq '' ) {
        ($net1,$net2) = ($1,$2) ;
        if ( $dir eq "out" ) {
            $remotegw=$net2;
            $local=$net1;
            $temp = $src;
            $src=$dst;
            $dst=$temp;
        }
        if ($dir eq "in")  {
            $remotegw=$net1;
            $local=$net2;

        }
        if ($dir eq "fwd")  {
            $remotegw=$net1;
            $local=$net2;
        }
    }

    if ( m/proto/ && $dir ne '') {
        $src .= "/32" if $src !~ m/\//;
        $dst .= "/32" if $dst !~ m/\//;
        printf("%3s %-18s -> %-18s => tun0x%s@%s\n",
            $dir,$src,$dst,$spi,$remotegw) unless $remotegw eq '0.0.0.0';
        $dir = '';
        $remotegw = '';
        $spi = '';
    }
}

close(IPSXP);
