Skip to content

Instantly share code, notes, and snippets.

@typhonius
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save typhonius/2bd7514bbb8594d61519 to your computer and use it in GitHub Desktop.
Save typhonius/2bd7514bbb8594d61519 to your computer and use it in GitHub Desktop.
Changes IP address CIDRs to varnish vcl regex.
#!/usr/env/perl
use strict;
use warnings;
use Net::Netmask;
use Regexp::Assemble::Compressed;
print "Enter the filename to varnishize: ";
my $filename = <STDIN>;
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;
print join('|', @output) . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment