#!/usr/bin/perl
use strict;
use warnings;
use MIME::Base64;
=head1 Binary PUT using POST method

 Sadly we cannot use CGI for this.

 If you must have CGI you will have to use the PUT method.

 $ENV{HTTP_FILEPUT_NAME} = Filenname (basename)
 $ENV{HTTP_FILEPUT_SIZE} = File size (bytes)
 $ENV{HTTP_FILEPUT_USER} = User ID (set by security protocols)
 $ENV{HTTP_FILEPUT_SSID} = Session ID (set by security layer)
 $ENV{HTTP_FILEPUT_PART} = File part number (0 if there is only one part)
 $ENV{HTTP_REFERER} = Referer URL
 $ENV{REMOTE_HOST} = Remote host IP addr

=cut

my $put_file;
my $max_slice = 1048576;
my $tmp = "/tmp";
die "Malformed Query - Missing PART" unless (defined $ENV{HTTP_FILEPUT_PART} && $ENV{HTTP_FILEPUT_PART} =~ /^\d+$/);
if ($ENV{HTTP_FILEPUT_PART}) {
	$put_file = "$tmp/$ENV{HTTP_FILEPUT_USER}.$ENV{HTTP_FILEPUT_SSID}.$ENV{HTTP_FILEPUT_NAME}.$ENV{HTTP_FILEPUT_PART}";
} else {
	$put_file = "$tmp/$ENV{HTTP_FILEPUT_USER}.$ENV{HTTP_FILEPUT_SSID}.$ENV{HTTP_FILEPUT_NAME}";
}
open PUT,">$put_file" || die "Cannot open $put_file - $!";
while (<STDIN>) { print PUT decode_base64($_) }
close PUT;
if ( $ENV{HTTP_FILEPUT_PART} && $ENV{HTTP_FILEPUT_PART} * $max_slice >= $ENV{HTTP_FILEPUT_SIZE} ) {
	$put_file = "$tmp/$ENV{HTTP_FILEPUT_USER}.$ENV{HTTP_FILEPUT_SSID}.$ENV{HTTP_FILEPUT_NAME}";
	open PUT,">$put_file" || die "Cannot open $put_file - $!";
	foreach my $part(1 .. $ENV{HTTP_FILEPUT_PART}) {
		my $part_file = "$tmp/$ENV{HTTP_FILEPUT_USER}.$ENV{HTTP_FILEPUT_SSID}.$ENV{HTTP_FILEPUT_NAME}.$part";
		open PART,"$part_file" || die "Cannot open $part_file - $!";
		while (<PART>) { print PUT }
		close PART;
		unlink $part_file || die "Cannot unlink $part_file - $!";
	}
}

# Signal everything ok back to browser ... In the real world, at this stage
# we might call another script that uses CGI perl (pass it some parameters
# re status and session id etc)
print "Content-Type: text/html; charset=ISO-8859-1

<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">
<html>
<head>
<title>Put File</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />
</head>
<body>
<h1>$ENV{HTTP_FILEPUT_NAME} Part $ENV{HTTP_FILEPUT_PART}</h1>
</body>
</html>
";
exit 0;