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

Last change on this file since 713 was 713, checked in by Kris Deugau, 9 years ago

/trunk

Review and revise splitBlock() and shrinkBlock() to properly handle
n-depth nested allocation structures, as well as making sure master
blocks can be shrunk or split without leaving dangling data. See #7.

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