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

Last change on this file since 561 was 561, checked in by Kris Deugau, 11 years ago

/trunk

Work in progress, see #5:
Replace listMaster() and listRBlock() with listSubs() due to
the merge of routing and other container types.

  • Property svn:keywords set to Date Rev Author
File size: 49.4 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: 2012-12-19 21:09:04 +0000 (Wed, 19 Dec 2012) $
6# SVN revision $Rev: 561 $
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( Compact );
19use POSIX;
20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
22$VERSION = 2; ##VERSION##
23@ISA = qw(Exporter);
24@EXPORT_OK = qw(
25 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
26 %IPDBacl %aclmsg
27 &initIPDBGlobals &connectDB &finish &checkDBSanity
28 &addMaster &touchMaster
29 &listSummary &listSubs &listFree &listPool
30 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
31 &ipParent &subParent &blockParent &getRoutedCity
32 &allocateBlock &updateBlock &deleteBlock &getBlockData
33 &getNodeList &getNodeName &getNodeInfo
34 &mailNotify
35 );
36
37@EXPORT = (); # Export nothing by default.
38%EXPORT_TAGS = ( ALL => [qw(
39 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
40 %IPDBacl %aclmsg
41 &initIPDBGlobals &connectDB &finish &checkDBSanity
42 &addMaster &touchMaster
43 &listSummary &listSubs &listFree &listPool
44 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
45 &ipParent &subParent &blockParent &getRoutedCity
46 &allocateBlock &updateBlock &deleteBlock &getBlockData
47 &getNodeList &getNodeName &getNodeInfo
48 &mailNotify
49 )]
50 );
51
52##
53## Global variables
54##
55our %disp_alloctypes;
56our %list_alloctypes;
57our %def_custids;
58our @citylist;
59our @poplist;
60our %IPDBacl;
61
62# mapping table for functional-area => error message
63our %aclmsg = (
64 addmaster => 'add a master block',
65 addblock => 'add an allocation',
66 updateblock => 'update a block',
67 delblock => 'delete an allocation',
68 );
69
70our $org_name = 'Example Corp';
71our $smtphost = 'smtp.example.com';
72our $domain = 'example.com';
73our $defcustid = '5554242';
74# mostly for rwhois
75##fixme: leave these blank by default?
76our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
77our $org_street = '123 4th Street';
78our $org_city = 'Anytown';
79our $org_prov_state = 'ON';
80our $org_pocode = 'H0H 0H0';
81our $org_country = 'CA';
82our $org_phone = '000-555-1234';
83our $org_techhandle = 'ISP-ARIN-HANDLE';
84our $org_email = 'noc@example.com';
85our $hostmaster = 'dns@example.com';
86
87our $syslog_facility = 'local2';
88
89# Let's initialize the globals.
90## IPDB::initIPDBGlobals()
91# Initialize all globals. Takes a database handle, returns a success or error code
92sub initIPDBGlobals {
93 my $dbh = $_[0];
94 my $sth;
95
96 # Initialize alloctypes hashes
97 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
98 $sth->execute;
99 while (my @data = $sth->fetchrow_array) {
100 $disp_alloctypes{$data[0]} = $data[2];
101 $def_custids{$data[0]} = $data[4];
102 if ($data[3] < 900) {
103 $list_alloctypes{$data[0]} = $data[1];
104 }
105 }
106
107 # City and POP listings
108 $sth = $dbh->prepare("select city,routing from cities order by city");
109 $sth->execute;
110 return (undef,$sth->errstr) if $sth->err;
111 while (my @data = $sth->fetchrow_array) {
112 push @citylist, $data[0];
113 if ($data[1] eq 'y') {
114 push @poplist, $data[0];
115 }
116 }
117
118 # Load ACL data. Specific username checks are done at a different level.
119 $sth = $dbh->prepare("select username,acl from users");
120 $sth->execute;
121 return (undef,$sth->errstr) if $sth->err;
122 while (my @data = $sth->fetchrow_array) {
123 $IPDBacl{$data[0]} = $data[1];
124 }
125
126##fixme: initialize HTML::Template env var for template path
127# something like $self->path().'/templates' ?
128# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
129
130 return (1,"OK");
131} # end initIPDBGlobals
132
133
134## IPDB::connectDB()
135# Creates connection to IPDB.
136# Requires the database name, username, and password.
137# Returns a handle to the db.
138# Set up for a PostgreSQL db; could be any transactional DBMS with the
139# right changes.
140sub connectDB {
141 my $dbname = shift;
142 my $user = shift;
143 my $pass = shift;
144 my $dbhost = shift;
145
146 my $dbh;
147 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
148
149# Note that we want to autocommit by default, and we will turn it off locally as necessary.
150# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
151 $dbh = DBI->connect($DSN, $user, $pass, {
152 AutoCommit => 1,
153 PrintError => 0
154 })
155 or return (undef, $DBI::errstr) if(!$dbh);
156
157# Return here if we can't select. Note that this indicates a
158# problem executing the select.
159 my $sth = $dbh->prepare("select type from alloctypes");
160 $sth->execute();
161 return (undef,$DBI::errstr) if ($sth->err);
162
163# See if the select returned anything (or null data). This should
164# succeed if the select executed, but...
165 $sth->fetchrow();
166 return (undef,$DBI::errstr) if ($sth->err);
167
168# If we get here, we should be OK.
169 return ($dbh,"DB connection OK");
170} # end connectDB
171
172
173## IPDB::finish()
174# Cleans up after database handles and so on.
175# Requires a database handle
176sub finish {
177 my $dbh = $_[0];
178 $dbh->disconnect if $dbh;
179} # end finish
180
181
182## IPDB::checkDBSanity()
183# Quick check to see if the db is responding. A full integrity
184# check will have to be a separate tool to walk the IP allocation trees.
185sub checkDBSanity {
186 my ($dbh) = $_[0];
187
188 if (!$dbh) {
189 print "No database handle, or connection has been closed.";
190 return -1;
191 } else {
192 # it connects, try a stmt.
193 my $sth = $dbh->prepare("select type from alloctypes");
194 my $err = $sth->execute();
195
196 if ($sth->fetchrow()) {
197 # all is well.
198 return 1;
199 } else {
200 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
201 return -1;
202 }
203 }
204 # Clean up after ourselves.
205# $dbh->disconnect;
206} # end checkDBSanity
207
208
209## IPDB::addMaster()
210# Does all the magic necessary to sucessfully add a master block
211# Requires database handle, block to add
212# Returns failure code and error message or success code and "message"
213sub addMaster {
214 my $dbh = shift;
215 my $cidr = new NetAddr::IP shift;
216
217 # Allow transactions, and raise an exception on errors so we can catch it later.
218 # Use local to make sure these get "reset" properly on exiting this block
219 local $dbh->{AutoCommit} = 0;
220 local $dbh->{RaiseError} = 1;
221
222 # Wrap all the SQL in a transaction
223 eval {
224 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
225
226 if (!$mexist) {
227 # First case - master is brand-spanking-new.
228##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
229## maybe a db table called "config"?
230 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr,'y') );
231
232# Unrouted blocks aren't associated with a city (yet). We don't rely on this
233# elsewhere though; legacy data may have traps and pitfalls in it to break this.
234# Thus the "routed" flag.
235 $dbh->do("INSERT INTO freeblocks (cidr,maskbits,city,routed,parent,rdepth) VALUES (?,?,?,?,?,?)", undef,
236 ($cidr, $cidr->masklen, '<NULL>', 'm', $cidr, 1) );
237
238 # If we get here, everything is happy. Commit changes.
239 $dbh->commit;
240
241 } # done new master does not contain existing master(s)
242 else {
243
244 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
245 my $smallmask = $cidr->masklen;
246 my $sth = $dbh->prepare("SELECT cidr FROM masterblocks WHERE cidr <<= ?");
247 $sth->execute($cidr);
248 my @cmasters;
249 while (my @data = $sth->fetchrow_array) {
250 my $master = new NetAddr::IP $data[0];
251 push @cmasters, $master;
252 $smallmask = $master->masklen if $master->masklen > $smallmask;
253 }
254
255 # split the new master, and keep only those blocks not part of an existing master
256 my @blocklist;
257 foreach my $seg ($cidr->split($smallmask)) {
258 my $contained = 0;
259 foreach my $master (@cmasters) {
260 $contained = 1 if $master->contains($seg);
261 }
262 push @blocklist, $seg if !$contained;
263 }
264
265 # collect the unrouted free blocks within the new master
266 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm'");
267 $sth->execute($smallmask, $cidr);
268 while (my @data = $sth->fetchrow_array) {
269 my $freeblock = new NetAddr::IP $data[0];
270 push @blocklist, $freeblock;
271 }
272
273 # combine the set of free blocks we should have now.
274 @blocklist = Compact(@blocklist);
275
276 # and now insert the new data. Make sure to delete old masters too.
277
278 # freeblocks
279 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ?");
280 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,maskbits,city,routed,parent,rdepth)".
281 " VALUES (?,?,'<NULL>','m',?,1)");
282 foreach my $newblock (@blocklist) {
283 $sth->execute($newblock);
284 $sth2->execute($newblock, $newblock->masklen, $cidr);
285 }
286
287 # update parent relations at rdepth=1
288 $dbh->do("UPDATE allocations SET parent = ? WHERE parent << ? AND rdepth=1", undef, ($cidr, $cidr) );
289 $dbh->do("UPDATE freeblocks SET parent = ? WHERE parent << ? AND rdepth=1", undef, ($cidr, $cidr) );
290
291 # master
292 $dbh->do("DELETE FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
293 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr, 'y') );
294
295 # *whew* If we got here, we likely suceeded.
296 $dbh->commit;
297 } # new master contained existing master(s)
298 }; # end eval
299
300 if ($@) {
301 my $msg = $@;
302 eval { $dbh->rollback; };
303 return ('FAIL',$msg);
304 } else {
305 return ('OK','OK');
306 }
307} # end addMaster
308
309
310## IPDB::touchMaster()
311# Update last-changed timestamp on a master block.
312sub touchMaster {
313 my $dbh = shift;
314 my $master = shift;
315
316 local $dbh->{AutoCommit} = 0;
317 local $dbh->{RaiseError} = 1;
318
319 eval {
320 $dbh->do("UPDATE masterblocks SET mtime=now() WHERE cidr = ?", undef, ($master));
321 $dbh->commit;
322 };
323
324 if ($@) {
325 my $msg = $@;
326 eval { $dbh->rollback; };
327 return ('FAIL',$msg);
328 }
329 return ('OK','OK');
330} # end touchMaster()
331
332
333## IPDB::listSummary()
334# Get summary list of all master blocks
335# Returns an arrayref to a list of hashrefs containing the master block, routed count,
336# allocated count, free count, and largest free block masklength
337sub listSummary {
338 my $dbh = shift;
339
340 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master FROM masterblocks ORDER BY cidr", { Slice => {} });
341
342 foreach (@{$mlist}) {
343 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm'",
344 undef, ($$_{master}));
345 $$_{routed} = $rcnt;
346 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND NOT type='rm'",
347 undef, ($$_{master}));
348 $$_{allocated} = $acnt;
349 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?",
350 undef, ($$_{master}));
351 $$_{free} = $fcnt;
352 my ($bigfree) = $dbh->selectrow_array("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
353 " AND parent = ? ORDER BY masklen(cidr) LIMIT 1", undef, ($$_{master}, $$_{master}));
354##fixme: should find a way to do this without having to HTMLize the <>
355 $bigfree = "/$bigfree" if $bigfree;
356 $bigfree = '<NONE>' if !$bigfree;
357 $$_{bigfree} = $bigfree;
358 }
359 return $mlist;
360} # end listSummary()
361
362
363## IPDB::listSubs()
364# Get list of subnets within a specified CIDR block, on a specified VRF.
365# Returns an arrayref to a list of hashrefs containing the CIDR block, customer location or
366# city it's routed to, block type, SWIP status, and description
367sub listSubs {
368 my $dbh = shift;
369 my %args = @_;
370
371 # Just In Case
372 $args{vrf} = '' if !$args{vrf};
373 $args{rdepth} = 1 if !$args{rdepth};
374
375 # Snag the allocations for this block
376 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
377 " FROM allocations WHERE parent = ? AND rdepth = ? ORDER BY cidr");
378 $sth->execute($args{block},$args{rdepth});
379
380 # hack hack hack
381 # set up to flag swip=y records if they don't actually have supporting data in the customers table
382 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
383
384 my @blocklist;
385 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
386 $custsth->execute($custid);
387 my ($ncust) = $custsth->fetchrow_array();
388 my %row = (
389 block => $cidr,
390 city => $city,
391 type => $disp_alloctypes{$type},
392 custid => $custid,
393 swip => ($swip eq 'y' ? 'Yes' : 'No'),
394 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
395 desc => $desc,
396 hassubs => ($type eq 'rm' || $type =~ /.c/ ? 1 : 0),
397 );
398# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
399 $row{listpool} = ($type =~ /^.[pd]$/);
400 push (@blocklist, \%row);
401 }
402 return \@blocklist;
403} # end listSubs()
404
405
406## IPDB::listMaster()
407# Get list of routed blocks in the requested master
408# Returns an arrayref to a list of hashrefs containing the routed block, POP/city the block is routed to,
409# allocated count, free count, and largest free block masklength
410sub listMaster {
411 my $dbh = shift;
412 my $master = shift;
413
414 my $rlist = $dbh->selectall_arrayref("SELECT cidr AS block,city FROM routed WHERE cidr <<= ? ORDER BY cidr",
415 { Slice => {} }, ($master) );
416
417 foreach (@{$rlist}) {
418 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{block}));
419 $$_{nsubs} = $acnt;
420 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
421 " AND (routed='y' OR routed='n')", undef, ($$_{block}));
422 $$_{nfree} = $fcnt;
423 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
424 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{block}));
425##fixme: should find a way to do this without having to HTMLize the <>
426 $bigfree = "/$bigfree" if $bigfree;
427 $bigfree = '<NONE>' if !$bigfree;
428 $$_{lfree} = $bigfree;
429 }
430 return $rlist;
431} # end listMaster()
432
433
434## IPDB::listRBlock()
435# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
436# Takes a parent/master and an optional flag to look at routed or unrouted blocks, depending
437# on whether the master is a direct master or a routed block
438# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
439sub listRBlock {
440 my $dbh = shift;
441 my $routed = shift;
442
443 # Snag the allocations for this block
444 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
445 " FROM allocations WHERE cidr <<= ? ORDER BY cidr");
446 $sth->execute($routed);
447
448 # hack hack hack
449 # set up to flag swip=y records if they don't actually have supporting data in the customers table
450 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
451
452 my @blocklist;
453 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
454 $custsth->execute($custid);
455 my ($ncust) = $custsth->fetchrow_array();
456 my %row = (
457 block => $cidr,
458 city => $city,
459 type => $disp_alloctypes{$type},
460 custid => $custid,
461 swip => ($swip eq 'y' ? 'Yes' : 'No'),
462 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
463 desc => $desc
464 );
465 $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
466 $row{listpool} = ($type =~ /^.[pd]$/);
467 push (@blocklist, \%row);
468 }
469 return \@blocklist;
470} # end listRBlock()
471
472
473## IPDB::listFree()
474# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
475# Takes a parent/master and an optional "routed or unrouted" flag that defaults to unrouted.
476# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
477# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
478sub listFree {
479 my $dbh = shift;
480 my $master = shift;
481 my $routed = shift || 'n';
482
483 # do it this way so we can waste a little less time iterating
484 my $sth = $dbh->prepare("SELECT cidr,routed FROM freeblocks WHERE cidr <<= ? AND ".
485 ($routed eq 'n' ? '' : 'NOT')." routed = 'n' ORDER BY cidr");
486 $sth->execute($master);
487 my @flist;
488 while (my ($cidr,$rtype) = $sth->fetchrow_array()) {
489 $cidr = new NetAddr::IP $cidr;
490 my %row = (
491 fblock => "$cidr",
492 frange => $cidr->range,
493 );
494 if ($routed eq 'y') {
495 $row{subblock} = ($rtype ne 'y' && $rtype ne 'n');
496 $row{fbtype} = $rtype;
497 }
498 push @flist, \%row;
499 }
500 return \@flist;
501} # end listFree()
502
503
504## IPDB::listPool()
505#
506sub listPool {
507 my $dbh = shift;
508 my $pool = shift;
509
510 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type".
511 " FROM poolips WHERE pool = ? ORDER BY ip");
512 $sth->execute($pool);
513 my @poolips;
514 while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
515 my %row = (
516 ip => $ip,
517 custid => $custid,
518 available => $available,
519 desc => $desc,
520 delme => $available eq 'n'
521 );
522 push @poolips, \%row;
523 }
524 return \@poolips;
525} # end listPool()
526
527
528## IPDB::getMasterList()
529# Get a list of master blocks, optionally including last-modified timestamps
530# Takes an optional flag to indicate whether to include timestamps;
531# 'm' includes ctime, all others (suggest 'c') do not.
532# Returns an arrayref to a list of hashrefs
533sub getMasterList {
534 my $dbh = shift;
535 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
536
537 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master".($stampme eq 'm' ? ',mtime' : '').
538 " FROM masterblocks ORDER BY cidr", { Slice => {} });
539 return $mlist;
540} # end getMasterList()
541
542
543## IPDB::getTypeList()
544# Get an alloctype/description pair list suitable for dropdowns
545# Takes a flag to determine which general groups of types are returned
546# Returns an reference to an array of hashrefs
547sub getTypeList {
548 my $dbh = shift;
549 my $tgroup = shift || 'a'; # technically optional, like this, but should
550 # really be specified in the call for clarity
551 my $tlist;
552 if ($tgroup eq 'p') {
553 # grouping 'p' - primary allocation types. These include static IP pools (_d and _p),
554 # dynamic-allocation ranges (_e), containers (_c), and the "miscellaneous" cn, in, and en types.
555 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder < 500 ".
556 "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
557 } elsif ($tgroup eq 'c') {
558 # grouping 'c' - contained types. These include all static IPs and all _r types.
559 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
560 " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
561 } else {
562 # grouping 'a' - all standard allocation types. This includes everything
563 # but mm (present only as a formality). Make this the default.
564 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
565 " ORDER BY listorder", { Slice => {} });
566 }
567 return $tlist;
568}
569
570
571## IPDB::getPoolSelect()
572# Get a list of pools matching the passed city and type that have 1 or more free IPs
573# Returns an arrayref to a list of hashrefs
574sub getPoolSelect {
575 my $dbh = shift;
576 my $iptype = shift;
577 my $pcity = shift;
578
579 my ($ptype) = ($iptype =~ /^(.)i$/);
580 return if !$ptype;
581 $ptype .= '_';
582
583 my $plist = $dbh->selectall_arrayref(
584 "SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool) AS poolcit, ".
585 "poolips.pool AS poolblock, COUNT(*) AS poolfree FROM poolips,allocations ".
586 "WHERE poolips.available='y' AND poolips.pool=allocations.cidr ".
587 "AND allocations.city = ? AND poolips.type LIKE ? ".
588 "GROUP BY pool", { Slice => {} }, ($pcity, $ptype) );
589 return $plist;
590} # end getPoolSelect()
591
592
593## IPDB::findAllocateFrom()
594# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
595# Takes
596# - mask length
597# - allocation type
598# - POP city "parent"
599# - optional master-block restriction
600# - optional flag to allow automatic pick-from-private-network-ranges
601# Returns a string with the first CIDR block matching the criteria, if any
602sub findAllocateFrom {
603 my $dbh = shift;
604 my $maskbits = shift;
605 my $type = shift;
606 my $city = shift;
607 my $pop = shift;
608 my %optargs = @_;
609
610 my $failmsg = "No suitable free block found\n";
611
612## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
613## Very large systems will require development of a reserve system (possibly an extension
614## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
615## Also populate a value list for the DBI call.
616
617 my @vallist = ($maskbits, ($type eq 'rm' ? 'n' : ($type =~ /^(.)r$/ ? "$1" : 'y')) );
618 my $sql = "SELECT cidr FROM freeblocks WHERE maskbits <= ? AND routed = ?";
619
620 # for PPP(oE) and container types, the POP city is the one attached to the pool.
621 # individual allocations get listed with the customer city site.
622 ##fixme: chain cities to align roughly with a full layer-2 node graph
623 $city = $pop if $type !~ /^.[pc]$/;
624 if ($type ne 'rm' && $city) {
625 $sql .= " AND city = ?";
626 push @vallist, $city;
627 }
628 # Allow specifying an arbitrary full block, instead of a master
629 if ($optargs{gimme}) {
630 $sql .= " AND cidr >>= ?";
631 push @vallist, $optargs{gimme};
632 }
633 # if a specific master was requested, allow the requestor to self->shoot(foot)
634 if ($optargs{master} && $optargs{master} ne '-') {
635 $sql .= " AND cidr <<= ?" if $optargs{master} ne '-';
636 push @vallist, $optargs{master};
637 } else {
638 # if a specific master was NOT requested, filter out the RFC 1918 private networks
639 if (!$optargs{allowpriv}) {
640 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
641 }
642 }
643 # Sorting and limiting, since we don't (currently) care to provide a selection of
644 # blocks to carve up. This preserves something resembling optimal usage of the IP
645 # space by forcing contiguous allocations and free blocks as much as possible.
646 $sql .= " ORDER BY maskbits DESC,cidr LIMIT 1";
647
648 my ($fbfound) = $dbh->selectrow_array($sql, undef, @vallist);
649 return $fbfound;
650} # end findAllocateFrom()
651
652
653## IPDB::ipParent()
654# Get an IP's parent pool's details
655# Takes a database handle and IP
656# Returns a hashref to the parent pool block, if any
657sub ipParent {
658 my $dbh = shift;
659 my $block = shift;
660
661 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
662 " WHERE cidr >>= ?", undef, ($block) );
663 return $pinfo;
664} # end ipParent()
665
666
667## IPDB::subParent()
668# Get a block's parent's details
669# Takes a database handle and CIDR block
670# Returns a hashref to the parent container block, if any
671sub subParent {
672 my $dbh = shift;
673 my $block = shift;
674
675 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
676 " WHERE cidr >>= ?", undef, ($block) );
677 return $pinfo;
678} # end subParent()
679
680
681## IPDB::blockParent()
682# Get a block's parent's details
683# Takes a database handle and CIDR block
684# Returns a hashref to the parent container block, if any
685sub blockParent {
686 my $dbh = shift;
687 my $block = shift;
688
689 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
690 " WHERE cidr >>= ?", undef, ($block) );
691 return $pinfo;
692} # end blockParent()
693
694
695## IPDB::getRoutedCity()
696# Get the city for a routed block.
697sub getRoutedCity {
698 my $dbh = shift;
699 my $block = shift;
700
701 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
702 return $rcity;
703} # end getRoutedCity()
704
705
706## IPDB::allocateBlock()
707# Does all of the magic of actually allocating a netblock
708# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
709# type, city, block to allocate from, and optionally a description, notes, circuit ID,
710# and private data
711# Returns a success code and optional error message.
712sub allocateBlock {
713 my $dbh = shift;
714
715 my %args = @_;
716
717 $args{cidr} = new NetAddr::IP $args{cidr};
718 $args{alloc_from} = new NetAddr::IP $args{alloc_from};
719
720 $args{desc} = '' if !$args{desc};
721 $args{notes} = '' if !$args{notes};
722 $args{circid} = '' if !$args{circid};
723 $args{privdata} = '' if !$args{privdata};
724 $args{vrf} = '' if !$args{vrf};
725
726 my $sth;
727
728 # Snag the "type" of the freeblock (alloc_from) "just in case"
729 $sth = $dbh->prepare("select routed from freeblocks where cidr='$args{alloc_from}'");
730 $sth->execute;
731 my ($alloc_from_type) = $sth->fetchrow_array;
732
733 # To contain the error message, if any.
734 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
735
736 # Enable transactions and error handling
737 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
738 local $dbh->{RaiseError} = 1; # step on our toes by accident.
739
740 if ($args{type} =~ /^.i$/) {
741 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
742 eval {
743 if ($args{cidr}) { # IP specified
744 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
745 die "IP is not in an IP pool.\n"
746 if !$isavail;
747 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
748 if $isavail eq 'n';
749 } else { # IP not specified, take first available
750 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
751 undef, ($args{alloc_from}) );
752 }
753 $dbh->do("UPDATE poolips SET custid=?,city=?,available='n',description=?,notes=?,circuitid=?,privdata=?,vrf=? ".
754 "WHERE ip=?", undef, ($args{custid}, $args{city}, $args{desc}, $args{notes}, $args{circid},
755 $args{privdata}, $args{vrf}, $args{cidr}) );
756
757# node hack
758 if ($args{nodeid} && $args{nodeid} ne '') {
759 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
760 }
761# end node hack
762
763 $dbh->commit;
764 };
765 if ($@) {
766 $msg .= ": $@";
767 eval { $dbh->rollback; };
768 return ('FAIL',$msg);
769 } else {
770 return ('OK',"$args{cidr}");
771 }
772
773 } else { # end IP-from-pool allocation
774
775 if ($args{cidr} == $args{alloc_from}) {
776 # Easiest case- insert in one table, delete in the other, and go home. More or less.
777 # insert into allocations values (cidr,custid,type,city,desc) and
778 # delete from freeblocks where cidr='cidr'
779 # For data safety on non-transaction DBs, we delete first.
780
781 eval {
782 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
783
784 # Get old freeblocks parent/depth/routed for new entries... before we delete it.
785 my ($fparent) = $dbh->selectrow_array("SELECT parent FROM freeblocks WHERE cidr=? AND rdepth=?",
786 undef, ($args{alloc_from}, $args{rdepth}) );
787
788 # Munge freeblocks
789 if ($args{type} =~ /^(.)[mc]$/) {
790 # special case - block is a routed or container/"reserve" block
791 my $rtype = $1;
792 $dbh->do("UPDATE freeblocks SET routed=?,rdepth=rdepth+1,city=?,parent=? WHERE cidr=? AND rdepth=?",
793 undef, ($rtype, $args{city}, $args{cidr}, $args{cidr}, $args{rdepth}));
794 } else {
795 # "normal" case
796 $dbh->do("DELETE FROM freeblocks WHERE cidr=? AND rdepth=?", undef, ($args{cidr}, $args{rdepth}));
797 }
798
799 # Insert the allocations entry
800 $dbh->do("INSERT INTO allocations ".
801 "(cidr,parent,vrf,rdepth,custid,type,city,description,notes,circuitid,privdata)".
802 " VALUES (?,?,?,?,?,?,?,?,?,?,?)", undef,
803 ($args{cidr}, $fparent, $args{vrf}, $args{rdepth}, $args{custid}, $args{type}, $args{city},
804 $args{desc}, $args{notes}, $args{circid}, $args{privdata}) );
805
806 # And initialize the pool, if necessary
807 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
808 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
809 if ($args{type} =~ /^.p$/) {
810 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
811 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all");
812 die $rmsg if $code eq 'FAIL';
813 } elsif ($args{type} =~ /^.d$/) {
814 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
815 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal");
816 die $rmsg if $code eq 'FAIL';
817 }
818
819# node hack
820 if ($args{nodeid} && $args{nodeid} ne '') {
821 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
822 }
823# end node hack
824 $dbh->commit;
825 }; # end of eval
826 if ($@) {
827 $msg .= ": ".$@;
828 eval { $dbh->rollback; };
829 return ('FAIL',$msg);
830 } else {
831 return ('OK',"OK");
832 }
833
834 } else { # cidr != alloc_from
835
836 # Hard case. Allocation is smaller than free block.
837 my $wantmaskbits = $args{cidr}->masklen;
838 my $maskbits = $args{alloc_from}->masklen;
839
840 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
841
842 # This determines which blocks will be left "free" after allocation. We take the
843 # block we're allocating from, and split it in half. We see which half the wanted
844 # block is in, and repeat until the wanted block is equal to one of the halves.
845 my $i=0;
846 my $tmp_from = $args{alloc_from}; # So we don't munge $args{alloc_from}
847 while ($maskbits++ < $wantmaskbits) {
848 my @subblocks = $tmp_from->split($maskbits);
849 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
850 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
851 } # while
852
853 # Begin SQL transaction block
854 eval {
855 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
856
857 # Get old freeblocks parent/depth/routed for new entries
858 my ($fparent,$fcity,$wasrouted) = $dbh->selectrow_array("SELECT parent,city,routed FROM freeblocks".
859 " WHERE cidr=? AND rdepth=?", undef, ($args{alloc_from}, $args{rdepth}) );
860
861 # Delete old freeblocks entry
862 $dbh->do("DELETE FROM freeblocks WHERE cidr=? AND rdepth=?", undef, ($args{alloc_from}, $args{rdepth}) );
863
864 # Insert new list of smaller free blocks left over
865 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent,rdepth) VALUES (?,?,?,?,?,?)");
866 foreach my $block (@newfreeblocks) {
867 $sth->execute($block, $fcity, $wasrouted, $args{vrf}, $fparent, $args{rdepth});
868 }
869
870 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
871 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
872 my $rtype = $1;
873 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $args{cidr}, $args{rdepth}+1);
874 }
875
876 # Insert the allocations entry
877 $dbh->do("INSERT INTO allocations ".
878 "(cidr,parent,vrf,rdepth,custid,type,city,description,notes,circuitid,privdata)".
879 " VALUES (?,?,?,?,?,?,?,?,?,?,?)", undef,
880 ($args{cidr}, $fparent, $args{vrf}, $args{rdepth}, $args{custid}, $args{type}, $args{city},
881 $args{desc}, $args{notes}, $args{circid}, $args{privdata}) );
882
883 # And initialize the pool, if necessary
884 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
885 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
886 if ($args{type} =~ /^.p$/) {
887 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
888 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all");
889 die $rmsg if $code eq 'FAIL';
890 } elsif ($args{type} =~ /^.d$/) {
891 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
892 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal");
893 die $rmsg if $code eq 'FAIL';
894 }
895
896# node hack
897 if ($args{nodeid} && $args{nodeid} ne '') {
898 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
899 }
900# end node hack
901
902 $dbh->commit;
903 }; # end eval
904 if ($@) {
905 $msg .= ": ".$@;
906 eval { $dbh->rollback; };
907 return ('FAIL',$msg);
908 } else {
909 return ('OK',"OK");
910 }
911
912 } # end fullcidr != alloc_from
913
914 } # end static-IP vs netblock allocation
915
916} # end allocateBlock()
917
918
919## IPDB::initPool()
920# Initializes a pool
921# Requires a database handle, the pool CIDR, type, city, and a parameter
922# indicating whether the pool should allow allocation of literally every
923# IP, or if it should reserve network/gateway/broadcast IPs
924# Note that this is NOT done in a transaction, that's why it's a private
925# function and should ONLY EVER get called from allocateBlock()
926sub initPool {
927 my ($dbh,undef,$type,$city,$class) = @_;
928 my $pool = new NetAddr::IP $_[1];
929
930##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
931 $type =~ s/[pd]$/i/;
932 my $sth;
933 my $msg;
934
935 # Trap errors so we can pass them back to the caller. Even if the
936 # caller is only ever supposed to be local, and therefore already
937 # trapping errors. >:(
938 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
939 local $dbh->{RaiseError} = 1; # step on our toes by accident.
940
941 eval {
942 # have to insert all pool IPs into poolips table as "unallocated".
943 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
944 " values ('$pool', ?, '$defcustid', ?, '$type')");
945 my @poolip_list = $pool->hostenum;
946 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
947 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
948 $sth->execute($pool->addr, $city);
949 }
950 for (my $i=0; $i<=$#poolip_list; $i++) {
951 $sth->execute($poolip_list[$i]->addr, $city);
952 }
953 $pool--;
954 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
955 $sth->execute($pool->addr, $city);
956 }
957 } else { # (real netblock)
958 for (my $i=1; $i<=$#poolip_list; $i++) {
959 $sth->execute($poolip_list[$i]->addr, $city);
960 }
961 }
962 };
963 if ($@) {
964 $msg = $@." '".$sth->errstr."'";
965 eval { $dbh->rollback; };
966 return ('FAIL',$msg);
967 } else {
968 return ('OK',"OK");
969 }
970} # end initPool()
971
972
973## IPDB::updateBlock()
974# Update an allocation
975# Takes all allocation fields in a hash
976sub updateBlock {
977 my $dbh = shift;
978 my %args = @_;
979
980 return ('FAIL', 'Missing block to update') if !$args{block};
981
982 # do it all in a transaction
983 local $dbh->{AutoCommit} = 0;
984 local $dbh->{RaiseError} = 1;
985
986 my @fieldlist;
987 my @vallist;
988 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata') {
989 if ($args{$_}) {
990 push @fieldlist, $_;
991 push @vallist, $args{$_};
992 }
993 }
994
995 my $updtable = 'allocations';
996 my $keyfield = 'cidr';
997 if ($args{type} =~ /^(.)i$/) {
998 $updtable = 'poolips';
999 $keyfield = 'ip';
1000 } else {
1001## fixme: there's got to be a better way...
1002 if ($args{swip}) {
1003 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1004 $args{swip} = 'y';
1005 } else {
1006 $args{swip} = 'n';
1007 }
1008 }
1009 foreach ('type', 'swip') {
1010 if ($args{$_}) {
1011 push @fieldlist, $_;
1012 push @vallist, $args{$_};
1013 }
1014 }
1015 }
1016
1017 return ('FAIL', 'No fields to update') if !@fieldlist;
1018
1019 push @vallist, $args{block};
1020 my $sql = "UPDATE $updtable SET ";
1021 $sql .= join " = ?, ", @fieldlist;
1022 $sql .= " = ? WHERE $keyfield = ?";
1023
1024 eval {
1025 # do the update
1026 $dbh->do($sql, undef, @vallist);
1027
1028 if ($args{node}) {
1029 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1030 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
1031 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
1032 }
1033
1034 $dbh->commit;
1035 };
1036 if ($@) {
1037 my $msg = $@;
1038 $dbh->rollback;
1039 return ('FAIL', $msg);
1040 }
1041 return 0;
1042} # end updateBlock()
1043
1044
1045## IPDB::deleteBlock()
1046# Removes an allocation from the database, including deleting IPs
1047# from poolips and recombining entries in freeblocks if possible
1048# Also handles "deleting" a static IP allocation, and removal of a master
1049# Requires a database handle, the block to delete, the routing depth (if applicable),
1050# and the VRF ID
1051sub deleteBlock {
1052 my ($dbh,undef,$rdepth,$vrf) = @_;
1053 my $cidr = new NetAddr::IP $_[1];
1054
1055# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1056# is_rfc1918 requires NetAddr::IP >= 4.059
1057# rather than doing this over and over and over.....
1058 my $tmpnum = $cidr->numeric;
1059# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1060# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1061# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1062 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1063 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1064 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1065
1066 my $sth;
1067
1068 # Magic variables used for odd allocation cases.
1069 my $container;
1070 my $con_type;
1071
1072 # Collect info about the block we're going to delete
1073 my $binfo = getBlockData($dbh, $cidr, $rdepth, $vrf);
1074
1075 # temporarily forced null, until a sane UI for VRF tracking can be found.
1076 $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
1077
1078 # To contain the error message, if any.
1079 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1080 my $goback; # to put the parent in so we can link back where the deallocate started
1081
1082 # Enable transactions and exception-on-errors... but only for this sub
1083 local $dbh->{AutoCommit} = 0;
1084 local $dbh->{RaiseError} = 1;
1085
1086 # First case. The "block" is a static IP
1087 # Note that we still need some additional code in the odd case
1088 # of a netblock-aligned contiguous group of static IPs
1089 if ($binfo->{type} =~ /^.i$/) {
1090
1091 eval {
1092 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1093 my ($pool,$pcust,$pvrf) = $dbh->selectrow_array("SELECT pool,custid,vrf FROM poolips WHERE ip=?", undef, ($cidr) );
1094##fixme: VRF and rdepth
1095 $dbh->do("UPDATE poolips SET custid=?,available='y',".
1096 "city=(SELECT city FROM allocations WHERE cidr=?),".
1097 "description='',notes='',circuitid='',vrf=? WHERE ip=?", undef, ($pcust, $pool, $pvrf, $cidr) );
1098 $goback = $pool;
1099 $dbh->commit;
1100 };
1101 if ($@) {
1102 $msg .= ": $@";
1103 eval { $dbh->rollback; };
1104 return ('FAIL',$msg);
1105 } else {
1106 return ('OK',"OK");
1107 }
1108
1109 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
1110
1111##fixme: VRF limit
1112 $msg = "Unable to delete master block $cidr";
1113 eval {
1114 $dbh->do("DELETE FROM masterblocks WHERE cidr = ?", undef, ($cidr) );
1115 $dbh->do("DELETE FROM allocations WHERE cidr <<= ?", undef, ($cidr) );
1116 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ?", undef, ($cidr) );
1117 $dbh->commit;
1118 };
1119 if ($@) {
1120 $msg .= ": $@";
1121 eval { $dbh->rollback; };
1122 return ('FAIL', $msg);
1123 } else {
1124 return ('OK',"OK");
1125 }
1126
1127 } else { # end alloctype master block case
1128
1129 ## This is a big block; but it HAS to be done in a chunk. Any removal
1130 ## of a netblock allocation may result in a larger chunk of free
1131 ## contiguous IP space - which may in turn be combined into a single
1132 ## netblock rather than a number of smaller netblocks.
1133
1134 my $retcode = 'OK';
1135
1136 eval {
1137
1138##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1139# explicitly deleting any suballocations of the block to be deleted.
1140
1141 # find the current parent of the block we're deleting
1142 my ($parent) = $dbh->selectrow_array("SELECT parent FROM allocations WHERE cidr=? AND rdepth=?",
1143 undef, ($cidr, $rdepth) );
1144
1145 # Delete the block
1146 $dbh->do("DELETE FROM allocations WHERE cidr=? AND rdepth=?", undef, ($cidr, $rdepth) );
1147
1148##fixme: we could maybe eliminate a special case if we put masterblocks in the allocations table...?
1149 my ($ptype,$pcity);
1150 if ($rdepth == 1) {
1151 # parent is a master block.
1152 $ptype = 'mm';
1153 $pcity = '<NULL>';
1154 } else {
1155 # get that parent's details
1156 ($ptype,$pcity) = $dbh->selectrow_array("SELECT type,city FROM allocations ".
1157 "WHERE cidr=? AND rdepth=?", undef, ($parent, $rdepth-1) );
1158 }
1159
1160 # munge the parent type a little
1161 $ptype = (split //, $ptype)[0];
1162
1163##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1164# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1165# -> $isprivnet flag from start of sub
1166
1167 my $fbrdepth = $rdepth;
1168
1169 # check to see if any container allocations could be the "true" parent
1170 my ($tparent,$trdepth,$trtype,$tcity) = $dbh->selectrow_array("SELECT cidr,rdepth,type,city FROM allocations ".
1171 "WHERE (type='rm' OR type LIKE '_c') AND cidr >> ? ".
1172 "ORDER BY masklen(cidr) DESC", undef, ($cidr) );
1173
1174 my $fparent;
1175 if ($tparent && $tparent ne $parent) {
1176 # found an alternate parent; reset some parent-info bits
1177 $parent = $tparent;
1178 $ptype = (split //, $trtype)[0];
1179 $pcity = $tcity;
1180 ##fixme: hmm. collect $rdepth into $goback here before vanishing?
1181 $retcode = 'WARN'; # may be redundant
1182 $goback = $tparent;
1183 # munge freeblock rdepth and parent to match true parent
1184 $dbh->do("UPDATE freeblocks SET rdepth = ?, parent = ?, routed = ? WHERE cidr <<= ? AND rdepth = ?", undef,
1185 ($trdepth+1, $parent, $ptype, $cidr, $rdepth) );
1186 $rdepth = $trdepth;
1187 $fbrdepth = $trdepth+1;
1188 }
1189
1190 $parent = new NetAddr::IP $parent;
1191 $goback = "$parent,$fbrdepth"; # breadcrumb in case of live-parent-is-not-true-parent
1192
1193 # Special case - delete pool IPs
1194 if ($binfo->{type} =~ /^.[pd]$/) {
1195 # We have to delete the IPs from the pool listing.
1196##fixme: rdepth? vrf?
1197 $dbh->do("DELETE FROM poolips WHERE pool = ?", undef, ($cidr) );
1198 }
1199
1200 # Find out if the block we're deallocating is within a DSL pool (legacy goo)
1201 my ($pool,$poolcity,$pooltype,$pooldepth) = $dbh->selectrow_array(
1202 "SELECT cidr,city,type,rdepth FROM allocations WHERE type LIKE '_p' AND cidr >>= ?",
1203 undef, ($cidr) );
1204
1205 # If so, return the block's IPs to the pool, instead of to freeblocks
1206## NB: not possible to currently cause this even via admin tools, only legacy data.
1207 if ($pool) {
1208 ## Deallocate legacy blocks stashed in the middle of a static IP pool
1209 ## This may be expandable to an even more general case of contained netblock, or other pool types.
1210 $retcode = 'WARNPOOL';
1211 $goback = "$pool,$pooldepth";
1212 # We've already deleted the block, now we have to stuff its IPs into the pool.
1213 $pooltype =~ s/p$/i/; # change type to static IP
1214 my $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) VALUES ".
1215 "('$pool',?,'$poolcity','$pooltype','$defcustid')");
1216 # don't insert .0
1217##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1218 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1219 foreach my $ip ($cidr->hostenum) {
1220 $sth2->execute($ip);
1221 }
1222 $cidr--;
1223 # don't insert .255
1224 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1225 } else { # done returning IPs from a block to a static DSL pool
1226
1227 # If the block wasn't legacy goo embedded in a static pool, we check the
1228 # freeblocks in the identified parent to see if we can combine any of them.
1229
1230 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1231 if ($binfo->{type} =~ /^.[mc]/) {
1232 # move the freeblocks into the parent
1233 # we don't insert a new freeblock because there could be a live reparented sub.
1234 $dbh->do("UPDATE freeblocks SET rdepth=rdepth-1,parent=?,routed=?,city=? ".
1235 "WHERE parent=? AND rdepth=?", undef,
1236 ($parent, $ptype, $pcity, $cidr, $rdepth+1) );
1237 } else {
1238 # ... otherwise, add the freeblock
1239 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent, rdepth) VALUES (?,?,?,?,?)", undef,
1240 ($cidr, $pcity, $ptype, $parent, $rdepth) );
1241 }
1242
1243##fixme: vrf
1244 # set up the query to get the list of blocks to try to merge.
1245 $sth = $dbh->prepare("SELECT cidr FROM freeblocks ".
1246 "WHERE parent = ? AND routed = ? AND rdepth = ? ".
1247 "ORDER BY masklen(cidr) DESC");
1248
1249 $sth->execute($parent, $ptype, $fbrdepth);
1250
1251# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1252# from the caller and the passed terms.
1253# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1254# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1255# .64-.95, and .96-.128), you will get an array containing a single
1256# /25 as element 0 (.0-.127). Order is not important; you could have
1257# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1258
1259 my (@rawfb, @combinelist);
1260 my $i=0;
1261 # for each free block under $parent, push a NetAddr::IP object into one list, and
1262 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
1263 while (my @data = $sth->fetchrow_array) {
1264 my $testIP = new NetAddr::IP $data[0];
1265 push @rawfb, $testIP;
1266 @combinelist = $testIP->compact(@combinelist);
1267 }
1268
1269 # now that we have the full list of "compacted" freeblocks, go back over
1270 # the list of raw freeblocks, and delete the ones that got merged.
1271 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr=? AND parent=? AND rdepth=?");
1272 foreach my $rawfree (@rawfb) {
1273 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
1274 $sth->execute($rawfree, $parent, $fbrdepth);
1275 }
1276
1277 # now we walk the new list of compacted blocks, and see which ones we need to insert
1278 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent,rdepth) VALUES (?,?,?,?,?)");
1279 foreach my $cme (@combinelist) {
1280 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
1281 $sth->execute($cme, $pcity, $ptype, $parent, $fbrdepth);
1282 }
1283
1284 } # done returning IPs to the appropriate place
1285
1286 # If we got here, we've succeeded. Whew!
1287 $dbh->commit;
1288 }; # end eval
1289 if ($@) {
1290 $msg .= ": $@";
1291 eval { $dbh->rollback; };
1292 return ('FAIL', $msg);
1293 } else {
1294 return ($retcode, $goback);
1295 }
1296
1297 } # end alloctype != netblock
1298
1299} # end deleteBlock()
1300
1301
1302## IPDB::getBlockData()
1303# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
1304# private/restricted data, for a CIDR block or pool IP
1305# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
1306# Takes the block/IP to look up, routing depth, and VRF identifier
1307# Returns a hashref to the block data
1308sub getBlockData {
1309 my $dbh = shift;
1310 my $block = shift;
1311 my $rdepth = shift;
1312 my $vrf = shift || '';
1313
1314 my $cidr = new NetAddr::IP $block;
1315
1316 # better way to find IP allocations vs /32 "netblocks"
1317 my $btype = $dbh->selectrow_array("SELECT type FROM searchme WHERE cidr=?", undef, ($block) );
1318
1319 if (defined($rdepth) && $rdepth == 0) {
1320 # Only master blocks exist at rdepth 0
1321 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, 'mm' AS type, 0 AS parent, cidr,".
1322 " ctime, mtime, rwhois, vrf".
1323 " FROM masterblocks WHERE cidr = ? AND vrf = ?", undef, ($block, $vrf) );
1324 return $binfo;
1325 } elsif ($btype =~ /^.i$/) {
1326 my $binfo = $dbh->selectrow_hashref("SELECT ip AS block, custid, type, city, circuitid, description,".
1327 " notes, modifystamp AS lastmod, privdata, vrf, pool, rdepth".
1328 " FROM poolips WHERE ip = ? AND vrf = ?", undef, ($block, $vrf) );
1329 return $binfo;
1330 } else {
1331 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, parent, custid, type, city, circuitid, ".
1332 "description, notes, modifystamp AS lastmod, privdata, vrf, swip, rdepth".
1333 " FROM allocations WHERE cidr = ? AND rdepth = ?", undef, ($block, $rdepth) );
1334# " FROM allocations WHERE cidr = ? AND rdepth = ? AND vrf = ?", undef, ($block, $rdepth, $vrf) );
1335 return $binfo;
1336 }
1337} # end getBlockData()
1338
1339
1340## IPDB::getNodeList()
1341# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1342sub getNodeList {
1343 my $dbh = shift;
1344
1345 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1346 { Slice => {} });
1347 return $ret;
1348} # end getNodeList()
1349
1350
1351## IPDB::getNodeName()
1352# Get node name from the ID
1353sub getNodeName {
1354 my $dbh = shift;
1355 my $nid = shift;
1356
1357 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1358 return $nname;
1359} # end getNodeName()
1360
1361
1362## IPDB::getNodeInfo()
1363# Get node name and ID associated with a block
1364sub getNodeInfo {
1365 my $dbh = shift;
1366 my $block = shift;
1367
1368 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1369 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1370 return ($nid, $nname);
1371} # end getNodeInfo()
1372
1373
1374## IPDB::mailNotify()
1375# Sends notification mail to recipients regarding an IPDB operation
1376sub mailNotify {
1377 my $dbh = shift;
1378 my ($action,$subj,$message) = @_;
1379
1380 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1381
1382##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1383
1384# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
1385 my @actionbits = split //, $action;
1386
1387 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1388 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1389 # and "all events with this action"
1390 my @actionsets = ($action);
1391##fixme: ick, eww. really gotta find a better way to handle this...
1392 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1393 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1394
1395 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1396
1397 # get recip list from db
1398 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1399
1400 my %reciplist;
1401 foreach (@actionsets) {
1402 $sth->execute($_);
1403##fixme - need to handle db errors
1404 my ($recipsub) = $sth->fetchrow_array;
1405 next if !$recipsub;
1406 foreach (split(/,/, $recipsub)) {
1407 $reciplist{$_}++;
1408 }
1409 }
1410
1411 return if !%reciplist;
1412
1413 foreach my $recip (keys %reciplist) {
1414 $mailer->mail("ipdb\@$domain");
1415 $mailer->to($recip);
1416 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1417 "To: $recip\n",
1418 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1419 "Subject: {IPDB} $subj\n",
1420 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1421 "Organization: $org_name\n",
1422 "\n$message\n");
1423 }
1424 $mailer->quit;
1425}
1426
1427# Indicates module loaded OK. Required by Perl.
14281;
Note: See TracBrowser for help on using the repository browser.