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

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

/trunk

Clean up and move SQL for finding a free block to allocate from
into IPDB.pm. See #34.
Also fix a minor "Use of uninitialized value...".

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