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

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

/trunk

Start extending rDNS support to allow entering per-IP reverse names. See #1.

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