#!/usr/bin/perl

#__________________________________________________________
#
#   File:    handler
#   By:      Matt Ho
#   Date:    7/23/95
#   Purpose: Appropriately packages documents for download
#            or display.
#__________________________________________________________


#__________________________________________________________
#
#	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'} ;

$ls       = "/sbin/ls -a1" ;

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

&ErrBadPath unless &ValidPath ; # Check for server spoofing

#__________________________________________________________
#
#	Read the form data in (we just may need this)
#__________________________________________________________

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 ;
}


#__________________________________________________________
#

$data = $FORM{'data'} ;
if( $data eq "Download" )
{
	unless( open(INPUT, $doc) )
	{
		print <<ENDOFTEXT ;
Content-type: text/html

<HEAD><TITLE>404 Not Found</TITLE></HEAD>
<BODY><H1>404 Not Found</H1>
The requested URL $ENV{'PATH_INFO'} was not found on this server.<P>
</BODY>
ENDOFTEXT
		return ;
	} 
	print <<ENDOFTEXT ;
Content-type: application/octet-stream

ENDOFTEXT

	while( read(INPUT, $buf, 16384) )
	{
    	print $buf ;
	} 

	close(INPUT) ;
}
elsif( $data eq "View" )
{
	substr($PATH, 0, 1) = "/~" ;
	print <<ENDOFTEXT ;
Location: $PATH

ENDOFTEXT
}
else
{
	print <<ENDOFTEXT ;
Content-type: text/html

<HEAD><TITLE>404 Not Found</TITLE></HEAD>
<BODY><H1>404 Not Found</H1>
The requested URL $PATH was not found on this server.<P>
</BODY>
ENDOFTEXT
}

#__________________________________________________________

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

    return 1 ;
}


