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

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

/trunk

Mostly fix up edge case of extending an IP pool allocation. See #24.

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