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

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

/trunk

Add rDNS update call for splitBlock(). Requires dnsadmin:trunk/@r680
for new RPC sub splitTemplate. See #7.
IPDB::splitBlock() required a change in argument handling to make sure
all the necessary bits got through where needed for the RPC call.

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