#! /usr/bin/perl
#
# run mtr and produce json document
# usage : traceroute.json?host=host_name_or_address&count=repetitions
# returns json-document with mtr output
# Olav Kvittem ( Olav.Kvittem@uninett.no )
#
# use CGI;
use CGI qw/:standard -debug/;
use JSON;
my $q = CGI->new;
print $q->header('application/json');
$feilmelding = "
%s
\n";
if ( $q->http('HTTP_X_TOKEN') ne "virre-virre-vapp"){
push(@mtr, "Error" , "Access to traceroute denied : unauthorized");
print STDERR "Error: ";
my %headers = map { $_ => $q->http($_) } $q->http();
print STDERR "Wrong secret : Got the following headers:\n";
for my $header ( keys %headers ) {
print STDERR "$header: $headers{$header}\n";
}
} else {
# print STDERR 'host', $q->param('host'), $q->param('nobs'), $q->param('psize');
my $host = $q->param('host'); # && ( $host =~ m/^[a-zA-ZæøåÆØÅ0-9\.\/\-_]+$/);
my $nobs = $q->param('nobs'); # && ( $nobs =~ m/^[0-9]+$/ );
my $psize = $q->param('psize'); # && ( psize =~ m/^[0-9]+$/ );
my $interval = $q->param('interval'); # && ( psize =~ m/^[0-9]+$/ );
my $ipprot = $q->param('ipprot');
$host =~ s/[^a-zA-ZæøåÆØÅ0-9\.\/\-_\:]+/_/g; # protect
$nobs =~ s/[^0-9]+/_/g;
$psize =~ s/[^0-9]+/_/g;
$host = $q->remote_host if $host eq "";
$nobs = 3 if $nobs < 1;
$psize = 64 if $psize < 1;
$interval= 0.1 if $interval <= 0;
my $ipopt='';
if($ipprot eq "ipv4"){
$ipopt='-4';
} elsif($ipprot eq "ipv6"){
$ipopt='-6';
}
# my $cmd= "/usr/bin/mtr -c $nobs -s $psize -i $interval --report --report-wide $host";
# mtr does not like interval less than 1sek from nonroot and therefore purposeless
my $cmd= "/usr/bin/mtr -c $nobs -s $psize --report --report-wide $host $ipopt";
# open MTR, $cmd || die "Could not open : $cmd : $!";
my $mtr = `$cmd`;
if ( $? != 0){
$error=$!;
push(@mtr, "Error" , $error || "Might be unknown host");
printf STDERR "Error: $cmd : $error \n";
} else { # ok
# print STDERR "Kode $? : $cmd";
#while(){
foreach ( split(/\n/, $mtr) ){
if (/^(Start): (.*)/){ # header line
push( @mtr, [$1, $2, $q->remote_host]);
} else {
s/^\s+//; # leading blanks
@F = split( /\s+/ );
if ( /^HOST/){
$F[0]="Hop";
$F[1]="Gateway";
} else {
if ($F[0] = /(\d+)[^\d]+/){
$F[0]=$1;
}
}
push( @mtr, [@F] );
}
}
}
}
print STDERR "mtr result: ".@mtr;
print encode_json \@mtr;
exit(0);