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

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

/trunk

Start on SQL in admin.cgi. See #34.

  • Convert Q-n-D allocation list on main page to use existing getTypeList()
  • Convert timestamp-update master block list to use new getMasterList(), with a flag set to return the last-modified time. Also convert main.cgi new assignment page to use this, with the flag set to not return the lastmod.
  • Tweak admin main template to match

While following the code for the master block list, I also removed
several useless globals (@masterblocks, %allocated, %free, and
%routed) since they were only used originally in one place (index
page from main.cgi), obsoleted by changes in r523, and in fact got
overridden locally before that anyway.

  • Property svn:keywords set to Date Rev Author
File size: 44.4 KB
Line 
1# ipdb/cgi-bin/IPDB.pm
2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
3###
4# SVN revision info
5# $Date: 2012-11-02 19:54:31 +0000 (Fri, 02 Nov 2012) $
6# SVN revision $Rev: 541 $
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') {
552 $sql .= " AND city = ?";
553 push @vallist, $city;
554 }
555 # if a specific master was requested, allow the requestor to self->shoot(foot)
556 if ($optargs{master} && $optargs{master} ne '-') {
557 $sql .= " AND cidr <<= ?" if $optargs{master} ne '-';
558 push @vallist, $optargs{master};
559 } else {
560 # if a specific master was NOT requested, filter out the RFC 1918 private networks
561 if (!$optargs{allowpriv}) {
562 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
563 }
564 }
565 # Sorting and limiting, since we don't (currently) care to provide a selection of
566 # blocks to carve up. This preserves something resembling optimal usage of the IP
567 # space by forcing contiguous allocations and free blocks as much as possible.
568 $sql .= " ORDER BY maskbits DESC,cidr LIMIT 1";
569
570 my ($fbfound) = $dbh->selectrow_array($sql, undef, @vallist);
571 return $fbfound;
572} # end findAllocateFrom()
573
574
575## IPDB::ipParent()
576# Get an IP's parent pool's details
577# Takes a database handle and IP
578# Returns a hashref to the parent pool block, if any
579sub ipParent {
580 my $dbh = shift;
581 my $block = shift;
582
583 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
584 " WHERE cidr >>= ?", undef, ($block) );
585 return $pinfo;
586} # end ipParent()
587
588
589## IPDB::subParent()
590# Get a block's parent's details
591# Takes a database handle and CIDR block
592# Returns a hashref to the parent container block, if any
593sub subParent {
594 my $dbh = shift;
595 my $block = shift;
596
597 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
598 " WHERE cidr >>= ?", undef, ($block) );
599 return $pinfo;
600} # end subParent()
601
602
603## IPDB::blockParent()
604# Get a block's parent's details
605# Takes a database handle and CIDR block
606# Returns a hashref to the parent container block, if any
607sub blockParent {
608 my $dbh = shift;
609 my $block = shift;
610
611 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
612 " WHERE cidr >>= ?", undef, ($block) );
613 return $pinfo;
614} # end blockParent()
615
616
617## IPDB::getRoutedCity()
618# Get the city for a routed block.
619sub getRoutedCity {
620 my $dbh = shift;
621 my $block = shift;
622
623 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
624 return $rcity;
625} # end getRoutedCity()
626
627
628## IPDB::allocateBlock()
629# Does all of the magic of actually allocating a netblock
630# Requires database handle, block to allocate, custid, type, city,
631# description, notes, circuit ID, block to allocate from, private data
632# Returns a success code and optional error message.
633sub allocateBlock {
634 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid) = @_;
635
636 my $cidr = new NetAddr::IP $_[1];
637 my $alloc_from = new NetAddr::IP $_[2];
638 my $sth;
639
640 $desc = '' if !$desc;
641 $notes = '' if !$notes;
642 $circid = '' if !$circid;
643 $privdata = '' if !$privdata;
644
645 # Snag the "type" of the freeblock (alloc_from) "just in case"
646 $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
647 $sth->execute;
648 my ($alloc_from_type) = $sth->fetchrow_array;
649
650 # To contain the error message, if any.
651 my $msg = "Unknown error allocating $cidr as '$type'";
652
653 # Enable transactions and error handling
654 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
655 local $dbh->{RaiseError} = 1; # step on our toes by accident.
656
657 if ($type =~ /^.i$/) {
658 $msg = "Unable to assign static IP $cidr to $custid";
659 eval {
660 # We have to do this in two parts because otherwise we lose
661 # the ability to return the IP assigned. Should that change,
662 # the commented SQL statement below may become usable.
663# update poolips set custid='$custid',city='$city',available='n',
664# description='$desc',notes='$notes',circuitid='$circid'
665# where ip=(select ip from poolips where pool='$alloc_from'
666# and available='y' order by ip limit 1);
667
668 $sth = $dbh->prepare("select ip from poolips where pool='$alloc_from'".
669 " and available='y' order by ip");
670 $sth->execute;
671
672 my @data = $sth->fetchrow_array;
673 $cidr = $data[0]; # $cidr is already declared when we get here!
674
675 $sth = $dbh->prepare("update poolips set custid=?,city=?,".
676 "available='n',description=?,notes=?,circuitid=?,privdata=?".
677 " where ip=?");
678 $sth->execute($custid, $city, $desc, $notes, $circid, $privdata, "$cidr");
679# node hack
680 if ($nodeid && $nodeid ne '') {
681 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
682 $sth->execute("$cidr",$nodeid);
683 }
684# end node hack
685 $dbh->commit;
686 };
687 if ($@) {
688 $msg .= ": '".$sth->errstr."'";
689 eval { $dbh->rollback; };
690 return ('FAIL',$msg);
691 } else {
692 return ('OK',"$cidr");
693 }
694
695 } else { # end IP-from-pool allocation
696
697 if ($cidr == $alloc_from) {
698 # Easiest case- insert in one table, delete in the other, and go home. More or less.
699 # insert into allocations values (cidr,custid,type,city,desc) and
700 # delete from freeblocks where cidr='cidr'
701 # For data safety on non-transaction DBs, we delete first.
702
703 eval {
704 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
705 if ($type eq 'rm') {
706 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
707 " where cidr='$cidr'");
708 $sth->execute;
709 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
710 " values ('$cidr',".$cidr->masklen.",'$city')");
711 $sth->execute;
712 } else {
713 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
714
715 # special case - block is a container/"reserve" block
716 if ($type =~ /^(.)c$/) {
717 $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
718 $sth->execute;
719 } else {
720 # "normal" case
721 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
722 $sth->execute;
723 }
724 $sth = $dbh->prepare("insert into allocations".
725 " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
726 " values (?,?,?,?,?,?,?,?,?)");
727 $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
728
729 # And initialize the pool, if necessary
730 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
731 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
732 if ($type =~ /^.p$/) {
733 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
734 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
735 die $rmsg if $code eq 'FAIL';
736 } elsif ($type =~ /^.d$/) {
737 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
738 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
739 die $rmsg if $code eq 'FAIL';
740 }
741
742 } # routing vs non-routing netblock
743
744# node hack
745 if ($nodeid && $nodeid ne '') {
746 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
747 $sth->execute("$cidr",$nodeid);
748 }
749# end node hack
750 $dbh->commit;
751 }; # end of eval
752 if ($@) {
753 $msg .= ": ".$@;
754 eval { $dbh->rollback; };
755 return ('FAIL',$msg);
756 } else {
757 return ('OK',"OK");
758 }
759
760 } else { # cidr != alloc_from
761
762 # Hard case. Allocation is smaller than free block.
763 my $wantmaskbits = $cidr->masklen;
764 my $maskbits = $alloc_from->masklen;
765
766 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
767
768 # This determines which blocks will be left "free" after allocation. We take the
769 # block we're allocating from, and split it in half. We see which half the wanted
770 # block is in, and repeat until the wanted block is equal to one of the halves.
771 my $i=0;
772 my $tmp_from = $alloc_from; # So we don't munge $alloc_from
773 while ($maskbits++ < $wantmaskbits) {
774 my @subblocks = $tmp_from->split($maskbits);
775 $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
776 $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
777 } # while
778
779 # Begin SQL transaction block
780 eval {
781 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
782
783 # Delete old freeblocks entry
784 $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
785 $sth->execute();
786
787 # now we have to do some magic for routing blocks
788 if ($type eq 'rm') {
789
790 # Insert the new freeblocks entries
791 # Note that non-routed blocks are assigned to <NULL>
792 # and use the default value for the routed column ('n')
793 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
794 " values (?, ?, '<NULL>')");
795 foreach my $block (@newfreeblocks) {
796 $sth->execute("$block", $block->masklen);
797 }
798
799 # Insert the entry in the routed table
800 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
801 " values ('$cidr',".$cidr->masklen.",'$city')");
802 $sth->execute;
803 # Insert the (almost) same entry in the freeblocks table
804 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
805 " values ('$cidr',".$cidr->masklen.",'$city','y')");
806 $sth->execute;
807
808 } else { # done with alloctype == rm
809
810 # Insert the new freeblocks entries
811 # Along with some more HairyPerl(TM):
812 # if $alloc_type_from is p
813 # OR
814 # $type matches /^(.)r$/
815 # inserted value for routed column should match.
816 # This solves the case of inserting an arbitrary block into a
817 # "Reserve-for-routed-DSL" block. Which you really shouldn't
818 # do in the first place, but anyway...
819 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
820 " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
821 ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
822 foreach my $block (@newfreeblocks) {
823 $sth->execute("$block", $block->masklen);
824 }
825 # Special-case for reserve/"container" blocks - generate
826 # the "extra" freeblocks entry for the container
827 if ($type =~ /^(.)c$/) {
828 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
829 " values ('$cidr',".$cidr->masklen.",'$city','$1')");
830 $sth->execute;
831 }
832 # Insert the allocations entry
833 $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
834 "description,notes,maskbits,circuitid,privdata)".
835 " values (?,?,?,?,?,?,?,?,?)");
836 $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
837
838 # And initialize the pool, if necessary
839 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
840 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
841 if ($type =~ /^.p$/) {
842 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
843 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
844 die $rmsg if $code eq 'FAIL';
845 } elsif ($type =~ /^.d$/) {
846 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
847 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
848 die $rmsg if $code eq 'FAIL';
849 }
850
851 } # done with netblock alloctype != rm
852
853# node hack
854 if ($nodeid && $nodeid ne '') {
855 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
856 $sth->execute("$cidr",$nodeid);
857 }
858# end node hack
859 $dbh->commit;
860 }; # end eval
861 if ($@) {
862 $msg .= ": ".$@;
863 eval { $dbh->rollback; };
864 return ('FAIL',$msg);
865 } else {
866 return ('OK',"OK");
867 }
868
869 } # end fullcidr != alloc_from
870
871 } # end static-IP vs netblock allocation
872
873} # end allocateBlock()
874
875
876## IPDB::initPool()
877# Initializes a pool
878# Requires a database handle, the pool CIDR, type, city, and a parameter
879# indicating whether the pool should allow allocation of literally every
880# IP, or if it should reserve network/gateway/broadcast IPs
881# Note that this is NOT done in a transaction, that's why it's a private
882# function and should ONLY EVER get called from allocateBlock()
883sub initPool {
884 my ($dbh,undef,$type,$city,$class) = @_;
885 my $pool = new NetAddr::IP $_[1];
886
887##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
888 $type =~ s/[pd]$/i/;
889 my $sth;
890 my $msg;
891
892 # Trap errors so we can pass them back to the caller. Even if the
893 # caller is only ever supposed to be local, and therefore already
894 # trapping errors. >:(
895 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
896 local $dbh->{RaiseError} = 1; # step on our toes by accident.
897
898 eval {
899 # have to insert all pool IPs into poolips table as "unallocated".
900 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
901 " values ('$pool', ?, '$defcustid', ?, '$type')");
902 my @poolip_list = $pool->hostenum;
903 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
904 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
905 $sth->execute($pool->addr, $city);
906 }
907 for (my $i=0; $i<=$#poolip_list; $i++) {
908 $sth->execute($poolip_list[$i]->addr, $city);
909 }
910 $pool--;
911 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
912 $sth->execute($pool->addr, $city);
913 }
914 } else { # (real netblock)
915 for (my $i=1; $i<=$#poolip_list; $i++) {
916 $sth->execute($poolip_list[$i]->addr, $city);
917 }
918 }
919 };
920 if ($@) {
921 $msg = $@." '".$sth->errstr."'";
922 eval { $dbh->rollback; };
923 return ('FAIL',$msg);
924 } else {
925 return ('OK',"OK");
926 }
927} # end initPool()
928
929
930## IPDB::updateBlock()
931# Update an allocation
932# Takes all allocation fields in a hash
933sub updateBlock {
934 my $dbh = shift;
935 my %args = @_;
936
937 return ('FAIL', 'Missing block to update') if !$args{block};
938
939 # do it all in a transaction
940 local $dbh->{AutoCommit} = 0;
941 local $dbh->{RaiseError} = 1;
942
943 my @fieldlist;
944 my @vallist;
945 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata') {
946 if ($args{$_}) {
947 push @fieldlist, $_;
948 push @vallist, $args{$_};
949 }
950 }
951
952 my $updtable = 'allocations';
953 my $keyfield = 'cidr';
954 if ($args{type} =~ /^(.)i$/) {
955 $updtable = 'poolips';
956 $keyfield = 'ip';
957 } else {
958## fixme: there's got to be a better way...
959 if ($args{swip}) {
960 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
961 $args{swip} = 'y';
962 } else {
963 $args{swip} = 'n';
964 }
965 }
966 foreach ('type', 'swip') {
967 if ($args{$_}) {
968 push @fieldlist, $_;
969 push @vallist, $args{$_};
970 }
971 }
972 }
973
974 return ('FAIL', 'No fields to update') if !@fieldlist;
975
976 push @vallist, $args{block};
977 my $sql = "UPDATE $updtable SET ";
978 $sql .= join " = ?, ", @fieldlist;
979 $sql .= " = ? WHERE $keyfield = ?";
980
981 eval {
982 # do the update
983 $dbh->do($sql, undef, @vallist);
984
985 if ($args{node}) {
986 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
987 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
988 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
989 }
990
991 $dbh->commit;
992 };
993 if ($@) {
994 my $msg = $@;
995 $dbh->rollback;
996 return ('FAIL', $msg);
997 }
998 return 0;
999} # end updateBlock()
1000
1001
1002## IPDB::deleteBlock()
1003# Removes an allocation from the database, including deleting IPs
1004# from poolips and recombining entries in freeblocks if possible
1005# Also handles "deleting" a static IP allocation, and removal of a master
1006# Requires a database handle, the block to delete, and the type of block
1007sub deleteBlock {
1008 my ($dbh,undef,$type) = @_;
1009 my $cidr = new NetAddr::IP $_[1];
1010
1011 my $sth;
1012
1013 # Magic variables used for odd allocation cases.
1014 my $container;
1015 my $con_type;
1016
1017 # To contain the error message, if any.
1018 my $msg = "Unknown error deallocating $type $cidr";
1019 # Enable transactions and exception-on-errors... but only for this sub
1020 local $dbh->{AutoCommit} = 0;
1021 local $dbh->{RaiseError} = 1;
1022
1023 # First case. The "block" is a static IP
1024 # Note that we still need some additional code in the odd case
1025 # of a netblock-aligned contiguous group of static IPs
1026 if ($type =~ /^.i$/) {
1027
1028 eval {
1029 $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
1030 $sth = $dbh->prepare("update poolips set custid=?,available='y',".
1031 "city=(select city from allocations where cidr >>= ?".
1032 " order by masklen(cidr) desc limit 1),".
1033 "description='',notes='',circuitid='' where ip=?");
1034 $sth->execute($defcustid, "$cidr", "$cidr");
1035 $dbh->commit;
1036 };
1037 if ($@) {
1038 eval { $dbh->rollback; };
1039 return ('FAIL',$msg);
1040 } else {
1041 return ('OK',"OK");
1042 }
1043
1044 } elsif ($type eq 'mm') { # end alloctype =~ /.i/
1045
1046 $msg = "Unable to delete master block $cidr";
1047 eval {
1048 $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
1049 $sth->execute;
1050 $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
1051 $sth->execute;
1052 $dbh->commit;
1053 };
1054 if ($@) {
1055 eval { $dbh->rollback; };
1056 return ('FAIL', $msg);
1057 } else {
1058 return ('OK',"OK");
1059 }
1060
1061 } else { # end alloctype master block case
1062
1063 ## This is a big block; but it HAS to be done in a chunk. Any removal
1064 ## of a netblock allocation may result in a larger chunk of free
1065 ## contiguous IP space - which may in turn be combined into a single
1066 ## netblock rather than a number of smaller netblocks.
1067
1068 eval {
1069
1070 if ($type eq 'rm') {
1071 $msg = "Unable to remove routing allocation $cidr";
1072 $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
1073 $sth->execute;
1074 # Make sure block getting deleted is properly accounted for.
1075 $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
1076 " where cidr='$cidr'");
1077 $sth->execute;
1078 # Set up query to start compacting free blocks.
1079 $sth = $dbh->prepare("select cidr from freeblocks where ".
1080 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
1081
1082 } else { # end alloctype routing case
1083
1084 # Magic. We need to get information about the containing block (if any)
1085 # so as to make sure that the freeblocks we insert get the correct "type".
1086 $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
1087 $sth->execute;
1088 ($container, $con_type) = $sth->fetchrow_array;
1089
1090 # Delete all allocations within the block being deleted. This is
1091 # deliberate and correct, and removes the need to special-case
1092 # removal of "container" blocks.
1093 $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
1094 $sth->execute;
1095
1096 # Special case - delete pool IPs
1097 if ($type =~ /^.[pd]$/) {
1098 # We have to delete the IPs from the pool listing.
1099 $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
1100 $sth->execute;
1101 }
1102
1103 # Set up query for compacting free blocks.
1104 if ($con_type && $con_type eq 'pc') {
1105 # Clean up after "bad" allocations (blocks that are not formally
1106 # contained which have nevertheless been allocated from a container block)
1107 # We want to make certain that the freeblocks are properly "labelled"
1108 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
1109 } else {
1110 # Standard deallocation.
1111 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
1112 "(select cidr from routed where cidr >>= '$cidr') ".
1113 " and maskbits<=".$cidr->masklen.
1114 " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
1115 "' order by maskbits desc");
1116 }
1117
1118 } # end alloctype general case
1119
1120 ## Deallocate legacy blocks stashed in the middle of a static IP pool
1121 ## This may be expandable to an even more general case of contained netblock, or other pool types.
1122
1123 # Find out if the block we're deallocating is within a DSL pool
1124 my $sth2 = $dbh->prepare("SELECT cidr,city,type FROM allocations WHERE type LIKE '_p' AND cidr >>= ?");
1125 $sth2->execute("$cidr");
1126 my ($pool,$poolcity,$pooltype) = $sth2->fetchrow_array;
1127
1128 if ($pool || $sth2->rows) {
1129 # We've already deleted the block, now we have to stuff its IPs into the pool.
1130 $pooltype =~ s/p$/i/; # change type to static IP
1131 $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) values ".
1132 "('$pool',?,'$poolcity','$pooltype','$defcustid')");
1133##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1134 # don't insert .0
1135 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1136 foreach my $ip ($cidr->hostenum) {
1137 $sth2->execute("$ip");
1138 }
1139 $cidr--;
1140 # don't insert .255
1141 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1142 } else { # done returning IPs from a block to a static DSL pool
1143
1144 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
1145 # (super)block. If there aren't any, we can't combine blocks anyway. If there
1146 # are, we check to see if we can combine blocks.
1147 # Execute the statement prepared in the if-else above.
1148
1149 $sth->execute;
1150
1151# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1152# from the caller and the passed terms.
1153# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1154# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1155# .64-.95, and .96-.128), you will get an array containing a single
1156# /25 as element 0 (.0-.127). Order is not important; you could have
1157# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1158
1159 my (@together, @combinelist);
1160 my $i=0;
1161 while (my @data = $sth->fetchrow_array) {
1162 my $testIP = new NetAddr::IP $data[0];
1163 @together = $testIP->compact($cidr);
1164 my $num = @together;
1165 if ($num == 1) {
1166 $cidr = $together[0];
1167 $combinelist[$i++] = $testIP;
1168 }
1169 }
1170
1171 # Clear old freeblocks entries - if any. They should all be within
1172 # the $cidr determined above.
1173 $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
1174 $sth->execute;
1175
1176 # insert "new" freeblocks entry
1177 if ($type eq 'rm') {
1178 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
1179 " values ('$cidr',".$cidr->masklen.",'<NULL>')");
1180 } else {
1181 # Magic hackery to insert "correct" data for deallocation of
1182 # non-contained blocks allocated from within a container.
1183 $type = 'pr' if $con_type && $con_type eq 'pc';
1184
1185 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
1186 " values ('$cidr',".$cidr->masklen.
1187 ",(select city from routed where cidr >>= '$cidr'),'".
1188 (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
1189 }
1190 $sth->execute;
1191
1192 } # done returning IPs to the appropriate place
1193
1194 # If we got here, we've succeeded. Whew!
1195 $dbh->commit;
1196 }; # end eval
1197 if ($@) {
1198 $msg = $@;
1199 eval { $dbh->rollback; };
1200 return ('FAIL', $msg);
1201 } else {
1202 return ('OK',"OK");
1203 }
1204
1205 } # end alloctype != netblock
1206
1207} # end deleteBlock()
1208
1209
1210## IPDB::getBlockData()
1211# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time, private/restricted
1212# data, for a CIDR block or pool IP
1213# Also returns SWIP status flag for CIDR blocks
1214# Takes the block/IP to look up
1215# Returns an arrayref to a list of hashrefs
1216sub getBlockData {
1217 my $dbh = shift;
1218 my $block = shift;
1219
1220 my $cidr = new NetAddr::IP $block;
1221
1222 my $keycol = 'cidr';
1223 my $blocktable = 'allocations';
1224 my $poolip = 0;
1225
1226 # Pool IP and IPv6 check all in one! Still needs to be tightened
1227 # up a little for the as-yet-unhandled case of IPv6 IP pools
1228 if ($cidr->bits == 32 && $cidr->masklen == 32) {
1229 $poolip = 1;
1230 $keycol = 'ip';
1231 $blocktable = 'poolips';
1232 }
1233 my $binfo = $dbh->selectrow_hashref("SELECT $keycol AS block, custid, type, city, circuitid, description,".
1234 " notes, modifystamp AS lastmod, privdata".($poolip ? '' : ', swip')." FROM $blocktable".
1235 " WHERE $keycol = ?", undef, ($block) );
1236 return $binfo;
1237} # end getBlockData()
1238
1239
1240## IPDB::getNodeList()
1241# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1242sub getNodeList {
1243 my $dbh = shift;
1244
1245 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1246 { Slice => {} });
1247 return $ret;
1248} # end getNodeList()
1249
1250
1251## IPDB::getNodeName()
1252# Get node name from the ID
1253sub getNodeName {
1254 my $dbh = shift;
1255 my $nid = shift;
1256
1257 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1258 return $nname;
1259} # end getNodeName()
1260
1261
1262## IPDB::getNodeInfo()
1263# Get node name and ID associated with a block
1264sub getNodeInfo {
1265 my $dbh = shift;
1266 my $block = shift;
1267
1268 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1269 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1270 return ($nid, $nname);
1271} # end getNodeInfo()
1272
1273
1274## IPDB::mailNotify()
1275# Sends notification mail to recipients regarding an IPDB operation
1276sub mailNotify {
1277 my $dbh = shift;
1278 my ($action,$subj,$message) = @_;
1279
1280 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1281
1282##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1283
1284# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
1285 my @actionbits = split //, $action;
1286
1287 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1288 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1289 # and "all events with this action"
1290 my @actionsets = ($action);
1291##fixme: ick, eww. really gotta find a better way to handle this...
1292 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1293 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1294
1295 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1296
1297 # get recip list from db
1298 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1299
1300 my %reciplist;
1301 foreach (@actionsets) {
1302 $sth->execute($_);
1303##fixme - need to handle db errors
1304 my ($recipsub) = $sth->fetchrow_array;
1305 next if !$recipsub;
1306 foreach (split(/,/, $recipsub)) {
1307 $reciplist{$_}++;
1308 }
1309 }
1310
1311 return if !%reciplist;
1312
1313 foreach my $recip (keys %reciplist) {
1314 $mailer->mail("ipdb\@$domain");
1315 $mailer->to($recip);
1316 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1317 "To: $recip\n",
1318 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1319 "Subject: {IPDB} $subj\n",
1320 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1321 "Organization: $org_name\n",
1322 "\n$message\n");
1323 }
1324 $mailer->quit;
1325}
1326
1327# Indicates module loaded OK. Required by Perl.
13281;
Note: See TracBrowser for help on using the repository browser.