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

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

/trunk

Fix subtle bug in deleting IPv6 blocks; the text representation coming
out of the database is not the normal stringification from NetAddr::IP

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