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

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

/trunk

Clean up and move SQL for post-update backlink to IPDB.pm. See #34.
Also rename getParent() to subParent() to fit in with ipParent() and
blockParent().

Fix a couple "Use of uninitialized..." log-noise bugs. See #31.

Move some HTML-entity-escaping into the template, and shuffle lines
munging the notes and restricted data on post-update value display
so we can properly munge in <br> for \n. Doesn't seem to be a way
to plug that into HTML::Template. :( See #3.

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