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

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

/trunk

Convert SMTP From: address to a configuration entry

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