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

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

/trunk

Clean up and move last-modified-change for master blocks to
IPDB.pm. See #34.

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