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

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

/trunk

Remove obsolete listMaster() and listRBlock() subs

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