/
rename-netspoc
executable file
·351 lines (283 loc) · 9.92 KB
/
rename-netspoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/perl -CSDAL
=head1 NAME
rename-netspoc - Rename one or more objects in netspoc files
=head1 SYNOPSIS
rename-netspoc [options] FILE|DIR SUBSTITUTION ...
=head1 DESCRIPTION
This program reads a netspoc configuration and one or more
SUBSTITUTIONS. It substitutes found objects with its replacement in
each file. Changes are done in place, no backup files are created. But
only changed files are touched. If FILE is `-', read standard input
and write to standard output.
=head1 SUBSTITUTION
A SUBSTITUTION is a pair of typed names "type:NAME1" "type:NAME2".
NAME1 is searched and replaced by NAME2. Both types of a single
SUBSTITUTION must use the same type. Multiple SUBSTITUTIONS can be applied in a single run of rename-netspoc.
A typed name can use any valid type and name in netspoc syntax.
Valid types are: B<router network host any group area service owner
admin protocol protocolgroup pathrestriction nat isakmp ipsec crypto>.
A SUBSTITUTION of type B<network> also changes B<interface> and B<host:id>
which reference the given network. A SUBSTITUTION of type B<router>
also changes B<interfaces> which reference the given router.
A SUBSTITUTION of type B<nat> also changes the corresponding B<bind_nat> list.
A SUBSTITUTION of type B<owner> also changes the corresponding B<sub_owner>.
=head1 OPTIONS
=over 4
=item B<-f> file
Read SUBSTITUTIONS from file.
If - is specified, read from standard input.
=item B<-q>
Quiet, don't print status messages.
=item B<-help>
Prints a brief help message and exits.
=item B<-man>
Prints the manual page and exits.
=back
=head1 COPYRIGHT AND DISCLAIMER
(c) 2012 by Heinz Knutzen <heinz.knutzen@googlemail.com>
http://hknutzen.github.com/Netspoc
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
=cut
use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use open qw(:std :utf8);
use utf8;
use Encode;
our $VERSION = '3.034'; # VERSION: inserted by DZP::OurPkgVersion
my $filename_encode = 'UTF-8';
my $ignore_files = '^(raw|config|CVS|RCS|\.#.*|.*~)$';
my $quiet;
## no critic (RequireArgUnpacking)
sub debug { print STDERR @_, "\n"; return; }
sub info { print STDERR @_, "\n"; return; }
sub fatal_err {
print STDERR "Error: ", @_, "\n";
die "Aborted\n";
}
## use critic
my %global_type =
map { $_ => 1 } qw(
router network host any group area service
owner protocol protocolgroup pathrestriction nat isakmp ipsec crypto
policy servicegroup
);
# NAT is applied with bind_nat.
# Owner is optionally referenced as sub_owner.
my %aliases = ( nat => ['bind_nat'],
owner => ['sub_owner'], );
my %subst;
# Fill %subst with arrays of search/replace pairs for given type.
sub setup_subst {
my ($type, $search, $replace) = @_;
$global_type{$type} or fatal_err("Unknown type $type");
# Quote pattern metacharacters.
$search = qr/\Q$search\E/;
# Escape perl sigils in replace string, because we apply eval on it.
$replace =~ s/([@%\$])/\\$1/g;
# Standard for all types.
push @{ $subst{$type} }, [qr/$search/, $replace];
# Network name occurs in interface name and in id: hosts.
if ($type eq 'network') {
# Definition of interface inside definition of router.
push(@{ $subst{interface} }, [ qr/$search/, $replace ]);
# Reference to interface ouside of definition of router.
push(@{ $subst{interface} },
[ qr/([\w@-]+\.)$search((?:\..*)?)/, '${1}'.$replace.'${2}' ]);
push(@{ $subst{host} },
[ qr/(id:.*\.)$search/, '${1}'.$replace ]);
}
# Router name occurs in interface name.
elsif ($type eq 'router') {
push(@{ $subst{interface} }, [ qr/$search([.@].*)/, $replace.'${1}' ]);
}
# Name of id: host is extended with some network name.
elsif ($type eq 'host') {
push(@{ $subst{host} }, [ qr/$search([.][\w-]+)/, $replace.'${1}' ]);
}
elsif (my $list = $aliases{$type}) {
for my $other (@$list) {
push @{ $subst{$other} }, [qr/$search/, $replace];
}
}
return;
}
sub subst {
my ($type, $name) = @_;
my $aref = $subst{$type} or return $name;
for my $pair (@$aref) {
my ($search, $replace) = @$pair;
# 1. eval gives double quoted string.
# 2. eval interpolates $1, $2 inside quoted string.
$name =~ s/^$search$/"qq($replace)"/ee;
}
return $name;
}
sub process {
my ($lines) = @_;
my $changed = 0;
my $type_list;
for my $line (@$lines) {
my $copy = '';
my $line_changed = 0;
TOKEN:
while(1) {
# Handle list of names
# - after "name = "
# - and on new line.
if ($type_list) {
LIST:
while (1) {
# Read list element.
if ($line =~ /\G (\s*) ([-\w.\@:]+) /gcx) {
$copy .= $1;
my $name = $2;
my $new = subst($type_list, $name);
$copy .= $new;
$line_changed++ if $name ne $new;
}
# Read comma.
elsif ($line =~ /\G (\s*,\s*) /gcx) {
$copy .= $1;
}
else {
last LIST;
}
}
# Whitespace or comment at end of line doesn't terminate list.
if ($line =~ /\G (\s* (?:[#].*)? ) $/gcsx) {
$copy .= $1;
last TOKEN;
}
# Everything else terminates list.
else {
$type_list = undef;
}
}
# Find next "type:name" or "type = name".
elsif ($line =~ /\G (.*?) (\w+) (:|\s*=\s*) /gcx) {
$copy .= "$1$2$3";
my $type = $2;
next if not $subst{$type};
next if $type_list = ($3 eq ':') ? undef : $type;
$line =~ /\G ([-\w.\@:]+) /gcx or next;
my $name = $1;
my $new = subst($type, $name);
$copy .= $new;
$line_changed++ if $name ne $new;
}
# Ignore rest of line if nothing matches.
else {
$line =~ /\G (.+) /gcsx and $copy .= $1;
last TOKEN;
}
}
if ($line_changed) {
$line = $copy;
$changed += $line_changed;
}
}
return $changed;
}
sub process_file {
my ($path) = @_;
# debug "File $path";
## no critic ProhibitTwoArgOpen
open(my $in, $path) or fatal_err "Can't open $path: $!";
my @input = <$in>;
close $in;
if (my $count = process(\@input) or $path eq '-') {
info "$count changes in $path" if not $quiet;
if ($path ne '-') {
unlink($path) or fatal_err "Can't remove $path: $!\n";
}
open(my $out, ">$path") or fatal_err "Can't create $path: $!";
print $out @input;
close $out;
}
## use critic
return;
}
sub process_file_or_dir {
my ($path) = @_;
if (-d $path) {
local (*DIR);
# Strip trailing slash.
$path =~ s</$><>;
opendir DIR, $path or fatal_err "Can't opendir $path: $!";
while (my $file = Encode::decode($filename_encode, readdir DIR)) {
next if $file eq '.' or $file eq '..';
next if $file =~ m/$ignore_files/;
$file = "$path/$file";
process_file_or_dir($file);
}
closedir DIR;
}
else {
process_file($path);
}
return;
}
sub setup_pattern {
my (@pattern) = @_;
while (@pattern) {
my $old = shift @pattern;
my $new = shift @pattern or
fatal_err "Missing replace string for '$old'";
my ($type, $old_name) = ($old =~ /^(\w+):(.*)$/) or
fatal_err "Missing type in '$old'";
my ($n_type, $new_name) = ($new =~ /^(\w+):(.*)$/) or
fatal_err "Missing type in '$new'";
$type eq $n_type or
fatal_err "Types '$type' and '$n_type' must be identical";
setup_subst($type, $old_name, $new_name);
}
return;
}
sub read_pattern {
my ($path) = @_;
# Read file as one large line.
local $/;
open(my $file, '<', $path) or fatal_err "Can't open $path: $!";
my $input = <$file>;
close $file;
my @pattern = split(' ', $input) or
fatal_err "Missing pattern in $path";
setup_pattern(@pattern);
return;
}
####################################################################
# Argument processing
####################################################################
# Read search / replace pairs from this file.
my $from_file;
my $help;
my $man;
GetOptions ( 'f=s' => \$from_file,
'q!' => \$quiet,
'help|?' => \$help,
man => \$man,
) or pod2usage(2);
pod2usage(1) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
my $path = shift @ARGV or pod2usage(2);
$from_file or @ARGV or pod2usage(2);
####################################################################
# Main program
####################################################################
# Initialize search/replace pairs.
read_pattern($from_file) if $from_file;
setup_pattern(@ARGV) if @ARGV;
# Do substitution.
process_file_or_dir($path);