#!/usr/local/bin/perl

# a continuation of http://cr.yp.to/surveys/smtpsoftware6.txt
# this code runs smtp_agent.pl

use strict;

#my $DEBUG = '--debug';
my $DEBUG;
my $timeout = 3;
my $total = 1000000;
my $procs = 160; # should divide $total evenly

my @oct1 = (1..9, 11..13, 15..23, 25..38, 40..126, 128..223); # most of RFC3330
my @oct = (0..255);

srand(time() ^($$ + ($$ << 15)));	

unless(0){ # set to 1 to use data made last time
	my %scanned;
	my $high = ($total/$procs);
	foreach my $n (1..$procs){
		warn "creating ips_to_scan.${n}\n" if($DEBUG);
		open(F, ">/tmp/ips_to_scan.${n}") || die "cannot write to /tmp/ips_to_scan.${n}: $!\n";
		foreach my $n (1..$high){
			my $ip = rand_ip();
			until(! exists($scanned{$ip})){
				warn "repeat ip: $ip\n" if($DEBUG); # just because im curious
				$ip = rand_ip();
			}
			$scanned{$ip} = 1;
			print F "$ip\n";
		}
		close F;
	}
}

opendir(D, '/tmp/') || die "cannot opendir /tmp: $!\n";
foreach my $file (grep {/^ips_to_scan\.\d+$/} readdir D){
	system("nice smtp_agent.pl $DEBUG --timeout=$timeout --file=/tmp/$file &");
}
closedir D;

sub rand_ip {
   my $ip = $oct1[rand(@oct1)] . '.' . $oct[rand(@oct)] . '.' . $oct[rand(@oct)] . '.' . $oct[rand(@oct)];
   return($ip);
}
