#!/usr/bin/perl
use HTTP::Daemon;
use HTTP::Status;
use HTTP::Response;
use LWP::UserAgent;
use Compress::Zlib;
our $DEBUG=0;
our $UA= LWP::UserAgent->new(
'agent'=>'ProxyAgent (Mozilla 9.0; compatible)',
'timeout' => 20,
);
$UA->env_proxy;
our $DAEMON = HTTP::Daemon->new(LocalPort => 8080) || die $!;
our $startGzipFromLength=512;
our $contentEncodingField='Content-Encoding';
#'Client-Transfer-Encoding'
#'Transfer-Encoding'
sub term {
my $signame=shift;
print STDERR "Signal $signame received. Terminating.\n";
exit(0);
}
$SIG{INT} = \&term;
$SIG{BREAK} = \&term;
print STDERR "Contact proxy at: <URL:", $DAEMON->url, ">, press ^C to terminate\n";
while (my ($c, $peeraddr) = $DAEMON->accept) {
my ($rport, $raddr) = sockaddr_in($peeraddr);
print STDOUT 'From: ',inet_ntoa($raddr),":$rport\n";
my $pid=fork();
unless (defined($pid)){
warn "can't fork: $!";
last;
}
next if $pid; #parent
while (my $r = $c->get_request){
print STDOUT $r->as_string,"\n";
my $resp=$UA->request($r);
if (
index($resp->protocol,'HTTP/1.1') >= 0 &&
!$resp->header($contentEncodingField) &&
$r->header('Accept-Encoding')=~m/gzip/io &&
length($resp->content()) > $startGzipFromLength)
{
my $nresp=HTTP::Response->new(
$resp->code,
$resp->message,
$resp->headers->clone
);
my $content=Compress::Zlib::memGzip($resp->content);
$nresp->content($content);
$nresp->header($contentEncodingField => 'gzip');
$nresp->header('Content-Length' => length($content));
print STDOUT $nresp->as_string,"\n\n" if $DEBUG;
print STDOUT $nresp->content,"\n" if $DEBUG;
$c->send_response($nresp);
} else {
$c->send_response($resp);
print STDOUT $resp->as_string,"\n\n" if $DEBUG;
print STDOUT $resp->content,"\n" if $DEBUG;
}
}
$c->close;
undef($c);
}
__END__
=head1 NAME
simple_proxy_gz - simple proxy compressing (gzip) HTTP traffic to save time and money
=head1 SYNOPSIS
perl simple_proxy_gz.pl >proxy.log &
=1=
THE END |