source: trunk/cgi-bin/IPDB.pm@ 705

Last change on this file since 705 was 705, checked in by Kris Deugau, 9 years ago

/trunk

  • Complete internal handling for "shrink block". See #7 (more or less).
  • Add "breadcrumb" navigation fragments to split/shrink prep and do pages
  • Add link to pool IP list on edit and split/shrink prep pages
  • Shave off some useless code showing the split results
  • Catch the theoretically impossible case of "no subact value" on submitting split/shrink form

Still need to add calls to monkey rDNS on split/shrink changes

  • Property svn:keywords set to Date Rev Author
File size: 78.3 KB
Line 
1# ipdb/cgi-bin/IPDB.pm
2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
3###
4# SVN revision info
5# $Date: 2015-02-25 23:09:13 +0000 (Wed, 25 Feb 2015) $
6# SVN revision $Rev: 705 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2010 - Kris Deugau
10
11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
17use Net::SMTP;
18use NetAddr::IP qw(:lower Compact );
19use Frontier::Client;
20use POSIX;
21use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
22
23$VERSION = 2; ##VERSION##
24@ISA = qw(Exporter);
25@EXPORT_OK = qw(
26 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
27 %IPDBacl %aclmsg %rpcacl $maxfcgi
28 $errstr
29 &initIPDBGlobals &connectDB &finish &checkDBSanity
30 &addMaster &touchMaster
31 &listSummary &listSubs &listContainers &listAllocations &listFree &listPool
32 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
33 &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
34 &allocateBlock &updateBlock &splitBlock &shrinkBlock &deleteBlock &getBlockData
35 &getBlockRDNS &getRDNSbyIP
36 &getNodeList &getNodeName &getNodeInfo
37 &mailNotify
38 );
39
40@EXPORT = (); # Export nothing by default.
41%EXPORT_TAGS = ( ALL => [qw(
42 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
43 %IPDBacl %aclmsg %rpcacl $maxfcgi
44 $errstr
45 &initIPDBGlobals &connectDB &finish &checkDBSanity
46 &addMaster &touchMaster
47 &listSummary &listSubs &listContainers &listAllocations &listFree &listPool
48 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
49 &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
50 &allocateBlock &updateBlock &splitBlock &shrinkBlock &deleteBlock &getBlockData
51 &getBlockRDNS &getRDNSbyIP
52 &getNodeList &getNodeName &getNodeInfo
53 &mailNotify
54 )]
55 );
56
57##
58## Global variables
59##
60our %disp_alloctypes;
61our %list_alloctypes;
62our %def_custids;
63our @citylist;
64our @poplist;
65our %IPDBacl;
66
67# mapping table for functional-area => error message
68our %aclmsg = (
69 addmaster => 'add a master block',
70 addblock => 'add an allocation',
71 updateblock => 'update a block',
72 delblock => 'delete an allocation',
73 );
74
75our %rpcacl;
76our $maxfcgi = 3;
77
78# error reporting
79our $errstr = '';
80
81our $org_name = 'Example Corp';
82our $smtphost = 'smtp.example.com';
83our $domain = 'example.com';
84our $defcustid = '5554242';
85our $smtpsender = 'ipdb@example.com';
86# mostly for rwhois
87##fixme: leave these blank by default?
88our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
89our $org_street = '123 4th Street';
90our $org_city = 'Anytown';
91our $org_prov_state = 'ON';
92our $org_pocode = 'H0H 0H0';
93our $org_country = 'CA';
94our $org_phone = '000-555-1234';
95our $org_techhandle = 'ISP-ARIN-HANDLE';
96our $org_email = 'noc@example.com';
97our $hostmaster = 'dns@example.com';
98
99our $syslog_facility = 'local2';
100
101our $rpc_url = '';
102our $revgroup = 1; # should probably be configurable somewhere
103our $rpccount = 0;
104
105# Largest inverse CIDR mask length to show per-IP rDNS list
106# (eg, NetAddr::IP->bits - NetAddr::IP->masklen)
107our $maxrevlist = 5; # /27
108
109# UI layout for subblocks/containers
110our $sublistlayout = 1;
111
112# VLAN validation mode. Set to 0 to allow alphanumeric vlan names instead of using the vlan number.
113our $numeric_vlan = 1;
114
115
116##
117## Internal utility functions
118##
119
120## IPDB::_rpc
121# Make an RPC call for DNS changes
122sub _rpc {
123 return if !$rpc_url; # Just In Case
124 my $rpcsub = shift;
125 my %args = @_;
126
127 # Make an object to represent the XML-RPC server.
128 my $server = Frontier::Client->new(url => $rpc_url, debug => 0);
129 my $result;
130
131 my %rpcargs = (
132 rpcsystem => 'ipdb',
133# must be provided by caller's caller
134# rpcuser => $args{user},
135 %args,
136 );
137
138 eval {
139 $result = $server->call("dnsdb.$rpcsub", %rpcargs);
140 };
141 if ($@) {
142 $errstr = $@;
143 $errstr =~ s/\s*$//;
144 $errstr =~ s/Fault returned from XML RPC Server, fault code 4: error executing RPC `dnsdb.$rpcsub'\.\s//;
145 }
146 $rpccount++;
147
148 return $result if $result;
149} # end _rpc()
150
151
152# Let's initialize the globals.
153## IPDB::initIPDBGlobals()
154# Initialize all globals. Takes a database handle, returns a success or error code
155sub initIPDBGlobals {
156 my $dbh = $_[0];
157 my $sth;
158
159 # Initialize alloctypes hashes
160 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
161 $sth->execute;
162 while (my @data = $sth->fetchrow_array) {
163 $disp_alloctypes{$data[0]} = $data[2];
164 $def_custids{$data[0]} = $data[4];
165 if ($data[3] < 900) {
166 $list_alloctypes{$data[0]} = $data[1];
167 }
168 }
169
170 # City and POP listings
171 $sth = $dbh->prepare("select city,routing from cities order by city");
172 $sth->execute;
173 return (undef,$sth->errstr) if $sth->err;
174 while (my @data = $sth->fetchrow_array) {
175 push @citylist, $data[0];
176 if ($data[1] eq 'y') {
177 push @poplist, $data[0];
178 }
179 }
180
181 # Load ACL data. Specific username checks are done at a different level.
182 $sth = $dbh->prepare("select username,acl from users");
183 $sth->execute;
184 return (undef,$sth->errstr) if $sth->err;
185 while (my @data = $sth->fetchrow_array) {
186 $IPDBacl{$data[0]} = $data[1];
187 }
188
189##fixme: initialize HTML::Template env var for template path
190# something like $self->path().'/templates' ?
191# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
192
193 return (1,"OK");
194} # end initIPDBGlobals
195
196
197## IPDB::connectDB()
198# Creates connection to IPDB.
199# Requires the database name, username, and password.
200# Returns a handle to the db.
201# Set up for a PostgreSQL db; could be any transactional DBMS with the
202# right changes.
203sub connectDB {
204 my $dbname = shift;
205 my $user = shift;
206 my $pass = shift;
207 my $dbhost = shift;
208
209 my $dbh;
210 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
211
212# Note that we want to autocommit by default, and we will turn it off locally as necessary.
213# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
214 $dbh = DBI->connect($DSN, $user, $pass, {
215 AutoCommit => 1,
216 PrintError => 0
217 })
218 or return (undef, $DBI::errstr) if(!$dbh);
219
220# Return here if we can't select. Note that this indicates a
221# problem executing the select.
222 my $sth = $dbh->prepare("select type from alloctypes");
223 $sth->execute();
224 return (undef,$DBI::errstr) if ($sth->err);
225
226# See if the select returned anything (or null data). This should
227# succeed if the select executed, but...
228 $sth->fetchrow();
229 return (undef,$DBI::errstr) if ($sth->err);
230
231# If we get here, we should be OK.
232 return ($dbh,"DB connection OK");
233} # end connectDB
234
235
236## IPDB::finish()
237# Cleans up after database handles and so on.
238# Requires a database handle
239sub finish {
240 my $dbh = $_[0];
241 $dbh->disconnect if $dbh;
242} # end finish
243
244
245## IPDB::checkDBSanity()
246# Quick check to see if the db is responding. A full integrity
247# check will have to be a separate tool to walk the IP allocation trees.
248sub checkDBSanity {
249 my ($dbh) = $_[0];
250
251 if (!$dbh) {
252 print "No database handle, or connection has been closed.";
253 return -1;
254 } else {
255 # it connects, try a stmt.
256 my $sth = $dbh->prepare("select type from alloctypes");
257 my $err = $sth->execute();
258
259 if ($sth->fetchrow()) {
260 # all is well.
261 return 1;
262 } else {
263 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
264 return -1;
265 }
266 }
267 # Clean up after ourselves.
268# $dbh->disconnect;
269} # end checkDBSanity
270
271
272## IPDB::addMaster()
273# Does all the magic necessary to sucessfully add a master block
274# Requires database handle, block to add
275# Returns failure code and error message or success code and "message"
276sub addMaster {
277 my $dbh = shift;
278 # warning! during testing, this somehow generated a "Bad file descriptor" error. O_o
279 my $cidr = new NetAddr::IP shift;
280 my %args = @_;
281
282 $args{vrf} = '' if !$args{vrf};
283 $args{rdns} = '' if !$args{rdns};
284 $args{defloc} = '' if !$args{defloc};
285 $args{rwhois} = 'n' if !$args{rwhois}; # fail "safe", sort of.
286 $args{rwhois} = 'n' if $args{rwhois} ne 'n' and $args{rwhois} ne 'y';
287
288 my $mid;
289
290 # Allow transactions, and raise an exception on errors so we can catch it later.
291 # Use local to make sure these get "reset" properly on exiting this block
292 local $dbh->{AutoCommit} = 0;
293 local $dbh->{RaiseError} = 1;
294
295 # Wrap all the SQL in a transaction
296 eval {
297 # First check - does the master exist? Ignore VRFs until we can see a sane UI
298 my ($mcontained) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr >>= ? AND type = 'mm'",
299 undef, ($cidr) );
300 die "Master block $mcontained already exists and entirely contains $cidr\n"
301 if $mcontained;
302
303 # Second check - does the new master contain an existing one or ones?
304 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr <<= ? AND type = 'mm'",
305 undef, ($cidr) );
306
307 if (!$mexist) {
308 # First case - master is brand-spanking-new.
309##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
310## maybe a db table called "config"?
311 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
312 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
313 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
314
315# Unrouted blocks aren't associated with a city (yet). We don't rely on this
316# elsewhere though; legacy data may have traps and pitfalls in it to break this.
317# Thus the "routed" flag.
318 $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
319 ($cidr, '<NULL>', 'm', $mid, $args{vrf}, $mid) );
320
321 # master should be its own master, so deletes directly at the master level work
322 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
323
324 # If we get here, everything is happy. Commit changes.
325 $dbh->commit;
326
327 } # done new master does not contain existing master(s)
328 else {
329
330 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
331 my $smallmask = $cidr->masklen;
332 my $sth = $dbh->prepare("SELECT cidr,id FROM allocations WHERE cidr <<= ? AND type='mm' AND parent_id=0");
333 $sth->execute($cidr);
334 my @cmasters;
335 my @oldmids;
336 while (my @data = $sth->fetchrow_array) {
337 my $master = new NetAddr::IP $data[0];
338 push @cmasters, $master;
339 push @oldmids, $data[1];
340 $smallmask = $master->masklen if $master->masklen > $smallmask;
341 }
342
343 # split the new master, and keep only those blocks not part of an existing master
344 my @blocklist;
345 foreach my $seg ($cidr->split($smallmask)) {
346 my $contained = 0;
347 foreach my $master (@cmasters) {
348 $contained = 1 if $master->contains($seg);
349 }
350 push @blocklist, $seg if !$contained;
351 }
352
353##fixme: master_id
354 # collect the unrouted free blocks within the new master
355 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm'");
356 $sth->execute($smallmask, $cidr);
357 while (my @data = $sth->fetchrow_array) {
358 my $freeblock = new NetAddr::IP $data[0];
359 push @blocklist, $freeblock;
360 }
361
362 # combine the set of free blocks we should have now.
363 @blocklist = Compact(@blocklist);
364
365 # master
366 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
367 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
368 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
369
370 # master should be its own master, so deletes directly at the master level work
371 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
372
373 # and now insert the new data. Make sure to delete old masters too.
374
375 # freeblocks
376 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ? AND parent_id IN (".join(',', @oldmids).")");
377 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id)".
378 " VALUES (?,'<NULL>','m',?,?,?)");
379 foreach my $newblock (@blocklist) {
380 $sth->execute($newblock);
381 $sth2->execute($newblock, $mid, $args{vrf}, $mid);
382 }
383
384 # Update immediate allocations, and remove the old parents
385 $sth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
386 $sth2 = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
387 foreach my $old (@oldmids) {
388 $sth->execute($mid, $old);
389 $sth2->execute($old);
390 }
391
392 # *whew* If we got here, we likely suceeded.
393 $dbh->commit;
394
395 } # new master contained existing master(s)
396 }; # end eval
397
398 if ($@) {
399 my $msg = $@;
400 eval { $dbh->rollback; };
401 return ('FAIL',$msg);
402 } else {
403
404 # Only attempt rDNS if the IPDB side succeeded
405 if ($rpc_url) {
406
407# Note *not* splitting reverse zones negates any benefit from caching the exported data.
408# IPv6 address space is far too large to split usefully, and in any case (also due to
409# the large address space) doesn't support the iterated template records v4 zones do
410# that causes the bulk of the slowdown that needs the cache anyway.
411
412 my @zonelist;
413# allow splitting reverse zones to be disabled, maybe, someday
414#if ($splitrevzones && !$cidr->{isv6}) {
415 if (1 && !$cidr->{isv6}) {
416 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
417 @zonelist = $cidr->split($splitpoint);
418 } else {
419 @zonelist = ($cidr);
420 }
421 my @fails;
422 ##fixme: remove hardcoding where possible
423 foreach my $subzone (@zonelist) {
424 my %rpcargs = (
425 rpcuser => $args{user},
426 revzone => "$subzone",
427 revpatt => $args{rdns},
428 defloc => $args{defloc},
429 group => $revgroup, # not sure how these two could sanely be exposed, tbh...
430 state => 1, # could make them globally configurable maybe
431 );
432 if ($rpc_url && !_rpc('addRDNS', %rpcargs)) {
433 push @fails, ("$subzone" => $errstr);
434 }
435 }
436 if (@fails) {
437 $errstr = "Warning(s) adding $cidr to reverse DNS:\n".join("\n", @fails);
438 return ('WARN',$mid);
439 }
440 }
441 return ('OK',$mid);
442 }
443} # end addMaster
444
445
446## IPDB::touchMaster()
447# Update last-changed timestamp on a master block.
448sub touchMaster {
449 my $dbh = shift;
450 my $master = shift;
451
452 local $dbh->{AutoCommit} = 0;
453 local $dbh->{RaiseError} = 1;
454
455 eval {
456 $dbh->do("UPDATE allocations SET modifystamp=now() WHERE id = ?", undef, ($master));
457 $dbh->commit;
458 };
459
460 if ($@) {
461 my $msg = $@;
462 eval { $dbh->rollback; };
463 return ('FAIL',$msg);
464 }
465 return ('OK','OK');
466} # end touchMaster()
467
468
469## IPDB::listSummary()
470# Get summary list of all master blocks
471# Returns an arrayref to a list of hashrefs containing the master block, routed count,
472# allocated count, free count, and largest free block masklength
473sub listSummary {
474 my $dbh = shift;
475
476 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master,id,vrf FROM allocations ".
477 "WHERE type='mm' ORDER BY cidr",
478 { Slice => {} });
479
480 foreach (@{$mlist}) {
481 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm' AND master_id = ?",
482 undef, ($$_{master}, $$_{id}));
483 $$_{routed} = $rcnt;
484 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
485 "AND NOT type='rm' AND NOT type='mm' AND master_id = ?",
486 undef, ($$_{master}, $$_{id}));
487 $$_{allocated} = $acnt;
488 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?",
489 undef, ($$_{master}, $$_{id}));
490 $$_{free} = $fcnt;
491 my ($bigfree) = $dbh->selectrow_array("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
492 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1", undef, ($$_{master}, $$_{id}));
493##fixme: should find a way to do this without having to HTMLize the <>
494 $bigfree = "/$bigfree" if $bigfree;
495 $bigfree = '<NONE>' if !$bigfree;
496 $$_{bigfree} = $bigfree;
497 }
498 return $mlist;
499} # end listSummary()
500
501
502## IPDB::listSubs()
503# Get list of subnets within a specified CIDR block, on a specified VRF.
504# Returns an arrayref to a list of hashrefs containing the CIDR block, customer location or
505# city it's routed to, block type, SWIP status, and description
506sub listSubs {
507 my $dbh = shift;
508 my %args = @_;
509
510 # Just In Case
511 $args{vrf} = '' if !$args{vrf};
512
513 # Snag the allocations for this block
514 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
515 " FROM allocations WHERE parent_id = ? ORDER BY cidr");
516 $sth->execute($args{parent});
517
518 # hack hack hack
519 # set up to flag swip=y records if they don't actually have supporting data in the customers table
520 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
521
522 # snag some more details
523 my $substh = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
524 "AND type ~ '[mc]\$' AND master_id = ? AND NOT cidr = ? ");
525 my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
526 "AND NOT type='rm' AND NOT type='mm' AND master_id = ?");
527 my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
528 my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
529 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
530
531 my @blocklist;
532 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
533 $desc .= " - vrf:$vrf" if $desc && $vrf;
534 $desc = "vrf:$vrf" if !$desc && $vrf;
535 $custsth->execute($custid);
536 my ($ncust) = $custsth->fetchrow_array();
537 $substh->execute($cidr, $mid, $cidr);
538 my ($cont) = $substh->fetchrow_array();
539 $alsth->execute($cidr, $mid);
540 my ($alloc) = $alsth->fetchrow_array();
541 $freesth->execute($cidr, $mid);
542 my ($free) = $freesth->fetchrow_array();
543 $lfreesth->execute($cidr, $mid);
544 my ($lfree) = $lfreesth->fetchrow_array();
545 $lfree = "/$lfree" if $lfree;
546 $lfree = '<NONE>' if !$lfree;
547 my %row = (
548 block => $cidr,
549 subcontainers => $cont,
550 suballocs => $alloc,
551 subfree => $free,
552 lfree => $lfree,
553 city => $city,
554 type => $disp_alloctypes{$type},
555 custid => $custid,
556 swip => ($swip eq 'y' ? 'Yes' : 'No'),
557 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
558 desc => $desc,
559 hassubs => ($type eq 'rm' || $type =~ /.c/ ? 1 : 0),
560 id => $id,
561 );
562# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
563 $row{listpool} = ($type =~ /^.[pd]$/);
564 push (@blocklist, \%row);
565 }
566 return \@blocklist;
567} # end listSubs()
568
569
570## IPDB::listContainers()
571# List all container-type allocations in a given parent
572# Takes a database handle and a hash:
573# - parent is the ID of the parent block
574# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
575# description, block ID, and counts for the nmber uf suballocations (all types),
576# free blocks, and the CIDR size of the largest free block
577sub listContainers {
578 my $dbh = shift;
579 my %args = @_;
580
581 # Just In Case
582 $args{vrf} = '' if !$args{vrf};
583
584 # Snag the allocations for this block
585 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
586 " FROM allocations WHERE parent_id = ? AND type ~ '[mc]\$' ORDER BY cidr");
587 $sth->execute($args{parent});
588
589 my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
590 "AND NOT type='rm' AND NOT type='mm' AND master_id = ?");
591 my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
592 my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
593 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
594
595 my @blocklist;
596 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
597 $desc .= " - vrf:$vrf" if $desc && $vrf;
598 $desc = "vrf:$vrf" if !$desc && $vrf;
599 $alsth->execute($cidr, $mid);
600 my ($alloc) = $alsth->fetchrow_array();
601 $freesth->execute($cidr, $mid);
602 my ($free) = $freesth->fetchrow_array();
603 $lfreesth->execute($cidr, $mid);
604 my ($lfree) = $lfreesth->fetchrow_array();
605 $lfree = "/$lfree" if $lfree;
606 $lfree = '<NONE>' if !$lfree;
607 my %row = (
608 block => $cidr,
609 suballocs => $alloc,
610 subfree => $free,
611 lfree => $lfree,
612 city => $city,
613 type => $disp_alloctypes{$type},
614 desc => $desc,
615 id => $id,
616 );
617 push (@blocklist, \%row);
618 }
619 return \@blocklist;
620} # end listContainers()
621
622
623## IPDB::listAllocations()
624# List all end-use allocations in a given parent
625# Takes a database handle and a hash:
626# - parent is the ID of the parent block
627# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
628# custID, SWIP flag, description, block ID, and master ID
629sub listAllocations {
630 my $dbh = shift;
631 my %args = @_;
632
633 # Snag the allocations for this block
634 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
635 " FROM allocations WHERE parent_id = ? AND type !~ '[mc]\$' ORDER BY cidr");
636 $sth->execute($args{parent});
637
638 # hack hack hack
639 # set up to flag swip=y records if they don't actually have supporting data in the customers table
640 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
641
642 my @blocklist;
643 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
644 $desc .= " - vrf:$vrf" if $desc && $vrf;
645 $desc = "vrf:$vrf" if !$desc && $vrf;
646 $custsth->execute($custid);
647 my ($ncust) = $custsth->fetchrow_array();
648 my %row = (
649 block => $cidr,
650 city => $city,
651 type => $disp_alloctypes{$type},
652 custid => $custid,
653 swip => ($swip eq 'y' ? 'Yes' : 'No'),
654 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
655 desc => $desc,
656 id => $id,
657 );
658# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
659 $row{listpool} = ($type =~ /^.[pd]$/);
660 push (@blocklist, \%row);
661 }
662 return \@blocklist;
663} # end listAllocations()
664
665
666## IPDB::listFree()
667# Gets a list of free blocks in the requested parent/master and VRF instance in both CIDR and range notation
668# Takes a parent/master ID and an optional VRF specifier that defaults to empty.
669# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
670# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
671sub listFree {
672 my $dbh = shift;
673
674 my %args = @_;
675 # Just In Case
676 $args{vrf} = '' if !$args{vrf};
677
678 my $sth = $dbh->prepare(q(
679 SELECT f.cidr,f.id,allocations.cidr
680 FROM freeblocks f
681 LEFT JOIN allocations ON f.reserve_for = allocations.id
682 WHERE f.parent_id = ?
683 ORDER BY f.cidr
684 ) );
685# $sth->execute($args{parent}, $args{vrf});
686 $sth->execute($args{parent});
687 my @flist;
688 while (my ($cidr,$id,$resv) = $sth->fetchrow_array()) {
689 $cidr = new NetAddr::IP $cidr;
690 my %row = (
691 fblock => "$cidr",
692 frange => $cidr->range,
693 fbid => $id,
694 fbparent => $args{parent},
695 resv => $resv,
696 );
697 push @flist, \%row;
698 }
699 return \@flist;
700} # end listFree()
701
702
703## IPDB::listPool()
704#
705sub listPool {
706 my $dbh = shift;
707 my $pool = shift;
708
709 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,id".
710 " FROM poolips WHERE parent_id = ? ORDER BY ip");
711 $sth->execute($pool);
712 my @poolips;
713 while (my ($ip,$custid,$available,$desc,$type,$id) = $sth->fetchrow_array) {
714 my %row = (
715 ip => $ip,
716 custid => $custid,
717 available => $available,
718 desc => $desc,
719 delme => $available eq 'n',
720 parent => $pool,
721 id => $id,
722 );
723 push @poolips, \%row;
724 }
725 return \@poolips;
726} # end listPool()
727
728
729## IPDB::getMasterList()
730# Get a list of master blocks, optionally including last-modified timestamps
731# Takes an optional flag to indicate whether to include timestamps;
732# 'm' includes ctime, all others (suggest 'c') do not.
733# Returns an arrayref to a list of hashrefs
734sub getMasterList {
735 my $dbh = shift;
736 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
737
738 my $mlist = $dbh->selectall_arrayref("SELECT id,vrf,cidr AS master".($stampme eq 'm' ? ',modifystamp AS mtime' : '').
739 " FROM allocations WHERE type='mm' ORDER BY cidr", { Slice => {} });
740 return $mlist;
741} # end getMasterList()
742
743
744## IPDB::getTypeList()
745# Get an alloctype/description pair list suitable for dropdowns
746# Takes a flag to determine which general groups of types are returned
747# Returns an reference to an array of hashrefs
748sub getTypeList {
749 my $dbh = shift;
750 my $tgroup = shift || 'a'; # technically optional, like this, but should
751 # really be specified in the call for clarity
752 my $tlist;
753 if ($tgroup eq 'n') {
754 # grouping 'p' - all netblock types. These include routed blocks, containers (_c)
755 # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
756 # and the "miscellaneous" cn, in, and en types.
757 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
758 "AND type NOT LIKE '_i' ORDER BY listorder", { Slice => {} });
759 } elsif ($tgroup eq 'p') {
760 # grouping 'p' - primary allocation types. As with 'n' above but without the _r contained types.
761 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
762 "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
763 } elsif ($tgroup eq 'c') {
764 # grouping 'c' - contained types. These include all static IPs and all _r types.
765 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
766 " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
767 } elsif ($tgroup eq 'i') {
768 # grouping 'i' - static IP types.
769 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
770 " AND type LIKE '_i' ORDER BY listorder", { Slice => {} });
771 } else {
772 # grouping 'a' - all standard allocation types. This includes everything
773 # but mm (present only as a formality). Make this the default.
774 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
775 " ORDER BY listorder", { Slice => {} });
776 }
777 return $tlist;
778}
779
780
781## IPDB::getPoolSelect()
782# Get a list of pools matching the passed city and type that have 1 or more free IPs
783# Returns an arrayref to a list of hashrefs
784sub getPoolSelect {
785 my $dbh = shift;
786 my $iptype = shift;
787 my $pcity = shift;
788
789 my ($ptype) = ($iptype =~ /^(.)i$/);
790 return if !$ptype;
791 $ptype .= '_';
792
793 my $plist = $dbh->selectall_arrayref( q(
794 SELECT count(*) AS poolfree,p.pool AS poolblock, a.city AS poolcit
795 FROM poolips p
796 JOIN allocations a ON p.parent_id=a.id
797 WHERE p.available='y' AND a.city = ? AND p.type LIKE ?
798 GROUP BY p.pool,a.city
799 ),
800 { Slice => {} }, ($pcity, $ptype) );
801 return $plist;
802} # end getPoolSelect()
803
804
805## IPDB::findAllocateFrom()
806# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
807# Takes
808# - mask length
809# - allocation type
810# - POP city "parent"
811# - optional master-block restriction
812# - optional flag to allow automatic pick-from-private-network-ranges
813# Returns a string with the first CIDR block matching the criteria, if any
814sub findAllocateFrom {
815 my $dbh = shift;
816 my $maskbits = shift;
817 my $type = shift;
818 my $city = shift;
819 my $pop = shift;
820 my %optargs = @_;
821
822 my $failmsg = "No suitable free block found\n";
823
824 my @vallist;
825 my $sql;
826
827 # Free pool IPs should be easy.
828 if ($type =~ /^.i$/) {
829 # User may get an IP from the wrong VRF. User should not be using admin tools to allocate static IPs.
830 $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
831 @vallist = ($optargs{gimme});
832 } else {
833
834## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
835## Very large systems will require development of a reserve system (possibly an extension
836## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
837## Also populate a value list for the DBI call.
838
839 @vallist = ($maskbits);
840 $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
841
842# cases, strict rules
843# .c -> container type
844# requires a routing container, fbtype r
845# .d -> DHCP/"normal-routing" static pool
846# requires a routing container, fbtype r
847# .e -> Dynamic-assignment connectivity
848# requires a routing container, fbtype r
849# .i -> error, can't allocate static IPs this way?
850# mm -> error, master block
851# rm -> routed block
852# requires master block, fbtype m
853# .n -> Miscellaneous usage
854# requires a routing container, fbtype r
855# .p -> PPP(oE) static pool
856# requires a routing container, fbtype r
857# .r -> contained type
858# requires a matching container, fbtype $1
859##fixme: strict-or-not flag
860
861##fixme: config or UI flag for "Strict" mode
862# if ($strictmode) {
863if (0) {
864 if ($type =~ /^(.)r$/) {
865 push @vallist, $1;
866 $sql .= " AND routed = ?";
867 } elsif ($type eq 'rm') {
868 $sql .= " AND routed = 'm'";
869 } else {
870 $sql .= " AND routed = 'r'";
871 }
872}
873
874 # for PPP(oE) and container types, the POP city is the one attached to the pool.
875 # individual allocations get listed with the customer city site.
876 ##fixme: chain cities to align roughly with a full layer-2 node graph
877 $city = $pop if $type !~ /^.[pc]$/;
878 if ($type ne 'rm' && $city) {
879 $sql .= " AND city = ?";
880 push @vallist, $city;
881 }
882 # Allow specifying an arbitrary full block, instead of a master
883 if ($optargs{gimme}) {
884 $sql .= " AND cidr >>= ?";
885 push @vallist, $optargs{gimme};
886 }
887 # if a specific master was requested, allow the requestor to self->shoot(foot)
888 if ($optargs{master} && $optargs{master} ne '-') {
889 $sql .= " AND master_id = ?";
890# if $optargs{master} ne '-';
891 push @vallist, $optargs{master};
892 } else {
893 # if a specific master was NOT requested, filter out the RFC 1918 private networks
894 if (!$optargs{allowpriv}) {
895 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
896 }
897 }
898 # Keep "reserved" blocks out of automatic assignment.
899##fixme: needs a UI flag or a config knob
900 $sql .= " AND reserve_for = 0";
901 # Sorting and limiting, since we don't (currently) care to provide a selection of
902 # blocks to carve up. This preserves something resembling optimal usage of the IP
903 # space by forcing contiguous allocations and free blocks as much as possible.
904 $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
905 } # done setting up SQL for free CIDR block
906
907 my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
908 return $fbid,$fbfound,$fbparent;
909} # end findAllocateFrom()
910
911
912## IPDB::ipParent()
913# Get an IP's parent pool's details
914# Takes a database handle and IP
915# Returns a hashref to the parent pool block, if any
916sub ipParent {
917 my $dbh = shift;
918 my $block = shift;
919
920 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
921 " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
922 return $pinfo;
923} # end ipParent()
924
925
926## IPDB::subParent()
927# Get a block's parent's details
928# Takes a database handle and CIDR block
929# Returns a hashref to the parent container block, if any
930sub subParent {
931 my $dbh = shift;
932 my $block = shift;
933
934 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
935 " WHERE cidr >>= ?", undef, ($block) );
936 return $pinfo;
937} # end subParent()
938
939
940## IPDB::blockParent()
941# Get a block's parent's details
942# Takes a database handle and CIDR block
943# Returns a hashref to the parent container block, if any
944sub blockParent {
945 my $dbh = shift;
946 my $block = shift;
947
948 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
949 " WHERE cidr >>= ?", undef, ($block) );
950 return $pinfo;
951} # end blockParent()
952
953
954## IPDB::getBreadCrumbs()
955# Retrieve the ID and CIDR of a block's parent(s) up to the master block
956# Returns an arrayref to a list of hashrefs with CIDR and block ID
957sub getBreadCrumbs {
958 my $dbh = shift;
959 my $parent = shift;
960 my @result;
961
962 my $sth = $dbh-> prepare("SELECT cidr,type,id,parent_id FROM allocations WHERE id=?");
963
964 while ($parent != 0) {
965 $sth->execute($parent);
966 my ($cidr,$type,$id,$pid) = $sth->fetchrow_array;
967 push @result, {cidr => $cidr, link => $id, ispool => ($type =~ /^.[dp]$/ ? 1 : 0)};
968 $parent = $pid;
969 }
970
971 return \@result;
972} # end getBread()
973
974
975## IPDB::getRoutedCity()
976# Get the city for a routed block.
977sub getRoutedCity {
978 my $dbh = shift;
979 my $block = shift;
980
981 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
982 return $rcity;
983} # end getRoutedCity()
984
985
986## IPDB::allocateBlock()
987# Does all of the magic of actually allocating a netblock
988# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
989# type, city, block to allocate from, and optionally a description, notes, circuit ID,
990# and private data
991# Returns a success code and optional error message.
992sub allocateBlock {
993 my $dbh = shift;
994
995 my %args = @_;
996
997 $args{cidr} = new NetAddr::IP $args{cidr};
998
999 $args{desc} = '' if !$args{desc};
1000 $args{notes} = '' if !$args{notes};
1001 $args{circid} = '' if !$args{circid};
1002 $args{privdata} = '' if !$args{privdata};
1003 $args{vrf} = '' if !$args{vrf};
1004 $args{vlan} = '' if !$args{vlan};
1005 $args{rdns} = '' if !$args{rdns};
1006
1007 # Could arguably allow this for eg /120 allocations, but end users who get a single v4 IP are
1008 # usually given a v6 /64, and most v6 addressing schemes need at least half that address space
1009 if ($args{cidr}->{isv6} && $args{rdns} =~ /\%/) {
1010 return ('FAIL','Reverse DNS template patterns are not supported for IPv6 allocations');
1011 }
1012
1013 my $sth;
1014
1015 # Snag the "type" of the freeblock and its CIDR
1016 my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
1017 $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
1018 undef, $args{fbid});
1019 $alloc_from = new NetAddr::IP $alloc_from;
1020 return ('FAIL',"Failed to allocate $args{cidr}; intended free block was used by another allocation.")
1021 if !$fbparent;
1022##fixme: fail here if !$alloc_from
1023# also consider "lock for allocation" due to multistep allocation process
1024
1025 # To contain the error message, if any.
1026 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
1027
1028 # Enable transactions and error handling
1029 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1030 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1031
1032 if ($args{type} =~ /^.i$/) {
1033 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
1034 eval {
1035 if ($args{cidr}) { # IP specified
1036 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
1037 die "IP is not in an IP pool.\n"
1038 if !$isavail;
1039 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
1040 if $isavail eq 'n';
1041 } else { # IP not specified, take first available
1042 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
1043 undef, ($args{alloc_from}) );
1044 }
1045 $dbh->do("UPDATE poolips SET custid = ?, city = ?,available='n', description = ?, notes = ?, ".
1046 "circuitid = ?, privdata = ?, vrf = ?, rdns = ? ".
1047 "WHERE ip = ? AND parent_id = ?", undef,
1048 ($args{custid}, $args{city}, $args{desc}, $args{notes},
1049 $args{circid}, $args{privdata}, $args{vrf}, $args{rdns},
1050 $args{cidr}, $args{parent}) );
1051
1052# node hack
1053 if ($args{nodeid} && $args{nodeid} ne '') {
1054 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1055 }
1056# end node hack
1057
1058 $dbh->commit; # Allocate IP from pool
1059 };
1060 if ($@) {
1061 $msg .= ": $@";
1062 eval { $dbh->rollback; };
1063 return ('FAIL', $msg);
1064 } else {
1065 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
1066 return ('OK', $args{cidr});
1067 }
1068
1069 } else { # end IP-from-pool allocation
1070
1071 if ($args{cidr} == $alloc_from) {
1072 # Easiest case- insert in one table, delete in the other, and go home. More or less.
1073 # insert into allocations values (cidr,custid,type,city,desc) and
1074 # delete from freeblocks where cidr='cidr'
1075 # For data safety on non-transaction DBs, we delete first.
1076
1077 eval {
1078 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1079
1080 # Insert the allocations entry
1081 $dbh->do("INSERT INTO allocations ".
1082 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1083 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1084 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1085 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1086 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1087
1088 # Munge freeblocks
1089 if ($args{type} =~ /^(.)[mc]$/) {
1090 # special case - block is a routed or container/"reserve" block
1091 my $rtype = $1;
1092 $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
1093 undef, ($rtype, $args{city}, $bid, $args{fbid}) );
1094 } else {
1095 # "normal" case
1096 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1097 }
1098
1099 # And initialize the pool, if necessary
1100 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1101 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1102 if ($args{type} =~ /^.p$/) {
1103 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1104 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1105 die $rmsg if $code eq 'FAIL';
1106 } elsif ($args{type} =~ /^.d$/) {
1107 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1108 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1109 die $rmsg if $code eq 'FAIL';
1110 }
1111
1112# node hack
1113 if ($args{nodeid} && $args{nodeid} ne '') {
1114 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1115 }
1116# end node hack
1117
1118 $dbh->commit; # Simple block allocation
1119 }; # end of eval
1120 if ($@) {
1121 $msg .= ": ".$@;
1122 eval { $dbh->rollback; };
1123 return ('FAIL',$msg);
1124 }
1125
1126 } else { # cidr != alloc_from
1127
1128 # Hard case. Allocation is smaller than free block.
1129
1130 # make sure new allocation is in fact within freeblock. *sigh*
1131 return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1132 if !$alloc_from->contains($args{cidr});
1133 my $wantmaskbits = $args{cidr}->masklen;
1134 my $maskbits = $alloc_from->masklen;
1135
1136 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1137
1138 # This determines which blocks will be left "free" after allocation. We take the
1139 # block we're allocating from, and split it in half. We see which half the wanted
1140 # block is in, and repeat until the wanted block is equal to one of the halves.
1141 my $i=0;
1142 my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
1143 while ($maskbits++ < $wantmaskbits) {
1144 my @subblocks = $tmp_from->split($maskbits);
1145 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1146 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
1147 } # while
1148
1149 # Begin SQL transaction block
1150 eval {
1151 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1152
1153 # Delete old freeblocks entry
1154 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1155
1156 # Insert the allocations entry
1157 $dbh->do("INSERT INTO allocations ".
1158 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1159 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1160 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1161 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1162 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1163
1164 # Insert new list of smaller free blocks left over. Flag the one that matches the
1165 # masklength of the new allocation, if a reserve block was requested.
1166 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id,reserve_for) ".
1167 "VALUES (?,?,?,?,?,?,?)");
1168 foreach my $block (@newfreeblocks) {
1169 $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster,
1170 ($block->masklen == $wantmaskbits ? $bid : 0));
1171 }
1172
1173 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1174 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1175 my $rtype = $1;
1176 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster, 0);
1177 }
1178
1179 # And initialize the pool, if necessary
1180 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1181 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1182 if ($args{type} =~ /^.p$/) {
1183 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1184 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1185 die $rmsg if $code eq 'FAIL';
1186 } elsif ($args{type} =~ /^.d$/) {
1187 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1188 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1189 die $rmsg if $code eq 'FAIL';
1190 }
1191
1192# node hack
1193 if ($args{nodeid} && $args{nodeid} ne '') {
1194 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1195 }
1196# end node hack
1197
1198 $dbh->commit; # Complex block allocation
1199 }; # end eval
1200 if ($@) {
1201 $msg .= ": ".$@;
1202 eval { $dbh->rollback; };
1203 return ('FAIL',$msg);
1204 }
1205
1206 } # end fullcidr != alloc_from
1207
1208 # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1209 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1210 if $args{rdns};
1211
1212 # and the per-IP set, if there is one.
1213 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user});
1214
1215 return ('OK', 'OK');
1216
1217 } # end static-IP vs netblock allocation
1218
1219} # end allocateBlock()
1220
1221
1222## IPDB::initPool()
1223# Initializes a pool
1224# Requires a database handle, the pool CIDR, type, city, and a parameter
1225# indicating whether the pool should allow allocation of literally every
1226# IP, or if it should reserve network/gateway/broadcast IPs
1227# Note that this is NOT done in a transaction, that's why it's a private
1228# function and should ONLY EVER get called from allocateBlock()
1229sub initPool {
1230 my ($dbh,undef,$type,$city,$class,$parent) = @_;
1231 my $pool = new NetAddr::IP $_[1];
1232
1233 # IPv6 does not lend itself to IP pools as supported
1234 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1235 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1236 # NetAddr::IP won't allow more than a /16 (65k hosts).
1237 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1238
1239 # Retrieve some odds and ends for defaults on the IPs
1240 my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
1241 my ($vrf,$vlan,$master) = $dbh->selectrow_array("SELECT vrf,vlan,master_id FROM allocations WHERE id = ?",
1242 undef, ($parent) );
1243
1244 $type =~ s/[pd]$/i/;
1245 my $sth;
1246 my $msg;
1247
1248 # Trap errors so we can pass them back to the caller. Even if the
1249 # caller is only ever supposed to be local, and therefore already
1250 # trapping errors. >:(
1251 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1252 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1253
1254 eval {
1255 # have to insert all pool IPs into poolips table as "unallocated".
1256 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1257
1258 # in case of pool extension by some means, we need to see what IPs were already inserted
1259 my $tmp1 = $dbh->selectall_arrayref("SELECT ip FROM poolips WHERE parent_id = ?", undef, $parent);
1260 my %foundips;
1261 foreach (@{$tmp1}) {
1262 $foundips{$_->[0]} = 1;
1263 }
1264
1265# Dodge an edge case - pool where IPs have been "stolen" and turned into a netblock assignment.
1266# We can't just "get all the current IPs, and add the missing ones", because some IPs are
1267# legitimately missing (for stretchy values of "legitimately").
1268
1269 my $pdata = getBlockData($dbh, $parent);
1270 my $pcidr = new NetAddr::IP $pdata->{block};
1271
1272 if ($pcidr != $pool) {
1273 # enumerate the IPs from the *old* pool, flag them as "found", so we can iterate the entire
1274 # requested pool and still make sure we skip the IPs in the old pool - even if they've been
1275 # "stolen" by legacy netblocks.
1276 my @oldips = $pcidr->hostenum;
1277 # decide whether to start excluding existing IPs at the "gateway" or "gateway+1"
1278 my $ostart = ($pdata->{type} =~ /^.d$/ ? 1 : 0);
1279 for (my $i = $ostart; $i<= $#oldips; $i++) {
1280 $foundips{$oldips[$i]} = 1;
1281 }
1282 }
1283
1284 # enumerate the hosts in the IP range - everything except the first (net) and last (bcast) IP
1285 my @poolip_list = $pool->hostenum;
1286
1287 # always check/add IPs from gw+1 through bcast-1:
1288 # (but the set won't be in oooorderrrrr! <pout>)
1289 for (my $i=1; $i<=$#poolip_list; $i++) {
1290 my $baseip = $poolip_list[$i]->addr;
1291 if ($baseip !~ /\.(?:0|255)$/ && !$foundips{$poolip_list[$i]}) {
1292 $sth->execute($baseip, $pcustid, $city, $type, $parent, $master);
1293 }
1294 }
1295
1296 # now do the special case - DSL/PPP blocks can use the "net", "gw", and "bcast" IPs.
1297 # we exclude .0 and .255 anyway, since while they'll mostly work, they *will* behave badly here and there.
1298 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
1299 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
1300 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1301 }
1302 $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$poolip_list[0]};
1303 $pool--;
1304 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
1305 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1306 }
1307 }
1308# don't commit here! the caller may not be done.
1309# $dbh->commit;
1310 };
1311 if ($@) {
1312 $msg = $@;
1313# Don't roll back! It's up to the caller to handle this.
1314# eval { $dbh->rollback; };
1315 return ('FAIL',$msg);
1316 } else {
1317 return ('OK',"OK");
1318 }
1319} # end initPool()
1320
1321
1322## IPDB::updateBlock()
1323# Update an allocation
1324# Takes all allocation fields in a hash
1325sub updateBlock {
1326 my $dbh = shift;
1327 my %args = @_;
1328
1329 return ('FAIL', 'Missing block to update') if !$args{block};
1330
1331 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1332 $args{custid} =~ s/^\s+//;
1333 $args{custid} =~ s/\s+$//;
1334
1335 # do it all in a transaction
1336 local $dbh->{AutoCommit} = 0;
1337 local $dbh->{RaiseError} = 1;
1338
1339 my @fieldlist;
1340 my @vallist;
1341 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
1342 if ($args{$_}) {
1343 push @fieldlist, $_;
1344 push @vallist, $args{$_};
1345 }
1346 }
1347
1348 my $binfo;
1349 my $updtable = 'allocations';
1350 my $keyfield = 'id';
1351 if ($args{type} =~ /^(.)i$/) {
1352 $updtable = 'poolips';
1353 $binfo = getBlockData($dbh, $args{block}, 'i');
1354 } else {
1355## fixme: there's got to be a better way...
1356 $binfo = getBlockData($dbh, $args{block});
1357 if ($args{swip}) {
1358 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1359 $args{swip} = 'y';
1360 } else {
1361 $args{swip} = 'n';
1362 }
1363 }
1364 foreach ('type', 'swip') {
1365 if ($args{$_}) {
1366 push @fieldlist, $_;
1367 push @vallist, $args{$_};
1368 }
1369 }
1370 }
1371
1372 return ('FAIL', 'No fields to update') if !@fieldlist;
1373
1374 my $sql = "UPDATE $updtable SET ";
1375 $sql .= join " = ?, ", @fieldlist;
1376
1377 eval {
1378 # check for block merge first...
1379 if ($args{fbmerge}) {
1380 my $cidr = NetAddr::IP->new($binfo->{block});
1381 my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1382 # safety net? make sure mergeable block passed in is really one or both of
1383 # a) reserved for expansion of the block and
1384 # b) confirmed CIDR-combinable
1385 # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
1386 $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
1387 # ... so we can append the change in the stored CIDR field to extend the allocation.
1388 $sql .= " = ?, cidr";
1389 push @vallist, $newblock;
1390 # if we have an IP pool, call initPool to fill in any missing entries in the pool
1391 if ($binfo->{type} =~ /^.p$/) {
1392 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
1393 die $rmsg if $code eq 'FAIL';
1394 } elsif ($binfo->{type} =~ /^.d$/) {
1395 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
1396 die $rmsg if $code eq 'FAIL';
1397 }
1398 }
1399
1400 # append another SQL fragment
1401 push @vallist, $args{block};
1402 $sql .= " = ? WHERE $keyfield = ?";
1403
1404 # do the update
1405 $dbh->do($sql, undef, @vallist);
1406
1407 if ($args{node}) {
1408 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1409 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1410 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1411 if $args{node} ne '--';
1412 }
1413
1414 $dbh->commit;
1415 };
1416 if ($@) {
1417 my $msg = $@;
1418 $dbh->rollback;
1419 return ('FAIL', $msg);
1420 }
1421
1422 # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
1423 # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
1424 if ($binfo->{type} =~ '.[mc]') {
1425 # Not using listFree() as it doesn't return quite all of the blocks wanted.
1426 # Retrieve the immediate free blocks
1427 my $sth = $dbh->prepare(q(
1428 SELECT cidr FROM freeblocks WHERE parent_id = ?
1429 UNION
1430 SELECT cidr FROM freeblocks f WHERE
1431 cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
1432 AND master_id = ?
1433 ) );
1434 $sth->execute($args{block}, $binfo->{master_id});
1435 my %fbset;
1436 while (my ($fb) = $sth->fetchrow_array) {
1437 $fbset{"host_$fb"} = $args{rdns};
1438 }
1439 # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
1440 # know how many records we'll be updating and more than 3-4 is far too slow. This
1441 # should be safe to call unconditionally.
1442 # Requires dnsadmin >= r678
1443 _rpc('updateRevSet', %fbset, rpcuser => $args{user});
1444
1445 } else {
1446 $binfo->{block} =~ s|/32$||;
1447 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
1448
1449 # and the per-IP set, if there is one.
1450 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}) if keys (%{$args{iprev}});
1451 }
1452
1453 return ('OK','OK');
1454} # end updateBlock()
1455
1456
1457## IPDB::splitBlock()
1458# Splits an existing allocation into two or more smaller allocations based on a passed netmask
1459# Duplicates all other data
1460# Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
1461# Should probably commit DNS magic to realign DNS data
1462sub splitBlock {
1463 my $dbh = shift;
1464 my $id = shift;
1465 my $basetype = shift;
1466 my $newmask = shift;
1467
1468##fixme: set errstr on errors so caller can suitably clue-by-four the user
1469 return if $basetype ne 'b'; # only netblocks allowed!
1470
1471 my $binfo = getBlockData($dbh, $id);
1472 return if !$binfo;
1473
1474 return if $newmask !~ /^\d+$/;
1475
1476 my @ret;
1477 my $block = new NetAddr::IP $binfo->{block};
1478 my $oldmask = $block->masklen;
1479
1480 # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
1481 # failure modes:
1482 # difference between $oldmask and $newmask is negative or 0
1483 if ($newmask - $oldmask <= 0) {
1484 $errstr = "Can't split a /$oldmask allocation into /$newmask pieces";
1485 return;
1486 }
1487# # difference between $oldmask and $newmask is > n, for arbitrary n?
1488# if ($newmask - $oldmask > 42) { # because 42
1489# }
1490 # $oldmask > n, for arbitrary n? At least check limits of data type.
1491 if ($block->{isv6}) {
1492 if ($newmask - $oldmask > 128) {
1493 $errstr = "Impossible IPv6 mask length /$newmask requested";
1494 return;
1495 }
1496 } else {
1497 if ($newmask - $oldmask > 32) {
1498 $errstr = "Impossible IPv4 mask length /$newmask requested";
1499 return;
1500 }
1501 }
1502
1503 my @newblocks = $block->split($newmask);
1504
1505 local $dbh->{AutoCommit} = 0;
1506 local $dbh->{RaiseError} = 1;
1507
1508 eval {
1509 # line up a list of fields and values. Be nice if there was a handy way to do,
1510 # direct in SQL, something like
1511 # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
1512 my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id);
1513 my $fields_sql = join(',', @fieldlist);
1514 my @vals;
1515 foreach (@fieldlist) {
1516 push @vals, $binfo->{$_};
1517 }
1518 # note the first block in the split for return
1519 push @ret, {nid => $id, nblock => "$newblocks[0]"};
1520
1521 # prepare
1522 my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
1523 my $poolsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
1524 " VALUES (?".',?'x(scalar(@fieldlist)).")");
1525 my $poolchildsth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE ip << ? AND parent_id = ?");
1526 my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1527
1528 # set up update of existing block
1529 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$newblocks[0]", $id) );
1530
1531 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
1532 if ($binfo->{type} =~ /.d/) {
1533 $newblocks[0]--;
1534 $nbsth->execute($id, $newblocks[0]->addr);
1535 }
1536
1537 # Loop over the new blocks that are not the base block
1538 for (my $i = 1; $i <= $#newblocks; $i++) {
1539 # add the new pool
1540 $poolsth->execute($newblocks[$i], @vals);
1541 # fetch the ID of the entry we just added...
1542 $idsth->execute();
1543 my ($nid) = $idsth->fetchrow_array();
1544 # ... so we can pass back the list of blocks and IDs...
1545 push @ret, {nid => $nid, nblock => "$newblocks[$i]"};
1546 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
1547 if ($binfo->{type} =~ /.d/) {
1548 # net
1549 $nbsth->execute($id, $newblocks[$i]->addr);
1550 $newblocks[$i]++;
1551 # gw
1552 $nbsth->execute($id, $newblocks[$i]->addr);
1553 $newblocks[$i]--;
1554 $newblocks[$i]--;
1555 # bcast
1556 $nbsth->execute($id, $newblocks[$i]->addr);
1557 $newblocks[$i]++;
1558 }
1559 # ... and update the existing IPs with the new parent_id
1560 $poolchildsth->execute($nid, $newblocks[$i], $id);
1561 }
1562
1563 $dbh->commit;
1564 };
1565 if ($@) {
1566 $errstr = "Error splitting $binfo->{block}: $@";
1567 $dbh->rollback;
1568 return;
1569 }
1570
1571 return \@ret;
1572} # end splitBlock()
1573
1574
1575## IPDB::shrinkBlock()
1576# Shrink an allocation to the passed CIDR block
1577# Takes an allocation ID and a new CIDR
1578# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
1579# Refuses to shrink "real netblock" pool types below /30
1580sub shrinkBlock {
1581 my $dbh = shift;
1582 my $id = shift;
1583
1584 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
1585 my $newblock = new NetAddr::IP shift;
1586
1587 if (!$newblock) {
1588 $errstr = "Can't shrink something that's not a netblock";
1589 return;
1590 }
1591
1592 my $binfo = getBlockData($dbh, $id);
1593 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1594
1595 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
1596 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
1597 return;
1598 }
1599
1600 my $oldblock = new NetAddr::IP $binfo->{block};
1601
1602 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
1603 if (!$oldblock->contains($newblock)) {
1604 $errstr = "Can't shrink an allocation outside of itself";
1605 return;
1606 }
1607
1608 local $dbh->{AutoCommit} = 0;
1609 local $dbh->{RaiseError} = 1;
1610
1611 my $fbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1612 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
1613 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
1614 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1615
1616 my @ret;
1617 eval {
1618 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
1619
1620 # find the netblock(s) that are now free
1621 my @workingblocks = $oldblock->split($newblock->masklen);
1622 my @wb2;
1623 foreach my $newsub (@workingblocks) {
1624 next if $newsub == $newblock;
1625 push @wb2, $newsub;
1626 }
1627 @wb2 = Compact(@wb2);
1628
1629 # set new freeblocks, and clean up any IP pool entries if needed.
1630 foreach my $newfree (@wb2) {
1631 # add as freeblock
1632 $fbsth->execute($newfree, $pinfo->{city}, (split //, $pinfo->{type})[1], $pinfo->{vrf},
1633 $binfo->{parent_id}, $binfo->{master_id});
1634 $idsth->execute;
1635 my ($nid) = $idsth->fetchrow_array();
1636 # add to return list
1637 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
1638 # clean up pool IPs if necessary
1639 if ($binfo->{type} =~ /.[dp]/) {
1640 $poolsth->execute($id, $newfree);
1641 }
1642 }
1643
1644 # additional cleanup on net/gw/bcast IPs in pool
1645 if ($binfo->{type} =~ /.d/) {
1646 $netsth->execute($id, $newblock->addr);
1647 $newblock++;
1648 $netsth->execute($id, $newblock->addr);
1649 $newblock--;
1650 $newblock--;
1651 $netsth->execute($id, $newblock->addr);
1652 }
1653
1654 $dbh->commit;
1655 };
1656 if ($@) {
1657 $errstr = "Error splitting $binfo->{block}: $@";
1658 $dbh->rollback;
1659 return;
1660 }
1661
1662 return \@ret;
1663} # end shrinkBlock()
1664
1665
1666## IPDB::deleteBlock()
1667# Removes an allocation from the database, including deleting IPs
1668# from poolips and recombining entries in freeblocks if possible
1669# Also handles "deleting" a static IP allocation, and removal of a master
1670# Requires a database handle, the block to delete, the routing depth (if applicable),
1671# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
1672# as well as the reverse entry
1673sub deleteBlock {
1674 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
1675
1676 # Collect info about the block we're going to delete
1677 my $binfo = getBlockData($dbh, $id, $basetype);
1678 my $cidr = new NetAddr::IP $binfo->{block};
1679
1680# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1681# is_rfc1918 requires NetAddr::IP >= 4.059
1682# rather than doing this over and over and over.....
1683 my $tmpnum = $cidr->numeric;
1684# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1685# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1686# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1687 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1688 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1689 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1690
1691 my $sth;
1692
1693 # Magic variables used for odd allocation cases.
1694 my $container;
1695 my $con_type;
1696
1697
1698 # temporarily forced null, until a sane UI for VRF tracking can be found.
1699# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
1700
1701 # To contain the error message, if any.
1702 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1703 my $goback; # to put the parent in so we can link back where the deallocate started
1704
1705 # Enable transactions and exception-on-errors... but only for this sub
1706 local $dbh->{AutoCommit} = 0;
1707 local $dbh->{RaiseError} = 1;
1708
1709 if ($binfo->{type} =~ /^.i$/) {
1710 # First case. The "block" is a static IP
1711 # Note that we still need some additional code in the odd case
1712 # of a netblock-aligned contiguous group of static IPs
1713
1714 eval {
1715 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1716 my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
1717##fixme: VRF and rdepth
1718 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
1719 "city = (SELECT city FROM allocations WHERE id = ?),".
1720 "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
1721 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
1722 $dbh->commit;
1723 };
1724 if ($@) {
1725 $msg .= ": $@";
1726 eval { $dbh->rollback; };
1727 return ('FAIL',$msg);
1728 } else {
1729##fixme: RPC return code?
1730 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
1731 return ('OK',"OK");
1732 }
1733
1734 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
1735 # Second case. The block is a full master block
1736
1737##fixme: VRF limit
1738 $msg = "Unable to delete master block $cidr";
1739 eval {
1740 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1741 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1742 $dbh->commit;
1743 };
1744 if ($@) {
1745 $msg .= ": $@";
1746 eval { $dbh->rollback; };
1747 return ('FAIL', $msg);
1748 }
1749
1750 # Have to handle potentially split reverse zones. Assume they *are* split,
1751 # since if we added them here, they would have been added split.
1752# allow splitting reverse zones to be disabled, maybe, someday
1753#if ($splitrevzones && !$cidr->{isv6}) {
1754 my @zonelist;
1755 if (1 && !$cidr->{isv6}) {
1756 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
1757 @zonelist = $cidr->split($splitpoint);
1758 } else {
1759 @zonelist = ($cidr);
1760 }
1761 my @fails;
1762 foreach my $subzone (@zonelist) {
1763 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
1764 push @fails, ("$subzone" => $errstr);
1765 }
1766 }
1767 if (@fails) {
1768 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
1769 }
1770 return ('OK','OK');
1771
1772 } else { # end alloctype master block case
1773
1774 ## This is a big block; but it HAS to be done in a chunk. Any removal
1775 ## of a netblock allocation may result in a larger chunk of free
1776 ## contiguous IP space - which may in turn be combined into a single
1777 ## netblock rather than a number of smaller netblocks.
1778
1779 my $retcode = 'OK';
1780 my ($ptype,$pcity,$ppatt,$p_id);
1781
1782 eval {
1783
1784##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1785# explicitly deleting any suballocations of the block to be deleted.
1786
1787 # get parent info of the block we're deleting
1788 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1789 $ptype = $pinfo->{type};
1790 $pcity = $pinfo->{city};
1791 $ppatt = $pinfo->{rdns};
1792 $p_id = $binfo->{parent_id};
1793
1794 # Delete the block
1795 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
1796
1797 # munge the parent type a little
1798 $ptype = (split //, $ptype)[1];
1799
1800##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1801# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1802# -> $isprivnet flag from start of sub
1803
1804 # check to see if any container allocations could be the "true" parent
1805 my ($tparent,$tpar_id,$trtype,$tcity);
1806 $tpar_id = 0;
1807
1808##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
1809# contained by a container is a part of the same allocation tree when the VRF fields are equal.
1810
1811# logic:
1812# For each possible container of $cidr
1813# note the parent id
1814# walk the chain up the parents
1815# if we intersect $cidr's current parent, break
1816# if we've intersected $cidr's current parent
1817# set some variables to track that block
1818# break
1819
1820# Set up part of "is it in the middle of a pool?" check
1821 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
1822 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
1823 ($cidr, $binfo->{master_id}) );
1824
1825##fixme?
1826# edge cases not handled, or handled badly:
1827# -> $cidr managed to get to be the entirety of an IP pool
1828
1829 if ($wuzpool && $wuzpool->{id} != $id) {
1830 # we have legacy goo to be purified
1831 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
1832
1833 # for convenience
1834 my $poolid = $wuzpool->{id};
1835 my $pool = $wuzpool->{cidr};
1836 my $poolcity = $wuzpool->{city};
1837 my $pooltype = $wuzpool->{type};
1838 my $poolcustid = $wuzpool->{custid};
1839
1840 $retcode = 'WARNPOOL';
1841 $goback = "$poolid,$pool";
1842 # We've already deleted the block, now we have to stuff its IPs into the pool.
1843 $pooltype =~ s/[dp]$/i/; # change type to static IP
1844 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
1845 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
1846
1847##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1848 # don't insert .0
1849 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1850 $cidr++;
1851 my $bcast = $cidr->broadcast;
1852 while ($cidr != $bcast) {
1853 $sth2->execute($cidr->addr);
1854 $cidr++;
1855 }
1856 # don't insert .255
1857 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1858
1859# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
1860# causing ->split, ->hostenum, and related methods to explode. O_o
1861# foreach my $ip ($cidr->hostenum) {
1862# $sth2->execute($ip);
1863# }
1864
1865 }
1866
1867## important!
1868# ... or IS IT?
1869# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
1870#if (!$wuzpool) {
1871
1872 else {
1873
1874# Edge case: Block is the same size as more than one parent level. Should be rare.
1875# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
1876# but it's likely still possible to fail in particularly well-mangled databases.
1877# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
1878 # Get all possible (and probably a number of impossible) containers for $cidr
1879 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
1880 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
1881 "ORDER BY masklen(cidr) DESC,parent_id DESC");
1882 $sth->execute($cidr, $binfo->{master_id});
1883
1884 # Quickly get certain fields (simpler than getBlockData()
1885 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
1886 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
1887
1888 # For each possible container of $cidr...
1889 while (my @data = $sth->fetchrow_array) {
1890 my $i = 0;
1891 # Save some state and set a start point - parent ID of container we're checking
1892 $tparent = $data[0];
1893 my $ppid = $data[1];
1894 $trtype = $data[2];
1895 $tcity = $data[3];
1896 $tpar_id = $data[4];
1897 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
1898 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
1899 while (1) {
1900 # Retrieve bits on that parent ID
1901 $sth2->execute($ppid, $binfo->{master_id});
1902 my @container = $sth2->fetchrow_array;
1903 $ppid = $container[1];
1904 last if $container[1] == 0; # Break if we've hit a master block
1905 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
1906 }
1907 last if $ppid == $binfo->{parent_id};
1908 }
1909
1910 # found an alternate parent; reset some parent-info bits
1911 if ($tpar_id != $binfo->{parent_id}) {
1912 $ptype = (split //, $trtype)[1];
1913 $pcity = $tcity;
1914 $retcode = 'WARNMERGE'; # may be redundant
1915 $p_id = $tpar_id;
1916 }
1917
1918 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
1919
1920 # Special case - delete pool IPs
1921 if ($binfo->{type} =~ /^.[pd]$/) {
1922 # We have to delete the IPs from the pool listing.
1923##fixme: rdepth? vrf?
1924 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
1925 }
1926
1927 $pinfo = getBlockData($dbh, $p_id);
1928
1929 # If the block wasn't legacy goo embedded in a static pool, we check the
1930 # freeblocks in the identified parent to see if we can combine any of them.
1931
1932 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1933 if ($binfo->{type} =~ /^.[mc]/) {
1934 # move the freeblocks into the parent
1935 # we don't insert a new freeblock because there could be a live reparented sub.
1936 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
1937 ($p_id, $ptype, $pcity, $id) );
1938 } else {
1939 # ... otherwise, add the freeblock
1940 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
1941 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
1942 }
1943
1944##fixme: vrf
1945##fixme: simplify since all containers now represent different "layers"/"levels"?
1946 # set up the query to get the list of blocks to try to merge.
1947 $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks ".
1948 "WHERE parent_id = ? ".
1949 "ORDER BY masklen(cidr) DESC");
1950
1951 $sth->execute($p_id);
1952
1953# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1954# from the caller and the passed terms.
1955# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1956# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1957# .64-.95, and .96-.128), you will get an array containing a single
1958# /25 as element 0 (.0-.127). Order is not important; you could have
1959# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1960
1961 my (@rawfb, @combinelist, %rawid);
1962 my $i=0;
1963 # for each free block under $parent, push a NetAddr::IP object into one list, and
1964 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
1965 while (my @data = $sth->fetchrow_array) {
1966 my $testIP = new NetAddr::IP $data[0];
1967 push @rawfb, $testIP;
1968 $rawid{"$testIP"} = $data[1]; # $data[0] vs "$testIP" *does* make a difference for v6
1969 @combinelist = $testIP->compact(@combinelist);
1970 }
1971
1972 # now that we have the full list of "compacted" freeblocks, go back over
1973 # the list of raw freeblocks, and delete the ones that got merged.
1974 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
1975 foreach my $rawfree (@rawfb) {
1976 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
1977 $sth->execute($rawid{$rawfree});
1978 }
1979
1980 # now we walk the new list of compacted blocks, and see which ones we need to insert
1981 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,master_id) VALUES (?,?,?,?,?)");
1982 foreach my $cme (@combinelist) {
1983 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
1984 $sth->execute($cme, $pcity, $ptype, $p_id, $binfo->{master_id});
1985 }
1986
1987 } # done returning IPs to the appropriate place
1988
1989 # If we got here, we've succeeded. Whew!
1990 $dbh->commit;
1991 }; # end eval
1992 if ($@) {
1993 $msg .= ": $@";
1994 eval { $dbh->rollback; };
1995 return ('FAIL', $msg);
1996 } else {
1997##fixme: RPC return code?
1998 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
1999 return ($retcode, $goback);
2000 }
2001
2002 } # end alloctype != netblock
2003
2004} # end deleteBlock()
2005
2006
2007## IPDB::getBlockData()
2008# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
2009# private/restricted data, for a CIDR block or pool IP
2010# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
2011# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
2012# instead of a netblock.
2013# Returns a hashref to the block data
2014sub getBlockData {
2015 my $dbh = shift;
2016 my $id = shift;
2017 my $type = shift || 'b'; # default to netblock for lazy callers
2018
2019 # netblocks are in the allocations table; pool IPs are in the poolips table.
2020 # If we try to look up a CIDR in an integer field we should just get back nothing.
2021 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
2022
2023 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
2024 my $commonfields = q(custid, type, circuitid, description, notes, modifystamp AS lastmod,
2025 privdata, vlan, rdns);
2026
2027 if ($type eq 'i') {
2028 my $binfo = $dbh->selectrow_hashref(qq(
2029 SELECT ip AS block, city, vrf, parent_id, master_id, $commonfields
2030 FROM poolips WHERE id = ?
2031 ), undef, ($id) );
2032 return $binfo;
2033 } else {
2034 my $binfo = $dbh->selectrow_hashref(qq(
2035 SELECT a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, swip, $commonfields,
2036 f.cidr AS reserve, f.id as reserve_id
2037 FROM allocations a LEFT JOIN freeblocks f ON a.id=f.reserve_for
2038 WHERE a.id = ?
2039 ), undef, ($id) );
2040 return $binfo;
2041 }
2042} # end getBlockData()
2043
2044
2045## IPDB::getBlockRDNS()
2046# Gets reverse DNS pattern for a block or IP. Note that this will also
2047# retrieve any default pattern following the parent chain up, and check via
2048# RPC (if available) to see what the narrowest pattern for the requested block is
2049# Returns the current pattern for the block or IP.
2050sub getBlockRDNS {
2051 my $dbh = shift;
2052 my %args = @_;
2053
2054 $args{type} = 'b' if !$args{type};
2055 my $cached = 1;
2056
2057 # snag entry from database
2058 my ($rdns,$rfrom,$pid);
2059 if ($args{type} =~ /.i/) {
2060 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
2061 undef, ($args{id}) );
2062 } else {
2063 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
2064 undef, ($args{id}) );
2065 }
2066
2067 # Can't see a way this could end up empty, for any case I care about. If the caller
2068 # doesn't know an allocation ID to request, then they don't know anything else anyway.
2069 my $selfblock = $rfrom;
2070
2071 my $type;
2072 while (!$rdns && $pid) {
2073 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
2074 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
2075 undef, ($pid) );
2076 last if $type eq 'mm'; # break loops in unfortunate legacy data
2077 }
2078
2079 # use the actual allocation to check against the DNS utility; we don't want
2080 # to always go chasing up the chain to the master... which may (usually won't)
2081 # be present directly in DNS anyway
2082 my $cidr = new NetAddr::IP $selfblock;
2083
2084 if ($rpc_url) {
2085 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
2086 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
2087
2088 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
2089 my %rpcargs = (
2090 rpcuser => $args{user},
2091 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2092 cidr => "$rpcblock",
2093 );
2094
2095 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
2096 $rdns = $remote_rdns if $remote_rdns;
2097 $cached = 0;
2098 }
2099
2100 # hmm. do we care about where it actually came from?
2101 return $rdns, $cached;
2102} # end getBlockRDNS()
2103
2104
2105## IPDB::getRDNSbyIP()
2106# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
2107# opposite direction down the netblock tree compared to getBlockRDNS() above.
2108sub getRDNSbyIP {
2109 my $dbh = shift;
2110 my %args = @_; # We want to accept a variety of call types
2111
2112 # key arguments: allocation ID, type
2113 unless ($args{id} || $args{type}) {
2114 $errstr = 'Missing allocation ID or type';
2115 return;
2116 }
2117
2118 my @ret = ();
2119 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
2120 if ($args{type} =~ /^.i$/) {
2121 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
2122 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
2123 } else {
2124 if ($rpc_url) {
2125 my %rpcargs = (
2126 rpcuser => $args{user},
2127 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2128 cidr => $args{range},
2129 );
2130
2131 my $remote_rdns = _rpc('getRevSet', %rpcargs);
2132 return $remote_rdns;
2133# $rdns = $remote_rdns if $remote_rdns;
2134# $cached = 0;
2135 }
2136 }
2137 return \@ret;
2138} # end getRDNSbyIP()
2139
2140
2141## IPDB::getNodeList()
2142# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
2143sub getNodeList {
2144 my $dbh = shift;
2145
2146 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
2147 { Slice => {} });
2148 return $ret;
2149} # end getNodeList()
2150
2151
2152## IPDB::getNodeName()
2153# Get node name from the ID
2154sub getNodeName {
2155 my $dbh = shift;
2156 my $nid = shift;
2157
2158 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
2159 return $nname;
2160} # end getNodeName()
2161
2162
2163## IPDB::getNodeInfo()
2164# Get node name and ID associated with a block
2165sub getNodeInfo {
2166 my $dbh = shift;
2167 my $block = shift;
2168
2169 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
2170 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
2171 return ($nid, $nname);
2172} # end getNodeInfo()
2173
2174
2175## IPDB::mailNotify()
2176# Sends notification mail to recipients regarding an IPDB operation
2177sub mailNotify {
2178 my $dbh = shift;
2179 my ($action,$subj,$message) = @_;
2180
2181 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2182
2183##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
2184
2185# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
2186 my @actionbits = split //, $action;
2187
2188 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
2189 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
2190 # and "all events with this action"
2191 my @actionsets = ($action);
2192##fixme: ick, eww. really gotta find a better way to handle this...
2193 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
2194 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
2195
2196 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
2197
2198 # get recip list from db
2199 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
2200
2201 my %reciplist;
2202 foreach (@actionsets) {
2203 $sth->execute($_);
2204##fixme - need to handle db errors
2205 my ($recipsub) = $sth->fetchrow_array;
2206 next if !$recipsub;
2207 foreach (split(/,/, $recipsub)) {
2208 $reciplist{$_}++;
2209 }
2210 }
2211
2212 return if !%reciplist;
2213
2214 foreach my $recip (keys %reciplist) {
2215 $mailer->mail($smtpsender);
2216 $mailer->to($recip);
2217 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
2218 "To: $recip\n",
2219 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2220 "Subject: {IPDB} $subj\n",
2221 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
2222 "Organization: $org_name\n",
2223 "\n$message\n");
2224 }
2225 $mailer->quit;
2226}
2227
2228# Indicates module loaded OK. Required by Perl.
22291;
Note: See TracBrowser for help on using the repository browser.