source: branches/htmlform/cgi-bin/IPDB.pm@ 448

Last change on this file since 448 was 448, checked in by Kris Deugau, 14 years ago

/branches/htmlform

Escape forwarded form data with $q->escapeHTML on most forms in
main.cgi (see #15)
Fix up most subs in IPDB.pm that deal with form data that needs
escaping (see #34)

  • Property svn:keywords set to Date Rev Author
File size: 29.2 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: 2010-07-27 17:56:39 +0000 (Tue, 27 Jul 2010) $
6# SVN revision $Rev: 448 $
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( Compact );
19use POSIX;
20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
22$VERSION = 2; ##VERSION##
23@ISA = qw(Exporter);
24@EXPORT_OK = qw(
25 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist @masterblocks
26 %allocated %free %routed %bigfree %IPDBacl
27 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock &addMaster
28 &deleteBlock &getBlockData &mailNotify
29 );
30
31@EXPORT = (); # Export nothing by default.
32%EXPORT_TAGS = ( ALL => [qw(
33 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
34 @masterblocks %allocated %free %routed %bigfree %IPDBacl
35 &initIPDBGlobals &connectDB &finish &checkDBSanity &allocateBlock
36 &addMaster &deleteBlock &getBlockData &mailNotify
37 )]
38 );
39
40##
41## Global variables
42##
43our %disp_alloctypes;
44our %list_alloctypes;
45our %def_custids;
46our @citylist;
47our @poplist;
48our @masterblocks;
49our %allocated;
50our %free;
51our %routed;
52our %bigfree;
53our %IPDBacl;
54
55our $org_name = 'Example Corp';
56our $smtphost = 'smtp.example.com';
57our $domain = 'example.com';
58our $defcustid = '5554242';
59# mostly for rwhois
60##fixme: leave these blank by default?
61our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
62our $org_street = '123 4th Street';
63our $org_city = 'Anytown';
64our $org_prov_state = 'ON';
65our $org_pocode = 'H0H 0H0';
66our $org_country = 'CA';
67our $org_phone = '000-555-1234';
68our $org_techhandle = 'ISP-ARIN-HANDLE';
69our $org_email = 'noc@example.com';
70our $hostmaster = 'dns@example.com';
71
72our $syslog_facility = 'local2';
73
74# Let's initialize the globals.
75## IPDB::initIPDBGlobals()
76# Initialize all globals. Takes a database handle, returns a success or error code
77sub initIPDBGlobals {
78 my $dbh = $_[0];
79 my $sth;
80
81 # Initialize alloctypes hashes
82 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
83 $sth->execute;
84 while (my @data = $sth->fetchrow_array) {
85 $disp_alloctypes{$data[0]} = $data[2];
86 $def_custids{$data[0]} = $data[4];
87 if ($data[3] < 900) {
88 $list_alloctypes{$data[0]} = $data[1];
89 }
90 }
91
92 # City and POP listings
93 $sth = $dbh->prepare("select city,routing from cities order by city");
94 $sth->execute;
95 return (undef,$sth->errstr) if $sth->err;
96 while (my @data = $sth->fetchrow_array) {
97 push @citylist, $data[0];
98 if ($data[1] eq 'y') {
99 push @poplist, $data[0];
100 }
101 }
102
103 # Master block list
104 $sth = $dbh->prepare("select cidr from masterblocks order by cidr");
105 $sth->execute;
106 return (undef,$sth->errstr) if $sth->err;
107 for (my $i=0; my @data = $sth->fetchrow_array(); $i++) {
108 $masterblocks[$i] = new NetAddr::IP $data[0];
109 $allocated{"$masterblocks[$i]"} = 0;
110 $free{"$masterblocks[$i]"} = 0;
111 $bigfree{"$masterblocks[$i]"} = 128; # Larger number means smaller block.
112 # Set to 128 to prepare for IPv6
113 $routed{"$masterblocks[$i]"} = 0;
114 }
115
116 # Load ACL data. Specific username checks are done at a different level.
117 $sth = $dbh->prepare("select username,acl from users");
118 $sth->execute;
119 return (undef,$sth->errstr) if $sth->err;
120 while (my @data = $sth->fetchrow_array) {
121 $IPDBacl{$data[0]} = $data[1];
122 }
123
124 return (1,"OK");
125} # end initIPDBGlobals
126
127
128## IPDB::connectDB()
129# Creates connection to IPDB.
130# Requires the database name, username, and password.
131# Returns a handle to the db.
132# Set up for a PostgreSQL db; could be any transactional DBMS with the
133# right changes.
134sub connectDB {
135 my $dbname = shift;
136 my $user = shift;
137 my $pass = shift;
138 my $dbhost = shift;
139
140 my $dbh;
141 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
142
143# Note that we want to autocommit by default, and we will turn it off locally as necessary.
144# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
145 $dbh = DBI->connect($DSN, $user, $pass, {
146 AutoCommit => 1,
147 PrintError => 0
148 })
149 or return (undef, $DBI::errstr) if(!$dbh);
150
151# Return here if we can't select. Note that this indicates a
152# problem executing the select.
153 my $sth = $dbh->prepare("select type from alloctypes");
154 $sth->execute();
155 return (undef,$DBI::errstr) if ($sth->err);
156
157# See if the select returned anything (or null data). This should
158# succeed if the select executed, but...
159 $sth->fetchrow();
160 return (undef,$DBI::errstr) if ($sth->err);
161
162# If we get here, we should be OK.
163 return ($dbh,"DB connection OK");
164} # end connectDB
165
166
167## IPDB::finish()
168# Cleans up after database handles and so on.
169# Requires a database handle
170sub finish {
171 my $dbh = $_[0];
172 $dbh->disconnect;
173} # end finish
174
175
176## IPDB::checkDBSanity()
177# Quick check to see if the db is responding. A full integrity
178# check will have to be a separate tool to walk the IP allocation trees.
179sub checkDBSanity {
180 my ($dbh) = $_[0];
181
182 if (!$dbh) {
183 print "No database handle, or connection has been closed.";
184 return -1;
185 } else {
186 # it connects, try a stmt.
187 my $sth = $dbh->prepare("select type from alloctypes");
188 my $err = $sth->execute();
189
190 if ($sth->fetchrow()) {
191 # all is well.
192 return 1;
193 } else {
194 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
195 return -1;
196 }
197 }
198 # Clean up after ourselves.
199# $dbh->disconnect;
200} # end checkDBSanity
201
202
203## IPDB::addMaster()
204# Does all the magic necessary to sucessfully add a master block
205# Requires database handle, block to add
206# Returns failure code and error message or success code and "message"
207sub addMaster {
208 my $dbh = shift;
209 my $cidr = new NetAddr::IP shift;
210
211 # Allow transactions, and raise an exception on errors so we can catch it later.
212 # Use local to make sure these get "reset" properly on exiting this block
213 local $dbh->{AutoCommit} = 0;
214 local $dbh->{RaiseError} = 1;
215
216 # Wrap all the SQL in a transaction
217 eval {
218 my $sth = $dbh->prepare("select count(*) from masterblocks where cidr <<= '$cidr'");
219 $sth->execute;
220 my @data = $sth->fetchrow_array;
221
222 if ($data[0] eq 0) {
223 # First case - master is brand-spanking-new.
224##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
225## maybe a db table called "config"?
226 $sth = $dbh->prepare("insert into masterblocks (cidr,rwhois) values ('$cidr','y')");
227 $sth->execute;
228
229# Unrouted blocks aren't associated with a city (yet). We don't rely on this
230# elsewhere though; legacy data may have traps and pitfalls in it to break this.
231# Thus the "routed" flag.
232
233 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
234 " values ('$cidr',".$cidr->masklen.",'<NULL>','n')");
235 $sth->execute;
236
237 # If we get here, everything is happy. Commit changes.
238 $dbh->commit;
239
240 } # new master does not contain existing master(s)
241 else {
242
243 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
244 my $smallmask = $cidr->masklen;
245 $sth = $dbh->prepare("select cidr as mask from masterblocks where cidr <<= '$cidr'");
246 $sth->execute;
247 my @cmasters;
248 while (my @data = $sth->fetchrow_array) {
249 my $master = new NetAddr::IP $data[0];
250 push @cmasters, $master;
251 $smallmask = $master->masklen if $master->masklen > $smallmask;
252 }
253
254 # split the new master, and keep only those blocks not part of an existing master
255 my @blocklist;
256 foreach my $seg ($cidr->split($smallmask)) {
257 my $contained = 0;
258 foreach my $master (@cmasters) {
259 $contained = 1 if $master->contains($seg);
260 }
261 push @blocklist, $seg if !$contained;
262 }
263
264 # collect the unrouted free blocks within the new master
265 $sth = $dbh->prepare("select cidr from freeblocks where ".
266 "maskbits>=$smallmask and cidr <<= '$cidr' and routed='n'");
267 $sth->execute;
268 while (my @data = $sth->fetchrow_array) {
269 my $freeblock = new NetAddr::IP $data[0];
270 push @blocklist, $freeblock;
271 }
272
273 # combine the set of free blocks we should have now.
274 @blocklist = Compact(@blocklist);
275
276 # and now insert the new data. Make sure to delete old masters too.
277
278 # freeblocks
279 $sth = $dbh->prepare("delete from freeblocks where cidr <<= ?");
280 my $sth2 = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed) values (?,?,'<NULL>','n')");
281 foreach my $newblock (@blocklist) {
282 $sth->execute("$newblock");
283 $sth2->execute("$newblock", $newblock->masklen);
284 }
285
286 # master
287 $sth = $dbh->prepare("delete from masterblocks where cidr <<= '$cidr'");
288 $sth->execute;
289 $sth = $dbh->prepare("insert into masterblocks (cidr,rwhois) values ('$cidr','y')");
290 $sth->execute;
291
292 # *whew* If we got here, we likely suceeded.
293 $dbh->commit;
294 } # new master contained existing master(s)
295 }; # end eval
296
297 if ($@) {
298 my $msg = $@;
299 eval { $dbh->rollback; };
300 return ('FAIL',$msg);
301 } else {
302 return ('OK','OK');
303 }
304} # end addMaster
305
306
307## IPDB::allocateBlock()
308# Does all of the magic of actually allocating a netblock
309# Requires database handle, block to allocate, custid, type, city,
310# description, notes, circuit ID, block to allocate from, private data
311# Returns a success code and optional error message.
312sub allocateBlock {
313 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid) = @_;
314
315 my $cidr = new NetAddr::IP $_[1];
316 my $alloc_from = new NetAddr::IP $_[2];
317 my $sth;
318
319 # Snag the "type" of the freeblock (alloc_from) "just in case"
320 $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
321 $sth->execute;
322 my ($alloc_from_type) = $sth->fetchrow_array;
323
324 # To contain the error message, if any.
325 my $msg = "Unknown error allocating $cidr as '$type'";
326
327 # Enable transactions and error handling
328 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
329 local $dbh->{RaiseError} = 1; # step on our toes by accident.
330
331 if ($type =~ /^.i$/) {
332 $msg = "Unable to assign static IP $cidr to $custid";
333 eval {
334 # We have to do this in two parts because otherwise we lose
335 # the ability to return the IP assigned. Should that change,
336 # the commented SQL statement below may become usable.
337# update poolips set custid='$custid',city='$city',available='n',
338# description='$desc',notes='$notes',circuitid='$circid'
339# where ip=(select ip from poolips where pool='$alloc_from'
340# and available='y' order by ip limit 1);
341
342 $sth = $dbh->prepare("select ip from poolips where pool='$alloc_from'".
343 " and available='y' order by ip");
344 $sth->execute;
345
346 my @data = $sth->fetchrow_array;
347 $cidr = $data[0]; # $cidr is already declared when we get here!
348
349 $sth = $dbh->prepare("update poolips set custid=?,city=?,".
350 "available='n',description=?,notes=?,circuitid=?,privdata=?".
351 " where ip=?");
352 $sth->execute($custid, $city, $desc, $notes, $circid, $privdata, "$cidr");
353# node hack
354 if ($nodeid && $nodeid ne '') {
355 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
356 $sth->execute("$cidr",$nodeid);
357 }
358# end node hack
359 $dbh->commit;
360 };
361 if ($@) {
362 $msg .= ": '".$sth->errstr."'";
363 eval { $dbh->rollback; };
364 return ('FAIL',$msg);
365 } else {
366 return ('OK',"$cidr");
367 }
368
369 } else { # end IP-from-pool allocation
370
371 if ($cidr == $alloc_from) {
372 # Easiest case- insert in one table, delete in the other, and go home. More or less.
373 # insert into allocations values (cidr,custid,type,city,desc) and
374 # delete from freeblocks where cidr='cidr'
375 # For data safety on non-transaction DBs, we delete first.
376
377 eval {
378 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
379 if ($type eq 'rm') {
380 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
381 " where cidr='$cidr'");
382 $sth->execute;
383 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
384 " values ('$cidr',".$cidr->masklen.",'$city')");
385 $sth->execute;
386 } else {
387 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
388
389 # special case - block is a container/"reserve" block
390 if ($type =~ /^(.)c$/) {
391 $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
392 $sth->execute;
393 } else {
394 # "normal" case
395 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
396 $sth->execute;
397 }
398 $sth = $dbh->prepare("insert into allocations".
399 " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
400 " values (?,?,?,?,?,?,?,?,?)");
401 $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
402
403 # And initialize the pool, if necessary
404 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
405 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
406 if ($type =~ /^.p$/) {
407 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
408 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
409 die $rmsg if $code eq 'FAIL';
410 } elsif ($type =~ /^.d$/) {
411 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
412 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
413 die $rmsg if $code eq 'FAIL';
414 }
415
416 } # routing vs non-routing netblock
417
418# node hack
419 if ($nodeid && $nodeid ne '') {
420 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
421 $sth->execute("$cidr",$nodeid);
422 }
423# end node hack
424 $dbh->commit;
425 }; # end of eval
426 if ($@) {
427 $msg .= ": ".$@;
428 eval { $dbh->rollback; };
429 return ('FAIL',$msg);
430 } else {
431 return ('OK',"OK");
432 }
433
434 } else { # cidr != alloc_from
435
436 # Hard case. Allocation is smaller than free block.
437 my $wantmaskbits = $cidr->masklen;
438 my $maskbits = $alloc_from->masklen;
439
440 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
441
442 # This determines which blocks will be left "free" after allocation. We take the
443 # block we're allocating from, and split it in half. We see which half the wanted
444 # block is in, and repeat until the wanted block is equal to one of the halves.
445 my $i=0;
446 my $tmp_from = $alloc_from; # So we don't munge $alloc_from
447 while ($maskbits++ < $wantmaskbits) {
448 my @subblocks = $tmp_from->split($maskbits);
449 $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
450 $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
451 } # while
452
453 # Begin SQL transaction block
454 eval {
455 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
456
457 # Delete old freeblocks entry
458 $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
459 $sth->execute();
460
461 # now we have to do some magic for routing blocks
462 if ($type eq 'rm') {
463
464 # Insert the new freeblocks entries
465 # Note that non-routed blocks are assigned to <NULL>
466 # and use the default value for the routed column ('n')
467 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
468 " values (?, ?, '<NULL>')");
469 foreach my $block (@newfreeblocks) {
470 $sth->execute("$block", $block->masklen);
471 }
472
473 # Insert the entry in the routed table
474 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
475 " values ('$cidr',".$cidr->masklen.",'$city')");
476 $sth->execute;
477 # Insert the (almost) same entry in the freeblocks table
478 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
479 " values ('$cidr',".$cidr->masklen.",'$city','y')");
480 $sth->execute;
481
482 } else { # done with alloctype == rm
483
484 # Insert the new freeblocks entries
485 # Along with some more HairyPerl(TM):
486 # if $alloc_type_from is p
487 # OR
488 # $type matches /^(.)r$/
489 # inserted value for routed column should match.
490 # This solves the case of inserting an arbitrary block into a
491 # "Reserve-for-routed-DSL" block. Which you really shouldn't
492 # do in the first place, but anyway...
493 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
494 " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
495 ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
496 foreach my $block (@newfreeblocks) {
497 $sth->execute("$block", $block->masklen);
498 }
499 # Special-case for reserve/"container" blocks - generate
500 # the "extra" freeblocks entry for the container
501 if ($type =~ /^(.)c$/) {
502 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
503 " values ('$cidr',".$cidr->masklen.",'$city','$1')");
504 $sth->execute;
505 }
506 # Insert the allocations entry
507 $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
508 "description,notes,maskbits,circuitid,privdata)".
509 " values (?,?,?,?,?,?,?,?,?)");
510 $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
511
512 # And initialize the pool, if necessary
513 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
514 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
515 if ($type =~ /^.p$/) {
516 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
517 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
518 die $rmsg if $code eq 'FAIL';
519 } elsif ($type =~ /^.d$/) {
520 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
521 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
522 die $rmsg if $code eq 'FAIL';
523 }
524
525 } # done with netblock alloctype != rm
526
527# node hack
528 if ($nodeid && $nodeid ne '') {
529 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
530 $sth->execute("$cidr",$nodeid);
531 }
532# end node hack
533 $dbh->commit;
534 }; # end eval
535 if ($@) {
536 $msg .= ": ".$@;
537 eval { $dbh->rollback; };
538 return ('FAIL',$msg);
539 } else {
540 return ('OK',"OK");
541 }
542
543 } # end fullcidr != alloc_from
544
545 } # end static-IP vs netblock allocation
546
547} # end allocateBlock()
548
549
550## IPDB::initPool()
551# Initializes a pool
552# Requires a database handle, the pool CIDR, type, city, and a parameter
553# indicating whether the pool should allow allocation of literally every
554# IP, or if it should reserve network/gateway/broadcast IPs
555# Note that this is NOT done in a transaction, that's why it's a private
556# function and should ONLY EVER get called from allocateBlock()
557sub initPool {
558 my ($dbh,undef,$type,$city,$class) = @_;
559 my $pool = new NetAddr::IP $_[1];
560
561##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
562 $type =~ s/[pd]$/i/;
563 my $sth;
564 my $msg;
565
566 # Trap errors so we can pass them back to the caller. Even if the
567 # caller is only ever supposed to be local, and therefore already
568 # trapping errors. >:(
569 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
570 local $dbh->{RaiseError} = 1; # step on our toes by accident.
571
572 eval {
573 # have to insert all pool IPs into poolips table as "unallocated".
574 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
575 " values ('$pool', ?, '$defcustid', '$city', '$type')");
576 my @poolip_list = $pool->hostenum;
577 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
578 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
579 $sth->execute($pool->addr);
580 }
581 for (my $i=0; $i<=$#poolip_list; $i++) {
582 $sth->execute($poolip_list[$i]->addr);
583 }
584 $pool--;
585 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
586 $sth->execute($pool->addr);
587 }
588 } else { # (real netblock)
589 for (my $i=1; $i<=$#poolip_list; $i++) {
590 $sth->execute($poolip_list[$i]->addr);
591 }
592 }
593 };
594 if ($@) {
595 $msg = "'".$sth->errstr."'";
596 eval { $dbh->rollback; };
597 return ('FAIL',$msg);
598 } else {
599 return ('OK',"OK");
600 }
601} # end initPool()
602
603
604## IPDB::deleteBlock()
605# Removes an allocation from the database, including deleting IPs
606# from poolips and recombining entries in freeblocks if possible
607# Also handles "deleting" a static IP allocation, and removal of a master
608# Requires a database handle, the block to delete, and the type of block
609sub deleteBlock {
610 my ($dbh,undef,$type) = @_;
611 my $cidr = new NetAddr::IP $_[1];
612
613 my $sth;
614
615 # Magic variables used for odd allocation cases.
616 my $container;
617 my $con_type;
618
619 # To contain the error message, if any.
620 my $msg = "Unknown error deallocating $type $cidr";
621 # Enable transactions and exception-on-errors... but only for this sub
622 local $dbh->{AutoCommit} = 0;
623 local $dbh->{RaiseError} = 1;
624
625 # First case. The "block" is a static IP
626 # Note that we still need some additional code in the odd case
627 # of a netblock-aligned contiguous group of static IPs
628 if ($type =~ /^.i$/) {
629
630 eval {
631 $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
632 $sth = $dbh->prepare("update poolips set custid=?,available='y',".
633 "city=(select city from allocations where cidr >>= ?".
634 " order by masklen(cidr) desc limit 1),".
635 "description='',notes='',circuitid='' where ip=?");
636 $sth->execute($defcustid, "$cidr", "$cidr");
637 $dbh->commit;
638 };
639 if ($@) {
640 eval { $dbh->rollback; };
641 return ('FAIL',$msg);
642 } else {
643 return ('OK',"OK");
644 }
645
646 } elsif ($type eq 'mm') { # end alloctype =~ /.i/
647
648 $msg = "Unable to delete master block $cidr";
649 eval {
650 $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
651 $sth->execute;
652 $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
653 $sth->execute;
654 $dbh->commit;
655 };
656 if ($@) {
657 eval { $dbh->rollback; };
658 return ('FAIL', $msg);
659 } else {
660 return ('OK',"OK");
661 }
662
663 } else { # end alloctype master block case
664
665 ## This is a big block; but it HAS to be done in a chunk. Any removal
666 ## of a netblock allocation may result in a larger chunk of free
667 ## contiguous IP space - which may in turn be combined into a single
668 ## netblock rather than a number of smaller netblocks.
669
670 eval {
671
672 if ($type eq 'rm') {
673 $msg = "Unable to remove routing allocation $cidr";
674 $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
675 $sth->execute;
676 # Make sure block getting deleted is properly accounted for.
677 $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
678 " where cidr='$cidr'");
679 $sth->execute;
680 # Set up query to start compacting free blocks.
681 $sth = $dbh->prepare("select cidr from freeblocks where ".
682 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
683
684 } else { # end alloctype routing case
685
686 # Magic. We need to get information about the containing block (if any)
687 # so as to make sure that the freeblocks we insert get the correct "type".
688 $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
689 $sth->execute;
690 ($container, $con_type) = $sth->fetchrow_array;
691
692 # Delete all allocations within the block being deleted. This is
693 # deliberate and correct, and removes the need to special-case
694 # removal of "container" blocks.
695 $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
696 $sth->execute;
697
698 # Special case - delete pool IPs
699 if ($type =~ /^.[pd]$/) {
700 # We have to delete the IPs from the pool listing.
701 $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
702 $sth->execute;
703 }
704
705 # Set up query for compacting free blocks.
706 if ($con_type && $con_type eq 'pc') {
707 # Clean up after "bad" allocations (blocks that are not formally
708 # contained which have nevertheless been allocated from a container block)
709 # We want to make certain that the freeblocks are properly "labelled"
710 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
711 } else {
712 # Standard deallocation.
713 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
714 "(select cidr from routed where cidr >>= '$cidr') ".
715 " and maskbits<=".$cidr->masklen.
716 " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
717 "' order by maskbits desc");
718 }
719
720 } # end alloctype general case
721
722 ## Deallocate legacy blocks stashed in the middle of a static IP pool
723 ## This may be expandable to an even more general case of contained netblock, or other pool types.
724
725 # Find out if the block we're deallocating is within a DSL pool
726 my $sth2 = $dbh->prepare("SELECT cidr,city,type FROM allocations WHERE type LIKE '_p' AND cidr >>= ?");
727 $sth2->execute("$cidr");
728 my ($pool,$poolcity,$pooltype) = $sth2->fetchrow_array;
729
730 if ($pool || $sth2->rows) {
731 # We've already deleted the block, now we have to stuff its IPs into the pool.
732 $pooltype =~ s/p$/i/; # change type to static IP
733 $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) values ".
734 "('$pool',?,'$poolcity','$pooltype','$defcustid')");
735##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
736 # don't insert .0
737 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
738 foreach my $ip ($cidr->hostenum) {
739 $sth2->execute("$ip");
740 }
741 $cidr--;
742 # don't insert .255
743 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
744 } else { # done returning IPs from a block to a static DSL pool
745
746 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
747 # (super)block. If there aren't any, we can't combine blocks anyway. If there
748 # are, we check to see if we can combine blocks.
749 # Execute the statement prepared in the if-else above.
750
751 $sth->execute;
752
753# NetAddr::IP->compact() attempts to produce the smallest inclusive block
754# from the caller and the passed terms.
755# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
756# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
757# .64-.95, and .96-.128), you will get an array containing a single
758# /25 as element 0 (.0-.127). Order is not important; you could have
759# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
760
761 my (@together, @combinelist);
762 my $i=0;
763 while (my @data = $sth->fetchrow_array) {
764 my $testIP = new NetAddr::IP $data[0];
765 @together = $testIP->compact($cidr);
766 my $num = @together;
767 if ($num == 1) {
768 $cidr = $together[0];
769 $combinelist[$i++] = $testIP;
770 }
771 }
772
773 # Clear old freeblocks entries - if any. They should all be within
774 # the $cidr determined above.
775 $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
776 $sth->execute;
777
778 # insert "new" freeblocks entry
779 if ($type eq 'rm') {
780 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
781 " values ('$cidr',".$cidr->masklen.",'<NULL>')");
782 } else {
783 # Magic hackery to insert "correct" data for deallocation of
784 # non-contained blocks allocated from within a container.
785 $type = 'pr' if $con_type && $con_type eq 'pc';
786
787 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
788 " values ('$cidr',".$cidr->masklen.
789 ",(select city from routed where cidr >>= '$cidr'),'".
790 (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
791 }
792 $sth->execute;
793
794 } # done returning IPs to the appropriate place
795
796 # If we got here, we've succeeded. Whew!
797 $dbh->commit;
798 }; # end eval
799 if ($@) {
800 $msg = $@;
801 eval { $dbh->rollback; };
802 return ('FAIL', $msg);
803 } else {
804 return ('OK',"OK");
805 }
806
807 } # end alloctype != netblock
808
809} # end deleteBlock()
810
811
812## IPDB::getBlockData()
813# Return custid, type, city, and description for a block
814sub getBlockData {
815 my $dbh = shift;
816 my $block = shift;
817
818 my $sth = $dbh->prepare("select cidr,custid,type,city,description from searchme".
819 " where cidr='$block'");
820 $sth->execute();
821 return $sth->fetchrow_array();
822} # end getBlockData()
823
824
825## IPDB::mailNotify()
826# Sends notification mail to recipients regarding an IPDB operation
827sub mailNotify {
828 my $dbh = shift;
829 my ($action,$subj,$message) = @_;
830
831##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
832
833# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
834 my @actionbits = split //, $action;
835
836 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
837 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
838 # and "all events with this action"
839 my @actionsets = ($action);
840##fixme: ick, eww. really gotta find a better way to handle this...
841 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
842 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
843
844 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
845
846 # get recip list from db
847 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
848
849 my %reciplist;
850 foreach (@actionsets) {
851 $sth->execute($_);
852##fixme - need to handle db errors
853 my ($recipsub) = $sth->fetchrow_array;
854 next if !$recipsub;
855 foreach (split(/,/, $recipsub)) {
856 $reciplist{$_}++;
857 }
858 }
859
860 return if !%reciplist;
861
862 foreach my $recip (keys %reciplist) {
863 $mailer->mail("ipdb\@$domain");
864 $mailer->to($recip);
865 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
866 "To: $recip\n",
867 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
868 "Subject: {IPDB} $subj\n",
869 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
870 "Organization: $org_name\n",
871 "\n$message\n");
872 }
873 $mailer->quit;
874}
875
876# Indicates module loaded OK. Required by Perl.
8771;
Note: See TracBrowser for help on using the repository browser.