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

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

/trunk

Missing variable declaration that should have been in r628. *sigh*.
See #5.

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