blib/lib/CIDR/Assign.pm untested

filter: Statementstmt 0.0% 0 / 299 Branchbran 0.0% 0 / 106 Conditioncond 0.0% 0 / 110 MC/DCmcdc 0.0% 0 / 62 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 609 CC 54 SCAR 48.8
CC
54
Cov
0%
assignNetwork
342.0
changeState
182.0
mergeNetwork
42.0
CRAP 131.6
1 package CIDR::Assign;
2  
3 # $Id: Assign.pm,v 1.14 1998/05/28 02:50:02 mrp Exp $
4  
5 =head1 NAME
6  
7 CIDR::Assign - Manage assignments out of a group of CIDR blocks
8  
9 =head1 SYNOPSIS
10  
11 use CIDR::Assign;
12  
13 $obj = CIDR::Assign->new($filename);
14  
15 $obj->DESTROY;
16  
17 $network = $obj->assignNetwork($length, $customer, $ones, $zeros, $location);
18  
19 $obj->changeState($network, $state, $customer, $location);
20  
21 $obj->initialiseBlock($network);
22  
23 ($network, $state, $date, $customer, $location) = $obj->iterateAllocations;
24  
25 =head1 DESCRIPTION
26  
27 This module can be used to manage customer assigments out of a provider
28 block. The CIDR block is represented as a B-Tree in a Berkeley DB database
29 and is originally populated by invoking initialiseBlock with each provider
30 block.
31  
32 =cut
33  
34 # The B-Tree is keyed to the address, which is "normalised" into CIDR length
35 # form where the address component always contains 4 octets.
36 #
37 # The value of each element is constructed as a series of $separator terminated
38 # strings which are interpreted as key/value pairs.
39 #
40 # The keys present in the element are
41 # state - 'free', 'taken' or 'holding' (required)
42 # date - date of the last operation on the block (required)
43 # customer - some customer "code", at Connect this a customer ID
44 # location - a location code, Connect use a 3 letter city code
45 #
46  
47 require 5.003;
48 require Exporter;
49  
50 use Carp;
51 use FileHandle;
52 use DB_File;
53 use File::lockf;
54  
55 $VERSION = '0.01'; # should be tied to the RCS rev eventually
56  
57 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
58 $today = sprintf "%4d%02d%02d", $year+1900, $mon+1, $mday,
59  
60 %states = (
61 free => 'unallocated',
62 taken => 'allocated',
63 holding => 'being considered for reuse',
64 );
65  
66 %messages = (
67 OK => '',
68 LENGTH => 'Length of request is invalid, must be between 2 and 32',
69 NOMATCH => 'No suitable allocation available',
70 STATE => 'New state "%s" is unrecognised',
71 NETWORK => 'Network "%s" is invalid, illegal octet value %s',
72 RANGE => 'Network not within the allocation pool',
73 OVERLAP => 'New block "%s" overlaps existing allocation',
74 );
75  
76 $separator = chr(0);
77  
78 @ISA = qw(Exporter);
79 @EXPORT = qw($VERSION new DESTROY assignNetwork changeState iterateAllocations
80 errorMessage);
81 @EXPORT_OK = qw(compareIP maskOfLength parseNet printIP overlap);
82  
83 sub compareIP {
84 my($netA, $lenA) = split(/\//, shift);
85 my($netB, $lenB) = split(/\//, shift);
86 my(@a) = split(/\./, $netA);
87 my(@b) = split(/\./, $netB);
88  
89 return $a[0] <=> $b[0] || $a[1] <=> $b[1]
90 || $a[2] <=> $b[2] || $a[3] <=> $b[3]
91 || $lenA <=> $lenB;
92 }
93  
94 sub new {
95  
96 =pod
97  
98 new will create the DB file, whose name is passed as a parameter, if necessary,
99 and then tie it to an internal hash used by the other routines. This routine
100 attempts to acquire a lock on the DB file using lockf in an attempt to control
101 access to the file. Should acquiring the lock fail the routine will return
102 "undef".
103  
104 =cut
105  
106 my($class) = shift;
107 my($i, %hash);
108 my($self) = {
109 NAME => shift,
110 FILE => new FileHandle,
111 DB => undef,
112 POS => undef,
113 ERROR => 'OK',
114 PARAMS => undef,
115 };
116  
117 $DB_BTREE->{'compare'} = \&compareIP;
118  
119 unless ( $self->{DB} = tie(%hash, 'DB_File', $self->{NAME},
120 O_CREAT|O_RDWR, 0660, $DB_BTREE) ) {
121 carp "dbopen failed: $!\n";
122 return undef;
123 }
124  
125 $self->{FILE}->fdopen($self->{DB}->fd, "r+") || die "fdopen: $!\n";
126 if ( File::lockf::tlock( $self->{FILE} ) != 0 ) {
127 # wait for the lock
128 my($i);
129 for ( $i = 5; $i > 0 ; $i-- ) {
130 sleep 5;
131 break if File::lockf::tlock( $self->{FILE} ) == 0;
132 }
133 if ( $i == 0 ) {
134 carp "Unable to acquire lock on DB\n";
135 undef $self->{DB};
136 $self->{FILE}->close;
137 return undef;
138 }
139 }
140 return bless ($self, ref $class || $class);
141 }
142  
143 sub DESTROY {
144  
145 =pod
146  
147 DESTROY closes the DB file and releases the lock on the file.
148  
149 =cut
150  
151 my($self) = shift;
152  
153 return unless defined $self->{DB};
154 File::lockf::ulock( $self->{FILE} );
155 $self->{FILE}->close;
156 undef $self->{DB};
157 }
158  
159 sub assignNetwork {
160  
161 =pod
162  
163 Networks can be allocated out of the assigned blocks by calling
164 assignNetwork specifying the size of the block required. The system then
165 scans the tree for a "free" block that is of the required size. If a block
166 isn't available then it splits the next largest block and invokes itself.
167 Should there be no free block available for allocation then the routing
168 returns "undef".
169  
170 The parameters "ones" and "zeroes" are used to indicate if the allocation can
171 make use of an all ones or all zeros network if necessary.
172  
173 The parameter "location" is optional but if present and the allocation is
174 smaller than a /24 it will try to choose a block in the same location as
175 other allocations in order to avoid too much fragmentation of the address
176 space.
177  
178 =cut
179  
180 my($self) = shift;
181 my($length, $customer, $ones, $zeroes, $location) = @_;
182 my($status, $network, $value, $bits);
183 my($spare, $match, $contents) = '';
184 my($smallest) = 0;
185 my($timestamp) = undef;
186 my(%hash);
187  
188 # Sanity check.
189 if ( $length < 2 || $length > 32 ) {
190 $self->{ERROR} = 'LENGTH';
191 return undef;
192 }
193  
194 $location = lc $location;
195  
196 # Look for a free block that matches our requirements
197 for ( $status = $self->{DB}->seq($network, $value, R_FIRST);
198 $status == 0;
199 $status = $self->{DB}->seq($network, $value, R_NEXT) ) {
200 %hash = split($separator, $value);
201 next unless $hash{'state'} eq 'free';
202 $network =~ /\/(\d+)$/;
203 $bits = $1;
204 next if $length > 24
205 && $location ne '' && $hash{'location'} ne $location;
206 if ( $bits > $length ) { # Too small.
207 next;
208 } elsif ( $bits == $length ) { # Match
209 next if $match ne ''
210 && defined $timestamp && $hash{'date'} >= $timestamp;
211 if ( $ones && $zeroes ) {
212 $timestamp = $hash{'date'};
213 $match = $network;
214 } elsif ( $network =~ /^\d+\.\d+\.(\d+)\.\d+\// ) {
215 my $subnet = $1;
216 if ( ( $subnet != 0 && $subnet != 255 )
217 || ( $subnet == 0 && $zeroes )
218 || ( $subnet == 255 && $ones ) ) {
219 $timestamp = $hash{'date'};
220 $match = $network;
221 }
222 }
223 } elsif ( $match eq '' ) {
224 $network =~ /^\d+\.\d+\.(\d+)\.\d+\//;
225 next if $bits >= 24
226 && ( ( $1 == 0 && $zeroes == 0 )
227 || ( $1 == 255 && $ones == 0 ) );
228 # No match, store for possible later breakdown
229 if ( $smallest < $bits ) {
230 $timestamp = $hash{'date'};
231 $smallest = $bits;
232 $spare = $network;
233 } elsif ( $smallest == $bits
234 && ( !defined $timestamp || $hash{'date'} < $timestamp ) ) {
235 $timestamp = $hash{'date'};
236 $spare = $network;
237 }
238 }
239 }
240 if ( $match ne '' ) {
241 $self->{DB}->get($match, $value);
242 %hash = split($separator, $value);
243 $hash{'state'} = 'taken';
244 $hash{'date'} = $today;
245 $hash{'customer'} = $customer;
246 $hash{'location'} = $location
247 if $length > 24 && defined $location && $location ne '';
248 $self->{DB}->put($match, join($separator, %hash) );
249 $self->{DB}->sync;
250 return $match;
251 }
252  
253 # OK, if we've got this far, there's no match.
254 # Do we have anything we can break down?
255 # If not, we can't succeed, so return now.
256  
257 if ( $spare eq '' ) {
258 $self->{ERROR} = 'NOMATCH';
259 return undef;
260 }
261  
262 # OK, we have something. Break it down, then try again.
263  
264 $self->{DB}->get($spare, $contents);
265 $self->{DB}->del($spare);
266 $spare =~ s/\/(\d+)$//;
267 $bits = $1;
268 %hash = split($separator, $contents);
269 $hash{'location'} = $location
270 if $bits == 24 && defined $location && $location ne '';
271 $network = sprintf "%s/%d", $spare, $bits + 1;
272 $self->{DB}->put( $network, join($separator, %hash) );
273 $self->{DB}->sync;
274 $spare = join ('.', unpack('C4',
275 (pack('C4', split(/\./, $spare)) |
276 pack('B32', scalar ('0' x $bits) . '1' .
277 scalar ('0' x (31 - $bits))))));
278 $network = sprintf "%s/%d", $spare, $bits + 1;
279 $self->{DB}->put( $network, join($separator, %hash) );
280 $self->{DB}->sync;
281 return $self->assignNetwork(@_);
282 }
283  
284 sub changeState {
285  
286 =pod
287  
288 changeState can be used to change the state of a block in the free, for
289 example, to add existing allocations to the tree or return an allocation
290 to the free pool.
291  
292 =cut
293  
294 my($self) = shift;
295 my($network, $state, $customer, $location) = @_;
296 my($ip, $length) = parseNet($network);
297 my($allocation) = sprintf "%s/%d", printIP($ip), $length;
298 my(@candidates) = ();;
299 my($net, $contents, $status, $bits);
300  
301 unless ( defined $states{$state} ) {
302 $self->{ERROR} = 'STATE',
303 $self->{PARAMS} = [ $state ];
304 return undef;
305 }
306 if ( $ip == 0 ) {
307 $self->{ERROR} = 'NETWORK';
308 $self->{PARAMS} = [ $network, $length ];
309 return undef;
310 }
311  
312 if ( $self->{DB}->get($allocation, $contents) == 0 ) {
313 %hash = split($separator, $contents);
314 $hash{'state'} = $state;
315 $hash{'date'} = $today;
316 $hash{'customer'} = $customer if defined $customer;
317 $hash{'location'} = $location
318 if $length > 24 && defined $location && $location ne '';
319 $self->{DB}->put($allocation, join($separator, %hash) );
320 $self->{DB}->sync;
321 # Should try to merge with surrounding nets if possible
322 return $self->mergeNetwork( $allocation );
323 }
324  
325 # It would be nice to use the cursor to just search the subtree
326 # where the allocation would be located but it will return the
327 # element in the tree after the one we want, since it returns
328 # equal or greater than. As a consequence we need to run through
329 # the whole of the tree looking for the bit we want.
330 #
331 for ( $status = $self->{DB}->seq($network, $value, R_FIRST);
332 $status == 0;
333 $status = $self->{DB}->seq($network, $value, R_NEXT) ) {
334 push @candidates, $network if overlap($allocation, $network);
335 }
336  
337 # Did we find an allocation that overlaps the bit we want to change?
338 if ( $#candidates == 0 ) {
339 ($net, $bits) = split(/\//, $candidates[0]);
340 if ( $bits < $length ) {
341 # OK, we have something bigger.
342 # Break it down, then try again.
343 $self->{DB}->get($candidates[0], $contents);
344 $self->{DB}->del($candidates[0]);
345 %hash = split($separator, $contents);
346 $hash{'location'} = $location
347 if $bits == 24
348 && defined $location && $location ne '';
349 $network = sprintf("%s/%d", $net, $bits + 1);
350 $self->{DB}->put($network, join($separator, %hash) );
351 $self->{DB}->sync;
352 $net = join ('.', unpack('C4',
353 (pack('C4', split(/\./, $net) ) |
354 pack('B32', scalar ('0' x $bits) . '1' .
355 scalar ('0' x (31 - $bits))))));
356 $network = sprintf("%s/%d", $net, $bits + 1);
357 $self->{DB}->put($network, join($separator, %hash) );
358 $self->{DB}->sync;
359 return $self->changeState(@_);
360 } else {
361 # The user wants us to change something that is not
362 # in the allocation pool, complain...
363 $self->{ERROR} = 'RANGE';
364 return undef;
365 }
366 } elsif ( $#candidates > 0 ) {
367 # We should check that these elements completely cover the
368 # entry we want to change but that's too hard for now so
369 # just assume they do...
370 #
371 # Remove the fragments enclosed by the new element
372 foreach ( @candidates ) {
373 $self->{DB}->del($_);
374 }
375 %hash = {};
376 $hash{'state'} = $state;
377 $hash{'date'} = $today;
378 $hash{'customer'} = $customer if defined $customer;
379 $hash{'location'} = $location
380 if $length > 24 && defined $location && $location ne '';
381 $self->{DB}->put($allocation, join($separator, %hash) );
382 $self->{DB}->sync;
383 return $self->mergeNetwork( $allocation );
384 } else {
385 # We can't find any evidence of the entry being part of
386 # the allocation pool.
387 $self->{ERROR} = 'RANGE';
388 return undef;
389 }
390 }
391  
392 sub initialiseBlock {
393  
394 =pod
395  
396 initialiseBlock adds a new block into the allocation pool.
397  
398 =cut
399  
400 my($self) = shift;
401 my($network, $length) = parseNet(@_);
402 my($allocation) = sprintf "%s/%d", printIP($network), $length;
403 my($status);
404 my(%hash) = {};
405 my(@candidates) = ();
406  
407 if ( $network == 0 ) {
408 $self->{ERROR} = 'NETWORK';
409 $self->{PARAMS} = [ @_, $length ];
410 return undef;
411 }
412  
413 if ( $self->{DB}->get($allocation, $contents) == 0 ) {
414 $self->{ERROR} = 'OVERLAP';
415 $self->{PARAMS} = [ $allocation ];
416 return undef;
417 }
418  
419 # OK now check that it's not part of an existing allocation
420 for ( $status = $self->{DB}->seq($network, $value, R_FIRST);
421 $status == 0;
422 $status = $self->{DB}->seq($network, $value, R_NEXT) ) {
423 push @candidates, $network if overlap($allocation, $network);
424 }
425  
426 if ( $#candidates < 0 ) {
427 $hash{'state'} = 'free';
428 $hash{'date'} = $today;
429 $status = $self->{DB}->put($allocation, join($separator, %hash) );
430 $status = $self->{DB}->sync;
431 return $self->mergeNetwork( $allocation );
432 } else {
433 $self->{ERROR} = 'OVERLAP';
434 $self->{PARAMS} = [ $allocation ];
435 return undef;
436 }
437 }
438  
439 sub mergeNetwork {
440 my($self) = shift;
441 my($network, $length) = parseNet(@_);
442 my($allocation) = sprintf "%s/%d", printIP($network), $length;
443 my($contents);
444 my($bits, $merge, $status, $value, $dummy, $larger);
445 my(@overlap) = ();
446 my($state, $location, $customer, $date);
447 my(%hash, %original);
448  
449 # Save the value of the component we want to merge so we can check
450 # that all the other components are like it.
451 $self->{DB}->get($allocation, $contents);
452  
453 %original = split($separator, $contents);
454  
455 $state = $original{state};
456 $location = $original{location};
457 $customer = $original{customer};
458 $date = $original{date};
459  
460 # Should try to merge networks into larger CIDR blocks if surrounding
461 # blocks are free or have the same customer ID
462 #
463 $bits = $length - 1;
464 $larger = join('.', unpack('C4', ( pack('L', $network) &
465 pack('B32', scalar('1' x $bits) .
466 scalar('0' x (32 - $bits))))));
467 $network = sprintf "%s/%d", $larger, $bits;
468  
469 # Initialise the cursor, this shouldn't be necessary but the for loop
470 # below doesn't work as I expected without it for the last subtree :-(
471 #
472 $status = $self->{DB}->seq($dummy, $value, R_FIRST);
473  
474 # Just run through the subtree checking that the components are the
475 # same, we don't care if the "free" date is different.
476 #
477 $merge = 1;
478 for ( $status = $self->{DB}->seq($network, $value, R_CURSOR);
479 $status == 0 && $merge;
480 $status = $self->{DB}->seq($network, $value, R_NEXT) ) {
481 if ( overlap( sprintf("%s/%d", $larger, $bits), $network ) ) {
482 %hash = split($separator, $value);
483 if ( $state ne $hash{'state'} ) {
484 $merge = 0;
485 } elsif ( $hash{'state'} ne 'free' ) {
486 $merge = $customer eq $hash{'customer'};
487 push @overlap, $network;
488 } else {
489 push @overlap, $network;
490 }
491 } else {
492 last;
493 }
494 }
495  
496 # We have a valid overlap of like components so merge them into a
497 # supernet then try to merge it
498 #
499 if ( $merge && $#overlap > 0 ) {
500 $allocation = sprintf "%s/%d", $larger, $bits;
501 undef $original{location} if defined $location && $bits >= 24;
502 $self->{DB}->put($allocation, join($separator, %original) );
503 $self->{DB}->sync;
504 foreach ( @overlap ) {
505 $self->{DB}->del($_);
506 }
507 return $self->mergeNetwork( $allocation );
508 } else {
509 return $allocation;
510 }
511 }
512  
513 sub iterateAllocations {
514  
515 =pod
516  
517 iterateAllocations allows the caller to traverse the tree, much like "each",
518 and returns a list of information about each allocation. This list is comprised
519 of network, state (currently 'taken', 'free' or 'holding'), date of last
520 operation and customer indentifer (and possibly location) if the block is not
521 free.
522  
523 =cut
524  
525 my($self) = shift;
526 my($status, $value);
527 my(%hash);
528  
529 unless ( wantarray ) {
530 $self->{POS} = undef;
531 return undef;
532 }
533 if ( defined $self->{POS} ) {
534 $self->{DB}->seq($self->{POS}, $value, R_CURSOR);
535 $status = $self->{DB}->seq($self->{POS}, $value, R_NEXT);
536 } else {
537 $status = $self->{DB}->seq($self->{POS}, $value, R_FIRST);
538 }
539 if ( $status == 0 ) {
540 %hash = split($separator, $value);
541 return ($self->{POS}, $hash{'state'}, $hash{'date'},
542 $hash{'customer'}, $hash{'location'});
543 } else {
544 $self->{POS} = undef;
545 return ();
546 }
547 }
548  
549 sub errorMessage {
550  
551 =pod
552  
553 errorMessage return a string suitable for printing that describes the latest
554 error condition.
555  
556 =cut
557  
558 my($self) = shift;
559 my(@params) = @{ $self->{PARAMS} };
560  
561 return sprintf $messages{$self->{ERROR}}, @params;
562 }
563  
564 sub maskOfLength {
565 my($len) = @_;
566  
567 return(-( 1 << (32 - $len )));
568 }
569  
570 sub parseNet {
571 my($prefix, $length) = split('/', shift, 2);
572 my(@bytes) = split(/\./, $prefix, 4);
573 my($ip, $byte);
574  
575 foreach $byte ( @bytes ) {
576 if ( $byte !~ /^\d+$/ || $byte > 255 ) {
577 return (0, $byte);
578 }
579 }
580  
581 $ip = unpack('L', pack('C4', @bytes));
582
583 # Supply a classful default length ONLY if no length was specified.
584  
585 if ( $length eq "" ) {
586 # Old version: user the classful default lengths.
587 #
588 # No explicit length given so default to classful definition
589 $length = ( $bytes[0] < 128 ) ? 8 :
590 ( $bytes[0] < 192 ) ? 16:
591 24;
592  
593 # *IF* this default causes a CIDR-alignment problem,
594 # then that's probably not what they wanted. Try
595 # 8, 16, 24, or 32 based on the number of octets
596 # that they supplied when they typed the address.
597 # E.g.,:
598 # 35 -> 35/8
599 # 35.1 -> 35/16
600 # 193 -> 193/8
601 # 193.128.2.15 -> 193.128.2.15/32
602  
603 $mask = &maskOfLength($length);
604 $length = (8,16,24,32)[$#bytes] if ($mask & $ip) != $ip;
605 }
606  
607 return ( $ip, $length );
608 }
609  
610 sub printIP {
611 return join('.', unpack('C4', pack('L', @_)));
612 }
613  
614 sub overlap {
615 my($old, $new) = @_;
616 my(@old, @new);
617  
618 @old = &parseNet($old);
619 @new = &parseNet($new);
620 if ( $old[1] == $new[1] ) {
621 return $old[0] == $new[0];
622 } else { # different lengths so we need to see if one is inside other
623 if ( $old[1] < $new[1] ) {
624 $mask = &maskOfLength($old[1]);
625 } else {
626 $mask = &maskOfLength($new[1]);
627 }
628 return ($old[0] & $mask) == ($new[0] & $mask);
629 }
630 }
631  
632 1;
633  
634 =head1 AUTHOR
635  
636 Mark Prior <mrp@connect.com.au>
637  
638 Original idea and code by Andrew Rutherford <andrewr@iagu.net>
639  
640 =head1 NOTES
641
642 This module uses the following modules
643  
644 =over 4
645  
646 =item DB_File
647  
648 The Berkeley DB is used for storage of the allocations, in B-Tree format.
649  
650 =item File::lockf
651  
652 The allocations file is locked with lockf to avoid problems with NFS.
653  
654 =back
655  
656 =cut
657