Debian Codegraph @

scripts/sql/rlm_sqlippool_tool

raw
1 #!/usr/bin/perl -Tw
2
3 ######################################################################
4 #
5 # Copyright (C) 2020 Network RADIUS
6 #
7 # $Id: 47a48fc4a3c9221d22eaa51c573bf92254a62c51 $
8 #
9 ######################################################################
10 #
11 # Helper script for populating IP pools with address entries.
12 #
13 # This script generates SQL output that is useful for populating an IP pool
14 # for use with FreeRADIUS (and possibly other purposes). Alternatively,
15 # if called with the -f option will directly operate on the database configured
16 # within the FreeRADIUS configuration to update the IP pool table specified
17 #
18 # Note: Direct connection to databases is done using Perl DBI. You may need
19 # to install the appropriate Perl DBD driver to enable this functionality.
20 # Formatted SQL output is produced using Perl Template::Toolkit which
21 # will need to be installed if this output is required.
22 #
23 #
24 # Use with a single address range
25 # -------------------------------
26 #
27 # For basic use, arguments can be provided to this script that denote the ends
28 # of a single IP (v4 or v6) address range together with the pool_name and
29 # SQL dialect or a raddb directory from which the database config will be
30 # read.
31 #
32 # If a raddb directory is specified, then the instance of the FreeRADIUS sql
33 # module to be found in the config can be specified. It defaults to "sql".
34 #
35 # Optionally the number of IPs to sparsely populate the range with can be
36 # provided. If the range is wider than a /16 then the population of the range
37 # is capped at 65536 IPs, unless otherwise specified.
38 #
39 # In the case that a sparse range is defined, a file containing pre-existing
40 # IP entries can be provided. The range will be populated with entries from
41 # this file that fall within the range, prior to the remainder of the range
42 # being populated with random address in the range.
43 #
44 # rlm_sqlippool_tool -p <pool_name> -s <range_start> -e <range_end> \
45 # -t <table_name> (-d <sql_dialect> | -f <raddb_dir> [ -i <instance> ]) \
46 # [ -c <capacity> ] [ -x <existing_ips_file> ]
47 #
48 # Note: Sparse ranges are populated using a deterministic, pseudo-random
49 # function. This allows pools to be trivially extended without having to
50 # supply the existing contents using a file. If you require
51 # less-predictable randomness or a different random sequence then remove
52 # or modify the line calling srand(), below.
53 #
54 #
55 # Use with multiple pools and address ranges
56 # ------------------------------------------
57 #
58 # For more complex us, the script allows a set of pool definitions to be
59 # provided in a YAML file which describes a set of one or more pools, each
60 # containing a set of one or more ranges.
61 #
62 # rlm_sqlippool_tool -y <pool_defs_yaml_file> -t <table_name> \
63 # ( -d <dialect> | -f <raddb_dir> [ -i <instance> ] ) \
64 # [ -x <existing_ips_file> ]
65 #
66 # The format for the YAML file is demonstrated by the following example:
67 #
68 # pool_with_a_single_contiguous_range:
69 # - start: 192.0.2.3
70 # end: 192.0.2.250
71 #
72 # pool_with_a_single_sparse_range:
73 # - start: 10.10.10.0
74 # end: 10.10.20.255
75 # capacity: 200
76 #
77 # pool_with_multiple_ranges:
78 # - start: 10.10.10.1
79 # end: 10.10.10.253
80 # - start: 10.10.100.0
81 # end: 10.10.199.255
82 # capacity: 1000
83 #
84 # v6_pool_with_contiguous_range:
85 # - start: '2001:db8:1:2:3:4:5:10'
86 # end: '2001:db8:1:2:3:4:5:7f'
87 #
88 # v6_pool_with_sparse_range:
89 # - start: '2001:db8:1:2::'
90 # end: '2001:db8:1:2:ffff:ffff:ffff:ffff'
91 # capacity: 200
92 #
93 # As with the basic use case, a file containing pre-existing IP entries can be
94 # provided with which any sparse ranges will be populated ahead of any random
95 # addresses.
96 #
97 #
98 # Output
99 # ------
100 #
101 # The script returns SQL formatted appropriately for one of a number of
102 # different SQL dialects.
103 #
104 # The SQL first creates a temporary table to insert the new pools into,
105 # inserts the addresses, then removes any exisitng entries from the pool
106 # table that do not exist in the new pool. Finally any new entries that
107 # don't exist in the existing pool table are copied from the temporary
108 # table.
109 #
110 # The SQL templates assume that the pool name will be in a field called
111 # "pool_name" and the IP address in a field named "framedipaddress",
112 # matching the default schema for ippools and DHCP ippools as shipped with
113 # FreeRADIUS.
114 #
115 #
116 # Examples
117 # --------
118 #
119 # rlm_sqlippool_tool -p main_pool -s 192.0.2.3 -e 192.0.2.249 \
120 # -d postgresql -t radippool
121 #
122 # Will create a pool from a full populated IPv4 range, i.e. all IPs in the
123 # range available for allocation, with SQL output suitable for PostgreSQL
124 #
125 # rlm_sqlippool_tool -p main_pool -s 10.66.0.0 -e 10.66.255.255 -c 10000 \
126 # -d mysql -t radippool
127 #
128 # Will create a pool from a sparsely populated IPv4 range for a /16
129 # network (maximum of 65.536 addresses), populating the range with 10,000
130 # addreses. With SQL output suitable for MySQL.
131 # The effective size of the pool can be increased in future by increasing
132 # the capacity of the range with:
133 #
134 # rlm_sqlippool_tool -p main_pool -s 10.66.0.0 -e 10.66.255.255 -c 20000 \
135 # -d mysql -t radippool
136 #
137 # This generates the same initial set of 10,000 addresses as the previous
138 # example but will create 20,000 addresses overall, unless the random seed
139 # has been amended since the initial run.
140 #
141 # rlm_sqlippool_tool -p main_pool -s 2001:db8:1:2:: \
142 # -e 2001:db8:1:2:ffff:ffff:ffff:ffff -d mssql -t radippool
143 #
144 # Will create a pool from the IPv6 range 2001:db8:1:2::/64, initially
145 # populating the range with 65536 (by default) addresses.
146 #
147 # rlm_sqlippool_tool -p main_pool -s 2001:db8:1:2:: \
148 # -e 2001:db8:1:2:ffff:ffff:ffff:ffff \
149 # -c 10000 -x existing_ips.txt -d mysql -t radippool
150 #
151 # Will create a pool using the same range as the previous example, but
152 # this time the range will be populated with 10,000 addresses. The range
153 # will be populated using lines extracted from the `existing_ips.txt` file
154 # that represent IPs which fall within range.
155 #
156 # rlm_sqlippool_tool -y pool_defs.yml -d postgresql -t radippool \
157 # -x existing_ips.txt
158 #
159 # Will create one of more pools using the definitions found in the
160 # pool_defs.yml YAML file. The pools will contain one or more ranges with
161 # each of the ranges first being populated with entries from the
162 # existing_ips.txt file that fall within the range, before being filled
163 # with random addresses to the defined capacity.
164 #
165
166 use strict;
167 use Net::IP qw/ip_bintoip ip_iptobin ip_bincomp ip_binadd ip_is_ipv4 ip_is_ipv6/;
168
169 #
170 # Option defaults
171 #
172 my $opts = {
173 instance => 'sql',
174 capacity => 65536
175 };
176
177 #
178 # Parse the command line arguments
179 #
180 my $opt = '';
181 for (my $i = 0; $i <= $#ARGV; $i++) {
182 if ($ARGV[$i] =~ m/^-(.)$/) {
183 if ($1 eq 'p') {
184 $opt = 'pool_name';
185 } elsif ($1 eq 's') {
186 $opt = 'range_start';
187 } elsif ($1 eq 'e') {
188 $opt = 'range_end';
189 } elsif ($1 eq 'c') {
190 $opt = 'capacity';
191 } elsif ($1 eq 't') {
192 $opt = 'table_name';
193 } elsif ($1 eq 'd') {
194 $opt = 'dialect';
195 } elsif ($1 eq 'y') {
196 $opt = 'yaml';
197 } elsif ($1 eq 'x') {
198 $opt = 'entries';
199 } elsif ($1 eq 'f') {
200 $opt = 'raddb_dir';
201 } elsif ($1 eq 'i') {
202 $opt = 'instance';
203 } else {
204 usage();
205 exit 1;
206 }
207 } else {
208 if ($opt eq '') {
209 usage();
210 exit 1;
211 } else {
212 $opts->{$opt} = $ARGV[$i]
213 }
214 }
215 }
216
217 #
218 # If a raddb dir is set then we parse the mods-enabled config
219 #
220
221 if ($opts->{raddb_dir}) {
222 my $found = 0;
223 if (-d $opts->{raddb_dir}.'/mods-enabled') {
224 opendir(my $dh, $opts->{raddb_dir}.'/mods-enabled') || die 'ERROR: Could not open directory '.$opts->{raddb_dir}.'/mods-enabled';
225 my @dir = grep { -f "$opts->{raddb_dir}/mods-enabled/$_" } readdir($dh);
226 closedir($dh);
227 my $instance = $opts->{instance};
228 foreach my $file (@dir) {
229 open (my $fh, $opts->{raddb_dir}.'/mods-enabled/'.$file);
230 my $level = 0;
231 my $section = '';
232 my $subsection = '';
233 while (<$fh>) {
234 if ($found) {
235 $_ =~ s/#.*//; # Remove comments
236 if ($_ =~ m/\s*([a-z_]+)\s*=\s*(.*)/) {
237 my $param = $1;
238 my $value = $2;
239 $value =~ s/^"//;
240 $value =~ s/"\s*$//;
241 if ($level == 1) {
242 $opts->{$param} = $value;
243 } elsif ($level == 2) {
244 $opts->{$section}->{$param} = $value;
245 } elsif ($level == 3) {
246 $opts->{$section}->{$subsection}->{$param} = $value;
247 }
248 }
249 if ($_ =~ m/([a-z_]*)\s+\{/) { # Find nested sectinos
250 $level++ ;
251 if ($level == 2) {
252 $section = $1;
253 } elsif ($level == 3) {
254 $subsection = $1;
255 }
256 }
257 $level-- if ($_ =~ m/\s+\}/); # Close of nesting
258 last if ($level == 0); # We've got to the end of the instance
259 }
260 if ($_ =~ m/\b$instance\s+\{/) {
261 # We've found the specified SQL instance
262 $found = 1;
263 $level = 1;
264 }
265 }
266 close ($fh);
267 if ($found) {
268 last;
269 }
270 }
271 } else {
272 die 'ERROR: Specified FreeRADIUS config directory does not contain mods-enabled';
273 }
274 if ($found == 0) {
275 die 'ERROR: SQL instance not found in FreeRADIUS config';
276 }
277 }
278
279 #
280 # The SQL dialect and table name must be set
281 #
282 if ((!($opts->{dialect})) || (!($opts->{table_name}))) {
283 usage();
284 exit 1;
285 }
286
287 if ($opts->{yaml}) {
288 my $yaml_available = 0;
289
290 eval {
291 require YAML::XS;
292 YAML::XS->import('LoadFile');
293 $yaml_available = 1;
294 };
295
296 unless ($yaml_available) {
297 die "ERROR: YAML is not available. Install the YAML::XS Perl module.";
298 }
299 process_yaml_file($opts);
300
301 goto done;
302
303 }
304
305
306 if ((!($opts->{pool_name})) || (!($opts->{range_start})) || (!($opts->{range_end}))) {
307 usage();
308 exit 1;
309 }
310
311 process_commandline($opts);
312
313 done:
314
315 exit 0;
316
317
318 sub usage {
319 print STDERR <<'EOF'
320 Usage:
321 rlm_sqlippool_tool -p <pool_name> -s <range_start> -e <range_end> -t <table_name> (-d <sql_dialect> | -f <raddb_dir> [ -i <instance> ]) [ -c <capacity> ] [ -x <existing_ips_file> ]
322 or:
323 rlm_sqlippool_tool -y <pool_defs_yaml_file> -t <table_name> (-d <dialect> | -f <raddb_dir> [ -i <instance> ]) [ -x <existing_ips_file> ]
324
325 EOF
326 }
327
328
329 sub process_commandline {
330
331 my $opts = shift;
332 $SIG{__DIE__} = sub { usage(); die(@_); };
333
334 (my $template, my $queries)=load_templates($opts->{table_name});
335
336 unless (defined $template->{$opts->{dialect}}) {
337 print STDERR "Unknown dialect. Pick one of: ";
338 print STDERR "$_ " foreach sort keys %{$template};
339 print STDERR "\n";
340 exit 1;
341 }
342
343 my @entries = ();
344 @entries = load_entries($opts->{entries}) if ($opts->{entries});
345
346 @entries = handle_range($opts->{range_start}, $opts->{range_end}, $opts->{capacity}, @entries);
347
348 if ($opts->{radius_db}) {
349 &call_database($opts, $queries, @entries);
350 } else {
351 &output_sql($template->{$opts->{dialect}}, {ranges => [{pool_name => $opts->{pool_name}, ips => \@entries}], batchsize => 100, tablename => $opts->{table_name}});
352 }
353 }
354
355 sub process_yaml_file {
356
357 my $opts = shift;
358
359 unless (-r $opts->{yaml}) {
360 die "ERROR: Cannot open <pool_defs_yaml_file> for reading: $opts->{yaml}";
361 }
362
363 my %pool_defs = %{LoadFile($opts->{yaml})};
364
365 (my $template, my $queries)=load_templates($opts->{table_name});
366
367 unless (defined $template->{$opts->{dialect}}) {
368 print STDERR "Unknown dialect. Pick one of: ";
369 print STDERR "$_ " foreach sort keys %{$template};
370 print STDERR "\n";
371 exit 1;
372 }
373
374 my @entries = ();
375 @entries = load_entries($opts->{entries}) if ($opts->{entries});
376
377 my @ranges;
378 foreach my $pool_name (sort keys %pool_defs) {
379 foreach my $range (@{$pool_defs{$pool_name}}) {
380 my $range_start = $range->{start};
381 my $range_end = $range->{end};
382 my $capacity = $range->{capacity};
383 my @ips = handle_range($range_start, $range_end, $capacity, @entries);
384 push (@ranges, {pool_name => $pool_name, ips => \@ips});
385 }
386 }
387
388 if ($opts->{radius_db}) {
389 &call_database($opts, $queries, @entries);
390 } else {
391 &output_sql($template->{$opts->{dialect}}, {ranges => \@ranges, batchsize => 100, tablename => $opts->{table_name}});
392 }
393 }
394
395 sub output_sql {
396 my $template = shift();
397 my $vars = shift();
398
399 my $tt_available = 0;
400 eval {
401 require Template;
402 $tt_available = 1;
403 };
404 if ($tt_available) {
405 my $tt=Template->new();
406 $tt->process(\$template, $vars) || die $tt->error();
407 } else {
408 die "ERROR: Template Toolkit is not available. Install the Template Perl module.";
409 }
410 }
411
412 sub call_database {
413
414 my $opts = shift;
415 my $queries = shift;
416 my @entries = @_;
417
418 my $dbi_avail = 0;
419 eval {
420 require DBI;
421 $dbi_avail = 1;
422 };
423 unless($dbi_avail) {
424 die "ERROR: DBI is not available. Install the DBI Perl module.";
425 }
426
427 my $dsn;
428 if ($opts->{dialect} eq 'mysql') {
429 $dsn = "DBI:mysql:database=$opts->{radius_db};host=$opts->{server}";
430 if (defined($opts->{mysql}->{tls})) {
431 $dsn .= ';mysql_ssl=1';
432 $dsn .= ';mysql_ssl_ca_file='.$opts->{mysql}->{tls}->{ca_file} if ($opts->{mysql}->{tls}->{ca_file});
433 $dsn .= ';mysql_ssl_ca_path='.$opts->{mysql}->{tls}->{ca_path} if ($opts->{mysql}->{tls}->{ca_path});
434 $dsn .= ';mysql_ssl_client_key='.$opts->{mysql}->{tls}->{private_key_file} if ($opts->{mysql}->{tls}->{private_key_file});
435 $dsn .= ';mysql_ssl_client_cert='.$opts->{mysql}->{tls}->{certificate_file} if ($opts->{mysql}->{tls}->{certificate_file});
436 $dsn .= ';mysql_ssl_cipher='.$opts->{mysql}->{tls}->{cipher} if ($opts->{mysql}->{tls}->{cipher});
437 }
438 } elsif ($opts->{dialect} eq 'postgresql') {
439 # Parse FreeRADIUS alternative connection string
440 if ($opts->{radius_db} =~ m/host=(.+?)\b/) {
441 $opts->{server} = $1;
442 }
443 if ($opts->{radius_db} =~ m/user=(.+?)\b/) {
444 $opts->{login} = $1;
445 }
446 if ($opts->{radius_db} =~ m/password=(.+?)\b/) {
447 $opts->{password} = $1;
448 }
449 if ($opts->{radius_db} =~ m/sslmode=(.+?)\b/) {
450 $opts->{sslmode} = $1;
451 }
452 if ($opts->{radius_db} =~ m/dbname=(.+?)\b/) {
453 $opts->{radius_db} = $1;
454 }
455 $dsn = "DBI:Pg:dbname=$opts->{radius_db};host=$opts->{server}";
456 #
457 # DBD doesn't have all the options used by FreeRADIUS - just enable ssl if
458 # FreeRADIUS has SSL options enabled
459 #
460 $dsn .= ';sslmode=prefer' if ($opts->{sslmode});
461 } elsif ($opts->{dialect} eq 'sqlite') {
462 $dsn = "DBI:SQLite:dbname=$opts->{sqlite}->{filename}";
463 } elsif ($opts->{dialect} eq 'mssql') {
464 if ($opts->{driver} eq 'rlm_sql_unixodbc') {
465 $dsn = "DBI:ODBC:DSN=$opts->{server}";
466 } else {
467 $dsn = "DBI:Sybase:server=$opts->{server};database=$opts->{radius_db}";
468 }
469 } elsif ($opts->{dialect} eq 'oracle') {
470 # Extract data from Oracle connection string as used by FreeRADIUS
471 if ($opts->{radius_db} =~ m/HOST=(.+?)\)/) {
472 $opts->{server} = $1;
473 }
474 if ($opts->{radius_db} =~ m/PORT=(.+?)\)/) {
475 $opts->{port} =$1;
476 }
477 if ($opts->{radius_db} =~ m/SID=(.+?)\)/) {
478 $opts->{sid} = $1;
479 }
480 $dsn = "DBI:Oracle:host=$opts->{server};sid=$opts->{sid}";
481 } else {
482 $dsn = "DBI:$opts->{dialect}:database=$opts->{radius_db};host=$opts->{server}";
483 }
484 $dsn .= ";port=$opts->{port}" if ($opts->{port}) && ($opts->{driver} ne 'rlm_sql_unixodbc');
485
486 # Read the results by running our query against the database
487 my $dbh = DBI->connect($dsn, $opts->{login}, $opts->{password}) || die "Unable to connect to database";
488
489 foreach my $query (@{$queries->{$opts->{dialect}}->{pre}}) {
490 $dbh->do($query);
491 }
492
493 my $sth = $dbh->prepare($queries->{$opts->{dialect}}->{insert});
494 foreach my $ip (@entries) {
495 $sth->execute($opts->{pool_name}, $ip);
496 }
497 $sth->finish();
498
499 foreach my $query (@{$queries->{$opts->{dialect}}->{post}}) {
500 $dbh->do($query);
501 }
502
503 $dbh->disconnect();
504 }
505
506 sub load_entries {
507
508 my $entries_file = shift;
509
510 my @entries = ();
511 unless (-r $entries_file) {
512 die "ERROR: Cannot open <existing_ips_file> for reading: $entries_file"
513 }
514 open(my $fh, "<", $entries_file) || die "Failed to open $entries_file";
515 while(<$fh>) {
516 chomp;
517 push @entries, $_;
518 }
519
520 return @entries;
521
522 }
523
524
525 sub handle_range {
526
527 my $range_start = shift;
528 my $range_end = shift;
529 my $capacity = shift;
530 my @entries = @_;
531
532 unless (ip_is_ipv4($range_start) || ip_is_ipv6($range_start)) {
533 die "ERROR: Incorrectly formatted IPv4/IPv6 address for range_start: $range_start";
534 }
535
536 unless (ip_is_ipv4($range_end) || ip_is_ipv6($range_end)) {
537 die "ERROR: Incorrectly formatted IPv4/IPv6 address for range_end: $range_end";
538 }
539
540 my $ip_start = new Net::IP($range_start);
541 my $ip_end = new Net::IP($range_end);
542 my $ip_range = new Net::IP("$range_start - $range_end");
543
544 unless (defined $ip_range) {
545 die "ERROR: The range defined by <range_start> - <range_end> is invalid: $range_start - $range_end";
546 }
547
548 my $range_size = $ip_range->size;
549
550 if ($range_size < $capacity) {
551 $capacity = "$range_size";
552 warn 'WARNING: Insufficent IPs in the range. Will create '.$capacity.' entries.';
553 }
554
555 # Prune the entries to only those within the specified range
556 for (my $i = 0; $i <= $#entries; $i++) {
557 my $version = ip_is_ipv4($entries[$i]) ? 4 : 6;
558 my $binip = ip_iptobin($entries[$i],$version);
559 if ($ip_start->version != $version ||
560 ip_bincomp($binip, 'lt', $ip_start->binip) == 1 ||
561 ip_bincomp($binip, 'gt', $ip_end->binip) == 1) {
562 $entries[$i]='';
563 }
564 }
565
566 #
567 # We use the sparse method if the number of entries available occupies < 80% of
568 # the network range, otherwise we use a method that involves walking the
569 # entire range.
570 #
571
572 srand(42); # Set the seed for the PRNG
573
574 if ($capacity / "$range_size" > 0.9) {
575 @entries = walk_fill($ip_start, $ip_end, $capacity, @entries);
576 } elsif (length($range_size) > 9 || $capacity / "$range_size" < 0.8) { # From "BigInt" to FP
577 @entries = sparse_fill($ip_start, $ip_end, $capacity, @entries);
578 } else {
579 @entries = dense_fill($ip_start, $ip_end, $ip_range, $capacity, @entries);
580 }
581
582 return @entries;
583 }
584
585
586 #
587 # With this sparse fill method we randomly allocate within the scope of the
588 # smallest enclosing network prefix, checking that we are within the given
589 # range, retrying if we are outside or we hit a duplicate.
590 #
591 # This method can efficiently choose a small number of addresses relative to
592 # the size of the range. It becomes slower as the population of a range nears
593 # the range's limit since it is harder to choose a free address at random.
594 #
595 # It is useful for selecting a handful of addresses from an enourmous IPv6 /64
596 # network for example.
597 #
598 sub sparse_fill {
599
600 my $ip_start = shift;
601 my $ip_end = shift;
602 my $capacity = shift;
603 my @entries = @_;
604
605 # Find the smallest network that encloses the given range
606 my $version = $ip_start->version;
607 ( $ip_start->binip ^ $ip_end->binip ) =~ /^\0*/;
608 my $net_prefix = $+[0];
609 my $net_bits = substr($ip_start->binip, 0, $net_prefix);
610 my $host_length = length($ip_start->binip) - $net_prefix;
611
612 my %ips = ();
613 my $i = 0;
614 while ($i < $capacity) {
615
616 # Use the given entries first
617 my $rand_ip;
618 my $given_lease = 0;
619 shift @entries while $#entries >= 0 && $entries[0] eq '';
620 if ($#entries >= 0) {
621 $rand_ip = ip_iptobin(shift @entries, $version);
622 $given_lease = 1;
623 } else {
624 $rand_ip = $net_bits;
625 $rand_ip .= [0..1]->[rand 2] for 1..$host_length;
626 # Check that we are inside the given range
627 next if ip_bincomp($rand_ip, 'lt', $ip_start->binip) == 1 ||
628 ip_bincomp($rand_ip, 'gt', $ip_end->binip) == 1;
629 }
630
631 next if defined $ips{$rand_ip};
632
633 $ips{$rand_ip} = $given_lease ? '=' : '+';
634 $i++;
635
636 }
637
638 return map { ip_bintoip($_, $version) } keys %ips;
639
640 }
641
642
643 #
644 # With this dense fill method, after first selecting the given entries we walk
645 # the network range picking IPs with evenly distributed probability.
646 #
647 # This method can efficiently choose a large number of addresses relative to
648 # the size of a range, provided that the range isn't massive. It becomes
649 # slower as the range size increases.
650 #
651 sub dense_fill {
652
653 my $ip_start = shift;
654 my $ip_end = shift;
655 my $ip_range = shift;
656 my $capacity = shift;
657 my @entries = @_;
658
659 my $version = $ip_start->version;
660
661 my $one = ("0"x($version == 4 ? 31 : 127)) . '1';
662
663 my %ips = ();
664 my $remaining_entries = $capacity;
665 my $remaining_ips = $ip_range->size;
666 my $ipbin = $ip_start->binip;
667
668 while ($remaining_entries > 0 && (ip_bincomp($ipbin, 'le', $ip_end->binip) == 1)) {
669
670 # Use the given entries first
671 shift @entries while $#entries >= 0 && $entries[0] eq '';
672 if ($#entries >= 0) {
673 $ips{ip_iptobin(shift @entries, $version)} = '=';
674 $remaining_entries--;
675 $remaining_ips--;
676 next;
677 }
678
679 goto next_ip if defined $ips{$ipbin};
680
681 # Skip the IP that we have already selected by given entries, otherwise
682 # randomly pick it
683 if (!defined $ips{$ipbin} &&
684 (rand) <= $remaining_entries / "$remaining_ips") { # From "BigInt" to FP
685 $ips{$ipbin} = '+';
686 $remaining_entries--;
687 }
688
689 $remaining_ips--;
690 $ipbin = ip_binadd($ipbin,$one);
691
692 }
693
694 return map { ip_bintoip($_, $version) } keys %ips;
695
696 }
697
698 #
699 # With this walk fill method we walk the IP range from the beginning
700 # for as many IPs as are required
701 #
702 # It is useful for selecting a fully populated network.
703 #
704
705 sub walk_fill {
706 my $ip_start = shift;
707 my $ip_end = shift;
708 my $capacity = shift;
709 my @entries = @_;
710
711 my $version = $ip_start->version;
712
713 my $one = ("0"x($version == 4 ? 31 : 127)) . '1';
714
715 my %ips = ();
716 my $remaining_entries = $capacity;
717 my $ipbin = $ip_start->binip;
718
719 # Sort existing IPs and remove any blank entries. Allows existing entries to be
720 # matched quickly in the new pool
721 my @sorted_entries = sort @entries;
722 shift @sorted_entries while $#sorted_entries >= 0 && $sorted_entries[0] eq '';
723
724 # Walk through the IP range from the beginning
725 while ($remaining_entries > 0 && (ip_bincomp($ipbin, 'le', $ip_end->binip) == 1)) {
726
727 if ($#sorted_entries >= 0) {
728 # If there are existing entries check if they match
729 $ips{$ipbin} = (ip_bincomp($ipbin, 'eq', ip_iptobin($sorted_entries[0]) == 1) && shift(@sorted_entries) ? '=' : '+');
730 } else {
731 $ips{$ipbin} = '+';
732 }
733 $remaining_entries--;
734 $ipbin = ip_binadd($ipbin,$one);
735
736 }
737
738 return map { ip_bintoip($_, $version) } keys %ips;
739
740 }
741
742
743
744 #
745 # SQL dialect templates
746 #
747
748 sub load_templates {
749
750 my $tablename = shift;
751
752 my $template;
753 my $queries;
754 #
755 # MySQL / MariaDB
756 #
757 $queries->{'mysql'}->{pre} = [
758 'DROP TEMPORARY TABLE IF EXISTS '.$tablename.'_temp;',
759 'CREATE TEMPORARY TABLE '.$tablename.'_temp (
760 id int(11) unsigned NOT NULL auto_increment,
761 pool_name varchar(30) NOT NULL,
762 framedipaddress varchar(15) NOT NULL,
763 PRIMARY KEY (id),
764 KEY pool_name_framedipaddress (pool_name,framedipaddress)
765 );'
766 ];
767 $queries->{'mysql'}->{insert} = 'INSERT INTO '.$tablename.'_temp (pool_name,framedipaddress) VALUES (?, ?)';
768 $queries->{'mysql'}->{post} = [
769 'START TRANSACTION;',
770 'DELETE r FROM '.$tablename.' r
771 LEFT JOIN '.$tablename.'_temp t USING (pool_name,framedipaddress)
772 WHERE t.id IS NULL;',
773 'INSERT INTO '.$tablename.' (pool_name,framedipaddress)
774 SELECT pool_name,framedipaddress FROM '.$tablename.'_temp t WHERE NOT EXISTS (
775 SELECT * FROM '.$tablename.' r
776 WHERE r.pool_name=t.pool_name AND r.framedipaddress=t.framedipaddress
777 );',
778 'COMMIT;'
779 ];
780 $template->{'mysql'} = join("\n", @{$queries->{'mysql'}->{pre}})."\n";
781 $template->{'mysql'} .= <<'END_mysql';
782 -- Populate the temporary table
783 [%- FOREACH r IN ranges %]
784 [%- FOREACH i IN r.ips %]
785 [%- "\n\nINSERT INTO ${tablename}_temp (pool_name,framedipaddress) VALUES" IF loop.index % batchsize == 0 %]
786 [%- IF (loop.index+1) % batchsize == 0 OR loop.last %]
787 ('[% r.pool_name %]','[% i %]');
788 [%- ELSE %]
789 ('[% r.pool_name %]','[% i %]'),
790 [%- END %]
791 [%- END %]
792 [%- END %]
793 END_mysql
794 $template->{'mysql'} .= join("\n", @{$queries->{'mysql'}->{post}})."\n";
795
796 #
797 # PostgreSQL
798 #
799 $queries->{'postgresql'}->{pre} = [
800 'DROP TABLE IF EXISTS '.$tablename.'_temp;',
801 'CREATE TEMPORARY TABLE '.$tablename.'_temp (
802 pool_name varchar(64) NOT NULL,
803 FramedIPAddress INET NOT NULL
804 );',
805 'CREATE INDEX '.$tablename.'_temp_idx ON '.$tablename.'_temp USING btree (pool_name,FramedIPAddress);'
806 ];
807 $queries->{'postgresql'}->{insert} = 'INSERT INTO '.$tablename.'_temp (pool_name,framedipaddress) VALUES (?, ?)';
808 $queries->{'postgresql'}->{post} = [
809 'START TRANSACTION;',
810 'DELETE FROM '.$tablename.' r WHERE NOT EXISTS (
811 SELECT FROM '.$tablename.'_temp t
812 WHERE t.pool_name = r.pool_name AND t.framedipaddress = r.framedipaddress
813 );',
814 'INSERT INTO '.$tablename.' (pool_name,framedipaddress)
815 SELECT pool_name,framedipaddress FROM '.$tablename.'_temp t WHERE NOT EXISTS (
816 SELECT * FROM '.$tablename.' r
817 WHERE r.pool_name=t.pool_name AND r.framedipaddress=t.framedipaddress
818 );',
819 'COMMIT;'
820 ];
821 $template->{'postgresql'} = join("\n", @{$queries->{'postgresql'}->{pre}})."\n";
822 $template->{'postgresql'} .= <<'END_postgresql';
823 -- Populate the temporary table
824 [%- FOREACH r IN ranges %]
825 [%- FOREACH i IN r.ips %]
826 [%- "\n\nINSERT INTO ${tablename}_temp (pool_name,framedipaddress) VALUES" IF loop.index % batchsize == 0 %]
827 [%- IF (loop.index+1) % batchsize == 0 OR loop.last %]
828 ('[% r.pool_name %]','[% i %]');
829 [%- ELSE %]
830 ('[% r.pool_name %]','[% i %]'),
831 [%- END %]
832 [%- END %]
833 [%- END %]
834 END_postgresql
835 $template->{'postgresql'} .= join("\n", @{$queries->{'postgresql'}->{post}})."\n";
836 #
837 # Oracle
838 #
839 $queries->{'oracle'}->{pre} = [
840 'CREATE TABLE '.$tablename.'_temp (
841 pool_name VARCHAR(30) NOT NULL,
842 FramedIPAddress VARCHAR(15) NOT NULL
843 )',
844 'CREATE INDEX '.$tablename.'_temp_idx ON '.$tablename.'_temp (pool_name,FramedIPAddress)'
845 ];
846 $queries->{'oracle'}->{insert} = 'INSERT INTO '.$tablename.'_temp (pool_name,FramedIPAddress) VALUES (?, ?)';
847 $queries->{'oracle'}->{post} = [
848 'DELETE FROM '.$tablename.' r WHERE NOT EXISTS
849 (SELECT * FROM '.$tablename.'_temp t WHERE
850 r.pool_name = t.pool_name AND r.framedipaddress = t.framedipaddress)',
851 'INSERT INTO '.$tablename.' (pool_name,framedipaddress)
852 SELECT pool_name,framedipaddress FROM '.$tablename.'_temp t WHERE NOT EXISTS (
853 SELECT * FROM '.$tablename.' r
854 WHERE r.pool_name=t.pool_name AND r.framedipaddress=t.framedipaddress
855 )',
856 'DROP TABLE '.$tablename.'_temp',
857 'COMMIT'
858 ];
859
860 $template->{'oracle'} = join(";\n", @{$queries->{'oracle'}->{pre}}).";\n";
861 $template->{'oracle'} .= <<'END_oracle';
862 -- Populate the temporary table
863 [%- FOREACH r IN ranges %]
864 [%- FOREACH i IN r.ips %]
865 [%- "\nINSERT INTO ${tablename}_temp (pool_name,framedipaddress) VALUES " %]('[% r.pool_name %]','[% i %]');
866 [%- END %]
867 [%- END %]
868 END_oracle
869 $template->{'oracle'} .= join(";\n", @{$queries->{'oracle'}->{post}})."\n";
870
871 #
872 # SQLite
873 #
874 $queries->{'sqlite'}->{pre} = [
875 'DROP TABLE IF EXISTS '.$tablename.'_temp;',
876 'CREATE TABLE '.$tablename.'_temp (
877 pool_name varchar(30) NOT NULL,
878 framedipaddress varchar(15) NOT NULL
879 );',
880 'CREATE INDEX '.$tablename.'_temp_idx ON '.$tablename.'_temp (pool_name,FramedIPAddress);'
881 ];
882 $queries->{'sqlite'}->{insert} = 'INSERT INTO '.$tablename.'_temp (pool_name,framedipaddress) VALUES (?, ?)';
883 $queries->{'sqlite'}->{post} = [
884 'BEGIN TRANSACTION;',
885 'DELETE FROM '.$tablename.' WHERE rowid IN (
886 SELECT r.rowid FROM '.$tablename.' r
887 LEFT JOIN '.$tablename.'_temp t USING (pool_name,framedipaddress)
888 WHERE t.rowid IS NULL);',
889 'INSERT INTO '.$tablename.' (pool_name,framedipaddress)
890 SELECT pool_name,framedipaddress FROM '.$tablename.'_temp t WHERE NOT EXISTS (
891 SELECT * FROM '.$tablename.' r
892 WHERE r.pool_name=t.pool_name AND r.framedipaddress=t.framedipaddress
893 );',
894 'COMMIT;',
895 'DROP TABLE '.$tablename.'_temp;'
896 ];
897
898 $template->{'sqlite'} = join("\n", @{$queries->{'sqlite'}->{pre}})."\n";
899 $template->{'sqlite'} .= <<'END_sqlite';
900 -- Populate the temporary table
901 [%- FOREACH r IN ranges %]
902 [%- FOREACH i IN r.ips %]
903 [%- "\n\nINSERT INTO ${tablename}_temp (pool_name,framedipaddress) VALUES" IF loop.index % batchsize == 0 %]
904 [%- IF (loop.index+1) % batchsize == 0 OR loop.last %]
905 ('[% r.pool_name %]','[% i %]');
906 [%- ELSE %]
907 ('[% r.pool_name %]','[% i %]'),
908 [%- END %]
909 [%- END %]
910 [%- END %]
911 END_sqlite
912 $template->{'sqlite'} .= join("\n", @{$queries->{'sqlite'}->{post}})."\n";
913
914 #
915 # MS SQL
916 #
917 $queries->{'mssql'}->{pre} = [
918 'DROP TABLE IF EXISTS #'.$tablename.'_temp;',
919 'CREATE TABLE #'.$tablename.'_temp (
920 id int identity(1, 1) NOT NULL,
921 pool_name varchar(30) NOT NULL,
922 framedipaddress varchar(15) NOT NULL,
923 PRIMARY KEY (id),
924 );',
925 'CREATE INDEX pool_name_framedipaddress ON #'.$tablename.'_temp(pool_name, framedipaddress);'
926 ];
927 $queries->{'mssql'}->{insert} = 'INSERT INTO #'.$tablename.'_temp (pool_name, framedipaddress) VALUES (?, ?)';
928 $queries->{'mssql'}->{post} = [
929 'BEGIN TRAN;',
930 'DELETE r FROM '.$tablename.' r
931 LEFT JOIN #'.$tablename.'_temp t ON r.pool_name = t.pool_name AND r.framedipaddress = t.framedipaddress
932 WHERE t.id IS NULL;',
933 'INSERT INTO '.$tablename.' (pool_name,framedipaddress)
934 SELECT pool_name,framedipaddress FROM #'.$tablename.'_temp t WHERE NOT EXISTS (
935 SELECT * FROM '.$tablename.' r
936 WHERE r.pool_name=t.pool_name AND r.framedipaddress=t.framedipaddress
937 );',
938 'COMMIT TRAN;'
939 ];
940
941 $template->{'mssql'} = join("\nGO\n", @{$queries->{'mssql'}->{pre}})."\nGO\n";
942 $template->{'mssql'} .= <<'END_mssql';
943 -- Populate the temporary table
944 [%- FOREACH r IN ranges %]
945 [%- FOREACH i IN r.ips %]
946 [%- "\n\nINSERT INTO #${tablename}_temp (pool_name,framedipaddress) VALUES" IF loop.index % batchsize == 0 %]
947 [%- IF (loop.index+1) % batchsize == 0 OR loop.last %]
948 ('[% r.pool_name %]','[% i %]');
949 GO
950 [%- ELSE %]
951 ('[% r.pool_name %]','[% i %]'),
952 [%- END %]
953 [%- END %]
954 [% END %]
955 END_mssql
956 $template->{'mssql'} .= join("\n", @{$queries->{'mssql'}->{post}})."\n";
957
958 return ($template, $queries);
959
960 }
961