#!/usr/bin/perl 
# extractasnames.pl 
# By Mike Leber 06/06/2003 
# Original By Hroi Sigurdsson 
# as is, no warranty, use at your own risk. 

use strict; 

use Net::FTP; 

my $gVerbose = $ARGV[0] eq "-v"; 

my @sources = qw( 
    ftp://ftp.ripe.net/ripe/dbase/split/ripe.db.aut-num.gz 
    ftp://ftp.apnic.net/public/apnic/whois-data/APNIC/split/apnic.db.aut-num.gz 
    ftp://ftp.radb.net/radb/dbase/arin.db.gz 
    ftp://ftp.radb.net/radb/dbase/radb.db.gz 
    ftp://ftp.arin.net/info/asn.txt 
    ); 

my %autnums; 

for my $source ( @sources ) 
{ 
    read_file( $source ); 
} 

map {printf "%d: %s\n" ,$_ ,$autnums{$_}} sort {$a <=> $b} keys %autnums; 

exit(0); 

sub read_file 
{ 
    my( $source ) = @_; 

    print "$source\n" if $gVerbose; 

    my $host; 
    my $file; 
    my $remotefile; 

    ($host,$remotefile) = ( $source =~ /^ftp:\/\/([^\/]+)\/(.*)$/ ); 

    system( "mkdir data" ) if ! -e "data"; 

    my $localfile; 
    ($localfile) = ( $remotefile =~ /\/([a-z\.\-]+)$/ ); 
    $localfile = "data/$localfile"; 

    print "host: $host rfile: $remotefile lfile: $localfile\n" 
	if $gVerbose; 

    my ($dev,$ino,$mode,$nlink,$uid,$gid, 
	$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) 
	= stat( $localfile ); 

    # refresh atleast once a week, minus a bit for slop. 
    if ( (! -e $localfile) || time - $mtime > 6 * 24 * 3600 ) 
	{ 
	    my $ftp = Net::FTP->new($host) 
		|| die "Can't connect: $@\n"; 
	    $ftp->login("anonymous","me\@me.com") 
		|| die "Couldn't login\n"; 
	    $ftp->type("I") 
		|| die "Couldn't change type to binary\n"; 
	    $ftp->get($remotefile,$localfile) 
		|| die "Couldn't get $remotefile\n"; 
	    $ftp->quit(); 
	    print "successfully FTP'd $remotefile\n" 
		if $gVerbose; 
	    } 

    my $lines = 0; 

    if ( $localfile =~ /\.gz$/ ) 
	{ 
	    open( FILE, "gzip -d -c $localfile |" ) 
		|| die "Unable to open $localfile"; 

	    my $autnum = 0; 
	    my $descr = ''; 

	    while (<FILE>) 
	    { 
		if(/^aut-num:\s+AS(\d+)$/) 
		{ 
		    $autnum = $1; 
		} 

		if($autnum && /^descr:\s+(.*)$/) 
		{ 
		    $descr = $1; 
		    $autnums{$autnum} = $descr; 
		    $autnum = 0; 
		} 

		$lines++; 
	    } 

	    close FILE; 
	} 
	else 
	{ 
	    open( FILE, "< $localfile" ) 
		|| die "Unable to open $localfile"; 

	    while (<FILE>) 
	    { 
		if(/^\s+(\d+)\s+(\S+)\s/) 
		{ 
		    my $autnum = $1; 
		    my $descr = $2; 
		    $autnums{$autnum} = $descr; 
		} 

		   $lines++; 
	    } 

	   close FILE; 
	} 

    print "lines: $lines\n" 
	if $gVerbose; 
} 

