source: branches/stable/cgi-bin/IPDB.pm@ 862

Last change on this file since 862 was 619, checked in by Kris Deugau, 10 years ago

/branches/stable

Clean up VRF field in poolips on delete

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