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

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

/trunk

Revise getTypeList() to accept another parameter to flag the the
"selected" type.

  • Property svn:keywords set to Date Rev Author
File size: 80.6 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-27 21:03:27 +0000 (Fri, 27 Mar 2015) $
6# SVN revision $Rev: 714 $
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 $seltype = shift || '';
753
754 my $sql = "SELECT type,listname,type=? AS sel FROM alloctypes WHERE listorder <= 500";
755 if ($tgroup eq 'n') {
756 # grouping 'p' - all netblock types. These include routed blocks, containers (_c)
757 # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
758 # and the "miscellaneous" cn, in, and en types.
759 $sql .= " AND type NOT LIKE '_i'";
760 } elsif ($tgroup eq 'p') {
761 # grouping 'p' - primary allocation types. As with 'n' above but without the _r contained types.
762 $sql .= " AND type NOT LIKE '_i' AND type NOT LIKE '_r'";
763 } elsif ($tgroup eq 'c') {
764 # grouping 'c' - contained types. These include all static IPs and all _r types.
765 $sql .= " AND (type LIKE '_i' OR type LIKE '_r')";
766 } elsif ($tgroup eq 'i') {
767 # grouping 'i' - static IP types.
768 $sql .= " AND type LIKE '_i'";
769 } else {
770 # grouping 'a' - all standard allocation types. This includes everything
771 # but mm (present only as a formality). Make this the default.
772 # ... whee! no extra WHERE clauses
773 }
774 $sql .= " ORDER BY listorder";
775 my $tlist = $dbh->selectall_arrayref($sql, { Slice => {} }, $seltype);
776 return $tlist;
777}
778
779
780## IPDB::getPoolSelect()
781# Get a list of pools matching the passed city and type that have 1 or more free IPs
782# Returns an arrayref to a list of hashrefs
783sub getPoolSelect {
784 my $dbh = shift;
785 my $iptype = shift;
786 my $pcity = shift;
787
788 my ($ptype) = ($iptype =~ /^(.)i$/);
789 return if !$ptype;
790 $ptype .= '_';
791
792 my $plist = $dbh->selectall_arrayref( q(
793 SELECT count(*) AS poolfree,p.pool AS poolblock, a.city AS poolcit
794 FROM poolips p
795 JOIN allocations a ON p.parent_id=a.id
796 WHERE p.available='y' AND a.city = ? AND p.type LIKE ?
797 GROUP BY p.pool,a.city
798 ),
799 { Slice => {} }, ($pcity, $ptype) );
800 return $plist;
801} # end getPoolSelect()
802
803
804## IPDB::findAllocateFrom()
805# Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
806# Takes
807# - mask length
808# - allocation type
809# - POP city "parent"
810# - optional master-block restriction
811# - optional flag to allow automatic pick-from-private-network-ranges
812# Returns a string with the first CIDR block matching the criteria, if any
813sub findAllocateFrom {
814 my $dbh = shift;
815 my $maskbits = shift;
816 my $type = shift;
817 my $city = shift;
818 my $pop = shift;
819 my %optargs = @_;
820
821 my $failmsg = "No suitable free block found\n";
822
823 my @vallist;
824 my $sql;
825
826 # Free pool IPs should be easy.
827 if ($type =~ /^.i$/) {
828 # User may get an IP from the wrong VRF. User should not be using admin tools to allocate static IPs.
829 $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
830 @vallist = ($optargs{gimme});
831 } else {
832
833## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
834## Very large systems will require development of a reserve system (possibly an extension
835## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
836## Also populate a value list for the DBI call.
837
838 @vallist = ($maskbits);
839 $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
840
841# cases, strict rules
842# .c -> container type
843# requires a routing container, fbtype r
844# .d -> DHCP/"normal-routing" static pool
845# requires a routing container, fbtype r
846# .e -> Dynamic-assignment connectivity
847# requires a routing container, fbtype r
848# .i -> error, can't allocate static IPs this way?
849# mm -> error, master block
850# rm -> routed block
851# requires master block, fbtype m
852# .n -> Miscellaneous usage
853# requires a routing container, fbtype r
854# .p -> PPP(oE) static pool
855# requires a routing container, fbtype r
856# .r -> contained type
857# requires a matching container, fbtype $1
858##fixme: strict-or-not flag
859
860##fixme: config or UI flag for "Strict" mode
861# if ($strictmode) {
862if (0) {
863 if ($type =~ /^(.)r$/) {
864 push @vallist, $1;
865 $sql .= " AND routed = ?";
866 } elsif ($type eq 'rm') {
867 $sql .= " AND routed = 'm'";
868 } else {
869 $sql .= " AND routed = 'r'";
870 }
871}
872
873 # for PPP(oE) and container types, the POP city is the one attached to the pool.
874 # individual allocations get listed with the customer city site.
875 ##fixme: chain cities to align roughly with a full layer-2 node graph
876 $city = $pop if $type !~ /^.[pc]$/;
877 if ($type ne 'rm' && $city) {
878 $sql .= " AND city = ?";
879 push @vallist, $city;
880 }
881 # Allow specifying an arbitrary full block, instead of a master
882 if ($optargs{gimme}) {
883 $sql .= " AND cidr >>= ?";
884 push @vallist, $optargs{gimme};
885 }
886 # if a specific master was requested, allow the requestor to self->shoot(foot)
887 if ($optargs{master} && $optargs{master} ne '-') {
888 $sql .= " AND master_id = ?";
889# if $optargs{master} ne '-';
890 push @vallist, $optargs{master};
891 } else {
892 # if a specific master was NOT requested, filter out the RFC 1918 private networks
893 if (!$optargs{allowpriv}) {
894 $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
895 }
896 }
897 # Keep "reserved" blocks out of automatic assignment.
898##fixme: needs a UI flag or a config knob
899 $sql .= " AND reserve_for = 0";
900 # Sorting and limiting, since we don't (currently) care to provide a selection of
901 # blocks to carve up. This preserves something resembling optimal usage of the IP
902 # space by forcing contiguous allocations and free blocks as much as possible.
903 $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
904 } # done setting up SQL for free CIDR block
905
906 my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
907 return $fbid,$fbfound,$fbparent;
908} # end findAllocateFrom()
909
910
911## IPDB::ipParent()
912# Get an IP's parent pool's details
913# Takes a database handle and IP
914# Returns a hashref to the parent pool block, if any
915sub ipParent {
916 my $dbh = shift;
917 my $block = shift;
918
919 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
920 " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
921 return $pinfo;
922} # end ipParent()
923
924
925## IPDB::subParent()
926# Get a block's parent's details
927# Takes a database handle and CIDR block
928# Returns a hashref to the parent container block, if any
929sub subParent {
930 my $dbh = shift;
931 my $block = shift;
932
933 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
934 " WHERE cidr >>= ?", undef, ($block) );
935 return $pinfo;
936} # end subParent()
937
938
939## IPDB::blockParent()
940# Get a block's parent's details
941# Takes a database handle and CIDR block
942# Returns a hashref to the parent container block, if any
943sub blockParent {
944 my $dbh = shift;
945 my $block = shift;
946
947 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
948 " WHERE cidr >>= ?", undef, ($block) );
949 return $pinfo;
950} # end blockParent()
951
952
953## IPDB::getBreadCrumbs()
954# Retrieve the ID and CIDR of a block's parent(s) up to the master block
955# Returns an arrayref to a list of hashrefs with CIDR and block ID
956sub getBreadCrumbs {
957 my $dbh = shift;
958 my $parent = shift;
959 my @result;
960
961 my $sth = $dbh-> prepare("SELECT cidr,type,id,parent_id FROM allocations WHERE id=?");
962
963 while ($parent != 0) {
964 $sth->execute($parent);
965 my ($cidr,$type,$id,$pid) = $sth->fetchrow_array;
966 push @result, {cidr => $cidr, link => $id, ispool => ($type =~ /^.[dp]$/ ? 1 : 0)};
967 $parent = $pid;
968 }
969
970 return \@result;
971} # end getBread()
972
973
974## IPDB::getRoutedCity()
975# Get the city for a routed block.
976sub getRoutedCity {
977 my $dbh = shift;
978 my $block = shift;
979
980 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
981 return $rcity;
982} # end getRoutedCity()
983
984
985## IPDB::allocateBlock()
986# Does all of the magic of actually allocating a netblock
987# Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
988# type, city, block to allocate from, and optionally a description, notes, circuit ID,
989# and private data
990# Returns a success code and optional error message.
991sub allocateBlock {
992 my $dbh = shift;
993
994 my %args = @_;
995
996 $args{cidr} = new NetAddr::IP $args{cidr};
997
998 $args{desc} = '' if !$args{desc};
999 $args{notes} = '' if !$args{notes};
1000 $args{circid} = '' if !$args{circid};
1001 $args{privdata} = '' if !$args{privdata};
1002 $args{vrf} = '' if !$args{vrf};
1003 $args{vlan} = '' if !$args{vlan};
1004 $args{rdns} = '' if !$args{rdns};
1005
1006 # Could arguably allow this for eg /120 allocations, but end users who get a single v4 IP are
1007 # usually given a v6 /64, and most v6 addressing schemes need at least half that address space
1008 if ($args{cidr}->{isv6} && $args{rdns} =~ /\%/) {
1009 return ('FAIL','Reverse DNS template patterns are not supported for IPv6 allocations');
1010 }
1011
1012 my $sth;
1013
1014 # Snag the "type" of the freeblock and its CIDR
1015 my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
1016 $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
1017 undef, $args{fbid});
1018 $alloc_from = new NetAddr::IP $alloc_from;
1019 return ('FAIL',"Failed to allocate $args{cidr}; intended free block was used by another allocation.")
1020 if !$fbparent;
1021##fixme: fail here if !$alloc_from
1022# also consider "lock for allocation" due to multistep allocation process
1023
1024 # To contain the error message, if any.
1025 my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
1026
1027 # Enable transactions and error handling
1028 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1029 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1030
1031 if ($args{type} =~ /^.i$/) {
1032 $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
1033 eval {
1034 if ($args{cidr}) { # IP specified
1035 my ($isavail) = $dbh->selectrow_array("SELECT available FROM poolips WHERE ip=?", undef, ($args{cidr}) );
1036 die "IP is not in an IP pool.\n"
1037 if !$isavail;
1038 die "IP already allocated. Deallocate and reallocate, or update the entry\n"
1039 if $isavail eq 'n';
1040 } else { # IP not specified, take first available
1041 ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE pool=? AND available='y' ORDER BY ip",
1042 undef, ($args{alloc_from}) );
1043 }
1044 $dbh->do("UPDATE poolips SET custid = ?, city = ?,available='n', description = ?, notes = ?, ".
1045 "circuitid = ?, privdata = ?, vrf = ?, rdns = ? ".
1046 "WHERE ip = ? AND parent_id = ?", undef,
1047 ($args{custid}, $args{city}, $args{desc}, $args{notes},
1048 $args{circid}, $args{privdata}, $args{vrf}, $args{rdns},
1049 $args{cidr}, $args{parent}) );
1050
1051# node hack
1052 if ($args{nodeid} && $args{nodeid} ne '') {
1053 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1054 }
1055# end node hack
1056
1057 $dbh->commit; # Allocate IP from pool
1058 };
1059 if ($@) {
1060 $msg .= ": $@";
1061 eval { $dbh->rollback; };
1062 return ('FAIL', $msg);
1063 } else {
1064 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user});
1065 return ('OK', $args{cidr});
1066 }
1067
1068 } else { # end IP-from-pool allocation
1069
1070 if ($args{cidr} == $alloc_from) {
1071 # Easiest case- insert in one table, delete in the other, and go home. More or less.
1072 # insert into allocations values (cidr,custid,type,city,desc) and
1073 # delete from freeblocks where cidr='cidr'
1074 # For data safety on non-transaction DBs, we delete first.
1075
1076 eval {
1077 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1078
1079 # Insert the allocations entry
1080 $dbh->do("INSERT INTO allocations ".
1081 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1082 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1083 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1084 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1085 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1086
1087 # Munge freeblocks
1088 if ($args{type} =~ /^(.)[mc]$/) {
1089 # special case - block is a routed or container/"reserve" block
1090 my $rtype = $1;
1091 $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
1092 undef, ($rtype, $args{city}, $bid, $args{fbid}) );
1093 } else {
1094 # "normal" case
1095 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1096 }
1097
1098 # And initialize the pool, if necessary
1099 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1100 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1101 if ($args{type} =~ /^.p$/) {
1102 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1103 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1104 die $rmsg if $code eq 'FAIL';
1105 } elsif ($args{type} =~ /^.d$/) {
1106 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1107 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1108 die $rmsg if $code eq 'FAIL';
1109 }
1110
1111# node hack
1112 if ($args{nodeid} && $args{nodeid} ne '') {
1113 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1114 }
1115# end node hack
1116
1117 $dbh->commit; # Simple block allocation
1118 }; # end of eval
1119 if ($@) {
1120 $msg .= ": ".$@;
1121 eval { $dbh->rollback; };
1122 return ('FAIL',$msg);
1123 }
1124
1125 } else { # cidr != alloc_from
1126
1127 # Hard case. Allocation is smaller than free block.
1128
1129 # make sure new allocation is in fact within freeblock. *sigh*
1130 return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
1131 if !$alloc_from->contains($args{cidr});
1132 my $wantmaskbits = $args{cidr}->masklen;
1133 my $maskbits = $alloc_from->masklen;
1134
1135 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
1136
1137 # This determines which blocks will be left "free" after allocation. We take the
1138 # block we're allocating from, and split it in half. We see which half the wanted
1139 # block is in, and repeat until the wanted block is equal to one of the halves.
1140 my $i=0;
1141 my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
1142 while ($maskbits++ < $wantmaskbits) {
1143 my @subblocks = $tmp_from->split($maskbits);
1144 $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
1145 $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
1146 } # while
1147
1148 # Begin SQL transaction block
1149 eval {
1150 $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
1151
1152 # Delete old freeblocks entry
1153 $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
1154
1155 # Insert the allocations entry
1156 $dbh->do("INSERT INTO allocations ".
1157 "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns)".
1158 " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", undef,
1159 ($args{cidr}, $fbparent, $fbmaster, $args{vrf}, $args{vlan}, $args{custid}, $args{type}, $args{city},
1160 $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}) );
1161 my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
1162
1163 # Insert new list of smaller free blocks left over. Flag the one that matches the
1164 # masklength of the new allocation, if a reserve block was requested.
1165 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id,reserve_for) ".
1166 "VALUES (?,?,?,?,?,?,?)");
1167 foreach my $block (@newfreeblocks) {
1168 $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster,
1169 ($block->masklen == $wantmaskbits ? $bid : 0));
1170 }
1171
1172 # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
1173 if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
1174 my $rtype = $1;
1175 $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster, 0);
1176 }
1177
1178 # And initialize the pool, if necessary
1179 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
1180 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
1181 if ($args{type} =~ /^.p$/) {
1182 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1183 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
1184 die $rmsg if $code eq 'FAIL';
1185 } elsif ($args{type} =~ /^.d$/) {
1186 $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
1187 my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
1188 die $rmsg if $code eq 'FAIL';
1189 }
1190
1191# node hack
1192 if ($args{nodeid} && $args{nodeid} ne '') {
1193 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
1194 }
1195# end node hack
1196
1197 $dbh->commit; # Complex block allocation
1198 }; # end eval
1199 if ($@) {
1200 $msg .= ": ".$@;
1201 eval { $dbh->rollback; };
1202 return ('FAIL',$msg);
1203 }
1204
1205 } # end fullcidr != alloc_from
1206
1207 # now we do the DNS dance for netblocks, if we have an RPC server to do it with and a pattern to use.
1208 _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user})
1209 if $args{rdns};
1210
1211 # and the per-IP set, if there is one.
1212 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user});
1213
1214 return ('OK', 'OK');
1215
1216 } # end static-IP vs netblock allocation
1217
1218} # end allocateBlock()
1219
1220
1221## IPDB::initPool()
1222# Initializes a pool
1223# Requires a database handle, the pool CIDR, type, city, and a parameter
1224# indicating whether the pool should allow allocation of literally every
1225# IP, or if it should reserve network/gateway/broadcast IPs
1226# Note that this is NOT done in a transaction, that's why it's a private
1227# function and should ONLY EVER get called from allocateBlock()
1228sub initPool {
1229 my ($dbh,undef,$type,$city,$class,$parent) = @_;
1230 my $pool = new NetAddr::IP $_[1];
1231
1232 # IPv6 does not lend itself to IP pools as supported
1233 return ('FAIL',"Refusing to create IPv6 static IP pool") if $pool->{isv6};
1234 # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
1235 # NetAddr::IP won't allow more than a /16 (65k hosts).
1236 return ('FAIL',"Refusing to create oversized static IP pool") if $pool->masklen <= 20;
1237
1238 # Retrieve some odds and ends for defaults on the IPs
1239 my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
1240 my ($vrf,$vlan,$master) = $dbh->selectrow_array("SELECT vrf,vlan,master_id FROM allocations WHERE id = ?",
1241 undef, ($parent) );
1242
1243 $type =~ s/[pd]$/i/;
1244 my $sth;
1245 my $msg;
1246
1247 # Trap errors so we can pass them back to the caller. Even if the
1248 # caller is only ever supposed to be local, and therefore already
1249 # trapping errors. >:(
1250 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
1251 local $dbh->{RaiseError} = 1; # step on our toes by accident.
1252
1253 eval {
1254 # have to insert all pool IPs into poolips table as "unallocated".
1255 $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1256
1257 # in case of pool extension by some means, we need to see what IPs were already inserted
1258 my $tmp1 = $dbh->selectall_arrayref("SELECT ip FROM poolips WHERE parent_id = ?", undef, $parent);
1259 my %foundips;
1260 foreach (@{$tmp1}) {
1261 $foundips{$_->[0]} = 1;
1262 }
1263
1264# Dodge an edge case - pool where IPs have been "stolen" and turned into a netblock assignment.
1265# We can't just "get all the current IPs, and add the missing ones", because some IPs are
1266# legitimately missing (for stretchy values of "legitimately").
1267
1268 my $pdata = getBlockData($dbh, $parent);
1269 my $pcidr = new NetAddr::IP $pdata->{block};
1270
1271 if ($pcidr != $pool) {
1272 # enumerate the IPs from the *old* pool, flag them as "found", so we can iterate the entire
1273 # requested pool and still make sure we skip the IPs in the old pool - even if they've been
1274 # "stolen" by legacy netblocks.
1275 my @oldips = $pcidr->hostenum;
1276 # decide whether to start excluding existing IPs at the "gateway" or "gateway+1"
1277 my $ostart = ($pdata->{type} =~ /^.d$/ ? 1 : 0);
1278 for (my $i = $ostart; $i<= $#oldips; $i++) {
1279 $foundips{$oldips[$i]} = 1;
1280 }
1281 }
1282
1283 # enumerate the hosts in the IP range - everything except the first (net) and last (bcast) IP
1284 my @poolip_list = $pool->hostenum;
1285
1286 # always check/add IPs from gw+1 through bcast-1:
1287 # (but the set won't be in oooorderrrrr! <pout>)
1288 for (my $i=1; $i<=$#poolip_list; $i++) {
1289 my $baseip = $poolip_list[$i]->addr;
1290 if ($baseip !~ /\.(?:0|255)$/ && !$foundips{$poolip_list[$i]}) {
1291 $sth->execute($baseip, $pcustid, $city, $type, $parent, $master);
1292 }
1293 }
1294
1295 # now do the special case - DSL/PPP blocks can use the "net", "gw", and "bcast" IPs.
1296 # we exclude .0 and .255 anyway, since while they'll mostly work, they *will* behave badly here and there.
1297 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
1298 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
1299 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1300 }
1301 $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$poolip_list[0]};
1302 $pool--;
1303 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
1304 $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master) unless $foundips{$pool->addr};
1305 }
1306 }
1307# don't commit here! the caller may not be done.
1308# $dbh->commit;
1309 };
1310 if ($@) {
1311 $msg = $@;
1312# Don't roll back! It's up to the caller to handle this.
1313# eval { $dbh->rollback; };
1314 return ('FAIL',$msg);
1315 } else {
1316 return ('OK',"OK");
1317 }
1318} # end initPool()
1319
1320
1321## IPDB::updateBlock()
1322# Update an allocation
1323# Takes all allocation fields in a hash
1324sub updateBlock {
1325 my $dbh = shift;
1326 my %args = @_;
1327
1328 return ('FAIL', 'Missing block to update') if !$args{block};
1329
1330 # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
1331 $args{custid} =~ s/^\s+//;
1332 $args{custid} =~ s/\s+$//;
1333
1334 # do it all in a transaction
1335 local $dbh->{AutoCommit} = 0;
1336 local $dbh->{RaiseError} = 1;
1337
1338 my @fieldlist;
1339 my @vallist;
1340 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
1341 if ($args{$_}) {
1342 push @fieldlist, $_;
1343 push @vallist, $args{$_};
1344 }
1345 }
1346
1347 my $binfo;
1348 my $updtable = 'allocations';
1349 my $keyfield = 'id';
1350 if ($args{type} =~ /^(.)i$/) {
1351 $updtable = 'poolips';
1352 $binfo = getBlockData($dbh, $args{block}, 'i');
1353 } else {
1354## fixme: there's got to be a better way...
1355 $binfo = getBlockData($dbh, $args{block});
1356 if ($args{swip}) {
1357 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
1358 $args{swip} = 'y';
1359 } else {
1360 $args{swip} = 'n';
1361 }
1362 }
1363 foreach ('type', 'swip') {
1364 if ($args{$_}) {
1365 push @fieldlist, $_;
1366 push @vallist, $args{$_};
1367 }
1368 }
1369 }
1370
1371 return ('FAIL', 'No fields to update') if !@fieldlist;
1372
1373 my $sql = "UPDATE $updtable SET ";
1374 $sql .= join " = ?, ", @fieldlist;
1375
1376 eval {
1377 # check for block merge first...
1378 if ($args{fbmerge}) {
1379 my $cidr = NetAddr::IP->new($binfo->{block});
1380 my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1381 # safety net? make sure mergeable block passed in is really one or both of
1382 # a) reserved for expansion of the block and
1383 # b) confirmed CIDR-combinable
1384 # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
1385 $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
1386 # ... so we can append the change in the stored CIDR field to extend the allocation.
1387 $sql .= " = ?, cidr";
1388 push @vallist, $newblock;
1389 # if we have an IP pool, call initPool to fill in any missing entries in the pool
1390 if ($binfo->{type} =~ /^.p$/) {
1391 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
1392 die $rmsg if $code eq 'FAIL';
1393 } elsif ($binfo->{type} =~ /^.d$/) {
1394 my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
1395 die $rmsg if $code eq 'FAIL';
1396 }
1397 }
1398
1399 # append another SQL fragment
1400 push @vallist, $args{block};
1401 $sql .= " = ? WHERE $keyfield = ?";
1402
1403 # do the update
1404 $dbh->do($sql, undef, @vallist);
1405
1406 if ($args{node}) {
1407 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
1408 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
1409 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
1410 if $args{node} ne '--';
1411 }
1412
1413 $dbh->commit;
1414 };
1415 if ($@) {
1416 my $msg = $@;
1417 $dbh->rollback;
1418 return ('FAIL', $msg);
1419 }
1420
1421 # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
1422 # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
1423 if ($binfo->{type} =~ '.[mc]') {
1424 # Not using listFree() as it doesn't return quite all of the blocks wanted.
1425 # Retrieve the immediate free blocks
1426 my $sth = $dbh->prepare(q(
1427 SELECT cidr FROM freeblocks WHERE parent_id = ?
1428 UNION
1429 SELECT cidr FROM freeblocks f WHERE
1430 cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
1431 AND master_id = ?
1432 ) );
1433 $sth->execute($args{block}, $binfo->{master_id});
1434 my %fbset;
1435 while (my ($fb) = $sth->fetchrow_array) {
1436 $fbset{"host_$fb"} = $args{rdns};
1437 }
1438 # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
1439 # know how many records we'll be updating and more than 3-4 is far too slow. This
1440 # should be safe to call unconditionally.
1441 # Requires dnsadmin >= r678
1442 _rpc('updateRevSet', %fbset, rpcuser => $args{user});
1443
1444 } else {
1445 $binfo->{block} =~ s|/32$||;
1446 _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user});
1447
1448 # and the per-IP set, if there is one.
1449 _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}) if keys (%{$args{iprev}});
1450 }
1451
1452 return ('OK','OK');
1453} # end updateBlock()
1454
1455
1456## IPDB::splitBlock()
1457# Splits an existing allocation into two or more smaller allocations based on a passed netmask
1458# Duplicates all other data
1459# Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
1460# Should probably commit DNS magic to realign DNS data
1461# Mostly works but may return Strange Things(TM) if used on a master block
1462sub splitBlock {
1463 my $dbh = shift;
1464 my %args = @_;
1465# my $id = shift;
1466# my $basetype = shift;
1467# my $newmask = shift;
1468
1469##fixme: set errstr on errors so caller can suitably clue-by-four the user
1470 return if $args{basetype} ne 'b'; # only netblocks allowed!
1471
1472 my $binfo = getBlockData($dbh, $args{id});
1473 return if !$binfo;
1474
1475 return if $args{newmask} !~ /^\d+$/;
1476
1477 my @ret;
1478 my $block = new NetAddr::IP $binfo->{block};
1479 my $oldmask = $block->masklen;
1480
1481 # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
1482 # failure modes:
1483 # difference between $oldmask and $newmask is negative or 0
1484 if ($args{newmask} - $oldmask <= 0) {
1485 $errstr = "Can't split a /$oldmask allocation into /$args{newmask} pieces";
1486 return;
1487 }
1488# # difference between $oldmask and $newmask is > n, for arbitrary n?
1489# if ($newmask - $oldmask > 42) { # because 42
1490# }
1491 # $oldmask > n, for arbitrary n? At least check limits of data type.
1492 if ($block->{isv6}) {
1493 if ($args{newmask} - $oldmask > 128) {
1494 $errstr = "Impossible IPv6 mask length /$args{newmask} requested";
1495 return;
1496 }
1497 } else {
1498 if ($args{newmask} - $oldmask > 32) {
1499 $errstr = "Impossible IPv4 mask length /$args{newmask} requested";
1500 return;
1501 }
1502 }
1503
1504 my @newblocks = $block->split($args{newmask});
1505
1506 local $dbh->{AutoCommit} = 0;
1507 local $dbh->{RaiseError} = 1;
1508
1509 eval {
1510 # line up a list of fields and values. Be nice if there was a handy way to do,
1511 # direct in SQL, something like
1512 # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
1513 my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id);
1514 my $fields_sql = join(',', @fieldlist);
1515 my @vals;
1516 foreach (@fieldlist) {
1517 push @vals, $binfo->{$_};
1518 }
1519 # note the first block in the split for return
1520 push @ret, {nid => $args{id}, nblock => "$newblocks[0]"};
1521
1522 # prepare
1523 my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
1524 my $allocsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
1525 " VALUES (?".',?'x(scalar(@fieldlist)).")");
1526 my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1527 my $upd_psth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1528 my $upd_msth = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1529 my $fb_psth = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
1530 my $fb_msth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
1531 my $pool_psth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE parent_id = ? AND ip << ?");
1532 my $pool_msth = $dbh->prepare("UPDATE poolips SET master_id = ? WHERE master_id = ? AND ip <<= ?");
1533
1534 # set up update of existing block
1535 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$newblocks[0]", $args{id}) );
1536
1537 # axe the new bcast IP from the smaller pool at the "base" block, if it's a "normal" pool
1538 if ($binfo->{type} =~ /.d/) {
1539 $newblocks[0]--;
1540 $nbsth->execute($args{id}, $newblocks[0]->addr);
1541 }
1542
1543 # Loop over the new blocks that are not the base block
1544 for (my $i = 1; $i <= $#newblocks; $i++) {
1545 # add the new allocation
1546 $allocsth->execute($newblocks[$i], @vals);
1547 # fetch the ID of the entry we just added...
1548 $idsth->execute();
1549 my ($nid) = $idsth->fetchrow_array();
1550 # ... so we can pass back the list of blocks and IDs...
1551 push @ret, {nid => $nid, nblock => "$newblocks[$i]"};
1552 # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
1553 if ($binfo->{type} =~ /.d/) {
1554 # net
1555 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1556 $newblocks[$i]++;
1557 # gw
1558 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1559 $newblocks[$i]--;
1560 $newblocks[$i]--;
1561 # bcast
1562 $nbsth->execute($args{id}, $newblocks[$i]->addr);
1563 $newblocks[$i]++;
1564 }
1565
1566 # Reparent allocations, freeblocks, and pool IPs.
1567 $upd_psth->execute($nid, $args{id}, $newblocks[$i]);
1568 $fb_psth->execute($nid, $args{id}, $newblocks[$i]);
1569 $pool_psth->execute($nid, $args{id}, $newblocks[$i]);
1570
1571 # Update master if we've split a master block
1572 if ($binfo->{type} eq 'mm') {
1573 $upd_msth->execute($nid, $args{id}, $newblocks[$i]);
1574 $fb_msth->execute($nid, $args{id}, $newblocks[$i]);
1575 $pool_msth->execute($nid, $args{id}, $newblocks[$i]);
1576 }
1577
1578 } # for (... @newblocks)
1579
1580 $dbh->commit;
1581 };
1582 if ($@) {
1583 $errstr = "Error splitting $binfo->{block}: $@";
1584 $dbh->rollback;
1585 return;
1586 }
1587##fixme: RPC return code?
1588# particularly useful in this case as there may be arbitrary combinations of pass, warn, fail
1589# results from each of the update and add(s), which could get the user to prod dnsadmin to see what exploded
1590 my $foo = _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user});
1591
1592 return \@ret;
1593} # end splitBlock()
1594
1595
1596## IPDB::shrinkBlock()
1597# Shrink an allocation to the passed CIDR block
1598# Takes an allocation ID and a new CIDR
1599# Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
1600# Refuses to shrink "real netblock" pool types below /30
1601sub shrinkBlock {
1602 my $dbh = shift;
1603 my $id = shift;
1604
1605 # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
1606 my $newblock = new NetAddr::IP shift;
1607
1608 if (!$newblock) {
1609 $errstr = "Can't shrink something that's not a netblock";
1610 return;
1611 }
1612
1613 my $binfo = getBlockData($dbh, $id);
1614 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1615
1616 if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
1617 $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
1618 return;
1619 }
1620
1621 my $oldblock = new NetAddr::IP $binfo->{block};
1622
1623 # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
1624 if (!$oldblock->contains($newblock)) {
1625 $errstr = "Can't shrink an allocation outside of itself";
1626 return;
1627 }
1628
1629 local $dbh->{AutoCommit} = 0;
1630 local $dbh->{RaiseError} = 1;
1631
1632 my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
1633 my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
1634 my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
1635 my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
1636 my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
1637 my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
1638
1639##fixme: turn this into a public/top-level sub?
1640 sub getchildren {
1641 my $dbh = shift;
1642 my $id = shift;
1643 my $master = shift;
1644 my $retlist = shift; # better than trying to return complex structures recursively. Ow.
1645 my $cidr = shift;
1646
1647 if (!$cidr) {
1648 my $bd = getBlockData($dbh, $id);
1649 $cidr = $bd->{cidr};
1650 }
1651
1652 my $sth = $dbh->prepare(q(
1653 SELECT id,cidr,type FROM allocations
1654 WHERE parent_id = ? AND master_id = ? AND cidr <<= ?
1655 ) );
1656 $sth->execute($id, $master, $cidr);
1657 while (my $row = $sth->fetchrow_hashref) {
1658 push @$retlist, $row;
1659 getchildren($dbh, $row->{id}, $master, $retlist, $cidr);
1660 }
1661 }
1662
1663 my @ret;
1664 eval {
1665 $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
1666
1667 # find the netblock(s) that are now free
1668 my @workingblocks = $oldblock->split($newblock->masklen);
1669 my @wb2;
1670 foreach my $newsub (@workingblocks) {
1671 next if $newsub == $newblock;
1672 push @wb2, $newsub;
1673 }
1674 @wb2 = Compact(@wb2);
1675
1676 # set new freeblocks, and clean up any IP pool entries if needed.
1677 foreach my $newfree (@wb2) {
1678 my @clist;
1679 # the block we're munging
1680 push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
1681 getchildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
1682
1683 foreach my $goner (@clist) {
1684 $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
1685 $allocsth->execute($goner->{id}, $newfree);
1686 $delfbsth->execute($goner->{id}, $newfree);
1687 }
1688
1689 # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
1690 if ($pinfo) {
1691 $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
1692 $idsth->execute;
1693 my ($nid) = $idsth->fetchrow_array();
1694 # add to return list
1695 push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
1696 }
1697
1698 } # $newfree (@wb2)
1699
1700 # additional cleanup on net/gw/bcast IPs in pool
1701 if ($binfo->{type} =~ /.d/) {
1702 $netsth->execute($id, $newblock->addr);
1703 $newblock++;
1704 $netsth->execute($id, $newblock->addr);
1705 $newblock--;
1706 $newblock--;
1707 $netsth->execute($id, $newblock->addr);
1708 }
1709
1710 $dbh->commit;
1711 };
1712 if ($@) {
1713 $errstr = "Error splitting $binfo->{block}: $@";
1714 $dbh->rollback;
1715 return;
1716 }
1717
1718 return \@ret;
1719} # end shrinkBlock()
1720
1721
1722## IPDB::deleteBlock()
1723# Removes an allocation from the database, including deleting IPs
1724# from poolips and recombining entries in freeblocks if possible
1725# Also handles "deleting" a static IP allocation, and removal of a master
1726# Requires a database handle, the block to delete, the routing depth (if applicable),
1727# the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
1728# as well as the reverse entry
1729sub deleteBlock {
1730 my ($dbh,$id,$basetype,$delfwd,$user) = @_;
1731
1732 # Collect info about the block we're going to delete
1733 my $binfo = getBlockData($dbh, $id, $basetype);
1734 my $cidr = new NetAddr::IP $binfo->{block};
1735
1736# For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
1737# is_rfc1918 requires NetAddr::IP >= 4.059
1738# rather than doing this over and over and over.....
1739 my $tmpnum = $cidr->numeric;
1740# 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
1741# 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
1742# 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
1743 my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
1744 (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
1745 (167772160 <= $tmpnum && $tmpnum <= 184549375);
1746
1747 my $sth;
1748
1749 # Magic variables used for odd allocation cases.
1750 my $container;
1751 my $con_type;
1752
1753
1754 # temporarily forced null, until a sane UI for VRF tracking can be found.
1755# $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
1756
1757 # To contain the error message, if any.
1758 my $msg = "Unknown error deallocating $binfo->{type} $cidr";
1759 my $goback; # to put the parent in so we can link back where the deallocate started
1760
1761 # Enable transactions and exception-on-errors... but only for this sub
1762 local $dbh->{AutoCommit} = 0;
1763 local $dbh->{RaiseError} = 1;
1764
1765 if ($binfo->{type} =~ /^.i$/) {
1766 # First case. The "block" is a static IP
1767 # Note that we still need some additional code in the odd case
1768 # of a netblock-aligned contiguous group of static IPs
1769
1770 eval {
1771 $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
1772 my $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
1773##fixme: VRF and rdepth
1774 $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
1775 "city = (SELECT city FROM allocations WHERE id = ?),".
1776 "description = '', notes = '', circuitid = '', vrf = ? WHERE id = ?", undef,
1777 ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
1778 $dbh->commit;
1779 };
1780 if ($@) {
1781 $msg .= ": $@";
1782 eval { $dbh->rollback; };
1783 return ('FAIL',$msg);
1784 } else {
1785##fixme: RPC return code?
1786 _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user);
1787 return ('OK',"OK");
1788 }
1789
1790 } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
1791 # Second case. The block is a full master block
1792
1793##fixme: VRF limit
1794 $msg = "Unable to delete master block $cidr";
1795 eval {
1796 $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1797 $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
1798 $dbh->commit;
1799 };
1800 if ($@) {
1801 $msg .= ": $@";
1802 eval { $dbh->rollback; };
1803 return ('FAIL', $msg);
1804 }
1805
1806 # Have to handle potentially split reverse zones. Assume they *are* split,
1807 # since if we added them here, they would have been added split.
1808# allow splitting reverse zones to be disabled, maybe, someday
1809#if ($splitrevzones && !$cidr->{isv6}) {
1810 my @zonelist;
1811 if (1 && !$cidr->{isv6}) {
1812 my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
1813 @zonelist = $cidr->split($splitpoint);
1814 } else {
1815 @zonelist = ($cidr);
1816 }
1817 my @fails;
1818 foreach my $subzone (@zonelist) {
1819 if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
1820 push @fails, ("$subzone" => $errstr);
1821 }
1822 }
1823 if (@fails) {
1824 return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
1825 }
1826 return ('OK','OK');
1827
1828 } else { # end alloctype master block case
1829
1830 ## This is a big block; but it HAS to be done in a chunk. Any removal
1831 ## of a netblock allocation may result in a larger chunk of free
1832 ## contiguous IP space - which may in turn be combined into a single
1833 ## netblock rather than a number of smaller netblocks.
1834
1835 my $retcode = 'OK';
1836 my ($ptype,$pcity,$ppatt,$p_id);
1837
1838 eval {
1839
1840##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
1841# explicitly deleting any suballocations of the block to be deleted.
1842
1843 # get parent info of the block we're deleting
1844 my $pinfo = getBlockData($dbh, $binfo->{parent_id});
1845 $ptype = $pinfo->{type};
1846 $pcity = $pinfo->{city};
1847 $ppatt = $pinfo->{rdns};
1848 $p_id = $binfo->{parent_id};
1849
1850 # Delete the block
1851 $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
1852
1853 # munge the parent type a little
1854 $ptype = (split //, $ptype)[1];
1855
1856##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
1857# 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
1858# -> $isprivnet flag from start of sub
1859
1860 # check to see if any container allocations could be the "true" parent
1861 my ($tparent,$tpar_id,$trtype,$tcity);
1862 $tpar_id = 0;
1863
1864##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
1865# contained by a container is a part of the same allocation tree when the VRF fields are equal.
1866
1867# logic:
1868# For each possible container of $cidr
1869# note the parent id
1870# walk the chain up the parents
1871# if we intersect $cidr's current parent, break
1872# if we've intersected $cidr's current parent
1873# set some variables to track that block
1874# break
1875
1876# Set up part of "is it in the middle of a pool?" check
1877 my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
1878 "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
1879 ($cidr, $binfo->{master_id}) );
1880
1881##fixme?
1882# edge cases not handled, or handled badly:
1883# -> $cidr managed to get to be the entirety of an IP pool
1884
1885 if ($wuzpool && $wuzpool->{id} != $id) {
1886 # we have legacy goo to be purified
1887 # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
1888
1889 # for convenience
1890 my $poolid = $wuzpool->{id};
1891 my $pool = $wuzpool->{cidr};
1892 my $poolcity = $wuzpool->{city};
1893 my $pooltype = $wuzpool->{type};
1894 my $poolcustid = $wuzpool->{custid};
1895
1896 $retcode = 'WARNPOOL';
1897 $goback = "$poolid,$pool";
1898 # We've already deleted the block, now we have to stuff its IPs into the pool.
1899 $pooltype =~ s/[dp]$/i/; # change type to static IP
1900 my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
1901 "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
1902
1903##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1904 # don't insert .0
1905 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1906 $cidr++;
1907 my $bcast = $cidr->broadcast;
1908 while ($cidr != $bcast) {
1909 $sth2->execute($cidr->addr);
1910 $cidr++;
1911 }
1912 # don't insert .255
1913 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1914
1915# Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
1916# causing ->split, ->hostenum, and related methods to explode. O_o
1917# foreach my $ip ($cidr->hostenum) {
1918# $sth2->execute($ip);
1919# }
1920
1921 }
1922
1923## important!
1924# ... or IS IT?
1925# we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
1926#if (!$wuzpool) {
1927
1928 else {
1929
1930# Edge case: Block is the same size as more than one parent level. Should be rare.
1931# - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
1932# but it's likely still possible to fail in particularly well-mangled databases.
1933# The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
1934 # Get all possible (and probably a number of impossible) containers for $cidr
1935 $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
1936 "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
1937 "ORDER BY masklen(cidr) DESC,parent_id DESC");
1938 $sth->execute($cidr, $binfo->{master_id});
1939
1940 # Quickly get certain fields (simpler than getBlockData()
1941 my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
1942 "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
1943
1944 # For each possible container of $cidr...
1945 while (my @data = $sth->fetchrow_array) {
1946 my $i = 0;
1947 # Save some state and set a start point - parent ID of container we're checking
1948 $tparent = $data[0];
1949 my $ppid = $data[1];
1950 $trtype = $data[2];
1951 $tcity = $data[3];
1952 $tpar_id = $data[4];
1953 last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
1954 last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
1955 while (1) {
1956 # Retrieve bits on that parent ID
1957 $sth2->execute($ppid, $binfo->{master_id});
1958 my @container = $sth2->fetchrow_array;
1959 $ppid = $container[1];
1960 last if $container[1] == 0; # Break if we've hit a master block
1961 last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
1962 }
1963 last if $ppid == $binfo->{parent_id};
1964 }
1965
1966 # found an alternate parent; reset some parent-info bits
1967 if ($tpar_id != $binfo->{parent_id}) {
1968 $ptype = (split //, $trtype)[1];
1969 $pcity = $tcity;
1970 $retcode = 'WARNMERGE'; # may be redundant
1971 $p_id = $tpar_id;
1972 }
1973
1974 $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
1975
1976 # Special case - delete pool IPs
1977 if ($binfo->{type} =~ /^.[pd]$/) {
1978 # We have to delete the IPs from the pool listing.
1979##fixme: rdepth? vrf?
1980 $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
1981 }
1982
1983 $pinfo = getBlockData($dbh, $p_id);
1984
1985 # If the block wasn't legacy goo embedded in a static pool, we check the
1986 # freeblocks in the identified parent to see if we can combine any of them.
1987
1988 # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
1989 if ($binfo->{type} =~ /^.[mc]/) {
1990 # move the freeblocks into the parent
1991 # we don't insert a new freeblock because there could be a live reparented sub.
1992 $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
1993 ($p_id, $ptype, $pcity, $id) );
1994 } else {
1995 # ... otherwise, add the freeblock
1996 $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
1997 ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
1998 }
1999
2000##fixme: vrf
2001##fixme: simplify since all containers now represent different "layers"/"levels"?
2002 # set up the query to get the list of blocks to try to merge.
2003 $sth = $dbh->prepare("SELECT cidr,id FROM freeblocks ".
2004 "WHERE parent_id = ? ".
2005 "ORDER BY masklen(cidr) DESC");
2006
2007 $sth->execute($p_id);
2008
2009# NetAddr::IP->compact() attempts to produce the smallest inclusive block
2010# from the caller and the passed terms.
2011# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
2012# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
2013# .64-.95, and .96-.128), you will get an array containing a single
2014# /25 as element 0 (.0-.127). Order is not important; you could have
2015# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
2016
2017 my (@rawfb, @combinelist, %rawid);
2018 my $i=0;
2019 # for each free block under $parent, push a NetAddr::IP object into one list, and
2020 # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
2021 while (my @data = $sth->fetchrow_array) {
2022 my $testIP = new NetAddr::IP $data[0];
2023 push @rawfb, $testIP;
2024 $rawid{"$testIP"} = $data[1]; # $data[0] vs "$testIP" *does* make a difference for v6
2025 @combinelist = $testIP->compact(@combinelist);
2026 }
2027
2028 # now that we have the full list of "compacted" freeblocks, go back over
2029 # the list of raw freeblocks, and delete the ones that got merged.
2030 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
2031 foreach my $rawfree (@rawfb) {
2032 next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
2033 $sth->execute($rawid{$rawfree});
2034 }
2035
2036 # now we walk the new list of compacted blocks, and see which ones we need to insert
2037 $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,master_id) VALUES (?,?,?,?,?)");
2038 foreach my $cme (@combinelist) {
2039 next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
2040 $sth->execute($cme, $pcity, $ptype, $p_id, $binfo->{master_id});
2041 }
2042
2043 } # done returning IPs to the appropriate place
2044
2045 # If we got here, we've succeeded. Whew!
2046 $dbh->commit;
2047 }; # end eval
2048 if ($@) {
2049 $msg .= ": $@";
2050 eval { $dbh->rollback; };
2051 return ('FAIL', $msg);
2052 } else {
2053##fixme: RPC return code?
2054 _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y', parpatt => $ppatt);
2055 return ($retcode, $goback);
2056 }
2057
2058 } # end alloctype != netblock
2059
2060} # end deleteBlock()
2061
2062
2063## IPDB::getBlockData()
2064# Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
2065# private/restricted data, for a CIDR block or pool IP
2066# Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
2067# Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
2068# instead of a netblock.
2069# Returns a hashref to the block data
2070sub getBlockData {
2071 my $dbh = shift;
2072 my $id = shift;
2073 my $type = shift || 'b'; # default to netblock for lazy callers
2074
2075 # netblocks are in the allocations table; pool IPs are in the poolips table.
2076 # If we try to look up a CIDR in an integer field we should just get back nothing.
2077 my ($btype) = $dbh->selectrow_array("SELECT type FROM allocations WHERE id=?", undef, ($id) );
2078
2079 # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
2080 my $commonfields = q(custid, type, circuitid, description, notes, modifystamp AS lastmod,
2081 privdata, vlan, rdns);
2082
2083 if ($type eq 'i') {
2084 my $binfo = $dbh->selectrow_hashref(qq(
2085 SELECT ip AS block, city, vrf, parent_id, master_id, $commonfields
2086 FROM poolips WHERE id = ?
2087 ), undef, ($id) );
2088 return $binfo;
2089 } else {
2090 my $binfo = $dbh->selectrow_hashref(qq(
2091 SELECT a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, swip, $commonfields,
2092 f.cidr AS reserve, f.id as reserve_id
2093 FROM allocations a LEFT JOIN freeblocks f ON a.id=f.reserve_for
2094 WHERE a.id = ?
2095 ), undef, ($id) );
2096 return $binfo;
2097 }
2098} # end getBlockData()
2099
2100
2101## IPDB::getBlockRDNS()
2102# Gets reverse DNS pattern for a block or IP. Note that this will also
2103# retrieve any default pattern following the parent chain up, and check via
2104# RPC (if available) to see what the narrowest pattern for the requested block is
2105# Returns the current pattern for the block or IP.
2106sub getBlockRDNS {
2107 my $dbh = shift;
2108 my %args = @_;
2109
2110 $args{type} = 'b' if !$args{type};
2111 my $cached = 1;
2112
2113 # snag entry from database
2114 my ($rdns,$rfrom,$pid);
2115 if ($args{type} =~ /.i/) {
2116 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id FROM poolips WHERE id = ?",
2117 undef, ($args{id}) );
2118 } else {
2119 ($rdns, $rfrom, $pid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id FROM allocations WHERE id = ?",
2120 undef, ($args{id}) );
2121 }
2122
2123 # Can't see a way this could end up empty, for any case I care about. If the caller
2124 # doesn't know an allocation ID to request, then they don't know anything else anyway.
2125 my $selfblock = $rfrom;
2126
2127 my $type;
2128 while (!$rdns && $pid) {
2129 ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
2130 "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
2131 undef, ($pid) );
2132 last if $type eq 'mm'; # break loops in unfortunate legacy data
2133 }
2134
2135 # use the actual allocation to check against the DNS utility; we don't want
2136 # to always go chasing up the chain to the master... which may (usually won't)
2137 # be present directly in DNS anyway
2138 my $cidr = new NetAddr::IP $selfblock;
2139
2140 if ($rpc_url) {
2141 # Use the first /16 or /24, rather than dithering over which sub-/14 /16
2142 # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
2143
2144 my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
2145 my %rpcargs = (
2146 rpcuser => $args{user},
2147 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2148 cidr => "$rpcblock",
2149 );
2150
2151 my $remote_rdns = _rpc('getRevPattern', %rpcargs);
2152 $rdns = $remote_rdns if $remote_rdns;
2153 $cached = 0;
2154 }
2155
2156 # hmm. do we care about where it actually came from?
2157 return $rdns, $cached;
2158} # end getBlockRDNS()
2159
2160
2161## IPDB::getRDNSbyIP()
2162# Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
2163# opposite direction down the netblock tree compared to getBlockRDNS() above.
2164sub getRDNSbyIP {
2165 my $dbh = shift;
2166 my %args = @_; # We want to accept a variety of call types
2167
2168 # key arguments: allocation ID, type
2169 unless ($args{id} || $args{type}) {
2170 $errstr = 'Missing allocation ID or type';
2171 return;
2172 }
2173
2174 my @ret = ();
2175 # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
2176 if ($args{type} =~ /^.i$/) {
2177 my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
2178 push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
2179 } else {
2180 if ($rpc_url) {
2181 my %rpcargs = (
2182 rpcuser => $args{user},
2183 group => $revgroup, # not sure how this could sanely be exposed, tbh...
2184 cidr => $args{range},
2185 );
2186
2187 my $remote_rdns = _rpc('getRevSet', %rpcargs);
2188 return $remote_rdns;
2189# $rdns = $remote_rdns if $remote_rdns;
2190# $cached = 0;
2191 }
2192 }
2193 return \@ret;
2194} # end getRDNSbyIP()
2195
2196
2197## IPDB::getNodeList()
2198# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
2199sub getNodeList {
2200 my $dbh = shift;
2201
2202 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
2203 { Slice => {} });
2204 return $ret;
2205} # end getNodeList()
2206
2207
2208## IPDB::getNodeName()
2209# Get node name from the ID
2210sub getNodeName {
2211 my $dbh = shift;
2212 my $nid = shift;
2213
2214 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
2215 return $nname;
2216} # end getNodeName()
2217
2218
2219## IPDB::getNodeInfo()
2220# Get node name and ID associated with a block
2221sub getNodeInfo {
2222 my $dbh = shift;
2223 my $block = shift;
2224
2225 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
2226 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
2227 return ($nid, $nname);
2228} # end getNodeInfo()
2229
2230
2231## IPDB::mailNotify()
2232# Sends notification mail to recipients regarding an IPDB operation
2233sub mailNotify {
2234 my $dbh = shift;
2235 my ($action,$subj,$message) = @_;
2236
2237 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
2238
2239##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
2240
2241# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
2242 my @actionbits = split //, $action;
2243
2244 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
2245 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
2246 # and "all events with this action"
2247 my @actionsets = ($action);
2248##fixme: ick, eww. really gotta find a better way to handle this...
2249 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
2250 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
2251
2252 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
2253
2254 # get recip list from db
2255 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
2256
2257 my %reciplist;
2258 foreach (@actionsets) {
2259 $sth->execute($_);
2260##fixme - need to handle db errors
2261 my ($recipsub) = $sth->fetchrow_array;
2262 next if !$recipsub;
2263 foreach (split(/,/, $recipsub)) {
2264 $reciplist{$_}++;
2265 }
2266 }
2267
2268 return if !%reciplist;
2269
2270 foreach my $recip (keys %reciplist) {
2271 $mailer->mail($smtpsender);
2272 $mailer->to($recip);
2273 $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
2274 "To: $recip\n",
2275 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
2276 "Subject: {IPDB} $subj\n",
2277 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
2278 "Organization: $org_name\n",
2279 "\n$message\n");
2280 }
2281 $mailer->quit;
2282}
2283
2284# Indicates module loaded OK. Required by Perl.
22851;
Note: See TracBrowser for help on using the repository browser.