-
-
Save bdashrad/cb9f60e00864c1b2a3ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use Net::Netmask; | |
use Regexp::Assemble::Compressed; | |
print "Enter the filename to varnishize: "; | |
#my $filename = <STDIN>; | |
my $filename = @ARGV[0]; | |
chomp $filename; | |
exit 0 if ($filename eq "") or (! -e $filename); | |
my @output = (); | |
open (my $fh, '<', $filename) or die "cannot open < $filename : $!"; | |
while (<$fh>) { | |
# Strip it down to just numbers, dots and slashes | |
$_ =~ s/[^0-9.\/]+//g; | |
# Convert CIDRs to Varnish Regex | |
my $block = new2 Net::Netmask ($_); | |
if ($block) { | |
my $first = $block->first(); | |
my $last = $block->last(); | |
my @regex = (); | |
my @firstarray = split(/\./, $first); | |
my @lastarray = split(/\./, $last); | |
foreach my $index (0 .. $#firstarray) { | |
if ($firstarray[$index] == $lastarray[$index]) { | |
push @regex, $firstarray[$index]; | |
} | |
elsif ($firstarray[$index] == 0 && $lastarray[$index] == 255 && $index == 3) { | |
push @regex, "[0-9]+"; | |
} | |
else { | |
# Split the number up into individual arrays to compare each one. | |
if (length($firstarray[$index]) == length($lastarray[$index])) { | |
my @firstsection = split(//, $firstarray[$index]); | |
my @lastsection = split(//, $lastarray[$index]); | |
my @firstclone = @firstsection; | |
my @lastclone = @lastsection; | |
my $ra = Regexp::Assemble::Compressed->new; | |
my $startrange = join('', @firstsection); | |
my $endrange = join('', @lastsection); | |
my @range = $startrange .. $endrange; | |
for my $part (@range) { | |
$ra->add($part); | |
} | |
my $delicious_regex = $ra->re; | |
# Varnish doesn't need the fancy ?^: so we can remove them. | |
$delicious_regex =~ s/[?^:]//g; | |
push @regex, $delicious_regex; | |
} | |
} | |
} | |
my $single_line = '^' . join('\.', @regex) . '$'; | |
print "$block => $single_line\n"; | |
push @output, $single_line; | |
} | |
} | |
#close $fh; | |
print "-" x 100 . "\n"; | |
print join('|', @output) . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment