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

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

/trunk

Factor out a chunk of deleteBlock() (compact free blocks to the minimal
CIDR set) so we can reuse it in the coming mergeBlocks().

  • Property svn:keywords set to Date Rev Author
File size: 81.2 KB
Line 
1# ipdb/cgi-bin/IPDB.pm
2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
3###
4# SVN revision info
5# $Date: 2015-04-30 21:28:21 +0000 (Thu, 30 Apr 2015) $
6# SVN revision $Rev: 715 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2010 - Kris Deugau
10
11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
17use Net::SMTP;
18use NetAddr::IP qw(:lower Compact );
19use Frontier::Client;
20use POSIX;
21use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
22
23$VERSION = 2; ##VERSION##
24@ISA = qw(Exporter);
25@EXPORT_OK = qw(
26 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
27 %IPDBacl %aclmsg %rpcacl $maxfcgi
28 $errstr
29 &initIPDBGlobals &connectDB &finish &checkDBSanity
30 &addMaster &touchMaster
31 &listSummary &listSubs &listContainers &listAllocations &listFree &listPool
32 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
33 &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
34 &allocateBlock &updateBlock &splitBlock &shrinkBlock &deleteBlock &getBlockData
35 &getBlockRDNS &getRDNSbyIP
36 &getNodeList &getNodeName &getNodeInfo
37 &mailNotify
38 );
39
40@EXPORT = (); # Export nothing by default.
41%EXPORT_TAGS = ( ALL => [qw(
42 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
43 %IPDBacl %aclmsg %rpcacl $maxfcgi
44 $errstr
45 &initIPDBGlobals &connectDB &finish &checkDBSanity
46 &addMaster &touchMaster
47 &listSummary &listSubs &listContainers &listAllocations &listFree &listPool
48 &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
49 &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
50 &allocateBlock &updateBlock &splitBlock &shrinkBlock &deleteBlock &getBlockData
51 &getBlockRDNS &getRDNSbyIP
52 &getNodeList &getNodeName &getNodeInfo
53 &mailNotify
54 )]
55 );
56
57##
58## Global variables
59##
60our %disp_alloctypes;
61our %list_alloctypes;
62our %def_custids;
63our @citylist;
64our @poplist;
65our %IPDBacl;
66
67# mapping table for functional-area => error message
68our %aclmsg = (
69 addmaster => 'add a master block',
70 addblock => 'add an allocation',
71 updateblock => 'update a block',
72 delblock => 'delete an allocation',
73 );
74
75our %rpcacl;
76our $maxfcgi = 3;
77
78# error reporting
79our $errstr = '';
80
81our $org_name = 'Example Corp';
82our $smtphost = 'smtp.example.com';
83our $domain = 'example.com';
84our $defcustid = '5554242';
85our $smtpsender = 'ipdb@example.com';
86# mostly for rwhois
87##fixme: leave these blank by default?
88our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
89our $org_street = '123 4th Street';
90our $org_city = 'Anytown';
91our $org_prov_state = 'ON';
92our $org_pocode = 'H0H 0H0';
93our $org_country = 'CA';
94our $org_phone = '000-555-1234';
95our $org_techhandle = 'ISP-ARIN-HANDLE';
96our $org_email = 'noc@example.com';
97our $hostmaster = 'dns@example.com';
98
99our $syslog_facility = 'local2';
100
101our $rpc_url = '';
102our $revgroup = 1; # should probably be configurable somewhere
103our $rpccount = 0;
104
105# Largest inverse CIDR mask length to show per-IP rDNS list
106# (eg, NetAddr::IP->bits - NetAddr::IP->masklen)
107our $maxrevlist = 5; # /27
108
109# UI layout for subblocks/containers
110our $sublistlayout = 1;
111
112# VLAN validation mode. Set to 0 to allow alphanumeric vlan names instead of using the vlan number.
113our $numeric_vlan = 1;
114
115
116##
117## Internal utility functions
118##
119
120## IPDB::_rpc
121# Make an RPC call for DNS changes
122sub _rpc {
123 return if !$rpc_url; # Just In Case
124 my $rpcsub = shift;
125 my %args = @_;
126
127 # Make an object to represent the XML-RPC server.
128 my $server = Frontier::Client->new(url => $rpc_url, debug => 0);
129 my $result;
130
131 my %rpcargs = (
132 rpcsystem => 'ipdb',
133# must be provided by caller's caller
134# rpcuser => $args{user},
135 %args,
136 );
137
138 eval {
139 $result = $server->call("dnsdb.$rpcsub", %rpcargs);
140 };
141 if ($@) {
142 $errstr = $@;
143 $errstr =~ s/\s*$//;
144 $errstr =~ s/Fault returned from XML RPC Server, fault code 4: error executing RPC `dnsdb.$rpcsub'\.\s//;
145 }
146 $rpccount++;
147
148 return $result if $result;
149} # end _rpc()
150
151
152## IPDB::_compactFree()
153# Utility sub to compact a set of free block entries down to the minimum possible set of CIDR entries
154# Not to be called outside of an eval{}!
155sub _compactFree {
156 my $dbh = shift;
157
158 my $parent = shift;
159
160 # Rather than having the caller provide all the details
161 my $pinfo = getBlockData($dbh, $parent);
162 my $ftype = (split //, $pinfo->{type})[1];
163
164# NetAddr::IP->compact() attempts to produce the smallest inclusive block
165# from the caller and the passed terms.
166# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
167# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
168# .64-.95, and .96-.128), you will get an array containing a single
169# /25 as element 0 (.0-.127). Order is not important; you could have
170# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
171
172##fixme: vrf
173##fixme: simplify since all containers now represent different "layers"/"levels"?
174
175 # set up the query to get the list of blocks to try to merge.
176 my $sth = $dbh->prepare(q{
177 SELECT cidr,id FROM freeblocks
178 WHERE parent_id = ?
179 ORDER BY masklen(cidr) DESC
180 });
181 $sth->execute($parent);
182
183 my (@rawfb, @combinelist, %rawid);
184 my $i=0;
185 # for each free block under $parent, push a NetAddr::IP object into one list, and
186 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
187 while (my ($fcidr, $fid) = $sth->fetchrow_array) {
188 my $testIP = new NetAddr::IP $fcidr;
189 push @rawfb, $testIP;
190 $rawid{"$testIP"} = $fid; # $data[0] vs "$testIP" *does* make a difference for v6
191 @combinelist = $testIP->compact(@combinelist);
192 }
193
194 # now that we have the full list of "compacted" freeblocks, go back over
195 # the list of raw freeblocks, and delete the ones that got merged.
196 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
197 foreach my $rawfree (@rawfb) {
198 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
199 $sth->execute($rawid{$rawfree});
200 }
201
202 # now we walk the new list of compacted blocks, and see which ones we need to insert
203 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,master_id) VALUES (?,?,?,?,?)");
204 foreach my $cme (@combinelist) {
205 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
206 $sth->execute($cme, $pinfo->{city}, $ftype, $parent, $pinfo->{master_id});
207 }
208
209} # end _compactFree()
210
211
212##
213## Public subs
214##
215
216
217## IPDB::initIPDBGlobals()
218# Initialize all globals. Takes a database handle, returns a success or error code
219sub initIPDBGlobals {
220 my $dbh = $_[0];
221 my $sth;
222
223 # Initialize alloctypes hashes
224 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
225 $sth->execute;
226 while (my @data = $sth->fetchrow_array) {
227 $disp_alloctypes{$data[0]} = $data[2];
228 $def_custids{$data[0]} = $data[4];
229 if ($data[3] < 900) {
230 $list_alloctypes{$data[0]} = $data[1];
231 }
232 }
233
234 # City and POP listings
235 $sth = $dbh->prepare("select city,routing from cities order by city");
236 $sth->execute;
237 return (undef,$sth->errstr) if $sth->err;
238 while (my @data = $sth->fetchrow_array) {
239 push @citylist, $data[0];
240 if ($data[1] eq 'y') {
241 push @poplist, $data[0];
242 }
243 }
244
245 # Load ACL data. Specific username checks are done at a different level.
246 $sth = $dbh->prepare("select username,acl from users");
247 $sth->execute;
248 return (undef,$sth->errstr) if $sth->err;
249 while (my @data = $sth->fetchrow_array) {
250 $IPDBacl{$data[0]} = $data[1];
251 }
252
253##fixme: initialize HTML::Template env var for template path
254# something like $self->path().'/templates' ?
255# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
256
257 return (1,"OK");
258} # end initIPDBGlobals
259
260
261## IPDB::connectDB()
262# Creates connection to IPDB.
263# Requires the database name, username, and password.
264# Returns a handle to the db.
265# Set up for a PostgreSQL db; could be any transactional DBMS with the
266# right changes.
267sub connectDB {
268 my $dbname = shift;
269 my $user = shift;
270 my $pass = shift;
271 my $dbhost = shift;
272
273 my $dbh;
274 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
275
276# Note that we want to autocommit by default, and we will turn it off locally as necessary.
277# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
278 $dbh = DBI->connect($DSN, $user, $pass, {
279 AutoCommit => 1,
280 PrintError => 0
281 })
282 or return (undef, $DBI::errstr) if(!$dbh);
283
284# Return here if we can't select. Note that this indicates a
285# problem executing the select.
286 my $sth = $dbh->prepare("select type from alloctypes");
287 $sth->execute();
288 return (undef,$DBI::errstr) if ($sth->err);
289
290# See if the select returned anything (or null data). This should
291# succeed if the select executed, but...
292 $sth->fetchrow();
293 return (undef,$DBI::errstr) if ($sth->err);
294
295# If we get here, we should be OK.
296 return ($dbh,"DB connection OK");
297} # end connectDB
298
299
300## IPDB::finish()
301# Cleans up after database handles and so on.
302# Requires a database handle
303sub finish {
304 my $dbh = $_[0];
305 $dbh->disconnect if $dbh;
306} # end finish
307
308
309## IPDB::checkDBSanity()
310# Quick check to see if the db is responding. A full integrity
311# check will have to be a separate tool to walk the IP allocation trees.
312sub checkDBSanity {
313 my ($dbh) = $_[0];
314
315 if (!$dbh) {
316 print "No database handle, or connection has been closed.";
317 return -1;
318 } else {
319 # it connects, try a stmt.
320 my $sth = $dbh->prepare("select type from alloctypes");
321 my $err = $sth->execute();
322
323 if ($sth->fetchrow()) {
324 # all is well.
325 return 1;
326 } else {
327 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
328 return -1;
329 }
330 }
331 # Clean up after ourselves.
332# $dbh->disconnect;
333} # end checkDBSanity
334
335
336## IPDB::addMaster()
337# Does all the magic necessary to sucessfully add a master block
338# Requires database handle, block to add
339# Returns failure code and error message or success code and "message"
340sub addMaster {
341 my $dbh = shift;
342 # warning! during testing, this somehow generated a "Bad file descriptor" error. O_o
343 my $cidr = new NetAddr::IP shift;
344 my %args = @_;
345
346 $args{vrf} = '' if !$args{vrf};
347 $args{rdns} = '' if !$args{rdns};
348 $args{defloc} = '' if !$args{defloc};
349 $args{rwhois} = 'n' if !$args{rwhois}; # fail "safe", sort of.
350 $args{rwhois} = 'n' if $args{rwhois} ne 'n' and $args{rwhois} ne 'y';
351
352 my $mid;
353
354 # Allow transactions, and raise an exception on errors so we can catch it later.
355 # Use local to make sure these get "reset" properly on exiting this block
356 local $dbh->{AutoCommit} = 0;
357 local $dbh->{RaiseError} = 1;
358
359 # Wrap all the SQL in a transaction
360 eval {
361 # First check - does the master exist? Ignore VRFs until we can see a sane UI
362 my ($mcontained) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr >>= ? AND type = 'mm'",
363 undef, ($cidr) );
364 die "Master block $mcontained already exists and entirely contains $cidr\n"
365 if $mcontained;
366
367 # Second check - does the new master contain an existing one or ones?
368 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr <<= ? AND type = 'mm'",
369 undef, ($cidr) );
370
371 if (!$mexist) {
372 # First case - master is brand-spanking-new.
373##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
374## maybe a db table called "config"?
375 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
376 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
377 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
378
379# Unrouted blocks aren't associated with a city (yet). We don't rely on this
380# elsewhere though; legacy data may have traps and pitfalls in it to break this.
381# Thus the "routed" flag.
382 $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
383 ($cidr, '<NULL>', 'm', $mid, $args{vrf}, $mid) );
384
385 # master should be its own master, so deletes directly at the master level work
386 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
387
388 # If we get here, everything is happy. Commit changes.
389 $dbh->commit;
390
391 } # done new master does not contain existing master(s)
392 else {
393
394 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
395 my $smallmask = $cidr->masklen;
396 my $sth = $dbh->prepare("SELECT cidr,id FROM allocations WHERE cidr <<= ? AND type='mm' AND parent_id=0");
397 $sth->execute($cidr);
398 my @cmasters;
399 my @oldmids;
400 while (my @data = $sth->fetchrow_array) {
401 my $master = new NetAddr::IP $data[0];
402 push @cmasters, $master;
403 push @oldmids, $data[1];
404 $smallmask = $master->masklen if $master->masklen > $smallmask;
405 }
406
407 # split the new master, and keep only those blocks not part of an existing master
408 my @blocklist;
409 foreach my $seg ($cidr->split($smallmask)) {
410 my $contained = 0;
411 foreach my $master (@cmasters) {
412 $contained = 1 if $master->contains($seg);
413 }
414 push @blocklist, $seg if !$contained;
415 }
416
417##fixme: master_id
418 # collect the unrouted free blocks within the new master
419 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm'");
420 $sth->execute($smallmask, $cidr);
421 while (my @data = $sth->fetchrow_array) {
422 my $freeblock = new NetAddr::IP $data[0];
423 push @blocklist, $freeblock;
424 }
425
426 # combine the set of free blocks we should have now.
427 @blocklist = Compact(@blocklist);
428
429 # master
430 $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
431 ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
432 ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
433
434 # master should be its own master, so deletes directly at the master level work
435 $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
436
437 # and now insert the new data. Make sure to delete old masters too.
438
439 # freeblocks
440 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ? AND parent_id IN (".join(',', @oldmids).")");
441 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id)".
442 " VALUES (?,'<NULL>','m',?,?,?)");
443 foreach my $newblock (@blocklist) {
444 $sth->execute($newblock);
445 $sth2->execute($newblock, $mid, $args{vrf}, $mid);
446 }
447
448 # Update immediate allocations, and remove the old parents
449 $sth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
450 $sth2 = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
451 foreach my $old (@oldmids) {
452 $sth->execute($mid, $old);
453 $sth2->execute($old);
454 }
455
456 # *whew* If we got here, we likely suceeded.
457 $dbh->commit;
458
459 } # new master contained existing master(s)
460 }; # end eval
461
462 if ($@) {
463 my $msg = $@;
464 eval { $dbh->rollback; };
465 return ('FAIL',$msg);
466 } else {
467
468 # Only attempt rDNS if the IPDB side succeeded
469 if ($rpc_url) {
470
471# Note *not* splitting reverse zones negates any benefit from caching the exported data.
472# IPv6 address space is far too large to split usefully, and in any case (also due to
473# the large address space) doesn't support the iterated template records v4 zones do
474# that causes the bulk of the slowdown that needs the cache anyway.
475
476 my @zonelist;
477# allow splitting reverse zones to be disabled, maybe, someday
478#if ($splitrevzones && !$cidr->{isv6}) {
479 if (1 && !$cidr->{isv6}) {
480 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
481 @zonelist = $cidr->split($splitpoint);
482 } else {
483 @zonelist = ($cidr);
484 }
485 my @fails;
486 ##fixme: remove hardcoding where possible
487 foreach my $subzone (@zonelist) {
488 my %rpcargs = (
489 rpcuser => $args{user},
490 revzone => "$subzone",
491 revpatt => $args{rdns},
492 defloc => $args{defloc},
493 group => $revgroup, # not sure how these two could sanely be exposed, tbh...
494 state => 1, # could make them globally configurable maybe
495 );
496 if ($rpc_url && !_rpc('addRDNS', %rpcargs)) {
497 push @fails, ("$subzone" => $errstr);
498 }
499 }
500 if (@fails) {
501 $errstr = "Warning(s) adding $cidr to reverse DNS:\n".join("\n", @fails);
502 return ('WARN',$mid);
503 }
504 }
505 return ('OK',$mid);
506 }
507} # end addMaster
508
509
510## IPDB::touchMaster()
511# Update last-changed timestamp on a master block.
512sub touchMaster {
513 my $dbh = shift;
514 my $master = shift;
515
516 local $dbh->{AutoCommit} = 0;
517 local $dbh->{RaiseError} = 1;
518
519 eval {
520 $dbh->do("UPDATE allocations SET modifystamp=now() WHERE id = ?", undef, ($master));
521 $dbh->commit;
522 };
523
524 if ($@) {
525 my $msg = $@;
526 eval { $dbh->rollback; };
527 return ('FAIL',$msg);
528 }
529 return ('OK','OK');
530} # end touchMaster()
531
532
533## IPDB::listSummary()
534# Get summary list of all master blocks
535# Returns an arrayref to a list of hashrefs containing the master block, routed count,
536# allocated count, free count, and largest free block masklength
537sub listSummary {
538 my $dbh = shift;
539
540 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master,id,vrf FROM allocations ".
541 "WHERE type='mm' ORDER BY cidr",
542 { Slice => {} });
543
544 foreach (@{$mlist}) {
545 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm' AND master_id = ?",
546 undef, ($$_{master}, $$_{id}));
547 $$_{routed} = $rcnt;
548 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
549 "AND NOT type='rm' AND NOT type='mm' AND master_id = ?",
550 undef, ($$_{master}, $$_{id}));
551 $$_{allocated} = $acnt;
552 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?",
553 undef, ($$_{master}, $$_{id}));
554 $$_{free} = $fcnt;
555 my ($bigfree) = $dbh->selectrow_array("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
556 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1", undef, ($$_{master}, $$_{id}));
557##fixme: should find a way to do this without having to HTMLize the <>
558 $bigfree = "/$bigfree" if $bigfree;
559 $bigfree = '<NONE>' if !$bigfree;
560 $$_{bigfree} = $bigfree;
561 }
562 return $mlist;
563} # end listSummary()
564
565
566## IPDB::listSubs()
567# Get list of subnets within a specified CIDR block, on a specified VRF.
568# Returns an arrayref to a list of hashrefs containing the CIDR block, customer location or
569# city it's routed to, block type, SWIP status, and description
570sub listSubs {
571 my $dbh = shift;
572 my %args = @_;
573
574 # Just In Case
575 $args{vrf} = '' if !$args{vrf};
576
577 # Snag the allocations for this block
578 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
579 " FROM allocations WHERE parent_id = ? ORDER BY cidr");
580 $sth->execute($args{parent});
581
582 # hack hack hack
583 # set up to flag swip=y records if they don't actually have supporting data in the customers table
584 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
585
586 # snag some more details
587 my $substh = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
588 "AND type ~ '[mc]\$' AND master_id = ? AND NOT cidr = ? ");
589 my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
590 "AND NOT type='rm' AND NOT type='mm' AND master_id = ? AND NOT id = ?");
591 my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
592 my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
593 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
594
595 my @blocklist;
596 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
597 $desc .= " - vrf:$vrf" if $desc && $vrf;
598 $desc = "vrf:$vrf" if !$desc && $vrf;
599 $custsth->execute($custid);
600 my ($ncust) = $custsth->fetchrow_array();
601 $substh->execute($cidr, $mid, $cidr);
602 my ($cont) = $substh->fetchrow_array();
603 $alsth->execute($cidr, $mid, $id);
604 my ($alloc) = $alsth->fetchrow_array();
605 $freesth->execute($cidr, $mid);
606 my ($free) = $freesth->fetchrow_array();
607 $lfreesth->execute($cidr, $mid);
608 my ($lfree) = $lfreesth->fetchrow_array();
609 $lfree = "/$lfree" if $lfree;
610 $lfree = '<NONE>' if !$lfree;
611 my %row = (
612 block => $cidr,
613 subcontainers => $cont,
614 suballocs => $alloc,
615 subfree => $free,
616 lfree => $lfree,
617 city => $city,
618 type => $disp_alloctypes{$type},
619 custid => $custid,
620 swip => ($swip eq 'y' ? 'Yes' : 'No'),
621 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
622 desc => $desc,
623 hassubs => ($type eq 'rm' || $type =~ /.c/ ? 1 : 0),
624 id => $id,
625 );
626# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
627 $row{listpool} = ($type =~ /^.[pd]$/);
628 push (@blocklist, \%row);
629 }
630 return \@blocklist;
631} # end listSubs()
632
633
634## IPDB::listContainers()
635# List all container-type allocations in a given parent
636# Takes a database handle and a hash:
637# - parent is the ID of the parent block
638# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
639# description, block ID, and counts for the nmber uf suballocations (all types),
640# free blocks, and the CIDR size of the largest free block
641sub listContainers {
642 my $dbh = shift;
643 my %args = @_;
644
645 # Just In Case
646 $args{vrf} = '' if !$args{vrf};
647
648 # Snag the allocations for this block
649 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
650 " FROM allocations WHERE parent_id = ? AND type ~ '[mc]\$' ORDER BY cidr");
651 $sth->execute($args{parent});
652
653 my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
654 "AND NOT type='rm' AND NOT type='mm' AND master_id = ? AND NOT id = ?");
655 my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
656 my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
657 " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
658
659 my @blocklist;
660 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
661 $desc .= " - vrf:$vrf" if $desc && $vrf;
662 $desc = "vrf:$vrf" if !$desc && $vrf;
663 $alsth->execute($cidr, $mid, $id);
664 my ($alloc) = $alsth->fetchrow_array();
665 $freesth->execute($cidr, $mid);
666 my ($free) = $freesth->fetchrow_array();
667 $lfreesth->execute($cidr, $mid);
668 my ($lfree) = $lfreesth->fetchrow_array();
669 $lfree = "/$lfree" if $lfree;
670 $lfree = '<NONE>' if !$lfree;
671 my %row = (
672 block => $cidr,
673 suballocs => $alloc,
674 subfree => $free,
675 lfree => $lfree,
676 city => $city,
677 type => $disp_alloctypes{$type},
678 desc => $desc,
679 id => $id,
680 );
681 push (@blocklist, \%row);
682 }
683 return \@blocklist;
684} # end listContainers()
685
686
687## IPDB::listAllocations()
688# List all end-use allocations in a given parent
689# Takes a database handle and a hash:
690# - parent is the ID of the parent block
691# Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
692# custID, SWIP flag, description, block ID, and master ID
693sub listAllocations {
694 my $dbh = shift;
695 my %args = @_;
696
697 # Snag the allocations for this block
698 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
699 " FROM allocations WHERE parent_id = ? AND type !~ '[mc]\$' ORDER BY cidr");
700 $sth->execute($args{parent});
701
702 # hack hack hack
703 # set up to flag swip=y records if they don't actually have supporting data in the customers table
704 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
705
706 my @blocklist;
707 while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
708 $desc .= " - vrf:$vrf" if $desc && $vrf;
709 $desc = "vrf:$vrf" if !$desc && $vrf;
710 $custsth->execute($custid);
711 my ($ncust) = $custsth->fetchrow_array();
712 my %row = (
713 block => $cidr,
714 city => $city,
715 type => $disp_alloctypes{$type},
716 custid => $custid,
717 swip => ($swip eq 'y' ? 'Yes' : 'No'),
718 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
719 desc => $desc,
720 id => $id,
721 );
722# $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
723 $row{listpool} = ($type =~ /^.[pd]$/);
724 push (@blocklist, \%row);
725 }
726 return \@blocklist;
727} # end listAllocations()
728
729
730## IPDB::listFree()
731# Gets a list of free blocks in the requested parent/master and VRF instance in both CIDR and range notation
732# Takes a parent/master ID and an optional VRF specifier that defaults to empty.
733# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
734# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
735sub listFree {
736 my $dbh = shift;
737
738 my %args = @_;
739 # Just In Case
740 $args{vrf} = '' if !$args{vrf};
741
742 my $sth = $dbh->prepare(q(
743 SELECT f.cidr,f.id,allocations.cidr
744 FROM freeblocks f
745 LEFT JOIN allocations ON f.reserve_for = allocations.id
746 WHERE f.parent_id = ?
747 ORDER BY f.cidr
748 ) );
749# $sth->execute($args{parent}, $args{vrf});
750 $sth->execute($args{parent});
751 my @flist;
752 while (my ($cidr,$id,$resv) = $sth->fetchrow_array()) {
753 $cidr = new NetAddr::IP $cidr;
754 my %row = (
755 fblock => "$cidr",
756 frange => $cidr->range,
757 fbid => $id,
758 fbparent => $args{parent},
759 resv => $resv,
760 );
761 push @flist, \%row;
762 }
763 return \@flist;
764} # end listFree()
765
766
767## IPDB::listPool()
768#
769sub listPool {
770 my $dbh = shift;
771 my $pool = shift;
772
773 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,id".
774 " FROM poolips WHERE parent_id = ? ORDER BY ip");
775 $sth->execute($pool);
776 my @poolips;
777 while (my ($ip,$custid,$available,$desc,$type,$id) = $sth->fetchrow_array) {
778 my %row = (
779 ip => $ip,
780 custid => $custid,
781 available => $available,
782 desc => $desc,
783 delme => $available eq 'n',
784 parent => $pool,
785 id => $id,
786 );
787 push @poolips, \%row;
788 }
789 return \@poolips;
790} # end listPool()
791
792
793## IPDB::getMasterList()
794# Get a list of master blocks, optionally including last-modified timestamps
795# Takes an optional flag to indicate whether to include timestamps;
796# 'm' includes ctime, all others (suggest 'c') do not.
797# Returns an arrayref to a list of hashrefs
798sub getMasterList {
799 my $dbh = shift;
800 my $stampme = shift || 'm'; # optional but should be set by caller for clarity
801
802 my $mlist = $dbh->selectall_arrayref("SELECT id,vrf,cidr AS master".($stampme eq 'm' ? ',modifystamp AS mtime' : '').
803 " FROM allocations WHERE type='mm' ORDER BY cidr", { Slice => {} });
804 return $mlist;
805} # end getMasterList()
806
807
808## IPDB::getTypeList()
809# Get an alloctype/description pair list suitable for dropdowns
810# Takes a flag to determine which general groups of types are returned
811# Returns an reference to an array of hashrefs
812sub getTypeList {
813 my $dbh = shift;
814 my $tgroup = shift || 'a'; # technically optional, like this, but should
815 # really be specified in the call for clarity
816 my $seltype = shift || '';
817
818 my $sql = "SELECT type,listname,type=? AS sel FROM alloctypes WHERE listorder <= 500";
819 if ($tgroup eq 'n') {
820 # grouping 'p' - all netblock types. These include routed blocks, containers (_c)
821 # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
822 # and the "miscellaneous" cn, in, and en types.
823 $sql .= " AND type NOT LIKE '_i'";
824 } elsif ($tgroup eq 'p') {
825 # grouping 'p' - primary allocation types. As with 'n' above but without the _r contained types.
826 $sql .= " AND type NOT LIKE '_i' AND type NOT LIKE '_r'";
827 } elsif ($tgroup eq 'c') {
828 # grouping 'c' - contained types. These include all static IPs and all _r types.
829 $sql .= " AND (type LIKE '_i' OR type LIKE '_r')";
830 } elsif ($tgroup eq 'i') {
831 # grouping 'i' - static IP types.
832 $sql .= " AND type LIKE '_i'";
833 } else {
834 # grouping 'a' - all standard allocation types. This includes everything
835 # but mm (present only as a formality). Make this the default.
836 # ... whee! no extra WHERE clauses
837 }
838 $sql .= " ORDER BY listorder";
839 my $tlist = $dbh->selectall_arrayref($sql, { Slice => {} }, $seltype);
840 return $tlist;
841}
842
843
844## IPDB::getPoolSelect()
845# Get a list of pools matching the passed city and type that have 1 or more free IPs
846# Returns an arrayref to a list of hashrefs
847sub getPoolSelect {
848 my $dbh = shift;
849 my $iptype = shift;
850 my $pcity = shift;
851
852 my ($ptype) = ($iptype =~ /^(.)i$/);
853 return if !$ptype;
854 $ptype .= '_';
855
856 my $plist = $dbh->selectall_arrayref( q(
857 SELECT count(*) AS poolfree,p.pool AS poolblock, a.city AS poolcit
858 FROM poolips p
859 JOIN allocations a ON p.parent_id=a.id
860 WHERE p.available='y' AND a.city = ? AND p.type LIKE ?
861 GROUP BY p.pool,a.city
862 ),
863 { Slice => {} }, ($pcity, $ptype) );
864 return $plist;
865} # end getPoolSelect()
866
867
868## IPDB::findAllocateFrom()
869# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
870# Takes
871# - mask length
872# - allocation type
873# - POP city "parent"
874# - optional master-block restriction
875# - optional flag to allow automatic pick-from-private-network-ranges
876# Returns a string with the first CIDR block matching the criteria, if any
877sub findAllocateFrom {
878 my $dbh = shift;
879 my $maskbits = shift;
880 my $type = shift;
881 my $city = shift;
882 my $pop = shift;
883 my %optargs = @_;
884
885 my $failmsg = "No suitable free block found\n";
886
887 my @vallist;
888 my $sql;
889
890 # Free pool IPs should be easy.
891 if ($type =~ /^.i$/) {
892 # User may get an IP from the wrong VRF. User should not be using admin tools to allocate static IPs.
893 $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
894 @vallist = ($optargs{gimme});
895 } else {
896
897## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
898## Very large systems will require development of a reserve system (possibly an extension
899## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
900## Also populate a value list for the DBI call.
901
902 @vallist = ($maskbits);
903 $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
904
905# cases, strict rules
906# .c -> container type
907# requires a routing container, fbtype r
908# .d -> DHCP/"normal-routing" static pool
909# requires a routing container, fbtype r
910# .e -> Dynamic-assignment connectivity
911# requires a routing container, fbtype r
912# .i -> error, can't allocate static IPs this way?
913# mm -> error, master block
914# rm -> routed block
915# requires master block, fbtype m
916# .n -> Miscellaneous usage
917# requires a routing container, fbtype r
918# .p -> PPP(oE) static pool
919# requires a routing container, fbtype r
920# .r -> contained type
921# requires a matching container, fbtype $1
922##fixme: strict-or-not flag
923
924##fixme: config or UI flag for "Strict" mode
925# if ($strictmode) {
926if (0) {
927 if ($type =~ /^(.)r$/) {
928 push @vallist, $1;
929 $sql .= " AND routed = ?";
930 } elsif ($type eq 'rm') {
931 $sql .= " AND routed = 'm'";
932 } else {
933 $sql .= " AND routed = 'r'";
934 }
935}
936
937 # for PPP(oE) and container types, the POP city is the one attached to the pool.
938 # individual allocations get listed with the customer city site.
939 ##fixme: chain cities to align roughly with a full layer-2 node graph
940 $city = $pop if $type !~ /^.[pc]$/;
941 if ($type ne 'rm' && $city) {
942 $sql .= " AND city = ?";
943 push @vallist, $city;
944 }
945 # Allow specifying an arbitrary full block, instead of a master
946 if ($optargs{gimme}) {
947 $sql .= " AND cidr >>= ?";
948 push @vallist, $optargs{gimme};
949 }
950 # if a specific master was requested, allow the requestor to self->shoot(foot)
951 if ($optargs{master} && $optargs{master} ne '-') {
952 $sql .= " AND master_id = ?";
953# if $optargs{master} ne '-';
954 push @vallist, $optargs{master};
955 } else {
956 # if a specific master was NOT requested, filter out the RFC 1918 private networks
957 if (!$optargs{allowpriv}) {
958 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
959 }
960 }
961 # Keep "reserved" blocks out of automatic assignment.
962##fixme: needs a UI flag or a config knob
963 $sql .= " AND reserve_for = 0";
964 # Sorting and limiting, since we don't (currently) care to provide a selection of
965 # blocks to carve up. This preserves something resembling optimal usage of the IP
966 # space by forcing contiguous allocations and free blocks as much as possible.
967 $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
968 } # done setting up SQL for free CIDR block
969
970 my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
971 return $fbid,$fbfound,$fbparent;
972} # end findAllocateFrom()
973
974
975## IPDB::ipParent()
976# Get an IP's parent pool's details
977# Takes a database handle and IP
978# Returns a hashref to the parent pool block, if any
979sub ipParent {
980 my $dbh = shift;
981 my $block = shift;
982
983 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
984 " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
985 return $pinfo;
986} # end ipParent()
987
988
989## IPDB::subParent()
990# Get a block's parent's details
991# Takes a database handle and CIDR block
992# Returns a hashref to the parent container block, if any
993sub subParent {
994 my $dbh = shift;
995 my $block = shift;
996
997 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
998 " WHERE cidr >>= ?", undef, ($block) );
999 return $pinfo;
1000} # end subParent()
1001
1002
1003## IPDB::blockParent()
1004# Get a block's parent's details
1005# Takes a database handle and CIDR block
1006# Returns a hashref to the parent container block, if any
1007sub blockParent {
1008 my $dbh = shift;
1009 my $block = shift;
1010
1011 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
1012 " WHERE cidr >>= ?", undef, ($block) );
1013 return $pinfo;
1014} # end blockParent()
1015
1016
1017## IPDB::getBreadCrumbs()
1018# Retrieve the ID and CIDR of a block's parent(s) up to the master block
1019# Returns an arrayref to a list of hashrefs with CIDR and block ID
1020sub getBreadCrumbs {
1021 my $dbh = shift;
1022 my $parent = shift;
1023 my @result;
1024
1025 my $sth = $dbh-> prepare("SELECT cidr,type,id,parent_id FROM allocations WHERE id=?");
1026
1027 while ($parent != 0) {
1028 $sth->execute($parent);
1029 my ($cidr,$type,$id,$pid) = $sth->fetchrow_array;
1030 push @result, {cidr => $cidr, link => $id, ispool => ($type =~ /^.[dp]$/ ? 1 : 0)};
1031 $parent = $pid;
1032 }
1033
1034 return \@result;
1035} # end getBread()
1036
1037
1038## IPDB::getRoutedCity()
1039# Get the city for a routed block.
1040sub getRoutedCity {
1041 my $dbh = shift;
1042 my $block = shift;
1043
1044 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
1045 return $rcity;
1046} # end getRoutedCity()
1047
1048
1049## IPDB::allocateBlock()
1050# Does all of the magic of actually allocating a netblock
1051# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
1052# type, city, block to allocate from, and optionally a description, notes, circuit ID,
1053# and private data
1054# Returns a success code and optional error message.
1055sub allocateBlock {
1056 my $dbh = shift;
1057
1058 my %args = @_;
1059
1060 $args{cidr} = new NetAddr::IP $args{cidr};
1061
1062 $args{desc} = '' if !$args{desc};
1063 $args{notes} = '' if !$args{notes};
1064 $args{circid} = '' if !$args{circid};
1065 $args{privdata} = '' if !$args{privdata};
1066 $args{vrf} = '' if !$args{vrf};
1067 $args{vlan} = '' if !$args{vlan};
1068 $args{rdns} = '' if !$args{rdns};
1069
1070 # Could arguably allow this for eg /120 allocations, but end users who get a single v4 IP are
1071 # usually given a v6 /64, and most v6 addressing schemes need at least half that address space
1072 if ($args{cidr}->{isv6} && $args{rdns} =~ /\%/) {
1073 return ('FAIL','Reverse DNS template patterns are not supported for IPv6 allocations');
1074 }
1075
1076 my $sth;
1077
1078 # Snag the "type" of the freeblock and its CIDR
1079 my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
1080 $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
1081 undef, $args{fbid});
1082 $alloc_from = new NetAddr::IP $alloc_from;
1083 return ('FAIL',"Failed to allocate $args{cidr}; intended free block was used by another allocation.")
1084 if !$fbparent;
1085##fixme: fail here if !$alloc_from
1086# also consider "lock for allocation" due to multistep allocation process
1087
1088 # To contain the error message, if any.
1089 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
1090
1091 # Enable transactions and error handling
1092 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1093 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1094
1095 if ($args{type} =~ /^.i$/) {
1096 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
1097 eval {
1098 if ($args{cidr}) { # IP specified
1099 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
1100 die "IP is not in an IP pool.\n"
1101 if !$isavail;
1102 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
1103 if $isavail eq 'n';
1104 } else { # IP not specified, take first available
1105 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
1106 undef, ($args{alloc_from}) );
1107 }
1108 $dbh->do("UPDATE poolips SET custid = ?, city = ?,available='n', description = ?, notes = ?, ".
1109 "circuitid = ?, privdata = ?, vrf = ?, rdns = ? ".
1110 "WHERE ip = ? AND parent_id = ?", undef,
1111 ($args{custid}, $args{city}, $args{desc}, $args{notes},
1112 $args{circid}, $args{privdata}, $args{vrf}, $args{rdns},
1113 $args{cidr}, $args{parent}) );
1114
1115# node hack
1116 if ($args{nodeid} && $args{nodeid} ne '') {
1117 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1118 }
1119# end node hack
1120
1121 $dbh->commit; # Allocate IP from pool
1122 };
1123 if ($@) {
1124 $msg .= ": $@";
1125 eval { $dbh->rollback; };
1126 return ('FAIL', $msg);
1127 } else {
1128 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
1129 return ('OK', $args{cidr});
1130 }
1131
1132 } else { # end IP-from-pool allocation
1133
1134 if ($args{cidr} == $alloc_from) {
1135 # Easiest case- insert in one table, delete in the other, and go home. More or less.
1136 # insert into allocations values (cidr,custid,type,city,desc) and
1137 # delete from freeblocks where cidr='cidr'
1138 # For data safety on non-transaction DBs, we delete first.
1139
1140 eval {
1141 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1142
1143 # Insert the allocations entry
1144 $dbh->do("INSERT INTO allocations ".
1145 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1146 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1147 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1148 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1149 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1150
1151 # Munge freeblocks
1152 if ($args{type} =~ /^(.)[mc]$/) {
1153 # special case - block is a routed or container/"reserve" block
1154 my $rtype = $1;
1155 $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
1156 undef, ($rtype, $args{city}, $bid, $args{fbid}) );
1157 } else {
1158 # "normal" case
1159 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1160 }
1161
1162 # And initialize the pool, if necessary
1163 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1164 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1165 if ($args{type} =~ /^.p$/) {
1166 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1167 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1168 die $rmsg if $code eq 'FAIL';
1169 } elsif ($args{type} =~ /^.d$/) {
1170 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1171 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1172 die $rmsg if $code eq 'FAIL';
1173 }
1174
1175# node hack
1176 if ($args{nodeid} && $args{nodeid} ne '') {
1177 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1178 }
1179# end node hack
1180
1181 $dbh->commit; # Simple block allocation
1182 }; # end of eval
1183 if ($@) {
1184 $msg .= ": ".$@;
1185 eval { $dbh->rollback; };
1186 return ('FAIL',$msg);
1187 }
1188
1189 } else { # cidr != alloc_from
1190
1191 # Hard case. Allocation is smaller than free block.
1192
1193 # make sure new allocation is in fact within freeblock. *sigh*
1194 return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1195 if !$alloc_from->contains($args{cidr});
1196 my $wantmaskbits = $args{cidr}->masklen;
1197 my $maskbits = $alloc_from->masklen;
1198
1199 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1200
1201 # This determines which blocks will be left "free" after allocation. We take the
1202 # block we're allocating from, and split it in half. We see which half the wanted
1203 # block is in, and repeat until the wanted block is equal to one of the halves.
1204 my $i=0;
1205 my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
1206 while ($maskbits++ < $wantmaskbits) {
1207 my @subblocks = $tmp_from->split($maskbits);
1208 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1209 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
1210 } # while
1211
1212 # Begin SQL transaction block
1213 eval {
1214 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1215
1216 # Delete old freeblocks entry
1217 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1218
1219 # Insert the allocations entry
1220 $dbh->do("INSERT INTO allocations ".
1221 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1222 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1223 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1224 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1225 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1226
1227 # Insert new list of smaller free blocks left over. Flag the one that matches the
1228 # masklength of the new allocation, if a reserve block was requested.
1229 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id,reserve_for) ".
1230 "VALUES (?,?,?,?,?,?,?)");
1231 foreach my $block (@newfreeblocks) {
1232 $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster,
1233 ($block->masklen == $wantmaskbits ? $bid : 0));
1234 }
1235
1236 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1237 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1238 my $rtype = $1;
1239 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster, 0);
1240 }
1241
1242 # And initialize the pool, if necessary
1243 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1244 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1245 if ($args{type} =~ /^.p$/) {
1246 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1247 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1248 die $rmsg if $code eq 'FAIL';
1249 } elsif ($args{type} =~ /^.d$/) {
1250 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1251 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1252 die $rmsg if $code eq 'FAIL';
1253 }
1254
1255# node hack
1256 if ($args{nodeid} && $args{nodeid} ne '') {
1257 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1258 }
1259# end node hack
1260
1261 $dbh->commit; # Complex block allocation
1262 }; # end eval
1263 if ($@) {
1264 $msg .= ": ".$@;
1265 eval { $dbh->rollback; };
1266 return ('FAIL',$msg);
1267 }
1268
1269 } # end fullcidr != alloc_from
1270
1271 # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1272 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1273 if $args{rdns};
1274
1275 # and the per-IP set, if there is one.
1276 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user});
1277
1278 return ('OK', 'OK');
1279
1280 } # end static-IP vs netblock allocation
1281
1282} # end allocateBlock()
1283
1284
1285## IPDB::initPool()
1286# Initializes a pool
1287# Requires a database handle, the pool CIDR, type, city, and a parameter
1288# indicating whether the pool should allow allocation of literally every
1289# IP, or if it should reserve network/gateway/broadcast IPs
1290# Note that this is NOT done in a transaction, that's why it's a private
1291# function and should ONLY EVER get called from allocateBlock()
1292sub initPool {
1293 my ($dbh,undef,$type,$city,$class,$parent) = @_;
1294 my $pool = new NetAddr::IP $_[1];
1295
1296 # IPv6 does not lend itself to IP pools as supported
1297 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1298 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1299 # NetAddr::IP won't allow more than a /16 (65k hosts).
1300 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1301
1302 # Retrieve some odds and ends for defaults on the IPs
1303 my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
1304 my ($vrf,$vlan,$master) = $dbh->selectrow_array("SELECT vrf,vlan,master_id FROM allocations WHERE id = ?",
1305 undef, ($parent) );
1306
1307 $type =~ s/[pd]$/i/;
1308 my $sth;
1309 my $msg;
1310
1311 # Trap errors so we can pass them back to the caller. Even if the
1312 # caller is only ever supposed to be local, and therefore already
1313 # trapping errors. >:(
1314 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1315 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1316
1317 eval {
1318 # have to insert all pool IPs into poolips table as "unallocated".
1319 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1320
1321 # in case of pool extension by some means, we need to see what IPs were already inserted
1322 my $tmp1 = $dbh->selectall_arrayref("SELECT ip FROM poolips WHERE parent_id = ?", undef, $parent);
1323 my %foundips;
1324 foreach (@{$tmp1}) {
1325 $foundips{$_->[0]} = 1;
1326 }
1327
1328# Dodge an edge case - pool where IPs have been "stolen" and turned into a netblock assignment.
1329# We can't just "get all the current IPs, and add the missing ones", because some IPs are
1330# legitimately missing (for stretchy values of "legitimately").
1331
1332 my $pdata = getBlockData($dbh, $parent);
1333 my $pcidr = new NetAddr::IP $pdata->{block};
1334
1335 if ($pcidr != $pool) {
1336 # enumerate the IPs from the *old* pool, flag them as "found", so we can iterate the entire
1337 # requested pool and still make sure we skip the IPs in the old pool - even if they've been
1338 # "stolen" by legacy netblocks.
1339 my @oldips = $pcidr->hostenum;
1340 # decide whether to start excluding existing IPs at the "gateway" or "gateway+1"
1341 my $ostart = ($pdata->{type} =~ /^.d$/ ? 1 : 0);
1342 for (my $i = $ostart; $i<= $#oldips; $i++) {
1343 $foundips{$oldips[$i]} = 1;
1344 }
1345 }
1346
1347 # enumerate the hosts in the IP range - everything except the first (net) and last (bcast) IP
1348 my @poolip_list = $pool->hostenum;
1349
1350 # always check/add IPs from gw+1 through bcast-1:
1351 # (but the set won't be in oooorderrrrr! <pout>)
1352 for (my $i=1; $i<=$#poolip_list; $i++) {
1353 my $baseip = $poolip_list[$i]->addr;
1354 if ($baseip !~ /\.(?:0|255)$/ && !$foundips{$poolip_list[$i]}) {
1355 $sth->execute($baseip, $pcustid, $city, $type, $parent, $master);
1356 }
1357 }
1358
1359 # now do the special case - DSL/PPP blocks can use the "net", "gw", and "bcast" IPs.
1360 # we exclude .0 and .255 anyway, since while they'll mostly work, they *will* behave badly here and there.
1361 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
1362 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
1363 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1364 }
1365 $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$poolip_list[0]};
1366 $pool--;
1367 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
1368 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1369 }
1370 }
1371# don't commit here! the caller may not be done.
1372# $dbh->commit;
1373 };
1374 if ($@) {
1375 $msg = $@;
1376# Don't roll back! It's up to the caller to handle this.
1377# eval { $dbh->rollback; };
1378 return ('FAIL',$msg);
1379 } else {
1380 return ('OK',"OK");
1381 }
1382} # end initPool()
1383
1384
1385## IPDB::updateBlock()
1386# Update an allocation
1387# Takes all allocation fields in a hash
1388sub updateBlock {
1389 my $dbh = shift;
1390 my %args = @_;
1391
1392 return ('FAIL', 'Missing block to update') if !$args{block};
1393
1394 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1395 $args{custid} =~ s/^\s+//;
1396 $args{custid} =~ s/\s+$//;
1397
1398 # do it all in a transaction
1399 local $dbh->{AutoCommit} = 0;
1400 local $dbh->{RaiseError} = 1;
1401
1402 my @fieldlist;
1403 my @vallist;
1404 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
1405 if ($args{$_}) {
1406 push @fieldlist, $_;
1407 push @vallist, $args{$_};
1408 }
1409 }
1410
1411 my $binfo;
1412 my $updtable = 'allocations';
1413 my $keyfield = 'id';
1414 if ($args{type} =~ /^(.)i$/) {
1415 $updtable = 'poolips';
1416 $binfo = getBlockData($dbh, $args{block}, 'i');
1417 } else {
1418## fixme: there's got to be a better way...
1419 $binfo = getBlockData($dbh, $args{block});
1420 if ($args{swip}) {
1421 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1422 $args{swip} = 'y';
1423 } else {
1424 $args{swip} = 'n';
1425 }
1426 }
1427 foreach ('type', 'swip') {
1428 if ($args{$_}) {
1429 push @fieldlist, $_;
1430 push @vallist, $args{$_};
1431 }
1432 }
1433 }
1434
1435 return ('FAIL', 'No fields to update') if !@fieldlist;
1436
1437 my $sql = "UPDATE $updtable SET ";
1438 $sql .= join " = ?, ", @fieldlist;
1439
1440 eval {
1441 # check for block merge first...
1442 if ($args{fbmerge}) {
1443 my $cidr = NetAddr::IP->new($binfo->{block});
1444 my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1445 # safety net? make sure mergeable block passed in is really one or both of
1446 # a) reserved for expansion of the block and
1447 # b) confirmed CIDR-combinable
1448 # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
1449 $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
1450 # ... so we can append the change in the stored CIDR field to extend the allocation.
1451 $sql .= " = ?, cidr";
1452 push @vallist, $newblock;
1453 # if we have an IP pool, call initPool to fill in any missing entries in the pool
1454 if ($binfo->{type} =~ /^.p$/) {
1455 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
1456 die $rmsg if $code eq 'FAIL';
1457 } elsif ($binfo->{type} =~ /^.d$/) {
1458 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
1459 die $rmsg if $code eq 'FAIL';
1460 }
1461 }
1462
1463 # append another SQL fragment
1464 push @vallist, $args{block};
1465 $sql .= " = ? WHERE $keyfield = ?";
1466
1467 # do the update
1468 $dbh->do($sql, undef, @vallist);
1469
1470 if ($args{node}) {
1471 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1472 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1473 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1474 if $args{node} ne '--';
1475 }
1476
1477 $dbh->commit;
1478 };
1479 if ($@) {
1480 my $msg = $@;
1481 $dbh->rollback;
1482 return ('FAIL', $msg);
1483 }
1484
1485 # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
1486 # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
1487 if ($binfo->{type} =~ '.[mc]') {
1488 # Not using listFree() as it doesn't return quite all of the blocks wanted.
1489 # Retrieve the immediate free blocks
1490 my $sth = $dbh->prepare(q(
1491 SELECT cidr FROM freeblocks WHERE parent_id = ?
1492 UNION
1493 SELECT cidr FROM freeblocks f WHERE
1494 cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
1495 AND master_id = ?
1496 ) );
1497 $sth->execute($args{block}, $binfo->{master_id});
1498 my %fbset;
1499 while (my ($fb) = $sth->fetchrow_array) {
1500 $fbset{"host_$fb"} = $args{rdns};
1501 }
1502 # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
1503 # know how many records we'll be updating and more than 3-4 is far too slow. This
1504 # should be safe to call unconditionally.
1505 # Requires dnsadmin >= r678
1506 _rpc('updateRevSet', %fbset, rpcuser => $args{user});
1507
1508 } else {
1509 $binfo->{block} =~ s|/32$||;
1510 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
1511
1512 # and the per-IP set, if there is one.
1513 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}) if keys (%{$args{iprev}});
1514 }
1515
1516 return ('OK','OK');
1517} # end updateBlock()
1518
1519
1520## IPDB::splitBlock()
1521# Splits an existing allocation into two or more smaller allocations based on a passed netmask
1522# Duplicates all other data
1523# Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
1524# Should probably commit DNS magic to realign DNS data
1525# Mostly works but may return Strange Things(TM) if used on a master block
1526sub splitBlock {
1527 my $dbh = shift;
1528 my %args = @_;
1529# my $id = shift;
1530# my $basetype = shift;
1531# my $newmask = shift;
1532
1533##fixme: set errstr on errors so caller can suitably clue-by-four the user
1534 return if $args{basetype} ne 'b'; # only netblocks allowed!
1535
1536 my $binfo = getBlockData($dbh, $args{id});
1537 return if !$binfo;
1538
1539 return if $args{newmask} !~ /^\d+$/;
1540
1541 my @ret;
1542 my $block = new NetAddr::IP $binfo->{block};
1543 my $oldmask = $block->masklen;
1544
1545 # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
1546 # failure modes:
1547 # difference between $oldmask and $newmask is negative or 0
1548 if ($args{newmask} - $oldmask <= 0) {
1549 $errstr = "Can't split a /$oldmask allocation into /$args{newmask} pieces";
1550 return;
1551 }
1552# # difference between $oldmask and $newmask is > n, for arbitrary n?
1553# if ($newmask - $oldmask > 42) { # because 42
1554# }
1555 # $oldmask > n, for arbitrary n? At least check limits of data type.
1556 if ($block->{isv6}) {
1557 if ($args{newmask} - $oldmask > 128) {
1558 $errstr = "Impossible IPv6 mask length /$args{newmask} requested";
1559 return;
1560 }
1561 } else {
1562 if ($args{newmask} - $oldmask > 32) {
1563 $errstr = "Impossible IPv4 mask length /$args{newmask} requested";
1564 return;
1565 }
1566 }
1567
1568 my @newblocks = $block->split($args{newmask});
1569
1570 local $dbh->{AutoCommit} = 0;
1571 local $dbh->{RaiseError} = 1;
1572
1573 eval {
1574 # line up a list of fields and values. Be nice if there was a handy way to do,
1575 # direct in SQL, something like
1576 # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
1577 my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id);
1578 my $fields_sql = join(',', @fieldlist);
1579 my @vals;
1580 foreach (@fieldlist) {
1581 push @vals, $binfo->{$_};
1582 }
1583 # note the first block in the split for return
1584 push @ret, {nid => $args{id}, nblock => "$newblocks[0]"};
1585
1586 # prepare
1587 my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
1588 my $allocsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
1589 " VALUES (?".',?'x(scalar(@fieldlist)).")");
1590 my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1591 my $upd_psth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1592 my $upd_msth = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1593 my $fb_psth = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1594 my $fb_msth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1595 my $pool_psth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE parent_id = ? AND ip << ?");
1596 my $pool_msth = $dbh->prepare("UPDATE poolips SET master_id = ? WHERE master_id = ? AND ip <<= ?");
1597
1598 # set up update of existing block
1599 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$newblocks[0]", $args{id}) );
1600
1601 # axe the new bcast IP from the smaller pool at the "base" block, if it's a "normal" pool
1602 if ($binfo->{type} =~ /.d/) {
1603 $newblocks[0]--;
1604 $nbsth->execute($args{id}, $newblocks[0]->addr);
1605 }
1606
1607 # Loop over the new blocks that are not the base block
1608 for (my $i = 1; $i <= $#newblocks; $i++) {
1609 # add the new allocation
1610 $allocsth->execute($newblocks[$i], @vals);
1611 # fetch the ID of the entry we just added...
1612 $idsth->execute();
1613 my ($nid) = $idsth->fetchrow_array();
1614 # ... so we can pass back the list of blocks and IDs...
1615 push @ret, {nid => $nid, nblock => "$newblocks[$i]"};
1616 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
1617 if ($binfo->{type} =~ /.d/) {
1618 # net
1619 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1620 $newblocks[$i]++;
1621 # gw
1622 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1623 $newblocks[$i]--;
1624 $newblocks[$i]--;
1625 # bcast
1626 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1627 $newblocks[$i]++;
1628 }
1629
1630 # Reparent allocations, freeblocks, and pool IPs.
1631 $upd_psth->execute($nid, $args{id}, $newblocks[$i]);
1632 $fb_psth->execute($nid, $args{id}, $newblocks[$i]);
1633 $pool_psth->execute($nid, $args{id}, $newblocks[$i]);
1634
1635 # Update master if we've split a master block
1636 if ($binfo->{type} eq 'mm') {
1637 $upd_msth->execute($nid, $args{id}, $newblocks[$i]);
1638 $fb_msth->execute($nid, $args{id}, $newblocks[$i]);
1639 $pool_msth->execute($nid, $args{id}, $newblocks[$i]);
1640 }
1641
1642 } # for (... @newblocks)
1643
1644 $dbh->commit;
1645 };
1646 if ($@) {
1647 $errstr = "Error splitting $binfo->{block}: $@";
1648 $dbh->rollback;
1649 return;
1650 }
1651##fixme: RPC return code?
1652# particularly useful in this case as there may be arbitrary combinations of pass, warn, fail
1653# results from each of the update and add(s), which could get the user to prod dnsadmin to see what exploded
1654 my $foo = _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user});
1655
1656 return \@ret;
1657} # end splitBlock()
1658
1659
1660## IPDB::shrinkBlock()
1661# Shrink an allocation to the passed CIDR block
1662# Takes an allocation ID and a new CIDR
1663# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
1664# Refuses to shrink "real netblock" pool types below /30
1665sub shrinkBlock {
1666 my $dbh = shift;
1667 my $id = shift;
1668
1669 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
1670 my $newblock = new NetAddr::IP shift;
1671
1672 if (!$newblock) {
1673 $errstr = "Can't shrink something that's not a netblock";
1674 return;
1675 }
1676
1677 my $binfo = getBlockData($dbh, $id);
1678 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1679
1680 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
1681 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
1682 return;
1683 }
1684
1685 my $oldblock = new NetAddr::IP $binfo->{block};
1686
1687 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
1688 if (!$oldblock->contains($newblock)) {
1689 $errstr = "Can't shrink an allocation outside of itself";
1690 return;
1691 }
1692
1693 local $dbh->{AutoCommit} = 0;
1694 local $dbh->{RaiseError} = 1;
1695
1696 my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1697 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
1698 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
1699 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1700 my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
1701 my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
1702
1703##fixme: turn this into a public/top-level sub?
1704 sub getchildren {
1705 my $dbh = shift;
1706 my $id = shift;
1707 my $master = shift;
1708 my $retlist = shift; # better than trying to return complex structures recursively. Ow.
1709 my $cidr = shift;
1710
1711 if (!$cidr) {
1712 my $bd = getBlockData($dbh, $id);
1713 $cidr = $bd->{cidr};
1714 }
1715
1716 my $sth = $dbh->prepare(q(
1717 SELECT id,cidr,type FROM allocations
1718 WHERE parent_id = ? AND master_id = ? AND cidr <<= ?
1719 ) );
1720 $sth->execute($id, $master, $cidr);
1721 while (my $row = $sth->fetchrow_hashref) {
1722 push @$retlist, $row;
1723 getchildren($dbh, $row->{id}, $master, $retlist, $cidr);
1724 }
1725 }
1726
1727 my @ret;
1728 eval {
1729 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
1730
1731 # find the netblock(s) that are now free
1732 my @workingblocks = $oldblock->split($newblock->masklen);
1733 my @wb2;
1734 foreach my $newsub (@workingblocks) {
1735 next if $newsub == $newblock;
1736 push @wb2, $newsub;
1737 }
1738 @wb2 = Compact(@wb2);
1739
1740 # set new freeblocks, and clean up any IP pool entries if needed.
1741 foreach my $newfree (@wb2) {
1742 my @clist;
1743 # the block we're munging
1744 push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
1745 getchildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
1746
1747 foreach my $goner (@clist) {
1748 $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
1749 $allocsth->execute($goner->{id}, $newfree);
1750 $delfbsth->execute($goner->{id}, $newfree);
1751 }
1752
1753 # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
1754 if ($pinfo) {
1755 $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
1756 $idsth->execute;
1757 my ($nid) = $idsth->fetchrow_array();
1758 # add to return list
1759 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
1760 }
1761
1762 } # $newfree (@wb2)
1763
1764 # additional cleanup on net/gw/bcast IPs in pool
1765 if ($binfo->{type} =~ /.d/) {
1766 $netsth->execute($id, $newblock->addr);
1767 $newblock++;
1768 $netsth->execute($id, $newblock->addr);
1769 $newblock--;
1770 $newblock--;
1771 $netsth->execute($id, $newblock->addr);
1772 }
1773
1774 $dbh->commit;
1775 };
1776 if ($@) {
1777 $errstr = "Error splitting $binfo->{block}: $@";
1778 $dbh->rollback;
1779 return;
1780 }
1781
1782 return \@ret;
1783} # end shrinkBlock()
1784
1785
1786## IPDB::deleteBlock()
1787# Removes an allocation from the database, including deleting IPs
1788# from poolips and recombining entries in freeblocks if possible
1789# Also handles "deleting" a static IP allocation, and removal of a master
1790# Requires a database handle, the block to delete, the routing depth (if applicable),
1791# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
1792# as well as the reverse entry
1793sub deleteBlock {
1794 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
1795
1796 # Collect info about the block we're going to delete
1797 my $binfo = getBlockData($dbh, $id, $basetype);
1798 my $cidr = new NetAddr::IP $binfo->{block};
1799
1800# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1801# is_rfc1918 requires NetAddr::IP >= 4.059
1802# rather than doing this over and over and over.....
1803 my $tmpnum = $cidr->numeric;
1804# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1805# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1806# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1807 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1808 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1809 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1810
1811 my $sth;
1812
1813 # Magic variables used for odd allocation cases.
1814 my $container;
1815 my $con_type;
1816
1817
1818 # temporarily forced null, until a sane UI for VRF tracking can be found.
1819# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
1820
1821 # To contain the error message, if any.
1822 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1823 my $goback; # to put the parent in so we can link back where the deallocate started
1824
1825 # Enable transactions and exception-on-errors... but only for this sub
1826 local $dbh->{AutoCommit} = 0;
1827 local $dbh->{RaiseError} = 1;
1828
1829 if ($binfo->{type} =~ /^.i$/) {
1830 # First case. The "block" is a static IP
1831 # Note that we still need some additional code in the odd case
1832 # of a netblock-aligned contiguous group of static IPs
1833
1834 eval {
1835 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1836 my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
1837##fixme: VRF and rdepth
1838 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
1839 "city = (SELECT city FROM allocations WHERE id = ?),".
1840 "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
1841 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
1842 $dbh->commit;
1843 };
1844 if ($@) {
1845 $msg .= ": $@";
1846 eval { $dbh->rollback; };
1847 return ('FAIL',$msg);
1848 } else {
1849##fixme: RPC return code?
1850 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
1851 return ('OK',"OK");
1852 }
1853
1854 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
1855 # Second case. The block is a full master block
1856
1857##fixme: VRF limit
1858 $msg = "Unable to delete master block $cidr";
1859 eval {
1860 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1861 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1862 $dbh->commit;
1863 };
1864 if ($@) {
1865 $msg .= ": $@";
1866 eval { $dbh->rollback; };
1867 return ('FAIL', $msg);
1868 }
1869
1870 # Have to handle potentially split reverse zones. Assume they *are* split,
1871 # since if we added them here, they would have been added split.
1872# allow splitting reverse zones to be disabled, maybe, someday
1873#if ($splitrevzones && !$cidr->{isv6}) {
1874 my @zonelist;
1875 if (1 && !$cidr->{isv6}) {
1876 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
1877 @zonelist = $cidr->split($splitpoint);
1878 } else {
1879 @zonelist = ($cidr);
1880 }
1881 my @fails;
1882 foreach my $subzone (@zonelist) {
1883 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
1884 push @fails, ("$subzone" => $errstr);
1885 }
1886 }
1887 if (@fails) {
1888 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
1889 }
1890 return ('OK','OK');
1891
1892 } else { # end alloctype master block case
1893
1894 ## This is a big block; but it HAS to be done in a chunk. Any removal
1895 ## of a netblock allocation may result in a larger chunk of free
1896 ## contiguous IP space - which may in turn be combined into a single
1897 ## netblock rather than a number of smaller netblocks.
1898
1899 my $retcode = 'OK';
1900 my ($ptype,$pcity,$ppatt,$p_id);
1901
1902 eval {
1903
1904##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1905# explicitly deleting any suballocations of the block to be deleted.
1906
1907 # get parent info of the block we're deleting
1908 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1909 $ptype = $pinfo->{type};
1910 $pcity = $pinfo->{city};
1911 $ppatt = $pinfo->{rdns};
1912 $p_id = $binfo->{parent_id};
1913
1914 # Delete the block
1915 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
1916
1917 # munge the parent type a little
1918 $ptype = (split //, $ptype)[1];
1919
1920##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1921# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1922# -> $isprivnet flag from start of sub
1923
1924 # check to see if any container allocations could be the "true" parent
1925 my ($tparent,$tpar_id,$trtype,$tcity);
1926 $tpar_id = 0;
1927
1928##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
1929# contained by a container is a part of the same allocation tree when the VRF fields are equal.
1930
1931# logic:
1932# For each possible container of $cidr
1933# note the parent id
1934# walk the chain up the parents
1935# if we intersect $cidr's current parent, break
1936# if we've intersected $cidr's current parent
1937# set some variables to track that block
1938# break
1939
1940# Set up part of "is it in the middle of a pool?" check
1941 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
1942 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
1943 ($cidr, $binfo->{master_id}) );
1944
1945##fixme?
1946# edge cases not handled, or handled badly:
1947# -> $cidr managed to get to be the entirety of an IP pool
1948
1949 if ($wuzpool && $wuzpool->{id} != $id) {
1950 # we have legacy goo to be purified
1951 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
1952
1953 # for convenience
1954 my $poolid = $wuzpool->{id};
1955 my $pool = $wuzpool->{cidr};
1956 my $poolcity = $wuzpool->{city};
1957 my $pooltype = $wuzpool->{type};
1958 my $poolcustid = $wuzpool->{custid};
1959
1960 $retcode = 'WARNPOOL';
1961 $goback = "$poolid,$pool";
1962 # We've already deleted the block, now we have to stuff its IPs into the pool.
1963 $pooltype =~ s/[dp]$/i/; # change type to static IP
1964 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
1965 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
1966
1967##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1968 # don't insert .0
1969 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1970 $cidr++;
1971 my $bcast = $cidr->broadcast;
1972 while ($cidr != $bcast) {
1973 $sth2->execute($cidr->addr);
1974 $cidr++;
1975 }
1976 # don't insert .255
1977 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1978
1979# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
1980# causing ->split, ->hostenum, and related methods to explode. O_o
1981# foreach my $ip ($cidr->hostenum) {
1982# $sth2->execute($ip);
1983# }
1984
1985 }
1986
1987## important!
1988# ... or IS IT?
1989# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
1990#if (!$wuzpool) {
1991
1992 else {
1993
1994# Edge case: Block is the same size as more than one parent level. Should be rare.
1995# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
1996# but it's likely still possible to fail in particularly well-mangled databases.
1997# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
1998 # Get all possible (and probably a number of impossible) containers for $cidr
1999 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
2000 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
2001 "ORDER BY masklen(cidr) DESC,parent_id DESC");
2002 $sth->execute($cidr, $binfo->{master_id});
2003
2004 # Quickly get certain fields (simpler than getBlockData()
2005 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
2006 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
2007
2008 # For each possible container of $cidr...
2009 while (my @data = $sth->fetchrow_array) {
2010 my $i = 0;
2011 # Save some state and set a start point - parent ID of container we're checking
2012 $tparent = $data[0];
2013 my $ppid = $data[1];
2014 $trtype = $data[2];
2015 $tcity = $data[3];
2016 $tpar_id = $data[4];
2017 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
2018 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
2019 while (1) {
2020 # Retrieve bits on that parent ID
2021 $sth2->execute($ppid, $binfo->{master_id});
2022 my @container = $sth2->fetchrow_array;
2023 $ppid = $container[1];
2024 last if $container[1] == 0; # Break if we've hit a master block
2025 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
2026 }
2027 last if $ppid == $binfo->{parent_id};
2028 }
2029
2030 # found an alternate parent; reset some parent-info bits
2031 if ($tpar_id != $binfo->{parent_id}) {
2032 $ptype = (split //, $trtype)[1];
2033 $pcity = $tcity;
2034 $retcode = 'WARNMERGE'; # may be redundant
2035 $p_id = $tpar_id;
2036 }
2037
2038 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
2039
2040 # Special case - delete pool IPs
2041 if ($binfo->{type} =~ /^.[pd]$/) {
2042 # We have to delete the IPs from the pool listing.
2043##fixme: rdepth? vrf?
2044 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
2045 }
2046
2047 $pinfo = getBlockData($dbh, $p_id);
2048
2049 # If the block wasn't legacy goo embedded in a static pool, we check the
2050 # freeblocks in the identified parent to see if we can combine any of them.
2051
2052 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
2053 if ($binfo->{type} =~ /^.[mc]/) {
2054 # move the freeblocks into the parent
2055 # we don't insert a new freeblock because there could be a live reparented sub.
2056 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
2057 ($p_id, $ptype, $pcity, $id) );
2058 } else {
2059 # ... otherwise, add the freeblock
2060 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
2061 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
2062 }
2063
2064 # Walk the free blocks in the parent and reduce them to the minimal set of CIDR ranges necessary
2065 _compactFree($dbh, $p_id);
2066
2067 } # done returning IPs to the appropriate place
2068
2069 # If we got here, we've succeeded. Whew!
2070 $dbh->commit;
2071 }; # end eval
2072 if ($@) {
2073 $msg .= ": $@";
2074 eval { $dbh->rollback; };
2075 return ('FAIL', $msg);
2076 } else {
2077##fixme: RPC return code?
2078 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
2079 return ($retcode, $goback);
2080 }
2081
2082 } # end alloctype != netblock
2083
2084} # end deleteBlock()
2085
2086
2087## IPDB::getBlockData()
2088# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
2089# private/restricted data, for a CIDR block or pool IP
2090# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
2091# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
2092# instead of a netblock.
2093# Returns a hashref to the block data
2094sub getBlockData {
2095 my $dbh = shift;
2096 my $id = shift;
2097 my $type = shift || 'b'; # default to netblock for lazy callers
2098
2099 # netblocks are in the allocations table; pool IPs are in the poolips table.
2100 # If we try to look up a CIDR in an integer field we should just get back nothing.
2101 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
2102
2103 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
2104 my $commonfields = q(custid, type, circuitid, description, notes, modifystamp AS lastmod,
2105 privdata, vlan, rdns);
2106
2107 if ($type eq 'i') {
2108 my $binfo = $dbh->selectrow_hashref(qq(
2109 SELECT ip AS block, city, vrf, parent_id, master_id, $commonfields
2110 FROM poolips WHERE id = ?
2111 ), undef, ($id) );
2112 return $binfo;
2113 } else {
2114 my $binfo = $dbh->selectrow_hashref(qq(
2115 SELECT a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, swip, $commonfields,
2116 f.cidr AS reserve, f.id as reserve_id
2117 FROM allocations a LEFT JOIN freeblocks f ON a.id=f.reserve_for
2118 WHERE a.id = ?
2119 ), undef, ($id) );
2120 return $binfo;
2121 }
2122} # end getBlockData()
2123
2124
2125## IPDB::getBlockRDNS()
2126# Gets reverse DNS pattern for a block or IP. Note that this will also
2127# retrieve any default pattern following the parent chain up, and check via
2128# RPC (if available) to see what the narrowest pattern for the requested block is
2129# Returns the current pattern for the block or IP.
2130sub getBlockRDNS {
2131 my $dbh = shift;
2132 my %args = @_;
2133
2134 $args{type} = 'b' if !$args{type};
2135 my $cached = 1;
2136
2137 # snag entry from database
2138 my ($rdns,$rfrom,$pid);
2139 if ($args{type} =~ /.i/) {
2140 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
2141 undef, ($args{id}) );
2142 } else {
2143 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
2144 undef, ($args{id}) );
2145 }
2146
2147 # Can't see a way this could end up empty, for any case I care about. If the caller
2148 # doesn't know an allocation ID to request, then they don't know anything else anyway.
2149 my $selfblock = $rfrom;
2150
2151 my $type;
2152 while (!$rdns && $pid) {
2153 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
2154 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
2155 undef, ($pid) );
2156 last if $type eq 'mm'; # break loops in unfortunate legacy data
2157 }
2158
2159 # use the actual allocation to check against the DNS utility; we don't want
2160 # to always go chasing up the chain to the master... which may (usually won't)
2161 # be present directly in DNS anyway
2162 my $cidr = new NetAddr::IP $selfblock;
2163
2164 if ($rpc_url) {
2165 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
2166 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
2167
2168 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
2169 my %rpcargs = (
2170 rpcuser => $args{user},
2171 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2172 cidr => "$rpcblock",
2173 );
2174
2175 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
2176 $rdns = $remote_rdns if $remote_rdns;
2177 $cached = 0;
2178 }
2179
2180 # hmm. do we care about where it actually came from?
2181 return $rdns, $cached;
2182} # end getBlockRDNS()
2183
2184
2185## IPDB::getRDNSbyIP()
2186# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
2187# opposite direction down the netblock tree compared to getBlockRDNS() above.
2188sub getRDNSbyIP {
2189 my $dbh = shift;
2190 my %args = @_; # We want to accept a variety of call types
2191
2192 # key arguments: allocation ID, type
2193 unless ($args{id} || $args{type}) {
2194 $errstr = 'Missing allocation ID or type';
2195 return;
2196 }
2197
2198 my @ret = ();
2199 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
2200 if ($args{type} =~ /^.i$/) {
2201 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
2202 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
2203 } else {
2204 if ($rpc_url) {
2205 my %rpcargs = (
2206 rpcuser => $args{user},
2207 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2208 cidr => $args{range},
2209 );
2210
2211 my $remote_rdns = _rpc('getRevSet', %rpcargs);
2212 return $remote_rdns;
2213# $rdns = $remote_rdns if $remote_rdns;
2214# $cached = 0;
2215 }
2216 }
2217 return \@ret;
2218} # end getRDNSbyIP()
2219
2220
2221## IPDB::getNodeList()
2222# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
2223sub getNodeList {
2224 my $dbh = shift;
2225
2226 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
2227 { Slice => {} });
2228 return $ret;
2229} # end getNodeList()
2230
2231
2232## IPDB::getNodeName()
2233# Get node name from the ID
2234sub getNodeName {
2235 my $dbh = shift;
2236 my $nid = shift;
2237
2238 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
2239 return $nname;
2240} # end getNodeName()
2241
2242
2243## IPDB::getNodeInfo()
2244# Get node name and ID associated with a block
2245sub getNodeInfo {
2246 my $dbh = shift;
2247 my $block = shift;
2248
2249 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
2250 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
2251 return ($nid, $nname);
2252} # end getNodeInfo()
2253
2254
2255## IPDB::mailNotify()
2256# Sends notification mail to recipients regarding an IPDB operation
2257sub mailNotify {
2258 my $dbh = shift;
2259 my ($action,$subj,$message) = @_;
2260
2261 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2262
2263##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
2264
2265# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
2266 my @actionbits = split //, $action;
2267
2268 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
2269 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
2270 # and "all events with this action"
2271 my @actionsets = ($action);
2272##fixme: ick, eww. really gotta find a better way to handle this...
2273 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
2274 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
2275
2276 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
2277
2278 # get recip list from db
2279 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
2280
2281 my %reciplist;
2282 foreach (@actionsets) {
2283 $sth->execute($_);
2284##fixme - need to handle db errors
2285 my ($recipsub) = $sth->fetchrow_array;
2286 next if !$recipsub;
2287 foreach (split(/,/, $recipsub)) {
2288 $reciplist{$_}++;
2289 }
2290 }
2291
2292 return if !%reciplist;
2293
2294 foreach my $recip (keys %reciplist) {
2295 $mailer->mail($smtpsender);
2296 $mailer->to($recip);
2297 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
2298 "To: $recip\n",
2299 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2300 "Subject: {IPDB} $subj\n",
2301 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
2302 "Organization: $org_name\n",
2303 "\n$message\n");
2304 }
2305 $mailer->quit;
2306}
2307
2308# Indicates module loaded OK. Required by Perl.
23091;
Note: See TracBrowser for help on using the repository browser.