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

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

/trunk

Work in progress, see #5:
Update allocateBlock() to support new concept for allocation nesting

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