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

Last change on this file since 560 was 560, checked in by Kris Deugau, 12 years ago

/trunk

Work in progress, see #5:
Update listSummary() for new table logic and fields

  • Property svn:keywords set to Date Rev Author
File size: 48.0 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:03:38 +0000 (Wed, 19 Dec 2012) $
6# SVN revision $Rev: 560 $
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 &listMaster &listRBlock &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 &listMaster &listRBlock &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::listMaster()
364# Get list of routed blocks in the requested master
365# Returns an arrayref to a list of hashrefs containing the routed block, POP/city the block is routed to,
366# allocated count, free count, and largest free block masklength
367sub listMaster {
368 my $dbh = shift;
369 my $master = shift;
370
371 my $rlist = $dbh->selectall_arrayref("SELECT cidr AS block,city FROM routed WHERE cidr <<= ? ORDER BY cidr",
372 { Slice => {} }, ($master) );
373
374 foreach (@{$rlist}) {
375 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{block}));
376 $$_{nsubs} = $acnt;
377 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
378 " AND (routed='y' OR routed='n')", undef, ($$_{block}));
379 $$_{nfree} = $fcnt;
380 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
381 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{block}));
382##fixme: should find a way to do this without having to HTMLize the <>
383 $bigfree = "/$bigfree" if $bigfree;
384 $bigfree = '<NONE>' if !$bigfree;
385 $$_{lfree} = $bigfree;
386 }
387 return $rlist;
388} # end listMaster()
389
390
391## IPDB::listRBlock()
392# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
393# Takes a parent/master and an optional flag to look at routed or unrouted blocks, depending
394# on whether the master is a direct master or a routed block
395# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
396sub listRBlock {
397 my $dbh = shift;
398 my $routed = shift;
399
400 # Snag the allocations for this block
401 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
402 " FROM allocations WHERE cidr <<= ? ORDER BY cidr");
403 $sth->execute($routed);
404
405 # hack hack hack
406 # set up to flag swip=y records if they don't actually have supporting data in the customers table
407 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
408
409 my @blocklist;
410 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
411 $custsth->execute($custid);
412 my ($ncust) = $custsth->fetchrow_array();
413 my %row = (
414 block => $cidr,
415 city => $city,
416 type => $disp_alloctypes{$type},
417 custid => $custid,
418 swip => ($swip eq 'y' ? 'Yes' : 'No'),
419 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
420 desc => $desc
421 );
422 $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
423 $row{listpool} = ($type =~ /^.[pd]$/);
424 push (@blocklist, \%row);
425 }
426 return \@blocklist;
427} # end listRBlock()
428
429
430## IPDB::listFree()
431# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
432# Takes a parent/master and an optional "routed or unrouted" flag that defaults to unrouted.
433# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
434# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
435sub listFree {
436 my $dbh = shift;
437 my $master = shift;
438 my $routed = shift || 'n';
439
440 # do it this way so we can waste a little less time iterating
441 my $sth = $dbh->prepare("SELECT cidr,routed FROM freeblocks WHERE cidr <<= ? AND ".
442 ($routed eq 'n' ? '' : 'NOT')." routed = 'n' ORDER BY cidr");
443 $sth->execute($master);
444 my @flist;
445 while (my ($cidr,$rtype) = $sth->fetchrow_array()) {
446 $cidr = new NetAddr::IP $cidr;
447 my %row = (
448 fblock => "$cidr",
449 frange => $cidr->range,
450 );
451 if ($routed eq 'y') {
452 $row{subblock} = ($rtype ne 'y' && $rtype ne 'n');
453 $row{fbtype} = $rtype;
454 }
455 push @flist, \%row;
456 }
457 return \@flist;
458} # end listFree()
459
460
461## IPDB::listPool()
462#
463sub listPool {
464 my $dbh = shift;
465 my $pool = shift;
466
467 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type".
468 " FROM poolips WHERE pool = ? ORDER BY ip");
469 $sth->execute($pool);
470 my @poolips;
471 while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
472 my %row = (
473 ip => $ip,
474 custid => $custid,
475 available => $available,
476 desc => $desc,
477 delme => $available eq 'n'
478 );
479 push @poolips, \%row;
480 }
481 return \@poolips;
482} # end listPool()
483
484
485## IPDB::getMasterList()
486# Get a list of master blocks, optionally including last-modified timestamps
487# Takes an optional flag to indicate whether to include timestamps;
488# 'm' includes ctime, all others (suggest 'c') do not.
489# Returns an arrayref to a list of hashrefs
490sub getMasterList {
491 my $dbh = shift;
492 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
493
494 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master".($stampme eq 'm' ? ',mtime' : '').
495 " FROM masterblocks ORDER BY cidr", { Slice => {} });
496 return $mlist;
497} # end getMasterList()
498
499
500## IPDB::getTypeList()
501# Get an alloctype/description pair list suitable for dropdowns
502# Takes a flag to determine which general groups of types are returned
503# Returns an reference to an array of hashrefs
504sub getTypeList {
505 my $dbh = shift;
506 my $tgroup = shift || 'a'; # technically optional, like this, but should
507 # really be specified in the call for clarity
508 my $tlist;
509 if ($tgroup eq 'p') {
510 # grouping 'p' - primary allocation types. These include static IP pools (_d and _p),
511 # dynamic-allocation ranges (_e), containers (_c), and the "miscellaneous" cn, in, and en types.
512 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder < 500 ".
513 "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
514 } elsif ($tgroup eq 'c') {
515 # grouping 'c' - contained types. These include all static IPs and all _r types.
516 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
517 " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
518 } else {
519 # grouping 'a' - all standard allocation types. This includes everything
520 # but mm (present only as a formality). Make this the default.
521 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
522 " ORDER BY listorder", { Slice => {} });
523 }
524 return $tlist;
525}
526
527
528## IPDB::getPoolSelect()
529# Get a list of pools matching the passed city and type that have 1 or more free IPs
530# Returns an arrayref to a list of hashrefs
531sub getPoolSelect {
532 my $dbh = shift;
533 my $iptype = shift;
534 my $pcity = shift;
535
536 my ($ptype) = ($iptype =~ /^(.)i$/);
537 return if !$ptype;
538 $ptype .= '_';
539
540 my $plist = $dbh->selectall_arrayref(
541 "SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool) AS poolcit, ".
542 "poolips.pool AS poolblock, COUNT(*) AS poolfree FROM poolips,allocations ".
543 "WHERE poolips.available='y' AND poolips.pool=allocations.cidr ".
544 "AND allocations.city = ? AND poolips.type LIKE ? ".
545 "GROUP BY pool", { Slice => {} }, ($pcity, $ptype) );
546 return $plist;
547} # end getPoolSelect()
548
549
550## IPDB::findAllocateFrom()
551# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
552# Takes
553# - mask length
554# - allocation type
555# - POP city "parent"
556# - optional master-block restriction
557# - optional flag to allow automatic pick-from-private-network-ranges
558# Returns a string with the first CIDR block matching the criteria, if any
559sub findAllocateFrom {
560 my $dbh = shift;
561 my $maskbits = shift;
562 my $type = shift;
563 my $city = shift;
564 my $pop = shift;
565 my %optargs = @_;
566
567 my $failmsg = "No suitable free block found\n";
568
569## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
570## Very large systems will require development of a reserve system (possibly an extension
571## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
572## Also populate a value list for the DBI call.
573
574 my @vallist = ($maskbits, ($type eq 'rm' ? 'n' : ($type =~ /^(.)r$/ ? "$1" : 'y')) );
575 my $sql = "SELECT cidr FROM freeblocks WHERE maskbits <= ? AND routed = ?";
576
577 # for PPP(oE) and container types, the POP city is the one attached to the pool.
578 # individual allocations get listed with the customer city site.
579 ##fixme: chain cities to align roughly with a full layer-2 node graph
580 $city = $pop if $type !~ /^.[pc]$/;
581 if ($type ne 'rm' && $city) {
582 $sql .= " AND city = ?";
583 push @vallist, $city;
584 }
585 # Allow specifying an arbitrary full block, instead of a master
586 if ($optargs{gimme}) {
587 $sql .= " AND cidr >>= ?";
588 push @vallist, $optargs{gimme};
589 }
590 # if a specific master was requested, allow the requestor to self->shoot(foot)
591 if ($optargs{master} && $optargs{master} ne '-') {
592 $sql .= " AND cidr <<= ?" if $optargs{master} ne '-';
593 push @vallist, $optargs{master};
594 } else {
595 # if a specific master was NOT requested, filter out the RFC 1918 private networks
596 if (!$optargs{allowpriv}) {
597 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
598 }
599 }
600 # Sorting and limiting, since we don't (currently) care to provide a selection of
601 # blocks to carve up. This preserves something resembling optimal usage of the IP
602 # space by forcing contiguous allocations and free blocks as much as possible.
603 $sql .= " ORDER BY maskbits DESC,cidr LIMIT 1";
604
605 my ($fbfound) = $dbh->selectrow_array($sql, undef, @vallist);
606 return $fbfound;
607} # end findAllocateFrom()
608
609
610## IPDB::ipParent()
611# Get an IP's parent pool's details
612# Takes a database handle and IP
613# Returns a hashref to the parent pool block, if any
614sub ipParent {
615 my $dbh = shift;
616 my $block = shift;
617
618 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
619 " WHERE cidr >>= ?", undef, ($block) );
620 return $pinfo;
621} # end ipParent()
622
623
624## IPDB::subParent()
625# Get a block's parent's details
626# Takes a database handle and CIDR block
627# Returns a hashref to the parent container block, if any
628sub subParent {
629 my $dbh = shift;
630 my $block = shift;
631
632 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
633 " WHERE cidr >>= ?", undef, ($block) );
634 return $pinfo;
635} # end subParent()
636
637
638## IPDB::blockParent()
639# Get a block's parent's details
640# Takes a database handle and CIDR block
641# Returns a hashref to the parent container block, if any
642sub blockParent {
643 my $dbh = shift;
644 my $block = shift;
645
646 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
647 " WHERE cidr >>= ?", undef, ($block) );
648 return $pinfo;
649} # end blockParent()
650
651
652## IPDB::getRoutedCity()
653# Get the city for a routed block.
654sub getRoutedCity {
655 my $dbh = shift;
656 my $block = shift;
657
658 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
659 return $rcity;
660} # end getRoutedCity()
661
662
663## IPDB::allocateBlock()
664# Does all of the magic of actually allocating a netblock
665# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
666# type, city, block to allocate from, and optionally a description, notes, circuit ID,
667# and private data
668# Returns a success code and optional error message.
669sub allocateBlock {
670 my $dbh = shift;
671
672 my %args = @_;
673
674 $args{cidr} = new NetAddr::IP $args{cidr};
675 $args{alloc_from} = new NetAddr::IP $args{alloc_from};
676
677 $args{desc} = '' if !$args{desc};
678 $args{notes} = '' if !$args{notes};
679 $args{circid} = '' if !$args{circid};
680 $args{privdata} = '' if !$args{privdata};
681 $args{vrf} = '' if !$args{vrf};
682
683 my $sth;
684
685 # Snag the "type" of the freeblock (alloc_from) "just in case"
686 $sth = $dbh->prepare("select routed from freeblocks where cidr='$args{alloc_from}'");
687 $sth->execute;
688 my ($alloc_from_type) = $sth->fetchrow_array;
689
690 # To contain the error message, if any.
691 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
692
693 # Enable transactions and error handling
694 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
695 local $dbh->{RaiseError} = 1; # step on our toes by accident.
696
697 if ($args{type} =~ /^.i$/) {
698 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
699 eval {
700 if ($args{cidr}) { # IP specified
701 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
702 die "IP is not in an IP pool.\n"
703 if !$isavail;
704 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
705 if $isavail eq 'n';
706 } else { # IP not specified, take first available
707 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
708 undef, ($args{alloc_from}) );
709 }
710 $dbh->do("UPDATE poolips SET custid=?,city=?,available='n',description=?,notes=?,circuitid=?,privdata=?,vrf=? ".
711 "WHERE ip=?", undef, ($args{custid}, $args{city}, $args{desc}, $args{notes}, $args{circid},
712 $args{privdata}, $args{vrf}, $args{cidr}) );
713
714# node hack
715 if ($args{nodeid} && $args{nodeid} ne '') {
716 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
717 }
718# end node hack
719
720 $dbh->commit;
721 };
722 if ($@) {
723 $msg .= ": $@";
724 eval { $dbh->rollback; };
725 return ('FAIL',$msg);
726 } else {
727 return ('OK',"$args{cidr}");
728 }
729
730 } else { # end IP-from-pool allocation
731
732 if ($args{cidr} == $args{alloc_from}) {
733 # Easiest case- insert in one table, delete in the other, and go home. More or less.
734 # insert into allocations values (cidr,custid,type,city,desc) and
735 # delete from freeblocks where cidr='cidr'
736 # For data safety on non-transaction DBs, we delete first.
737
738 eval {
739 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
740
741 # Get old freeblocks parent/depth/routed for new entries... before we delete it.
742 my ($fparent) = $dbh->selectrow_array("SELECT parent FROM freeblocks WHERE cidr=? AND rdepth=?",
743 undef, ($args{alloc_from}, $args{rdepth}) );
744
745 # Munge freeblocks
746 if ($args{type} =~ /^(.)[mc]$/) {
747 # special case - block is a routed or container/"reserve" block
748 my $rtype = $1;
749 $dbh->do("UPDATE freeblocks SET routed=?,rdepth=rdepth+1,city=?,parent=? WHERE cidr=? AND rdepth=?",
750 undef, ($rtype, $args{city}, $args{cidr}, $args{cidr}, $args{rdepth}));
751 } else {
752 # "normal" case
753 $dbh->do("DELETE FROM freeblocks WHERE cidr=? AND rdepth=?", undef, ($args{cidr}, $args{rdepth}));
754 }
755
756 # Insert the allocations entry
757 $dbh->do("INSERT INTO allocations ".
758 "(cidr,parent,vrf,rdepth,custid,type,city,description,notes,circuitid,privdata)".
759 " VALUES (?,?,?,?,?,?,?,?,?,?,?)", undef,
760 ($args{cidr}, $fparent, $args{vrf}, $args{rdepth}, $args{custid}, $args{type}, $args{city},
761 $args{desc}, $args{notes}, $args{circid}, $args{privdata}) );
762
763 # And initialize the pool, if necessary
764 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
765 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
766 if ($args{type} =~ /^.p$/) {
767 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
768 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all");
769 die $rmsg if $code eq 'FAIL';
770 } elsif ($args{type} =~ /^.d$/) {
771 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
772 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal");
773 die $rmsg if $code eq 'FAIL';
774 }
775
776# node hack
777 if ($args{nodeid} && $args{nodeid} ne '') {
778 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
779 }
780# end node hack
781 $dbh->commit;
782 }; # end of eval
783 if ($@) {
784 $msg .= ": ".$@;
785 eval { $dbh->rollback; };
786 return ('FAIL',$msg);
787 } else {
788 return ('OK',"OK");
789 }
790
791 } else { # cidr != alloc_from
792
793 # Hard case. Allocation is smaller than free block.
794 my $wantmaskbits = $args{cidr}->masklen;
795 my $maskbits = $args{alloc_from}->masklen;
796
797 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
798
799 # This determines which blocks will be left "free" after allocation. We take the
800 # block we're allocating from, and split it in half. We see which half the wanted
801 # block is in, and repeat until the wanted block is equal to one of the halves.
802 my $i=0;
803 my $tmp_from = $args{alloc_from}; # So we don't munge $args{alloc_from}
804 while ($maskbits++ < $wantmaskbits) {
805 my @subblocks = $tmp_from->split($maskbits);
806 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
807 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
808 } # while
809
810 # Begin SQL transaction block
811 eval {
812 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
813
814 # Get old freeblocks parent/depth/routed for new entries
815 my ($fparent,$fcity,$wasrouted) = $dbh->selectrow_array("SELECT parent,city,routed FROM freeblocks".
816 " WHERE cidr=? AND rdepth=?", undef, ($args{alloc_from}, $args{rdepth}) );
817
818 # Delete old freeblocks entry
819 $dbh->do("DELETE FROM freeblocks WHERE cidr=? AND rdepth=?", undef, ($args{alloc_from}, $args{rdepth}) );
820
821 # Insert new list of smaller free blocks left over
822 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent,rdepth) VALUES (?,?,?,?,?,?)");
823 foreach my $block (@newfreeblocks) {
824 $sth->execute($block, $fcity, $wasrouted, $args{vrf}, $fparent, $args{rdepth});
825 }
826
827 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
828 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
829 my $rtype = $1;
830 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $args{cidr}, $args{rdepth}+1);
831 }
832
833 # Insert the allocations entry
834 $dbh->do("INSERT INTO allocations ".
835 "(cidr,parent,vrf,rdepth,custid,type,city,description,notes,circuitid,privdata)".
836 " VALUES (?,?,?,?,?,?,?,?,?,?,?)", undef,
837 ($args{cidr}, $fparent, $args{vrf}, $args{rdepth}, $args{custid}, $args{type}, $args{city},
838 $args{desc}, $args{notes}, $args{circid}, $args{privdata}) );
839
840 # And initialize the pool, if necessary
841 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
842 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
843 if ($args{type} =~ /^.p$/) {
844 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
845 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all");
846 die $rmsg if $code eq 'FAIL';
847 } elsif ($args{type} =~ /^.d$/) {
848 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
849 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal");
850 die $rmsg if $code eq 'FAIL';
851 }
852
853# node hack
854 if ($args{nodeid} && $args{nodeid} ne '') {
855 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
856 }
857# end node hack
858
859 $dbh->commit;
860 }; # end eval
861 if ($@) {
862 $msg .= ": ".$@;
863 eval { $dbh->rollback; };
864 return ('FAIL',$msg);
865 } else {
866 return ('OK',"OK");
867 }
868
869 } # end fullcidr != alloc_from
870
871 } # end static-IP vs netblock allocation
872
873} # end allocateBlock()
874
875
876## IPDB::initPool()
877# Initializes a pool
878# Requires a database handle, the pool CIDR, type, city, and a parameter
879# indicating whether the pool should allow allocation of literally every
880# IP, or if it should reserve network/gateway/broadcast IPs
881# Note that this is NOT done in a transaction, that's why it's a private
882# function and should ONLY EVER get called from allocateBlock()
883sub initPool {
884 my ($dbh,undef,$type,$city,$class) = @_;
885 my $pool = new NetAddr::IP $_[1];
886
887##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
888 $type =~ s/[pd]$/i/;
889 my $sth;
890 my $msg;
891
892 # Trap errors so we can pass them back to the caller. Even if the
893 # caller is only ever supposed to be local, and therefore already
894 # trapping errors. >:(
895 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
896 local $dbh->{RaiseError} = 1; # step on our toes by accident.
897
898 eval {
899 # have to insert all pool IPs into poolips table as "unallocated".
900 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
901 " values ('$pool', ?, '$defcustid', ?, '$type')");
902 my @poolip_list = $pool->hostenum;
903 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
904 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
905 $sth->execute($pool->addr, $city);
906 }
907 for (my $i=0; $i<=$#poolip_list; $i++) {
908 $sth->execute($poolip_list[$i]->addr, $city);
909 }
910 $pool--;
911 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
912 $sth->execute($pool->addr, $city);
913 }
914 } else { # (real netblock)
915 for (my $i=1; $i<=$#poolip_list; $i++) {
916 $sth->execute($poolip_list[$i]->addr, $city);
917 }
918 }
919 };
920 if ($@) {
921 $msg = $@." '".$sth->errstr."'";
922 eval { $dbh->rollback; };
923 return ('FAIL',$msg);
924 } else {
925 return ('OK',"OK");
926 }
927} # end initPool()
928
929
930## IPDB::updateBlock()
931# Update an allocation
932# Takes all allocation fields in a hash
933sub updateBlock {
934 my $dbh = shift;
935 my %args = @_;
936
937 return ('FAIL', 'Missing block to update') if !$args{block};
938
939 # do it all in a transaction
940 local $dbh->{AutoCommit} = 0;
941 local $dbh->{RaiseError} = 1;
942
943 my @fieldlist;
944 my @vallist;
945 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata') {
946 if ($args{$_}) {
947 push @fieldlist, $_;
948 push @vallist, $args{$_};
949 }
950 }
951
952 my $updtable = 'allocations';
953 my $keyfield = 'cidr';
954 if ($args{type} =~ /^(.)i$/) {
955 $updtable = 'poolips';
956 $keyfield = 'ip';
957 } else {
958## fixme: there's got to be a better way...
959 if ($args{swip}) {
960 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
961 $args{swip} = 'y';
962 } else {
963 $args{swip} = 'n';
964 }
965 }
966 foreach ('type', 'swip') {
967 if ($args{$_}) {
968 push @fieldlist, $_;
969 push @vallist, $args{$_};
970 }
971 }
972 }
973
974 return ('FAIL', 'No fields to update') if !@fieldlist;
975
976 push @vallist, $args{block};
977 my $sql = "UPDATE $updtable SET ";
978 $sql .= join " = ?, ", @fieldlist;
979 $sql .= " = ? WHERE $keyfield = ?";
980
981 eval {
982 # do the update
983 $dbh->do($sql, undef, @vallist);
984
985 if ($args{node}) {
986 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
987 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
988 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
989 }
990
991 $dbh->commit;
992 };
993 if ($@) {
994 my $msg = $@;
995 $dbh->rollback;
996 return ('FAIL', $msg);
997 }
998 return 0;
999} # end updateBlock()
1000
1001
1002## IPDB::deleteBlock()
1003# Removes an allocation from the database, including deleting IPs
1004# from poolips and recombining entries in freeblocks if possible
1005# Also handles "deleting" a static IP allocation, and removal of a master
1006# Requires a database handle, the block to delete, the routing depth (if applicable),
1007# and the VRF ID
1008sub deleteBlock {
1009 my ($dbh,undef,$rdepth,$vrf) = @_;
1010 my $cidr = new NetAddr::IP $_[1];
1011
1012# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1013# is_rfc1918 requires NetAddr::IP >= 4.059
1014# rather than doing this over and over and over.....
1015 my $tmpnum = $cidr->numeric;
1016# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1017# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1018# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1019 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1020 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1021 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1022
1023 my $sth;
1024
1025 # Magic variables used for odd allocation cases.
1026 my $container;
1027 my $con_type;
1028
1029 # Collect info about the block we're going to delete
1030 my $binfo = getBlockData($dbh, $cidr, $rdepth, $vrf);
1031
1032 # temporarily forced null, until a sane UI for VRF tracking can be found.
1033 $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
1034
1035 # To contain the error message, if any.
1036 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1037 my $goback; # to put the parent in so we can link back where the deallocate started
1038
1039 # Enable transactions and exception-on-errors... but only for this sub
1040 local $dbh->{AutoCommit} = 0;
1041 local $dbh->{RaiseError} = 1;
1042
1043 # First case. The "block" is a static IP
1044 # Note that we still need some additional code in the odd case
1045 # of a netblock-aligned contiguous group of static IPs
1046 if ($binfo->{type} =~ /^.i$/) {
1047
1048 eval {
1049 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1050 my ($pool,$pcust,$pvrf) = $dbh->selectrow_array("SELECT pool,custid,vrf FROM poolips WHERE ip=?", undef, ($cidr) );
1051##fixme: VRF and rdepth
1052 $dbh->do("UPDATE poolips SET custid=?,available='y',".
1053 "city=(SELECT city FROM allocations WHERE cidr=?),".
1054 "description='',notes='',circuitid='',vrf=? WHERE ip=?", undef, ($pcust, $pool, $pvrf, $cidr) );
1055 $goback = $pool;
1056 $dbh->commit;
1057 };
1058 if ($@) {
1059 $msg .= ": $@";
1060 eval { $dbh->rollback; };
1061 return ('FAIL',$msg);
1062 } else {
1063 return ('OK',"OK");
1064 }
1065
1066 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
1067
1068##fixme: VRF limit
1069 $msg = "Unable to delete master block $cidr";
1070 eval {
1071 $dbh->do("DELETE FROM masterblocks WHERE cidr = ?", undef, ($cidr) );
1072 $dbh->do("DELETE FROM allocations WHERE cidr <<= ?", undef, ($cidr) );
1073 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ?", undef, ($cidr) );
1074 $dbh->commit;
1075 };
1076 if ($@) {
1077 $msg .= ": $@";
1078 eval { $dbh->rollback; };
1079 return ('FAIL', $msg);
1080 } else {
1081 return ('OK',"OK");
1082 }
1083
1084 } else { # end alloctype master block case
1085
1086 ## This is a big block; but it HAS to be done in a chunk. Any removal
1087 ## of a netblock allocation may result in a larger chunk of free
1088 ## contiguous IP space - which may in turn be combined into a single
1089 ## netblock rather than a number of smaller netblocks.
1090
1091 my $retcode = 'OK';
1092
1093 eval {
1094
1095##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1096# explicitly deleting any suballocations of the block to be deleted.
1097
1098 # find the current parent of the block we're deleting
1099 my ($parent) = $dbh->selectrow_array("SELECT parent FROM allocations WHERE cidr=? AND rdepth=?",
1100 undef, ($cidr, $rdepth) );
1101
1102 # Delete the block
1103 $dbh->do("DELETE FROM allocations WHERE cidr=? AND rdepth=?", undef, ($cidr, $rdepth) );
1104
1105##fixme: we could maybe eliminate a special case if we put masterblocks in the allocations table...?
1106 my ($ptype,$pcity);
1107 if ($rdepth == 1) {
1108 # parent is a master block.
1109 $ptype = 'mm';
1110 $pcity = '<NULL>';
1111 } else {
1112 # get that parent's details
1113 ($ptype,$pcity) = $dbh->selectrow_array("SELECT type,city FROM allocations ".
1114 "WHERE cidr=? AND rdepth=?", undef, ($parent, $rdepth-1) );
1115 }
1116
1117 # munge the parent type a little
1118 $ptype = (split //, $ptype)[0];
1119
1120##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1121# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1122# -> $isprivnet flag from start of sub
1123
1124 my $fbrdepth = $rdepth;
1125
1126 # check to see if any container allocations could be the "true" parent
1127 my ($tparent,$trdepth,$trtype,$tcity) = $dbh->selectrow_array("SELECT cidr,rdepth,type,city FROM allocations ".
1128 "WHERE (type='rm' OR type LIKE '_c') AND cidr >> ? ".
1129 "ORDER BY masklen(cidr) DESC", undef, ($cidr) );
1130
1131 my $fparent;
1132 if ($tparent && $tparent ne $parent) {
1133 # found an alternate parent; reset some parent-info bits
1134 $parent = $tparent;
1135 $ptype = (split //, $trtype)[0];
1136 $pcity = $tcity;
1137 ##fixme: hmm. collect $rdepth into $goback here before vanishing?
1138 $retcode = 'WARN'; # may be redundant
1139 $goback = $tparent;
1140 # munge freeblock rdepth and parent to match true parent
1141 $dbh->do("UPDATE freeblocks SET rdepth = ?, parent = ?, routed = ? WHERE cidr <<= ? AND rdepth = ?", undef,
1142 ($trdepth+1, $parent, $ptype, $cidr, $rdepth) );
1143 $rdepth = $trdepth;
1144 $fbrdepth = $trdepth+1;
1145 }
1146
1147 $parent = new NetAddr::IP $parent;
1148 $goback = "$parent,$fbrdepth"; # breadcrumb in case of live-parent-is-not-true-parent
1149
1150 # Special case - delete pool IPs
1151 if ($binfo->{type} =~ /^.[pd]$/) {
1152 # We have to delete the IPs from the pool listing.
1153##fixme: rdepth? vrf?
1154 $dbh->do("DELETE FROM poolips WHERE pool = ?", undef, ($cidr) );
1155 }
1156
1157 # Find out if the block we're deallocating is within a DSL pool (legacy goo)
1158 my ($pool,$poolcity,$pooltype,$pooldepth) = $dbh->selectrow_array(
1159 "SELECT cidr,city,type,rdepth FROM allocations WHERE type LIKE '_p' AND cidr >>= ?",
1160 undef, ($cidr) );
1161
1162 # If so, return the block's IPs to the pool, instead of to freeblocks
1163## NB: not possible to currently cause this even via admin tools, only legacy data.
1164 if ($pool) {
1165 ## Deallocate legacy blocks stashed in the middle of a static IP pool
1166 ## This may be expandable to an even more general case of contained netblock, or other pool types.
1167 $retcode = 'WARNPOOL';
1168 $goback = "$pool,$pooldepth";
1169 # We've already deleted the block, now we have to stuff its IPs into the pool.
1170 $pooltype =~ s/p$/i/; # change type to static IP
1171 my $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) VALUES ".
1172 "('$pool',?,'$poolcity','$pooltype','$defcustid')");
1173 # don't insert .0
1174##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1175 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1176 foreach my $ip ($cidr->hostenum) {
1177 $sth2->execute($ip);
1178 }
1179 $cidr--;
1180 # don't insert .255
1181 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1182 } else { # done returning IPs from a block to a static DSL pool
1183
1184 # If the block wasn't legacy goo embedded in a static pool, we check the
1185 # freeblocks in the identified parent to see if we can combine any of them.
1186
1187 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1188 if ($binfo->{type} =~ /^.[mc]/) {
1189 # move the freeblocks into the parent
1190 # we don't insert a new freeblock because there could be a live reparented sub.
1191 $dbh->do("UPDATE freeblocks SET rdepth=rdepth-1,parent=?,routed=?,city=? ".
1192 "WHERE parent=? AND rdepth=?", undef,
1193 ($parent, $ptype, $pcity, $cidr, $rdepth+1) );
1194 } else {
1195 # ... otherwise, add the freeblock
1196 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent, rdepth) VALUES (?,?,?,?,?)", undef,
1197 ($cidr, $pcity, $ptype, $parent, $rdepth) );
1198 }
1199
1200##fixme: vrf
1201 # set up the query to get the list of blocks to try to merge.
1202 $sth = $dbh->prepare("SELECT cidr FROM freeblocks ".
1203 "WHERE parent = ? AND routed = ? AND rdepth = ? ".
1204 "ORDER BY masklen(cidr) DESC");
1205
1206 $sth->execute($parent, $ptype, $fbrdepth);
1207
1208# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1209# from the caller and the passed terms.
1210# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1211# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1212# .64-.95, and .96-.128), you will get an array containing a single
1213# /25 as element 0 (.0-.127). Order is not important; you could have
1214# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1215
1216 my (@rawfb, @combinelist);
1217 my $i=0;
1218 # for each free block under $parent, push a NetAddr::IP object into one list, and
1219 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
1220 while (my @data = $sth->fetchrow_array) {
1221 my $testIP = new NetAddr::IP $data[0];
1222 push @rawfb, $testIP;
1223 @combinelist = $testIP->compact(@combinelist);
1224 }
1225
1226 # now that we have the full list of "compacted" freeblocks, go back over
1227 # the list of raw freeblocks, and delete the ones that got merged.
1228 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr=? AND parent=? AND rdepth=?");
1229 foreach my $rawfree (@rawfb) {
1230 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
1231 $sth->execute($rawfree, $parent, $fbrdepth);
1232 }
1233
1234 # now we walk the new list of compacted blocks, and see which ones we need to insert
1235 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent,rdepth) VALUES (?,?,?,?,?)");
1236 foreach my $cme (@combinelist) {
1237 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
1238 $sth->execute($cme, $pcity, $ptype, $parent, $fbrdepth);
1239 }
1240
1241 } # done returning IPs to the appropriate place
1242
1243 # If we got here, we've succeeded. Whew!
1244 $dbh->commit;
1245 }; # end eval
1246 if ($@) {
1247 $msg .= ": $@";
1248 eval { $dbh->rollback; };
1249 return ('FAIL', $msg);
1250 } else {
1251 return ($retcode, $goback);
1252 }
1253
1254 } # end alloctype != netblock
1255
1256} # end deleteBlock()
1257
1258
1259## IPDB::getBlockData()
1260# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
1261# private/restricted data, for a CIDR block or pool IP
1262# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
1263# Takes the block/IP to look up, routing depth, and VRF identifier
1264# Returns a hashref to the block data
1265sub getBlockData {
1266 my $dbh = shift;
1267 my $block = shift;
1268 my $rdepth = shift;
1269 my $vrf = shift || '';
1270
1271 my $cidr = new NetAddr::IP $block;
1272
1273 # better way to find IP allocations vs /32 "netblocks"
1274 my $btype = $dbh->selectrow_array("SELECT type FROM searchme WHERE cidr=?", undef, ($block) );
1275
1276 if (defined($rdepth) && $rdepth == 0) {
1277 # Only master blocks exist at rdepth 0
1278 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, 'mm' AS type, 0 AS parent, cidr,".
1279 " ctime, mtime, rwhois, vrf".
1280 " FROM masterblocks WHERE cidr = ? AND vrf = ?", undef, ($block, $vrf) );
1281 return $binfo;
1282 } elsif ($btype =~ /^.i$/) {
1283 my $binfo = $dbh->selectrow_hashref("SELECT ip AS block, custid, type, city, circuitid, description,".
1284 " notes, modifystamp AS lastmod, privdata, vrf, pool, rdepth".
1285 " FROM poolips WHERE ip = ? AND vrf = ?", undef, ($block, $vrf) );
1286 return $binfo;
1287 } else {
1288 my $binfo = $dbh->selectrow_hashref("SELECT cidr AS block, parent, custid, type, city, circuitid, ".
1289 "description, notes, modifystamp AS lastmod, privdata, vrf, swip, rdepth".
1290 " FROM allocations WHERE cidr = ? AND rdepth = ?", undef, ($block, $rdepth) );
1291# " FROM allocations WHERE cidr = ? AND rdepth = ? AND vrf = ?", undef, ($block, $rdepth, $vrf) );
1292 return $binfo;
1293 }
1294} # end getBlockData()
1295
1296
1297## IPDB::getNodeList()
1298# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1299sub getNodeList {
1300 my $dbh = shift;
1301
1302 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1303 { Slice => {} });
1304 return $ret;
1305} # end getNodeList()
1306
1307
1308## IPDB::getNodeName()
1309# Get node name from the ID
1310sub getNodeName {
1311 my $dbh = shift;
1312 my $nid = shift;
1313
1314 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1315 return $nname;
1316} # end getNodeName()
1317
1318
1319## IPDB::getNodeInfo()
1320# Get node name and ID associated with a block
1321sub getNodeInfo {
1322 my $dbh = shift;
1323 my $block = shift;
1324
1325 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1326 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1327 return ($nid, $nname);
1328} # end getNodeInfo()
1329
1330
1331## IPDB::mailNotify()
1332# Sends notification mail to recipients regarding an IPDB operation
1333sub mailNotify {
1334 my $dbh = shift;
1335 my ($action,$subj,$message) = @_;
1336
1337 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1338
1339##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1340
1341# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
1342 my @actionbits = split //, $action;
1343
1344 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1345 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1346 # and "all events with this action"
1347 my @actionsets = ($action);
1348##fixme: ick, eww. really gotta find a better way to handle this...
1349 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1350 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1351
1352 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1353
1354 # get recip list from db
1355 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1356
1357 my %reciplist;
1358 foreach (@actionsets) {
1359 $sth->execute($_);
1360##fixme - need to handle db errors
1361 my ($recipsub) = $sth->fetchrow_array;
1362 next if !$recipsub;
1363 foreach (split(/,/, $recipsub)) {
1364 $reciplist{$_}++;
1365 }
1366 }
1367
1368 return if !%reciplist;
1369
1370 foreach my $recip (keys %reciplist) {
1371 $mailer->mail("ipdb\@$domain");
1372 $mailer->to($recip);
1373 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1374 "To: $recip\n",
1375 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1376 "Subject: {IPDB} $subj\n",
1377 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1378 "Organization: $org_name\n",
1379 "\n$message\n");
1380 }
1381 $mailer->quit;
1382}
1383
1384# Indicates module loaded OK. Required by Perl.
13851;
Note: See TracBrowser for help on using the repository browser.