#!/usr/bin/perl

# Quick and dirty reproducer for bug #629770
# Usage: 
#   service snmpd start
#   perl reproduce.pl <snmpd.strc
# -> snmpd shows assert in syslog
#

use strict;
use Socket;


my %sockets={};
my $addr = "/var/agentx/master";
my $sock_addr = sockaddr_un($addr);

while(<>) {
    if (m/accept\(10.*= (.*)/) {
        print "opening new socket $1\n";
        socket(my $server, PF_UNIX,SOCK_STREAM,0) || die "socket: $!";
        connect($server, $sock_addr) || die "connect: $!";
        $sockets{$1} = $server;
    }
    if (m/close\((.*)\)/) {
        if ($sockets{$1} >0) {
            close($sockets{$1});
            $sockets{$1} = 0;
            print "closing $1\n";
        }
    }
    if (m/recvfrom\(([0-9]*), \"(.*)\".*/) {
        if ($sockets{$1} >0) {
            print "sending on socket $1";
            my $s=$sockets{$1};
            my $data = $2;
            $data =~ s/\$/\\\$/g;
            $data =~ s/\@/\\\@/g;
            $data = eval("\"$data\"");
            print ", ", length($data), " bytes\n";
            syswrite($s, $data);
        }
    }
    if (m/sendto\(([0-9]*), \"(.*)\".*/) {
        if ($sockets{$1} > 0) {
            print "receiving on socket $1, ";
            my $s=$sockets{$1};

            my $expected = $2;
            $expected =~  s/\$/\\\$/g;
            $expected =~ s/\@/\\\@/g;
            $expected = eval("\"$expected\"");

            my $data="";
            sysread($s, $data, length($expected));
            print "expected: ", length($expected), ", received: ", length($data), "\n";
        }
    }
}