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

Last change on this file since 532 was 532, checked in by Kris Deugau, 12 years ago

/trunk

Clean up and move SQL to IPDB.pm for pool-selector for static IPs
on allocation confirmation page. See #34.

  • Property svn:keywords set to Date Rev Author
File size: 40.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: 2012-10-30 20:01:39 +0000 (Tue, 30 Oct 2012) $
6# SVN revision $Rev: 532 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2010 - Kris Deugau
10
11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
17use Net::SMTP;
18use NetAddr::IP qw( Compact );
19use POSIX;
20use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21
22$VERSION = 2; ##VERSION##
23@ISA = qw(Exporter);
24@EXPORT_OK = qw(
25 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist @masterblocks
26 %allocated %free %routed %bigfree %IPDBacl %aclmsg
27 &initIPDBGlobals &connectDB &finish &checkDBSanity
28 &addMaster
29 &listSummary &listMaster &listRBlock &listFree &listPool
30 &getTypeList &getPoolSelect
31 &getParent &getRoutedCity
32 &allocateBlock &updateBlock &deleteBlock &getBlockData
33 &getNodeList &getNodeName &getNodeInfo
34 &mailNotify
35 );
36
37@EXPORT = (); # Export nothing by default.
38%EXPORT_TAGS = ( ALL => [qw(
39 %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
40 @masterblocks %allocated %free %routed %bigfree %IPDBacl %aclmsg
41 &initIPDBGlobals &connectDB &finish &checkDBSanity
42 &addMaster
43 &listSummary &listMaster &listRBlock &listFree &listPool
44 &getTypeList &getPoolSelect
45 &getParent &getRoutedCity
46 &allocateBlock &updateBlock &deleteBlock &getBlockData
47 &getNodeList &getNodeName &getNodeInfo
48 &mailNotify
49 )]
50 );
51
52##
53## Global variables
54##
55our %disp_alloctypes;
56our %list_alloctypes;
57our %def_custids;
58our @citylist;
59our @poplist;
60our @masterblocks;
61our %allocated;
62our %free;
63our %routed;
64our %bigfree;
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 $org_name = 'Example Corp';
76our $smtphost = 'smtp.example.com';
77our $domain = 'example.com';
78our $defcustid = '5554242';
79# mostly for rwhois
80##fixme: leave these blank by default?
81our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
82our $org_street = '123 4th Street';
83our $org_city = 'Anytown';
84our $org_prov_state = 'ON';
85our $org_pocode = 'H0H 0H0';
86our $org_country = 'CA';
87our $org_phone = '000-555-1234';
88our $org_techhandle = 'ISP-ARIN-HANDLE';
89our $org_email = 'noc@example.com';
90our $hostmaster = 'dns@example.com';
91
92our $syslog_facility = 'local2';
93
94# Let's initialize the globals.
95## IPDB::initIPDBGlobals()
96# Initialize all globals. Takes a database handle, returns a success or error code
97sub initIPDBGlobals {
98 my $dbh = $_[0];
99 my $sth;
100
101 # Initialize alloctypes hashes
102 $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
103 $sth->execute;
104 while (my @data = $sth->fetchrow_array) {
105 $disp_alloctypes{$data[0]} = $data[2];
106 $def_custids{$data[0]} = $data[4];
107 if ($data[3] < 900) {
108 $list_alloctypes{$data[0]} = $data[1];
109 }
110 }
111
112 # City and POP listings
113 $sth = $dbh->prepare("select city,routing from cities order by city");
114 $sth->execute;
115 return (undef,$sth->errstr) if $sth->err;
116 while (my @data = $sth->fetchrow_array) {
117 push @citylist, $data[0];
118 if ($data[1] eq 'y') {
119 push @poplist, $data[0];
120 }
121 }
122
123 # Master block list
124 $sth = $dbh->prepare("select cidr from masterblocks order by cidr");
125 $sth->execute;
126 return (undef,$sth->errstr) if $sth->err;
127 for (my $i=0; my @data = $sth->fetchrow_array(); $i++) {
128 $masterblocks[$i] = new NetAddr::IP $data[0];
129 $allocated{"$masterblocks[$i]"} = 0;
130 $free{"$masterblocks[$i]"} = 0;
131 $bigfree{"$masterblocks[$i]"} = 128; # Larger number means smaller block.
132 # Set to 128 to prepare for IPv6
133 $routed{"$masterblocks[$i]"} = 0;
134 }
135
136 # Load ACL data. Specific username checks are done at a different level.
137 $sth = $dbh->prepare("select username,acl from users");
138 $sth->execute;
139 return (undef,$sth->errstr) if $sth->err;
140 while (my @data = $sth->fetchrow_array) {
141 $IPDBacl{$data[0]} = $data[1];
142 }
143
144##fixme: initialize HTML::Template env var for template path
145# something like $self->path().'/templates' ?
146# $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
147
148 return (1,"OK");
149} # end initIPDBGlobals
150
151
152## IPDB::connectDB()
153# Creates connection to IPDB.
154# Requires the database name, username, and password.
155# Returns a handle to the db.
156# Set up for a PostgreSQL db; could be any transactional DBMS with the
157# right changes.
158sub connectDB {
159 my $dbname = shift;
160 my $user = shift;
161 my $pass = shift;
162 my $dbhost = shift;
163
164 my $dbh;
165 my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
166
167# Note that we want to autocommit by default, and we will turn it off locally as necessary.
168# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
169 $dbh = DBI->connect($DSN, $user, $pass, {
170 AutoCommit => 1,
171 PrintError => 0
172 })
173 or return (undef, $DBI::errstr) if(!$dbh);
174
175# Return here if we can't select. Note that this indicates a
176# problem executing the select.
177 my $sth = $dbh->prepare("select type from alloctypes");
178 $sth->execute();
179 return (undef,$DBI::errstr) if ($sth->err);
180
181# See if the select returned anything (or null data). This should
182# succeed if the select executed, but...
183 $sth->fetchrow();
184 return (undef,$DBI::errstr) if ($sth->err);
185
186# If we get here, we should be OK.
187 return ($dbh,"DB connection OK");
188} # end connectDB
189
190
191## IPDB::finish()
192# Cleans up after database handles and so on.
193# Requires a database handle
194sub finish {
195 my $dbh = $_[0];
196 $dbh->disconnect if $dbh;
197} # end finish
198
199
200## IPDB::checkDBSanity()
201# Quick check to see if the db is responding. A full integrity
202# check will have to be a separate tool to walk the IP allocation trees.
203sub checkDBSanity {
204 my ($dbh) = $_[0];
205
206 if (!$dbh) {
207 print "No database handle, or connection has been closed.";
208 return -1;
209 } else {
210 # it connects, try a stmt.
211 my $sth = $dbh->prepare("select type from alloctypes");
212 my $err = $sth->execute();
213
214 if ($sth->fetchrow()) {
215 # all is well.
216 return 1;
217 } else {
218 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
219 return -1;
220 }
221 }
222 # Clean up after ourselves.
223# $dbh->disconnect;
224} # end checkDBSanity
225
226
227## IPDB::addMaster()
228# Does all the magic necessary to sucessfully add a master block
229# Requires database handle, block to add
230# Returns failure code and error message or success code and "message"
231sub addMaster {
232 my $dbh = shift;
233 my $cidr = new NetAddr::IP shift;
234
235 # Allow transactions, and raise an exception on errors so we can catch it later.
236 # Use local to make sure these get "reset" properly on exiting this block
237 local $dbh->{AutoCommit} = 0;
238 local $dbh->{RaiseError} = 1;
239
240 # Wrap all the SQL in a transaction
241 eval {
242 my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
243
244 if (!$mexist) {
245 # First case - master is brand-spanking-new.
246##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
247## maybe a db table called "config"?
248 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr,'y') );
249
250# Unrouted blocks aren't associated with a city (yet). We don't rely on this
251# elsewhere though; legacy data may have traps and pitfalls in it to break this.
252# Thus the "routed" flag.
253 $dbh->do("INSERT INTO freeblocks (cidr,maskbits,city,routed) VALUES (?,?,?,?)", undef,
254 ($cidr, $cidr->masklen, '<NULL>', 'n') );
255
256 # If we get here, everything is happy. Commit changes.
257 $dbh->commit;
258
259 } # done new master does not contain existing master(s)
260 else {
261
262 # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
263 my $smallmask = $cidr->masklen;
264 my $sth = $dbh->prepare("SELECT cidr FROM masterblocks WHERE cidr <<= ?");
265 $sth->execute($cidr);
266 my @cmasters;
267 while (my @data = $sth->fetchrow_array) {
268 my $master = new NetAddr::IP $data[0];
269 push @cmasters, $master;
270 $smallmask = $master->masklen if $master->masklen > $smallmask;
271 }
272
273 # split the new master, and keep only those blocks not part of an existing master
274 my @blocklist;
275 foreach my $seg ($cidr->split($smallmask)) {
276 my $contained = 0;
277 foreach my $master (@cmasters) {
278 $contained = 1 if $master->contains($seg);
279 }
280 push @blocklist, $seg if !$contained;
281 }
282
283 # collect the unrouted free blocks within the new master
284 $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE maskbits <= ? AND cidr <<= ? AND routed = 'n'");
285 $sth->execute($smallmask, $cidr);
286 while (my @data = $sth->fetchrow_array) {
287 my $freeblock = new NetAddr::IP $data[0];
288 push @blocklist, $freeblock;
289 }
290
291 # combine the set of free blocks we should have now.
292 @blocklist = Compact(@blocklist);
293
294 # and now insert the new data. Make sure to delete old masters too.
295
296 # freeblocks
297 $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ?");
298 my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,maskbits,city,routed) VALUES (?,?,'<NULL>','n')");
299 foreach my $newblock (@blocklist) {
300 $sth->execute($newblock);
301 $sth2->execute($newblock, $newblock->masklen);
302 }
303
304 # master
305 $dbh->do("DELETE FROM masterblocks WHERE cidr <<= ?", undef, ($cidr) );
306 $dbh->do("INSERT INTO masterblocks (cidr,rwhois) VALUES (?,?)", undef, ($cidr, 'y') );
307
308 # *whew* If we got here, we likely suceeded.
309 $dbh->commit;
310 } # new master contained existing master(s)
311 }; # end eval
312
313 if ($@) {
314 my $msg = $@;
315 eval { $dbh->rollback; };
316 return ('FAIL',$msg);
317 } else {
318 return ('OK','OK');
319 }
320} # end addMaster
321
322
323## IPDB::listSummary()
324# Get summary list of all master blocks
325# Returns an arrayref to a list of hashrefs containing the master block, routed count,
326# allocated count, free count, and largest free block masklength
327sub listSummary {
328 my $dbh = shift;
329
330 my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master FROM masterblocks ORDER BY cidr", { Slice => {} });
331
332 foreach (@{$mlist}) {
333 my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM routed WHERE cidr <<= ?", undef, ($$_{master}));
334 $$_{routed} = $rcnt;
335 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{master}));
336 $$_{allocated} = $acnt;
337 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
338 " AND (routed='y' OR routed='n')", undef, ($$_{master}));
339 $$_{free} = $fcnt;
340 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
341 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{master}));
342##fixme: should find a way to do this without having to HTMLize the <>
343 $bigfree = "/$bigfree" if $bigfree;
344 $bigfree = '<NONE>' if !$bigfree;
345 $$_{bigfree} = $bigfree;
346 }
347 return $mlist;
348} # end listSummary()
349
350
351## IPDB::listMaster()
352# Get list of routed blocks in the requested master
353# Returns an arrayref to a list of hashrefs containing the routed block, POP/city the block is routed to,
354# allocated count, free count, and largest free block masklength
355sub listMaster {
356 my $dbh = shift;
357 my $master = shift;
358
359 my $rlist = $dbh->selectall_arrayref("SELECT cidr AS block,city FROM routed WHERE cidr <<= ? ORDER BY cidr",
360 { Slice => {} }, ($master) );
361
362 foreach (@{$rlist}) {
363 my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ?", undef, ($$_{block}));
364 $$_{nsubs} = $acnt;
365 my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ?".
366 " AND (routed='y' OR routed='n')", undef, ($$_{block}));
367 $$_{nfree} = $fcnt;
368 my ($bigfree) = $dbh->selectrow_array("SELECT maskbits FROM freeblocks WHERE cidr <<= ?".
369 " AND (routed='y' OR routed='n') ORDER BY maskbits LIMIT 1", undef, ($$_{block}));
370##fixme: should find a way to do this without having to HTMLize the <>
371 $bigfree = "/$bigfree" if $bigfree;
372 $bigfree = '<NONE>' if !$bigfree;
373 $$_{lfree} = $bigfree;
374 }
375 return $rlist;
376} # end listMaster()
377
378
379## IPDB::listRBlock()
380# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
381# Takes a parent/master and an optional flag to look at routed or unrouted blocks, depending
382# on whether the master is a direct master or a routed block
383# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
384sub listRBlock {
385 my $dbh = shift;
386 my $routed = shift;
387
388 # Snag the allocations for this block
389 my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description".
390 " FROM allocations WHERE cidr <<= ? ORDER BY cidr");
391 $sth->execute($routed);
392
393 # hack hack hack
394 # set up to flag swip=y records if they don't actually have supporting data in the customers table
395 my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
396
397 my @blocklist;
398 while (my ($cidr,$city,$type,$custid,$swip,$desc) = $sth->fetchrow_array()) {
399 $custsth->execute($custid);
400 my ($ncust) = $custsth->fetchrow_array();
401 my %row = (
402 block => $cidr,
403 city => $city,
404 type => $disp_alloctypes{$type},
405 custid => $custid,
406 swip => ($swip eq 'y' ? 'Yes' : 'No'),
407 partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
408 desc => $desc
409 );
410 $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
411 $row{listpool} = ($type =~ /^.[pd]$/);
412 push (@blocklist, \%row);
413 }
414 return \@blocklist;
415} # end listRBlock()
416
417
418## IPDB::listFree()
419# Gets a list of free blocks in the requested parent/master in both CIDR and range notation
420# Takes a parent/master and an optional "routed or unrouted" flag that defaults to unrouted.
421# Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
422# Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
423sub listFree {
424 my $dbh = shift;
425 my $master = shift;
426 my $routed = shift || 'n';
427
428 # do it this way so we can waste a little less time iterating
429 my $sth = $dbh->prepare("SELECT cidr,routed FROM freeblocks WHERE cidr <<= ? AND ".
430 ($routed eq 'n' ? '' : 'NOT')." routed = 'n' ORDER BY cidr");
431 $sth->execute($master);
432 my @flist;
433 while (my ($cidr,$rtype) = $sth->fetchrow_array()) {
434 $cidr = new NetAddr::IP $cidr;
435 my %row = (
436 fblock => "$cidr",
437 frange => $cidr->range,
438 );
439 if ($routed eq 'y') {
440 $row{subblock} = ($rtype ne 'y' && $rtype ne 'n');
441 $row{fbtype} = $rtype;
442 }
443 push @flist, \%row;
444 }
445 return \@flist;
446} # end listFree()
447
448
449## IPDB::listPool()
450#
451sub listPool {
452 my $dbh = shift;
453 my $pool = shift;
454
455 my $sth = $dbh->prepare("SELECT ip,custid,available,description,type".
456 " FROM poolips WHERE pool = ? ORDER BY ip");
457 $sth->execute($pool);
458 my @poolips;
459 while (my ($ip,$custid,$available,$desc,$type) = $sth->fetchrow_array) {
460 my %row = (
461 ip => $ip,
462 custid => $custid,
463 available => $available,
464 desc => $desc,
465 delme => $available eq 'n'
466 );
467 push @poolips, \%row;
468 }
469 return \@poolips;
470} # end listPool()
471
472
473## IPDB::getTypeList()
474# Get an alloctype/description pair list suitable for dropdowns
475# Takes a flag to determine which general groups of types are returned
476# Returns an reference to an array of hashrefs
477sub getTypeList {
478 my $dbh = shift;
479 my $tgroup = shift || 'a'; # technically optional, like this, but should
480 # really be specified in the call for clarity
481 my $tlist;
482 if ($tgroup eq 'p') {
483 # grouping 'p' - primary allocation types. These include static IP pools (_d and _p),
484 # dynamic-allocation ranges (_e), containers (_c), and the "miscellaneous" cn, in, and en types.
485 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder < 500 ".
486 "AND type NOT LIKE '_i' AND type NOT LIKE '_r' ORDER BY listorder", { Slice => {} });
487 } elsif ($tgroup eq 'c') {
488 # grouping 'c' - contained types. These include all static IPs and all _r types.
489 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
490 " AND (type LIKE '_i' OR type LIKE '_r') ORDER BY listorder", { Slice => {} });
491 } else {
492 # grouping 'a' - all standard allocation types. This includes everything
493 # but mm (present only as a formality). Make this the default.
494 $tlist = $dbh->selectall_arrayref("SELECT type,listname FROM alloctypes WHERE listorder <= 500 ".
495 " ORDER BY listorder", { Slice => {} });
496 }
497 return $tlist;
498}
499
500
501## IPDB::getPoolSelect()
502# Get a list of pools matching the passed city and type that have 1 or more free IPs
503sub getPoolSelect {
504 my $dbh = shift;
505 my $iptype = shift;
506 my $pcity = shift;
507
508 my ($ptype) = ($iptype =~ /^(.)i$/);
509 return if !$ptype;
510 $ptype .= '_';
511
512 my $plist = $dbh->selectall_arrayref(
513 "SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool) AS poolcit, ".
514 "poolips.pool AS poolblock, COUNT(*) AS poolfree FROM poolips,allocations ".
515 "WHERE poolips.available='y' AND poolips.pool=allocations.cidr ".
516 "AND allocations.city = ? AND poolips.type LIKE ? ".
517 "GROUP BY pool", { Slice => {} }, ($pcity, $ptype) );
518 return $plist;
519} # end getPoolSelect()
520
521
522## IPDB::getParent()
523# Get a block's parent's details
524# Takes a database handle and CIDR block
525# Returns a hashref to the parent routed or container block, if any
526sub getParent {
527 my $dbh = shift;
528 my $block = shift;
529
530 my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
531 " WHERE cidr >>= ?", undef, ($block) );
532 return $pinfo;
533} # end getParent()
534
535
536## IPDB::getRoutedCity()
537# Get the city for a routed block.
538sub getRoutedCity {
539 my $dbh = shift;
540 my $block = shift;
541
542 my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
543 return $rcity;
544} # end getRoutedCity()
545
546
547## IPDB::allocateBlock()
548# Does all of the magic of actually allocating a netblock
549# Requires database handle, block to allocate, custid, type, city,
550# description, notes, circuit ID, block to allocate from, private data
551# Returns a success code and optional error message.
552sub allocateBlock {
553 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid) = @_;
554
555 my $cidr = new NetAddr::IP $_[1];
556 my $alloc_from = new NetAddr::IP $_[2];
557 my $sth;
558
559 $desc = '' if !$desc;
560 $notes = '' if !$notes;
561 $circid = '' if !$circid;
562 $privdata = '' if !$privdata;
563
564 # Snag the "type" of the freeblock (alloc_from) "just in case"
565 $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
566 $sth->execute;
567 my ($alloc_from_type) = $sth->fetchrow_array;
568
569 # To contain the error message, if any.
570 my $msg = "Unknown error allocating $cidr as '$type'";
571
572 # Enable transactions and error handling
573 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
574 local $dbh->{RaiseError} = 1; # step on our toes by accident.
575
576 if ($type =~ /^.i$/) {
577 $msg = "Unable to assign static IP $cidr to $custid";
578 eval {
579 # We have to do this in two parts because otherwise we lose
580 # the ability to return the IP assigned. Should that change,
581 # the commented SQL statement below may become usable.
582# update poolips set custid='$custid',city='$city',available='n',
583# description='$desc',notes='$notes',circuitid='$circid'
584# where ip=(select ip from poolips where pool='$alloc_from'
585# and available='y' order by ip limit 1);
586
587 $sth = $dbh->prepare("select ip from poolips where pool='$alloc_from'".
588 " and available='y' order by ip");
589 $sth->execute;
590
591 my @data = $sth->fetchrow_array;
592 $cidr = $data[0]; # $cidr is already declared when we get here!
593
594 $sth = $dbh->prepare("update poolips set custid=?,city=?,".
595 "available='n',description=?,notes=?,circuitid=?,privdata=?".
596 " where ip=?");
597 $sth->execute($custid, $city, $desc, $notes, $circid, $privdata, "$cidr");
598# node hack
599 if ($nodeid && $nodeid ne '') {
600 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
601 $sth->execute("$cidr",$nodeid);
602 }
603# end node hack
604 $dbh->commit;
605 };
606 if ($@) {
607 $msg .= ": '".$sth->errstr."'";
608 eval { $dbh->rollback; };
609 return ('FAIL',$msg);
610 } else {
611 return ('OK',"$cidr");
612 }
613
614 } else { # end IP-from-pool allocation
615
616 if ($cidr == $alloc_from) {
617 # Easiest case- insert in one table, delete in the other, and go home. More or less.
618 # insert into allocations values (cidr,custid,type,city,desc) and
619 # delete from freeblocks where cidr='cidr'
620 # For data safety on non-transaction DBs, we delete first.
621
622 eval {
623 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
624 if ($type eq 'rm') {
625 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
626 " where cidr='$cidr'");
627 $sth->execute;
628 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
629 " values ('$cidr',".$cidr->masklen.",'$city')");
630 $sth->execute;
631 } else {
632 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
633
634 # special case - block is a container/"reserve" block
635 if ($type =~ /^(.)c$/) {
636 $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
637 $sth->execute;
638 } else {
639 # "normal" case
640 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
641 $sth->execute;
642 }
643 $sth = $dbh->prepare("insert into allocations".
644 " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
645 " values (?,?,?,?,?,?,?,?,?)");
646 $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
647
648 # And initialize the pool, if necessary
649 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
650 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
651 if ($type =~ /^.p$/) {
652 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
653 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
654 die $rmsg if $code eq 'FAIL';
655 } elsif ($type =~ /^.d$/) {
656 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
657 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
658 die $rmsg if $code eq 'FAIL';
659 }
660
661 } # routing vs non-routing netblock
662
663# node hack
664 if ($nodeid && $nodeid ne '') {
665 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
666 $sth->execute("$cidr",$nodeid);
667 }
668# end node hack
669 $dbh->commit;
670 }; # end of eval
671 if ($@) {
672 $msg .= ": ".$@;
673 eval { $dbh->rollback; };
674 return ('FAIL',$msg);
675 } else {
676 return ('OK',"OK");
677 }
678
679 } else { # cidr != alloc_from
680
681 # Hard case. Allocation is smaller than free block.
682 my $wantmaskbits = $cidr->masklen;
683 my $maskbits = $alloc_from->masklen;
684
685 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
686
687 # This determines which blocks will be left "free" after allocation. We take the
688 # block we're allocating from, and split it in half. We see which half the wanted
689 # block is in, and repeat until the wanted block is equal to one of the halves.
690 my $i=0;
691 my $tmp_from = $alloc_from; # So we don't munge $alloc_from
692 while ($maskbits++ < $wantmaskbits) {
693 my @subblocks = $tmp_from->split($maskbits);
694 $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
695 $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
696 } # while
697
698 # Begin SQL transaction block
699 eval {
700 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
701
702 # Delete old freeblocks entry
703 $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
704 $sth->execute();
705
706 # now we have to do some magic for routing blocks
707 if ($type eq 'rm') {
708
709 # Insert the new freeblocks entries
710 # Note that non-routed blocks are assigned to <NULL>
711 # and use the default value for the routed column ('n')
712 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
713 " values (?, ?, '<NULL>')");
714 foreach my $block (@newfreeblocks) {
715 $sth->execute("$block", $block->masklen);
716 }
717
718 # Insert the entry in the routed table
719 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
720 " values ('$cidr',".$cidr->masklen.",'$city')");
721 $sth->execute;
722 # Insert the (almost) same entry in the freeblocks table
723 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
724 " values ('$cidr',".$cidr->masklen.",'$city','y')");
725 $sth->execute;
726
727 } else { # done with alloctype == rm
728
729 # Insert the new freeblocks entries
730 # Along with some more HairyPerl(TM):
731 # if $alloc_type_from is p
732 # OR
733 # $type matches /^(.)r$/
734 # inserted value for routed column should match.
735 # This solves the case of inserting an arbitrary block into a
736 # "Reserve-for-routed-DSL" block. Which you really shouldn't
737 # do in the first place, but anyway...
738 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
739 " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
740 ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
741 foreach my $block (@newfreeblocks) {
742 $sth->execute("$block", $block->masklen);
743 }
744 # Special-case for reserve/"container" blocks - generate
745 # the "extra" freeblocks entry for the container
746 if ($type =~ /^(.)c$/) {
747 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
748 " values ('$cidr',".$cidr->masklen.",'$city','$1')");
749 $sth->execute;
750 }
751 # Insert the allocations entry
752 $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
753 "description,notes,maskbits,circuitid,privdata)".
754 " values (?,?,?,?,?,?,?,?,?)");
755 $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
756
757 # And initialize the pool, if necessary
758 # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
759 # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
760 if ($type =~ /^.p$/) {
761 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
762 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
763 die $rmsg if $code eq 'FAIL';
764 } elsif ($type =~ /^.d$/) {
765 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
766 my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
767 die $rmsg if $code eq 'FAIL';
768 }
769
770 } # done with netblock alloctype != rm
771
772# node hack
773 if ($nodeid && $nodeid ne '') {
774 $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
775 $sth->execute("$cidr",$nodeid);
776 }
777# end node hack
778 $dbh->commit;
779 }; # end eval
780 if ($@) {
781 $msg .= ": ".$@;
782 eval { $dbh->rollback; };
783 return ('FAIL',$msg);
784 } else {
785 return ('OK',"OK");
786 }
787
788 } # end fullcidr != alloc_from
789
790 } # end static-IP vs netblock allocation
791
792} # end allocateBlock()
793
794
795## IPDB::initPool()
796# Initializes a pool
797# Requires a database handle, the pool CIDR, type, city, and a parameter
798# indicating whether the pool should allow allocation of literally every
799# IP, or if it should reserve network/gateway/broadcast IPs
800# Note that this is NOT done in a transaction, that's why it's a private
801# function and should ONLY EVER get called from allocateBlock()
802sub initPool {
803 my ($dbh,undef,$type,$city,$class) = @_;
804 my $pool = new NetAddr::IP $_[1];
805
806##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
807 $type =~ s/[pd]$/i/;
808 my $sth;
809 my $msg;
810
811 # Trap errors so we can pass them back to the caller. Even if the
812 # caller is only ever supposed to be local, and therefore already
813 # trapping errors. >:(
814 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
815 local $dbh->{RaiseError} = 1; # step on our toes by accident.
816
817 eval {
818 # have to insert all pool IPs into poolips table as "unallocated".
819 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
820 " values ('$pool', ?, '$defcustid', ?, '$type')");
821 my @poolip_list = $pool->hostenum;
822 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
823 if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
824 $sth->execute($pool->addr, $city);
825 }
826 for (my $i=0; $i<=$#poolip_list; $i++) {
827 $sth->execute($poolip_list[$i]->addr, $city);
828 }
829 $pool--;
830 if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
831 $sth->execute($pool->addr, $city);
832 }
833 } else { # (real netblock)
834 for (my $i=1; $i<=$#poolip_list; $i++) {
835 $sth->execute($poolip_list[$i]->addr, $city);
836 }
837 }
838 };
839 if ($@) {
840 $msg = $@." '".$sth->errstr."'";
841 eval { $dbh->rollback; };
842 return ('FAIL',$msg);
843 } else {
844 return ('OK',"OK");
845 }
846} # end initPool()
847
848
849## IPDB::updateBlock()
850# Update an allocation
851# Takes all allocation fields in a hash
852sub updateBlock {
853 my $dbh = shift;
854 my %args = @_;
855
856 return ('FAIL', 'Missing block to update') if !$args{block};
857
858 # do it all in a transaction
859 local $dbh->{AutoCommit} = 0;
860 local $dbh->{RaiseError} = 1;
861
862 my @fieldlist;
863 my @vallist;
864 foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata') {
865 if ($args{$_}) {
866 push @fieldlist, $_;
867 push @vallist, $args{$_};
868 }
869 }
870
871 my $updtable = 'allocations';
872 my $keyfield = 'cidr';
873 if ($args{alloctype} =~ /^(.)i$/) {
874 $updtable = 'poolips';
875 $keyfield = 'ip';
876 } else {
877## fixme: there's got to be a better way...
878 if ($args{swip}) {
879 if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
880 $args{swip} = 'y';
881 } else {
882 $args{swip} = 'n';
883 }
884 }
885 foreach ('type', 'swip') {
886 if ($args{$_}) {
887 push @fieldlist, $_;
888 push @vallist, $args{$_};
889 }
890 }
891 }
892
893 return ('FAIL', 'No fields to update') if !@fieldlist;
894
895 push @vallist, $args{block};
896 my $sql = "UPDATE $updtable SET ";
897 $sql .= join " = ?, ", @fieldlist;
898 $sql .= " = ? WHERE $keyfield = ?";
899
900 eval {
901 # do the update
902 $dbh->do($sql, undef, @vallist);
903
904 if ($args{node}) {
905 # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
906 $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($args{block}) );
907 $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{block}, $args{node}) );
908 }
909
910 $dbh->commit;
911 };
912 if ($@) {
913 my $msg = $@;
914 $dbh->rollback;
915 return ('FAIL', $msg);
916 }
917 return 0;
918} # end updateBlock()
919
920
921## IPDB::deleteBlock()
922# Removes an allocation from the database, including deleting IPs
923# from poolips and recombining entries in freeblocks if possible
924# Also handles "deleting" a static IP allocation, and removal of a master
925# Requires a database handle, the block to delete, and the type of block
926sub deleteBlock {
927 my ($dbh,undef,$type) = @_;
928 my $cidr = new NetAddr::IP $_[1];
929
930 my $sth;
931
932 # Magic variables used for odd allocation cases.
933 my $container;
934 my $con_type;
935
936 # To contain the error message, if any.
937 my $msg = "Unknown error deallocating $type $cidr";
938 # Enable transactions and exception-on-errors... but only for this sub
939 local $dbh->{AutoCommit} = 0;
940 local $dbh->{RaiseError} = 1;
941
942 # First case. The "block" is a static IP
943 # Note that we still need some additional code in the odd case
944 # of a netblock-aligned contiguous group of static IPs
945 if ($type =~ /^.i$/) {
946
947 eval {
948 $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
949 $sth = $dbh->prepare("update poolips set custid=?,available='y',".
950 "city=(select city from allocations where cidr >>= ?".
951 " order by masklen(cidr) desc limit 1),".
952 "description='',notes='',circuitid='' where ip=?");
953 $sth->execute($defcustid, "$cidr", "$cidr");
954 $dbh->commit;
955 };
956 if ($@) {
957 eval { $dbh->rollback; };
958 return ('FAIL',$msg);
959 } else {
960 return ('OK',"OK");
961 }
962
963 } elsif ($type eq 'mm') { # end alloctype =~ /.i/
964
965 $msg = "Unable to delete master block $cidr";
966 eval {
967 $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
968 $sth->execute;
969 $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
970 $sth->execute;
971 $dbh->commit;
972 };
973 if ($@) {
974 eval { $dbh->rollback; };
975 return ('FAIL', $msg);
976 } else {
977 return ('OK',"OK");
978 }
979
980 } else { # end alloctype master block case
981
982 ## This is a big block; but it HAS to be done in a chunk. Any removal
983 ## of a netblock allocation may result in a larger chunk of free
984 ## contiguous IP space - which may in turn be combined into a single
985 ## netblock rather than a number of smaller netblocks.
986
987 eval {
988
989 if ($type eq 'rm') {
990 $msg = "Unable to remove routing allocation $cidr";
991 $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
992 $sth->execute;
993 # Make sure block getting deleted is properly accounted for.
994 $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
995 " where cidr='$cidr'");
996 $sth->execute;
997 # Set up query to start compacting free blocks.
998 $sth = $dbh->prepare("select cidr from freeblocks where ".
999 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
1000
1001 } else { # end alloctype routing case
1002
1003 # Magic. We need to get information about the containing block (if any)
1004 # so as to make sure that the freeblocks we insert get the correct "type".
1005 $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
1006 $sth->execute;
1007 ($container, $con_type) = $sth->fetchrow_array;
1008
1009 # Delete all allocations within the block being deleted. This is
1010 # deliberate and correct, and removes the need to special-case
1011 # removal of "container" blocks.
1012 $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
1013 $sth->execute;
1014
1015 # Special case - delete pool IPs
1016 if ($type =~ /^.[pd]$/) {
1017 # We have to delete the IPs from the pool listing.
1018 $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
1019 $sth->execute;
1020 }
1021
1022 # Set up query for compacting free blocks.
1023 if ($con_type && $con_type eq 'pc') {
1024 # Clean up after "bad" allocations (blocks that are not formally
1025 # contained which have nevertheless been allocated from a container block)
1026 # We want to make certain that the freeblocks are properly "labelled"
1027 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
1028 } else {
1029 # Standard deallocation.
1030 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
1031 "(select cidr from routed where cidr >>= '$cidr') ".
1032 " and maskbits<=".$cidr->masklen.
1033 " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
1034 "' order by maskbits desc");
1035 }
1036
1037 } # end alloctype general case
1038
1039 ## Deallocate legacy blocks stashed in the middle of a static IP pool
1040 ## This may be expandable to an even more general case of contained netblock, or other pool types.
1041
1042 # Find out if the block we're deallocating is within a DSL pool
1043 my $sth2 = $dbh->prepare("SELECT cidr,city,type FROM allocations WHERE type LIKE '_p' AND cidr >>= ?");
1044 $sth2->execute("$cidr");
1045 my ($pool,$poolcity,$pooltype) = $sth2->fetchrow_array;
1046
1047 if ($pool || $sth2->rows) {
1048 # We've already deleted the block, now we have to stuff its IPs into the pool.
1049 $pooltype =~ s/p$/i/; # change type to static IP
1050 $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) values ".
1051 "('$pool',?,'$poolcity','$pooltype','$defcustid')");
1052##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
1053 # don't insert .0
1054 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
1055 foreach my $ip ($cidr->hostenum) {
1056 $sth2->execute("$ip");
1057 }
1058 $cidr--;
1059 # don't insert .255
1060 $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
1061 } else { # done returning IPs from a block to a static DSL pool
1062
1063 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
1064 # (super)block. If there aren't any, we can't combine blocks anyway. If there
1065 # are, we check to see if we can combine blocks.
1066 # Execute the statement prepared in the if-else above.
1067
1068 $sth->execute;
1069
1070# NetAddr::IP->compact() attempts to produce the smallest inclusive block
1071# from the caller and the passed terms.
1072# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
1073# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
1074# .64-.95, and .96-.128), you will get an array containing a single
1075# /25 as element 0 (.0-.127). Order is not important; you could have
1076# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
1077
1078 my (@together, @combinelist);
1079 my $i=0;
1080 while (my @data = $sth->fetchrow_array) {
1081 my $testIP = new NetAddr::IP $data[0];
1082 @together = $testIP->compact($cidr);
1083 my $num = @together;
1084 if ($num == 1) {
1085 $cidr = $together[0];
1086 $combinelist[$i++] = $testIP;
1087 }
1088 }
1089
1090 # Clear old freeblocks entries - if any. They should all be within
1091 # the $cidr determined above.
1092 $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
1093 $sth->execute;
1094
1095 # insert "new" freeblocks entry
1096 if ($type eq 'rm') {
1097 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
1098 " values ('$cidr',".$cidr->masklen.",'<NULL>')");
1099 } else {
1100 # Magic hackery to insert "correct" data for deallocation of
1101 # non-contained blocks allocated from within a container.
1102 $type = 'pr' if $con_type && $con_type eq 'pc';
1103
1104 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
1105 " values ('$cidr',".$cidr->masklen.
1106 ",(select city from routed where cidr >>= '$cidr'),'".
1107 (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
1108 }
1109 $sth->execute;
1110
1111 } # done returning IPs to the appropriate place
1112
1113 # If we got here, we've succeeded. Whew!
1114 $dbh->commit;
1115 }; # end eval
1116 if ($@) {
1117 $msg = $@;
1118 eval { $dbh->rollback; };
1119 return ('FAIL', $msg);
1120 } else {
1121 return ('OK',"OK");
1122 }
1123
1124 } # end alloctype != netblock
1125
1126} # end deleteBlock()
1127
1128
1129## IPDB::getBlockData()
1130# Return custid, type, city, and description for a block
1131sub getBlockData {
1132 my $dbh = shift;
1133 my $block = shift;
1134
1135 my $binfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM searchme".
1136 " WHERE cidr = ?", undef, ($block) );
1137 return $binfo;
1138} # end getBlockData()
1139
1140
1141## IPDB::getNodeList()
1142# Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
1143sub getNodeList {
1144 my $dbh = shift;
1145
1146 my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
1147 { Slice => {} });
1148 return $ret;
1149} # end getNodeList()
1150
1151
1152## IPDB::getNodeName()
1153# Get node name from the ID
1154sub getNodeName {
1155 my $dbh = shift;
1156 my $nid = shift;
1157
1158 my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
1159 return $nname;
1160} # end getNodeName()
1161
1162
1163## IPDB::getNodeInfo()
1164# Get node name and ID associated with a block
1165sub getNodeInfo {
1166 my $dbh = shift;
1167 my $block = shift;
1168
1169 my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
1170 " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
1171 return ($nid, $nname);
1172} # end getNodeInfo()
1173
1174
1175## IPDB::mailNotify()
1176# Sends notification mail to recipients regarding an IPDB operation
1177sub mailNotify {
1178 my $dbh = shift;
1179 my ($action,$subj,$message) = @_;
1180
1181 return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
1182
1183##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
1184
1185# split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
1186 my @actionbits = split //, $action;
1187
1188 # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
1189 # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
1190 # and "all events with this action"
1191 my @actionsets = ($action);
1192##fixme: ick, eww. really gotta find a better way to handle this...
1193 push @actionsets, ($actionbits[0].'.'.$actionbits[2],
1194 $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
1195
1196 my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
1197
1198 # get recip list from db
1199 my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
1200
1201 my %reciplist;
1202 foreach (@actionsets) {
1203 $sth->execute($_);
1204##fixme - need to handle db errors
1205 my ($recipsub) = $sth->fetchrow_array;
1206 next if !$recipsub;
1207 foreach (split(/,/, $recipsub)) {
1208 $reciplist{$_}++;
1209 }
1210 }
1211
1212 return if !%reciplist;
1213
1214 foreach my $recip (keys %reciplist) {
1215 $mailer->mail("ipdb\@$domain");
1216 $mailer->to($recip);
1217 $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
1218 "To: $recip\n",
1219 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
1220 "Subject: {IPDB} $subj\n",
1221 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
1222 "Organization: $org_name\n",
1223 "\n$message\n");
1224 }
1225 $mailer->quit;
1226}
1227
1228# Indicates module loaded OK. Required by Perl.
12291;
Note: See TracBrowser for help on using the repository browser.