11.2 Some Sample Redirectors

Example 11-1 is a very simple redirector written in Perl. Its purpose is to send HTTP requests for the squid-cache.org site to a local mirror site in Australia. If the requested URI looks like it is for www.squid-cache.org or one of its mirror sites, this script outputs a new URI with the hostname set to www1.au.squid-cache.org.

A common problem first-time redirector writers encounter is buffered I/O. Note that here I make sure stdout is unbuffered.

Example 11-1. A simple redirector in Perl
#!/usr/bin/perl -wl

$|=1;   # don't buffer the output

while (<>) {

        ($uri,$client,$ident,$method) = ( );

        ($uri,$client,$ident,$method) = split;

        next unless ($uri =~ m,^http://.*\.squid-cache\.org(\S*),);

        $uri = "http://www1.au.squid-cache.org$1";

} continue {

        print "$uri";

}

Example 11-2 is another, somewhat more complicated, example. Here I make a feeble attempt to deny requests when the URI contains "bad words." This script demonstrates an alternative way to parse the input fields. If I don't get all five required fields, the redirector returns a blank line, leaving the request unchanged.

This example also gives preferential treatment to some users. If the ident string is equal to "BigBoss," or comes from the 192.168.4.0 subnet, the request is passed through. Finally, I use the 301: trick to make Squid return an HTTP redirect to the client. Note, this program is neither efficient nor smart enough to correctly deny so-called bad requests.

Example 11-2. A slightly less simple redirector in Perl
#!/usr/bin/perl -wl

$|=1;   # don't buffer the output



$DENIED = "http://www.example.com/denied.html";

&load_word_list( );



while (<>) {

        unless (m,(\S+) (\S+)/(\S+) (\S+) (\S+),) {

                $uri = '';

                next;

        }

        $uri = $1;

        $ipaddr = $2;

        #$fqdn = $3;

        $ident = $4;

        #$method = $5;

        next if ($ident eq 'TheBoss');

        next if ($ipaddr =~ /^192\.168\.4\./);

        $uri = "301:$DENIED" if &word_match($uri);

} continue {

        print "$uri";

}



sub load_word_list {

        @words = qw(sex drugs rock roll);

}



sub word_match {

        my $uri = shift;

        foreach $w (@words) { return 1 if ($uri =~ /$w/); }

        return 0;

}

For more ideas about writing your own redirector, I recommend reading the source code for the redirectors mentioned in Section 11.5.



    Appendix A. Config File Reference
     
    ASPTreeView.com
     
    Evaluation has ЪСКЛЅexpired.
    Info...