#!/usr/bin/perl

#__________________________________________________________
#
#	File:    wrap
#	By:      Matt Ho
#   Date:    7/23/95
#   Purpose: Wrapper to dynamically create HTML documents
#            that contain a easy to read directory content.
#__________________________________________________________


#__________________________________________________________
#
#	Set some environment variables, we'll need through the
#	script and do some initial error checking.
#__________________________________________________________

$ROOT     = "/var/www/htdocs" ;	# Root directory
$PATH     = $ENV{'PATH_INFO'} ; 
$wrap     = "/cgi-bin/wrap" ;		# Script alias for this CGI
$ls       = "/sbin/ls -a1" ;

#__________________________________________________________
#
#	Read the form data in.  PATH_INFO may be passed here
#	if this was called from a SSI.  We're going to make
#	one final tweak and read from the arg list as well
#	for SSI's.
#__________________________________________________________

if( $ENV{'REQUEST_METHOD'} eq "GET" )
{
   $buffer=$ENV{'QUERY_STRING'} ;
} 
else
{
   read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}) ;
}

@pairs = split(/&/, $buffer) ;
foreach (@pairs)
{
	tr/+/ / ;	
   ($name,$value) =  split(/=/) ;
    $value        =~ s/%(..)/pack("c",hex($1))/ge ;
    $name         =~ s/%(..)/pack("c",hex($1))/ge ;

	$FORM{$name} = $value ;
}

#_________________________________
#
#	Some basic checks to take
#	care of
#_________________________________

