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

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

/trunk

Tweak allocateBlock() to usefully handle passing an IP as an
override on the automatic IP-chooser.
Convert allocation of a pool IP in admin.cgi to use updated
allocateBlock(). See #34.

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