#!/usr/bin/perl ## Copyright (c) 2009 Mark S. Kolich ## http://mark.kolich.com ## Permission is hereby granted, free of charge, to any person ## obtaining a copy of this software and associated documentation ## files (the "Software"), to deal in the Software without ## restriction, including without limitation the rights to use, ## copy, modify, merge, publish, distribute, sublicense, and/or sell ## copies of the Software, and to permit persons to whom the ## Software is furnished to do so, subject to the following ## conditions: ## The above copyright notice and this permission notice shall be ## included in all copies or substantial portions of the Software. ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ## EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ## OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ## NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ## HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ## WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ## OTHER DEALINGS IN THE SOFTWARE. use constant MAPFILE => "/my/server/root/kolich.cc/map.txt"; ## The URL to redirect to if there was ## an error reading/opening the MAPFILE use constant DEFAULT_URL => "http://mark.kolich.com"; ## A common mistake is to use buffered I/O on stdout. ## Avoid this, as it will cause a deadloop! ## $|=1 is used to prevent this. $|=1; while(){ print lookup($_); } sub lookup { ## BTW, returning "NULL" to mod_rewrite means ## that the lookup/key wasn't found so then ## mod_rewrite will fallback to its backup lookup ## mechanism. my $key = shift; my $url = "NULL\n"; chomp $key; ## Since I'm taking the key and sticking it ## right into a regular expression, there's a ## chance that someone would do something nasty ## So I need strip out any non word characters ## from the user input. This avoids any of those ## annoying regular expression injection problems. $key =~ s/\W//sg; ## If the key is empty, bail return $url if $key =~ /^$/; ## You DONT want to open() then ||die if there was any ## problem reading the MAPFILE. In this case, if the ## mapper couldn't open the map, then just return our ## DEFAULT_URL open( HANDLE, "< " . MAPFILE ) || return DEFAULT_URL."\n"; while(){ ## Skip empty lines, and lines with comments ## in the mapfile. Comment lines start with a # next if $_ =~ /^$/ || $_ =~ /^#/; if($_=~m/^($key)\s+/i){ @line = split(/\s{2,}/); chomp $line[1]; $url = $line[1]."\n"; last; } } close( HANDLE ); ## You need a \n newline at the end of a string ## your gonna send back to Apache with the URL ## to redirect to. I'm not sure if you need a ## \r too, but \n alone seems to work fine in ## my case. return $url; }