Smart Proxies

With mod_perl you can control Apache's proxy features.

This example shows how to block banner ads.

Configuration Entry

 ProxyRequests    On
 PerlTransHandler Apache::AdBlocker

Script III.5.1: Apache::AdBlocker

 package Apache::AdBlocker;
 # file: Apache/AdBlocker.pm
 
 use strict;
 use vars qw(@ISA $VERSION);
 use Apache::Constants qw(:common);
 use GD ();
 use Image::Size qw(imgsize);
 use LWP::UserAgent ();
 
 @ISA = qw(LWP::UserAgent);
 $VERSION = '1.00';
 
 my $UA = __PACKAGE__->new;
 $UA->agent(join "/", __PACKAGE__, $VERSION);
 
 my $Ad = join "|", qw{ads? advertisement banner};
 
 sub handler {
     my($r) = @_;
     return DECLINED unless $r->proxyreq;
     $r->handler("perl-script"); #ok, let's do it
     $r->push_handlers(PerlHandler => \&proxy_handler);
     return OK;
 }
 
 sub proxy_handler {
     my($r) = @_;
 
     my $request = HTTP::Request->new($r->method, $r->uri);
 
     my $headers_in = $r->headers_in;
     while(my($key,$val) = each %$headers_in) {
 	$request->header($key,$val);
     }
 
     my $response = $UA->request($request);
     $r->content_type($response->header('Content-type'));
 
     #feed reponse back into our request_rec*
     $r->status($response->code);
     $r->status_line(join " ", $response->code, $response->message);
     $response->scan(sub {
 	$r->header_out(@_);
     });
 
     $r->send_http_header();
     my $content = \$response->content;
 
     if($r->content_type =~ /^image/ and $r->uri =~ /\b($Ad)\b/i) {
 	block_ad($content);
 	$r->content_type("image/gif");
     }
 
     $r->print($content);
 
     return OK;
 }
 
 sub block_ad {
     my $data = shift;
     my($x, $y) = imgsize($data);
 
     my $im = GD::Image->new($x,$y);
 
     my $white = $im->colorAllocate(255,255,255);
     my $black = $im->colorAllocate(0,0,0);       
     my $red = $im->colorAllocate(255,0,0);      
 
     $im->transparent($white);
     $im->string(GD::gdLargeFont(),5,5,"Blocked Ad",$red);
     $im->rectangle(0,0,$x-1,$y-1,$black);
 
     $$data = $im->gif;
 }
  
 1;

<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Mon Aug 17 10:50:09 EDT 1998