if( $ARGV[0] )
{
	$PATH = $ARGV[0] ;
	$arg  = 1 ;
}
chop $PATH if substr($PATH, -1) eq "/" ;
@_        = split('/', $PATH) ;
$pathRoot = $_[$#_] ;
$doc      = $ROOT.$PATH ;

&DefaultMesg if ! defined $PATH || $PATH eq "" ;	# Get a base listing =)
&ErrBadPath unless &ValidPath ;	# Check for server spoofing
&ErrBadPath unless -e $doc ;	# Check to see it exists
&HandleDownload if -f $doc ;	# Do the right thing

#__________________________________________________________
#
#	If we get to this point, we can be reasonably certain
#	that this is a valid shared directory.  We want to
#	show it using the appropriate method.  The following
#	section is the leading data.  ShowContents will supply
#	the rest of the data.
#
#	We do, however, need to account for the user putting
#	an index.html file in the directory.  We'll handle 
#	that as follows.  If the file exists, it is assumed to
#	be in the right.  We will append out data at the end,
#	using the index.html's head section. Otherwise, we
#	will use ours.
#__________________________________________________________

if( $arg == 1 )
{
	#	This is intentionally left blank
}
elsif( -r "$doc/index.html" )
{
	print "Content-type: text/html\n\n" ;

	open(INDEX, "$doc/index.html") ;
	while( <INDEX> )
	{
		next if /<!--#/ ;
		last if /<\/body>/i ;
		last if /<\/html>/i ;
		print ;
	}
	close(INDEX) ;
}
else
{
	print <<ENDOFTEXT ;
Content-type: text/html

<head>
	<title>
		Contents of $pathRoot
	</title>
</head>

<body bgcolor="42426f" text="ffffff" link="ffff00" vlink="93db70"
alink="cc3232" background=/images/logo.gif>

<h1 align=center>
	Contents of $pathRoot
</h1>

<hr size=3 width=75% noshade>

ENDOFTEXT
}

#
# RFE - people getting confused with all these choices.
#
#  &ShowSelection ;
&ShowContents ;

print "\n</body>\n</html>\n\n" unless $arg == 1 ;



#__________________________________________________________
#__________________________________________________________
#__________________________________________________________



sub ErrBadPath
{
	print <<ENDOFTEXT ;
Content-type: text/html

<HEAD><TITLE>404 Not Found</TITLE></HEAD>
<BODY><H1>404 Not Found</H1>
The requested URL $wrap$ENV{'PATH_INFO'} was not found on this server.<P>
PathInfo = '$PATH'
</BODY>
ENDOFTEXT

	die ;
}

#__________________________________________________________

sub DefaultMesg
{
	open(FILE, "/etc/passwd") ;
	@passwd = <FILE> ;
	close(FILE) ;

	unless( $arg == 1 )
	{
		print <<ENDOFTEXT ;
Content-type: text/html

<head>
	<title>
		User List
	</title>
</head>

<body>
<h1 align=center> 
	User List
</h1>

<hr size=3 width=50% noshade>
<p>
<h3 align=center>
	This site supports the following users:
</h3>
<p>
<hr size=3 width=50% noshade>

<ul>
ENDOFTEXT
	}

	print "<center>\n<table cellpadding=10>\n" ;

	open (FIND,"$ls $ROOT |") ;
	while( <FIND> )
	{
		chop ;
		next if $_ eq "\." ;
		next if $_ eq "\.\." ;
		next unless -d "$ROOT/$_" ;

		$name = "" ;

		foreach $line (@passwd)
		{
			@field = split(':', $line) ;
			@_     = split(',', $field[4]) ;
			($name = $_[0]), last if $_ eq $field[0] ;
		}

		print <<ENDOFTEXT ;
<tr>
	<th align=right>
		<font size=+2>
		<a href="$wrap/$_">$_</a>
		</font>
	</th>
	<td>
		<li>
	</td>
	<td>
		<font size=+2>
		<a href="$wrap/$_">$name</a>
		</font>
	</td>
</tr>
ENDOFTEXT
	}
	close(FIND) ;

	print "</table></center>\n</ul>\n</body>\n\n" ;

	die ;
}

#__________________________________________________________

sub ValidPath
{
	return 1 unless /\.\./ ;
	
	return '' if /^\.\./ ;
	return '' if /\/\.\.\// ;
	return '' if /\.\.$/ ;

	return 1 ;
}

#__________________________________________________________

sub HandleDownload
{
	print <<ENDOFTEXT ;
Location: $PATH

ENDOFTEXT

	die ;
}

#__________________________________________________________

sub ShowSelection
{
	local(@select) ;
	
	$FORM{'format'} = "default" unless defined $FORM{'format'} ;
	$select{$FORM{'format'}} = "checked" ;

	print <<ENDOFTEXT ;

<center>
<table cellpadding=2 cellspacing=0 border=0>
<form action="$wrap$PATH" method=get>
<tr>
	<td><b>Viewing format:</b>
		<input	type="radio"
				name="format"
				value="default"
				$select{'default'}> Default
		<input	type="radio"
				name="format"
				value="long"
				$select{'long'}> Long
		<input	type="radio"
				name="format"
				value="short"
				$select{'short'}> Short </th>
	<td align=center>
		<input type="submit" value="Apply"></td>	
</tr>
</form>
</table>
</center>

ENDOFTEXT
}

#__________________________________________________________

sub ShowContents
{
	local($format) = $FORM{'format'} ;

	#_________________________________
	#
	#	Get the directory and do
	#	some sorting (directories)
	#	come first, then files.
	#_________________________________

	open (FIND,"$ls $ROOT$PATH |") ;
	while( <FIND> )
	{
		chop ;
		next if $_ eq "\." ;
		next if $_ eq "\.\." ;
		push(@d, $_), next if -d "$ROOT$PATH/$_" ;
		push(@f, $_) ;
	}

	#_________________________________
	#
	#	Select method of display
	#_________________________________

	&ListFolders(@d) ;
	$format = "default" if ! defined $format ;

	if( $format eq "long" )
	{
		&ListLong(@f) ;
	}
	elsif( $format eq "short" )
	{
		&ListShort(@f) ;
	}
	else		# default format
	{
		&ListDefault(@f) ;
	}
}

#__________________________________________________________

sub ListFolders
{
	local($size) = $#_ + 1 ;
	local($i) ;
	local($j) ;
	local($index) ;
	local($format) ;
	local($cols) = 3 ;
	local($rows) = $size / $cols ;
	local($left) = $size % $cols ;

	return if $size == 0 ;

	#_________________________________

	$format = "?format=$FORM{'format'}" if defined $FORM{'format'} ;

	#_________________________________

	$rows = sprintf("%.0d", $rows) ;
	$rows++ if $left > 0 ;
	
	print <<ENDOFTEXT ;

</center>
<h3>Shared Folders:</h3>

<table cellpadding=5 cellspacing=3 border width=100%><tr><td>
<table cellpadding=3 width=100%>
ENDOFTEXT
	LOOP:
	for( $i = 0 ; $i < $rows ; $i++ )
	{
		print "<tr>\n" ;
		for( $j = 0 ; $j < $cols ; $j++ )
		{
			$index = $i + $j * $rows ;
			if( $index >= $size )
			{
				print "<td></td>\n" ;
				next ;
			}
			print <<ENDOFTEXT ;
<td>
	<a href=$wrap$PATH/$_[$index]$format>
		<img src=/images/directory.gif align=middle border=0>
		$_[$index]
	</a>
</td>
ENDOFTEXT
		}
		print "</tr>\n" ;
	}

	print <<ENDOFTEXT ;
</table>
</td></tr></table>
<p>
ENDOFTEXT
}

#__________________________________________________________

sub ListDefault
{
	local($isdir) ;
	local($icon) ;
	local($type) ;
	local(@notes) ;
	local($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,@other) ;
	local($USERPATH) = $PATH ;

	return if ( $#_ == -1 ) ;

	substr($USERPATH, 0, 1) = "/~" ;

	print <<ENDOFTEXT ;

</center>
<h3>Shared Files:</h3>
<table cellpadding=5 cellspacing=3 border width=100%>

<tr>
	<th width=50%>Name</th>
	<th width=5%>Size</th>
	<th width=45%>Action</th>
</tr>
ENDOFTEXT

	foreach (@_)
	{
		#_________________________________
		#
		#	Calculate the size of this
		#	file
		#_________________________________

		($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,@other) =
			stat("$doc/$_") ; 

		if( $size == 1 )
		{
			$size = "<b>$size</b> byte" ;
		}
		elsif( $size >= 1024 )
		{
			$size = $size / 1024 ;
			$size = sprintf("%.0d", $size) ;
			$size = "<b>$size</b> KB" ;
		}
		else
		{
			$size = "<b>$size</b> bytes" ;
		}

		#_________________________________
		#
		#	Add notes if applicable
		#_________________________________

		if( -e "$doc/$_.notes" )
		{
			open(DATA, "$doc/$_.notes") ;
			@notes = <DATA> ;
			close(DATA) ;
			$row = 2 ;
		}
		else
		{
			$row = 1 ;
		}
		
		#_________________________________
		#
		#	Diplay the data in table form
		#_________________________________

		print <<ENDOFTEXT ;
<form action="/cgi-bin/handler$PATH/$_" method=post>
<tr>
	<td rowspan=$row>
		<a href="$USERPATH/$_">
			<img src=/images/data.gif align=middle border=0>
			$_
		</a>
		<br>
	</td>
	<td align=center>
		$size
	</td>
	<td align=center>
		<input type="submit" name="data" value="View">
		<input type="submit" name="data" value="Download">
	</td>
</tr>
ENDOFTEXT

		#_________________________________
		#
		#	If there is a .notes file,
		#	show the message within the
		#	HTML doc.
		#_________________________________

		if( $row == 2 )
		{
			print "<tr> <td colspan=2>\n" ;
			print "<b>Notes: </b>\n" ;
			foreach (@notes)
			{
				print ;
			}
			print "</td> </tr>\n" ;
		}
		print "</form>\n" ;
	}
	print "</table></center>\n"
}

#__________________________________________________________

sub ListShort
{
	local($size) = $#_ + 1 ;
	local($i) ;
	local($j) ;
	local($index) ;
	local($cols) = 3 ;
	local($rows) = $size / $cols ;
	local($left) = $size % $cols ;

	return if $size == 0 ;

	$rows = sprintf("%.0d", $rows) ;
	$rows++ if $left > 0 ;
	
	print <<ENDOFTEXT ;

</center>
<h3>Shared Files:</h3>

<table cellpadding=5 cellspacing=3 border width=100%><tr><td>
<table cellpadding=3 width=100%>
ENDOFTEXT
	LOOP:
	for( $i = 0 ; $i < $rows ; $i++ )
	{
		print "<tr>\n" ;
		for( $j = 0 ; $j < $cols ; $j++ )
		{
			$index = $i + $j * $rows ;
			if( $index >= $size )
			{
				print "<td></td>\n" ;
				next ;
			}
			print <<ENDOFTEXT ;
<td>
	<a href=$PATH/$_[$index]>
		<img src=/images/data.gif align=middle border=0>
		$_[$index]
	</a>
</td>
ENDOFTEXT
		}
		print "</tr>\n" ;
	}

	print <<ENDOFTEXT ;
</table>
</td></tr></table>
ENDOFTEXT
}

#__________________________________________________________

sub ListLong
{
	local($unit) ;
	local(@other) ;
	local($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size) ;
	local($atime, $mtime, $ctime) ;
	local($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) ;
	
	return if $#_ == -1 ;
	
	print <<ENDOFTEXT ;

<h3>Shared Files:</h3>
<table cellpadding=5 cellspacing=3 border width=100%>
<tr><td>
<pre>

ENDOFTEXT

	foreach (@_)
	{
		#_________________________________
		#
		#	stat document and get the 
		#	pertinent info on it.  Also
		#	get a unit for the size, ie
		#	bytes or Kb, etc
		#_________________________________
		
		($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
			$atime, $mtime, $ctime, @other) =
			stat("$doc/$_") ; 

		if( $size == 1 )
		{
			$unit = "byte" ;
		}
		elsif( $size >= 1024 )
		{
			$size = $size / 1024 ;
			$size = sprintf("%.0d", $size) ;
			$unit = "KB" ;
		}
		else
		{
			$unit = "bytes" ;
		}

		#_________________________________
		#
		#	Get last mod time
		#_________________________________

		($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,@other) = 
			localtime($ctime) ;
		$theDay   = (Sun,Mon,Tue,Wed,Thu,Fri,Sat)[$wday] ;
		$theMonth = (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)[$mon] ;
		$date     = sprintf("$theDay $theMonth $mday %02d:%02d:%02d 19$year",
							$hour, $min, $sec) ;

		#_________________________________

		local($filler) = " " x (25 - length($_)) ;
		$filler = 0 if $filler < 0 ;
		print sprintf("<a href=$PATH/$_><img src=/images/data.gif align=middle border=0>%.25s</a>%s %6d %-5.5s %s\n", $_, $filler, $size, $unit, $date) ;
	}

	print <<ENDOFTEXT ;
</pre>
</td></tr>
</table>
ENDOFTEXT
}

