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

Last change on this file since 727 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
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: 2014-05-27 19:09:38 +0000 (Tue, 27 May 2014) $
6# SVN revision $Rev: 619 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2013 Kris Deugau <kdeugau@deepnet.cx>
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 %rpcacl $maxfcgi
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 %rpcacl $maxfcgi
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 %rpcacl;
71our $maxfcgi = 3;
72
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
92# Allow allocations to come from private IP ranges by default?
93# Set to 'y' or 'on' to enable.
94our $allowprivrange = '';
95
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
104 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
105 $sth->execute;
106 while (my @data = $sth->fetchrow_array) {
107 $disp_alloctypes{$data[0]} = $data[2];
108 $def_custids{$data[0]} = $data[4];
109 if ($data[3] < 900) {
110 $list_alloctypes{$data[0]} = $data[1];
111 }
112 }
113
114 # City and POP listings
115 $sth = $dbh->prepare("select city,routing from cities order by city");
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
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;
128 return (undef,$sth->errstr) if $sth->err;
129 while (my @data = $sth->fetchrow_array) {
130 $IPDBacl{$data[0]} = $data[1];
131 }
132
133##fixme: initialize HTML::Template env var for template path
134# something like $self->path().'/templates' ?
135# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
136
137 return (1,"OK");
138} # end initIPDBGlobals
139
140
141## IPDB::connectDB()
142# Creates connection to IPDB.
143# Requires the database name, username, and password.
144# Returns a handle to the db.
145# Set up for a PostgreSQL db; could be any transactional DBMS with the
146# right changes.
147sub connectDB {
148 my $dbname = shift;
149 my $user = shift;
150 my $pass = shift;
151 my $dbhost = shift;
152
153 my $dbh;
154 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
155
156# Note that we want to autocommit by default, and we will turn it off locally as necessary.
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);
163
164# Return here if we can't select. Note that this indicates a
165# problem executing the select.
166 my $sth = $dbh->prepare("select type from alloctypes");
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");
177} # end connectDB
178
179
180## IPDB::finish()
181# Cleans up after database handles and so on.
182# Requires a database handle
183sub finish {
184 my $dbh = $_[0];
185 $dbh->disconnect if $dbh;
186} # end finish
187
188
189## IPDB::checkDBSanity()
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 {
193 my ($dbh) = $_[0];
194
195 if (!$dbh) {
196 print "No database handle, or connection has been closed.";
197 return -1;
198 } else {
199 # it connects, try a stmt.
200 my $sth = $dbh->prepare("select type from alloctypes");
201 my $err = $sth->execute();
202
203 if ($sth->fetchrow()) {
204 # all is well.
205 return 1;
206 } else {
207 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
208 return -1;
209 }
210 }
211 # Clean up after ourselves.
212# $dbh->disconnect;
213} # end checkDBSanity
214
215
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 {
231 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
232
233 if (!$mexist) {
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"?
237 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr,'y') );
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.
242 $dbh->do("INSERT INTO freeblocks (cidr,maskbits,city,routed) VALUES (?,?,?,?)", undef,
243 ($cidr, $cidr->masklen, '<NULL>', 'n') );
244
245 # If we get here, everything is happy. Commit changes.
246 $dbh->commit;
247
248 } # done new master does not contain existing master(s)
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;
253 my $sth = $dbh->prepare("SELECT cidr FROM masterblocks WHERE cidr <<= ?");
254 $sth->execute($cidr);
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
273 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE maskbits <= ? AND cidr <<= ? AND routed = 'n'");
274 $sth->execute($smallmask, $cidr);
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
286 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ?");
287 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,maskbits,city,routed) VALUES (?,?,'<NULL>','n')");
288 foreach my $newblock (@blocklist) {
289 $sth->execute($newblock);
290 $sth2->execute($newblock, $newblock->masklen);
291 }
292
293 # master
294 $dbh->do("DELETE FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
295 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr, 'y') );
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
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
401 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf".
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;
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;
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
469 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,vrf".
470 " FROM poolips WHERE pool = ? ORDER BY ip");
471 $sth->execute($pool);
472 my @poolips;
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;
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;
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.
517 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder < 500 ".
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 => {} });
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 ".
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 => {} });
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 ".
535 " ORDER BY listorder", { Slice => {} });
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
676## IPDB::allocateBlock()
677# Does all of the magic of actually allocating a netblock
678# Requires database handle, block to allocate, custid, type, city,
679# description, notes, circuit ID, block to allocate from, private data
680# Returns a success code and optional error message.
681sub allocateBlock {
682 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid,$vrf) = @_;
683 $privdata = '' if !defined($privdata);
684 $vrf = '' if !defined($vrf);
685
686 my $cidr = new NetAddr::IP $_[1];
687 my $alloc_from = new NetAddr::IP $_[2];
688 my $sth;
689
690 $desc = '' if !$desc;
691 $notes = '' if !$notes;
692 $circid = '' if !$circid;
693 $privdata = '' if !$privdata;
694
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
700 # To contain the error message, if any.
701 my $msg = "Unknown error allocating $cidr as '$type'";
702
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
707 if ($type =~ /^.i$/) {
708 $msg = "Unable to assign static IP $cidr to $custid";
709 eval {
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.
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);
717
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) );
729 }
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) );
733
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
740
741 $dbh->commit;
742 };
743 if ($@) {
744 $msg .= ": $@";
745 eval { $dbh->rollback; };
746 return ('FAIL',$msg);
747 } else {
748 return ('OK',"$cidr");
749 }
750
751 } else { # end IP-from-pool allocation
752
753 my $errcode = 'OK';
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}'";
762 if ($type eq 'rm') {
763 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
764 " where cidr='$cidr'");
765 $sth->execute;
766 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
767 " values ('$cidr',".$cidr->masklen.",'$city')");
768 $sth->execute;
769 } else {
770 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
771
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 }
781 $sth = $dbh->prepare("insert into allocations".
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);
785
786 # And initialize the pool, if necessary
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.
789 if ($type =~ /^.p$/) {
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';
793 $msg = $rmsg;
794 $errcode = $code;
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';
799 $msg = $rmsg;
800 $errcode = $code;
801 }
802
803 } # routing vs non-routing netblock
804
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
811 $dbh->commit;
812 }; # end of eval
813 if ($@) {
814 $msg .= ": ".$@;
815 eval { $dbh->rollback; };
816 return ('FAIL',$msg);
817 } else {
818 return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
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
849 if ($type eq 'rm') {
850
851 # Insert the new freeblocks entries
852 # Note that non-routed blocks are assigned to <NULL>
853 # and use the default value for the routed column ('n')
854 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
855 " values (?, ?, '<NULL>')");
856 foreach my $block (@newfreeblocks) {
857 $sth->execute("$block", $block->masklen);
858 }
859
860 # Insert the entry in the routed table
861 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
862 " values ('$cidr',".$cidr->masklen.",'$city')");
863 $sth->execute;
864 # Insert the (almost) same entry in the freeblocks table
865 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
866 " values ('$cidr',".$cidr->masklen.",'$city','y')");
867 $sth->execute;
868
869 } else { # done with alloctype == rm
870
871 # Insert the new freeblocks entries
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...
880 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
881 " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
882 ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
883 foreach my $block (@newfreeblocks) {
884 $sth->execute("$block", $block->masklen);
885 }
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 }
893 # Insert the allocations entry
894 $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
895 "description,notes,maskbits,circuitid,privdata,vrf)".
896 " values (?,?,?,?,?,?,?,?,?,?)");
897 $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata, $vrf);
898
899 # And initialize the pool, if necessary
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.
902 if ($type =~ /^.p$/) {
903 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
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';
910 }
911
912 } # done with netblock alloctype != rm
913
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
920 $dbh->commit;
921 }; # end eval
922 if ($@) {
923 $msg .= ": ".$@;
924 eval { $dbh->rollback; };
925 return ('FAIL',$msg);
926 } else {
927 return ($errcode,($type =~ /^.[pd]$/ ? $msg : "OK"));
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
948 return ('WARN','Refusing to melt server with IPv6 IP pool') if $pool->bits == 128;
949
950##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
951 $type =~ s/[pd]$/i/;
952 my $sth;
953 my $msg;
954
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)".
964 " values ('$pool', ?, '$defcustid', ?, '$type')");
965 my @poolip_list = $pool->hostenum;
966 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
967 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
968 $sth->execute($pool->addr, $city);
969 }
970 for (my $i=0; $i<=$#poolip_list; $i++) {
971 $sth->execute($poolip_list[$i]->addr, $city);
972 }
973 $pool--;
974 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
975 $sth->execute($pool->addr, $city);
976 }
977 } else { # (real netblock)
978 for (my $i=1; $i<=$#poolip_list; $i++) {
979 $sth->execute($poolip_list[$i]->addr, $city);
980 }
981 }
982 };
983 if ($@) {
984 $msg = $@." '".$sth->errstr."'";
985 eval { $dbh->rollback; };
986 return ('FAIL',$msg);
987 } else {
988 return ('OK',"OK");
989 }
990} # end initPool()
991
992
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;
1008 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'vrf') {
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
1048 if ($args{node} && $args{node} ne '--') {
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
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
1076 # Magic variables used for odd allocation cases.
1077 my $container;
1078 my $con_type;
1079
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 {
1092 $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
1093 $sth = $dbh->prepare("update poolips set custid=?,available='y',".
1094 "city=(select city from allocations where cidr >>= ?".
1095 " order by masklen(cidr) desc limit 1),".
1096 "description='',notes='',circuitid='',vrf='' where ip=?");
1097 $sth->execute($defcustid, "$cidr", "$cidr");
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 {
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);
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
1133 if ($type eq 'rm') {
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.
1142 $sth = $dbh->prepare("select cidr from freeblocks where ".
1143 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
1144
1145 } else { # end alloctype routing case
1146
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
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'");
1157 $sth->execute;
1158
1159 # Special case - delete pool IPs
1160 if ($type =~ /^.[pd]$/) {
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.
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"
1171 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
1172 } else {
1173 # Standard deallocation.
1174 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
1175 "(select cidr from routed where cidr >>= '$cidr') ".
1176 " and maskbits<=".$cidr->masklen.
1177 " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
1178 "' order by maskbits desc");
1179 }
1180
1181 } # end alloctype general case
1182
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.
1185
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;
1190
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
1206
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.
1211
1212 $sth->execute;
1213
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
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 }
1232 }
1233
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;
1238
1239 # insert "new" freeblocks entry
1240 if ($type eq 'rm') {
1241 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
1242 " values ('$cidr',".$cidr->masklen.",'<NULL>')");
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';
1247
1248 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
1249 " values ('$cidr',".$cidr->masklen.
1250 ",(select city from routed where cidr >>= '$cidr'),'".
1251 (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
1252 }
1253 $sth->execute;
1254
1255 } # done returning IPs to the appropriate place
1256
1257 # If we got here, we've succeeded. Whew!
1258 $dbh->commit;
1259 }; # end eval
1260 if ($@) {
1261 $msg = $@;
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
1273## IPDB::getBlockData()
1274# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time, private/restricted
1275# data, and VRF tag, for a CIDR block or pool IP
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
1279sub getBlockData {
1280 my $dbh = shift;
1281 my $block = shift;
1282
1283 my $cidr = new NetAddr::IP $block;
1284
1285 my $keycol = 'cidr';
1286 my $blocktable = 'allocations';
1287 my $poolip = 0;
1288
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*
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
1303# if ($cidr->bits == 32 && $cidr->masklen == 32) {
1304 if (!$binfo) {
1305 $poolip = 1;
1306 $keycol = 'ip';
1307 $blocktable = 'poolips';
1308 $binfo = $dbh->selectrow_hashref("SELECT $keycol AS block, custid, type, city, circuitid, description,".
1309 " notes, modifystamp AS lastmod, privdata, vrf".($poolip ? '' : ', swip')." FROM $blocktable".
1310 " WHERE $keycol = ?", undef, ($block) );
1311 }
1312 return $binfo;
1313} # end getBlockData()
1314
1315
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
1350## IPDB::mailNotify()
1351# Sends notification mail to recipients regarding an IPDB operation
1352sub mailNotify {
1353 my $dbh = shift;
1354 my ($action,$subj,$message) = @_;
1355
1356 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1357
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",
1393 "To: $recip\n",
1394 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1395 "Subject: {IPDB} $subj\n",
1396 "X-Mailer: IPDB Notify v$IPDB::VERSION\n",
1397 "Organization: $org_name\n",
1398 "\n$message\n");
1399 }
1400 $mailer->quit;
1401}
1402
1403# Indicates module loaded OK. Required by Perl.
14041;
Note: See TracBrowser for help on using the repository browser.