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

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

/trunk

Collect and pass through per-IP rDNS. Still need to cache these locally.
See #1.

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