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-25 21:59:15 +0000 (Thu, 25 Oct 2012) $
|
---|
6 | # SVN revision $Rev: 530 $
|
---|
7 | # Last update by $Author: kdeugau $
|
---|
8 | ###
|
---|
9 | # Copyright (C) 2004-2010 - Kris Deugau
|
---|
10 |
|
---|
11 | package IPDB;
|
---|
12 |
|
---|
13 | use strict;
|
---|
14 | use warnings;
|
---|
15 | use Exporter;
|
---|
16 | use DBI;
|
---|
17 | use Net::SMTP;
|
---|
18 | use NetAddr::IP qw( Compact );
|
---|
19 | use POSIX;
|
---|
20 | use 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
|
---|
31 | &getParent &getRoutedCity
|
---|
32 | &allocateBlock &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
|
---|
45 | &getParent &getRoutedCity
|
---|
46 | &allocateBlock &deleteBlock &getBlockData
|
---|
47 | &getNodeList &getNodeName &getNodeInfo
|
---|
48 | &mailNotify
|
---|
49 | )]
|
---|
50 | );
|
---|
51 |
|
---|
52 | ##
|
---|
53 | ## Global variables
|
---|
54 | ##
|
---|
55 | our %disp_alloctypes;
|
---|
56 | our %list_alloctypes;
|
---|
57 | our %def_custids;
|
---|
58 | our @citylist;
|
---|
59 | our @poplist;
|
---|
60 | our @masterblocks;
|
---|
61 | our %allocated;
|
---|
62 | our %free;
|
---|
63 | our %routed;
|
---|
64 | our %bigfree;
|
---|
65 | our %IPDBacl;
|
---|
66 |
|
---|
67 | # mapping table for functional-area => error message
|
---|
68 | our %aclmsg = (
|
---|
69 | addmaster => 'add a master block',
|
---|
70 | addblock => 'add an allocation',
|
---|
71 | updateblock => 'update a block',
|
---|
72 | delblock => 'delete an allocation',
|
---|
73 | );
|
---|
74 |
|
---|
75 | our $org_name = 'Example Corp';
|
---|
76 | our $smtphost = 'smtp.example.com';
|
---|
77 | our $domain = 'example.com';
|
---|
78 | our $defcustid = '5554242';
|
---|
79 | # mostly for rwhois
|
---|
80 | ##fixme: leave these blank by default?
|
---|
81 | our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
|
---|
82 | our $org_street = '123 4th Street';
|
---|
83 | our $org_city = 'Anytown';
|
---|
84 | our $org_prov_state = 'ON';
|
---|
85 | our $org_pocode = 'H0H 0H0';
|
---|
86 | our $org_country = 'CA';
|
---|
87 | our $org_phone = '000-555-1234';
|
---|
88 | our $org_techhandle = 'ISP-ARIN-HANDLE';
|
---|
89 | our $org_email = 'noc@example.com';
|
---|
90 | our $hostmaster = 'dns@example.com';
|
---|
91 |
|
---|
92 | our $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
|
---|
97 | sub 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.
|
---|
158 | sub 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
|
---|
194 | sub 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.
|
---|
203 | sub 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"
|
---|
231 | sub 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
|
---|
327 | sub 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
|
---|
355 | sub 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
|
---|
384 | sub 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
|
---|
423 | sub 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 | #
|
---|
451 | sub 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
|
---|
477 | sub 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::getParent()
|
---|
502 | # Get a block's parent's details
|
---|
503 | # Takes a database handle and CIDR block
|
---|
504 | # Returns a hashref to the parent routed or container block, if any
|
---|
505 | sub getParent {
|
---|
506 | my $dbh = shift;
|
---|
507 | my $block = shift;
|
---|
508 |
|
---|
509 | my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
|
---|
510 | " WHERE cidr >>= ?", undef, ($block) );
|
---|
511 | return $pinfo;
|
---|
512 | } # end getParent()
|
---|
513 |
|
---|
514 |
|
---|
515 | ## IPDB::getRoutedCity()
|
---|
516 | # Get the city for a routed block.
|
---|
517 | sub getRoutedCity {
|
---|
518 | my $dbh = shift;
|
---|
519 | my $block = shift;
|
---|
520 |
|
---|
521 | my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
|
---|
522 | return $rcity;
|
---|
523 | } # end getRoutedCity()
|
---|
524 |
|
---|
525 |
|
---|
526 | ## IPDB::allocateBlock()
|
---|
527 | # Does all of the magic of actually allocating a netblock
|
---|
528 | # Requires database handle, block to allocate, custid, type, city,
|
---|
529 | # description, notes, circuit ID, block to allocate from, private data
|
---|
530 | # Returns a success code and optional error message.
|
---|
531 | sub allocateBlock {
|
---|
532 | my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid,$privdata,$nodeid) = @_;
|
---|
533 |
|
---|
534 | my $cidr = new NetAddr::IP $_[1];
|
---|
535 | my $alloc_from = new NetAddr::IP $_[2];
|
---|
536 | my $sth;
|
---|
537 |
|
---|
538 | $desc = '' if !$desc;
|
---|
539 | $notes = '' if !$notes;
|
---|
540 | $circid = '' if !$circid;
|
---|
541 | $privdata = '' if !$privdata;
|
---|
542 |
|
---|
543 | # Snag the "type" of the freeblock (alloc_from) "just in case"
|
---|
544 | $sth = $dbh->prepare("select routed from freeblocks where cidr='$alloc_from'");
|
---|
545 | $sth->execute;
|
---|
546 | my ($alloc_from_type) = $sth->fetchrow_array;
|
---|
547 |
|
---|
548 | # To contain the error message, if any.
|
---|
549 | my $msg = "Unknown error allocating $cidr as '$type'";
|
---|
550 |
|
---|
551 | # Enable transactions and error handling
|
---|
552 | local $dbh->{AutoCommit} = 0; # These need to be local so we don't
|
---|
553 | local $dbh->{RaiseError} = 1; # step on our toes by accident.
|
---|
554 |
|
---|
555 | if ($type =~ /^.i$/) {
|
---|
556 | $msg = "Unable to assign static IP $cidr to $custid";
|
---|
557 | eval {
|
---|
558 | # We have to do this in two parts because otherwise we lose
|
---|
559 | # the ability to return the IP assigned. Should that change,
|
---|
560 | # the commented SQL statement below may become usable.
|
---|
561 | # update poolips set custid='$custid',city='$city',available='n',
|
---|
562 | # description='$desc',notes='$notes',circuitid='$circid'
|
---|
563 | # where ip=(select ip from poolips where pool='$alloc_from'
|
---|
564 | # and available='y' order by ip limit 1);
|
---|
565 |
|
---|
566 | $sth = $dbh->prepare("select ip from poolips where pool='$alloc_from'".
|
---|
567 | " and available='y' order by ip");
|
---|
568 | $sth->execute;
|
---|
569 |
|
---|
570 | my @data = $sth->fetchrow_array;
|
---|
571 | $cidr = $data[0]; # $cidr is already declared when we get here!
|
---|
572 |
|
---|
573 | $sth = $dbh->prepare("update poolips set custid=?,city=?,".
|
---|
574 | "available='n',description=?,notes=?,circuitid=?,privdata=?".
|
---|
575 | " where ip=?");
|
---|
576 | $sth->execute($custid, $city, $desc, $notes, $circid, $privdata, "$cidr");
|
---|
577 | # node hack
|
---|
578 | if ($nodeid && $nodeid ne '') {
|
---|
579 | $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
|
---|
580 | $sth->execute("$cidr",$nodeid);
|
---|
581 | }
|
---|
582 | # end node hack
|
---|
583 | $dbh->commit;
|
---|
584 | };
|
---|
585 | if ($@) {
|
---|
586 | $msg .= ": '".$sth->errstr."'";
|
---|
587 | eval { $dbh->rollback; };
|
---|
588 | return ('FAIL',$msg);
|
---|
589 | } else {
|
---|
590 | return ('OK',"$cidr");
|
---|
591 | }
|
---|
592 |
|
---|
593 | } else { # end IP-from-pool allocation
|
---|
594 |
|
---|
595 | if ($cidr == $alloc_from) {
|
---|
596 | # Easiest case- insert in one table, delete in the other, and go home. More or less.
|
---|
597 | # insert into allocations values (cidr,custid,type,city,desc) and
|
---|
598 | # delete from freeblocks where cidr='cidr'
|
---|
599 | # For data safety on non-transaction DBs, we delete first.
|
---|
600 |
|
---|
601 | eval {
|
---|
602 | $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
|
---|
603 | if ($type eq 'rm') {
|
---|
604 | $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
|
---|
605 | " where cidr='$cidr'");
|
---|
606 | $sth->execute;
|
---|
607 | $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
|
---|
608 | " values ('$cidr',".$cidr->masklen.",'$city')");
|
---|
609 | $sth->execute;
|
---|
610 | } else {
|
---|
611 | # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
|
---|
612 |
|
---|
613 | # special case - block is a container/"reserve" block
|
---|
614 | if ($type =~ /^(.)c$/) {
|
---|
615 | $sth = $dbh->prepare("update freeblocks set routed='$1' where cidr='$cidr'");
|
---|
616 | $sth->execute;
|
---|
617 | } else {
|
---|
618 | # "normal" case
|
---|
619 | $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
|
---|
620 | $sth->execute;
|
---|
621 | }
|
---|
622 | $sth = $dbh->prepare("insert into allocations".
|
---|
623 | " (cidr,custid,type,city,description,notes,maskbits,circuitid,privdata)".
|
---|
624 | " values (?,?,?,?,?,?,?,?,?)");
|
---|
625 | $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
|
---|
626 |
|
---|
627 | # And initialize the pool, if necessary
|
---|
628 | # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
|
---|
629 | # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
|
---|
630 | if ($type =~ /^.p$/) {
|
---|
631 | $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
|
---|
632 | my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
|
---|
633 | die $rmsg if $code eq 'FAIL';
|
---|
634 | } elsif ($type =~ /^.d$/) {
|
---|
635 | $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
|
---|
636 | my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
|
---|
637 | die $rmsg if $code eq 'FAIL';
|
---|
638 | }
|
---|
639 |
|
---|
640 | } # routing vs non-routing netblock
|
---|
641 |
|
---|
642 | # node hack
|
---|
643 | if ($nodeid && $nodeid ne '') {
|
---|
644 | $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
|
---|
645 | $sth->execute("$cidr",$nodeid);
|
---|
646 | }
|
---|
647 | # end node hack
|
---|
648 | $dbh->commit;
|
---|
649 | }; # end of eval
|
---|
650 | if ($@) {
|
---|
651 | $msg .= ": ".$@;
|
---|
652 | eval { $dbh->rollback; };
|
---|
653 | return ('FAIL',$msg);
|
---|
654 | } else {
|
---|
655 | return ('OK',"OK");
|
---|
656 | }
|
---|
657 |
|
---|
658 | } else { # cidr != alloc_from
|
---|
659 |
|
---|
660 | # Hard case. Allocation is smaller than free block.
|
---|
661 | my $wantmaskbits = $cidr->masklen;
|
---|
662 | my $maskbits = $alloc_from->masklen;
|
---|
663 |
|
---|
664 | my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
|
---|
665 |
|
---|
666 | # This determines which blocks will be left "free" after allocation. We take the
|
---|
667 | # block we're allocating from, and split it in half. We see which half the wanted
|
---|
668 | # block is in, and repeat until the wanted block is equal to one of the halves.
|
---|
669 | my $i=0;
|
---|
670 | my $tmp_from = $alloc_from; # So we don't munge $alloc_from
|
---|
671 | while ($maskbits++ < $wantmaskbits) {
|
---|
672 | my @subblocks = $tmp_from->split($maskbits);
|
---|
673 | $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
|
---|
674 | $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
|
---|
675 | } # while
|
---|
676 |
|
---|
677 | # Begin SQL transaction block
|
---|
678 | eval {
|
---|
679 | $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
|
---|
680 |
|
---|
681 | # Delete old freeblocks entry
|
---|
682 | $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
|
---|
683 | $sth->execute();
|
---|
684 |
|
---|
685 | # now we have to do some magic for routing blocks
|
---|
686 | if ($type eq 'rm') {
|
---|
687 |
|
---|
688 | # Insert the new freeblocks entries
|
---|
689 | # Note that non-routed blocks are assigned to <NULL>
|
---|
690 | # and use the default value for the routed column ('n')
|
---|
691 | $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
|
---|
692 | " values (?, ?, '<NULL>')");
|
---|
693 | foreach my $block (@newfreeblocks) {
|
---|
694 | $sth->execute("$block", $block->masklen);
|
---|
695 | }
|
---|
696 |
|
---|
697 | # Insert the entry in the routed table
|
---|
698 | $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
|
---|
699 | " values ('$cidr',".$cidr->masklen.",'$city')");
|
---|
700 | $sth->execute;
|
---|
701 | # Insert the (almost) same entry in the freeblocks table
|
---|
702 | $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
|
---|
703 | " values ('$cidr',".$cidr->masklen.",'$city','y')");
|
---|
704 | $sth->execute;
|
---|
705 |
|
---|
706 | } else { # done with alloctype == rm
|
---|
707 |
|
---|
708 | # Insert the new freeblocks entries
|
---|
709 | # Along with some more HairyPerl(TM):
|
---|
710 | # if $alloc_type_from is p
|
---|
711 | # OR
|
---|
712 | # $type matches /^(.)r$/
|
---|
713 | # inserted value for routed column should match.
|
---|
714 | # This solves the case of inserting an arbitrary block into a
|
---|
715 | # "Reserve-for-routed-DSL" block. Which you really shouldn't
|
---|
716 | # do in the first place, but anyway...
|
---|
717 | $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
|
---|
718 | " values (?, ?, (select city from routed where cidr >>= '$cidr'),'".
|
---|
719 | ( ( ($alloc_from_type =~ /^(p)$/) || ($type =~ /^(.)r$/) ) ? "$1" : 'y')."')");
|
---|
720 | foreach my $block (@newfreeblocks) {
|
---|
721 | $sth->execute("$block", $block->masklen);
|
---|
722 | }
|
---|
723 | # Special-case for reserve/"container" blocks - generate
|
---|
724 | # the "extra" freeblocks entry for the container
|
---|
725 | if ($type =~ /^(.)c$/) {
|
---|
726 | $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
|
---|
727 | " values ('$cidr',".$cidr->masklen.",'$city','$1')");
|
---|
728 | $sth->execute;
|
---|
729 | }
|
---|
730 | # Insert the allocations entry
|
---|
731 | $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
|
---|
732 | "description,notes,maskbits,circuitid,privdata)".
|
---|
733 | " values (?,?,?,?,?,?,?,?,?)");
|
---|
734 | $sth->execute("$cidr", $custid, $type, $city, $desc, $notes, $cidr->masklen, $circid, $privdata);
|
---|
735 |
|
---|
736 | # And initialize the pool, if necessary
|
---|
737 | # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
|
---|
738 | # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
|
---|
739 | if ($type =~ /^.p$/) {
|
---|
740 | $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
|
---|
741 | my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"all");
|
---|
742 | die $rmsg if $code eq 'FAIL';
|
---|
743 | } elsif ($type =~ /^.d$/) {
|
---|
744 | $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
|
---|
745 | my ($code,$rmsg) = initPool($dbh,$cidr,$type,$city,"normal");
|
---|
746 | die $rmsg if $code eq 'FAIL';
|
---|
747 | }
|
---|
748 |
|
---|
749 | } # done with netblock alloctype != rm
|
---|
750 |
|
---|
751 | # node hack
|
---|
752 | if ($nodeid && $nodeid ne '') {
|
---|
753 | $sth = $dbh->prepare("INSERT INTO noderef (block,node_id) VALUES (?,?)");
|
---|
754 | $sth->execute("$cidr",$nodeid);
|
---|
755 | }
|
---|
756 | # end node hack
|
---|
757 | $dbh->commit;
|
---|
758 | }; # end eval
|
---|
759 | if ($@) {
|
---|
760 | $msg .= ": ".$@;
|
---|
761 | eval { $dbh->rollback; };
|
---|
762 | return ('FAIL',$msg);
|
---|
763 | } else {
|
---|
764 | return ('OK',"OK");
|
---|
765 | }
|
---|
766 |
|
---|
767 | } # end fullcidr != alloc_from
|
---|
768 |
|
---|
769 | } # end static-IP vs netblock allocation
|
---|
770 |
|
---|
771 | } # end allocateBlock()
|
---|
772 |
|
---|
773 |
|
---|
774 | ## IPDB::initPool()
|
---|
775 | # Initializes a pool
|
---|
776 | # Requires a database handle, the pool CIDR, type, city, and a parameter
|
---|
777 | # indicating whether the pool should allow allocation of literally every
|
---|
778 | # IP, or if it should reserve network/gateway/broadcast IPs
|
---|
779 | # Note that this is NOT done in a transaction, that's why it's a private
|
---|
780 | # function and should ONLY EVER get called from allocateBlock()
|
---|
781 | sub initPool {
|
---|
782 | my ($dbh,undef,$type,$city,$class) = @_;
|
---|
783 | my $pool = new NetAddr::IP $_[1];
|
---|
784 |
|
---|
785 | ##fixme Need to just replace 2nd char of type with i rather than capturing 1st char of type
|
---|
786 | $type =~ s/[pd]$/i/;
|
---|
787 | my $sth;
|
---|
788 | my $msg;
|
---|
789 |
|
---|
790 | # Trap errors so we can pass them back to the caller. Even if the
|
---|
791 | # caller is only ever supposed to be local, and therefore already
|
---|
792 | # trapping errors. >:(
|
---|
793 | local $dbh->{AutoCommit} = 0; # These need to be local so we don't
|
---|
794 | local $dbh->{RaiseError} = 1; # step on our toes by accident.
|
---|
795 |
|
---|
796 | eval {
|
---|
797 | # have to insert all pool IPs into poolips table as "unallocated".
|
---|
798 | $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,type)".
|
---|
799 | " values ('$pool', ?, '$defcustid', ?, '$type')");
|
---|
800 | my @poolip_list = $pool->hostenum;
|
---|
801 | if ($class eq 'all') { # (DSL-ish block - *all* IPs available
|
---|
802 | if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
|
---|
803 | $sth->execute($pool->addr, $city);
|
---|
804 | }
|
---|
805 | for (my $i=0; $i<=$#poolip_list; $i++) {
|
---|
806 | $sth->execute($poolip_list[$i]->addr, $city);
|
---|
807 | }
|
---|
808 | $pool--;
|
---|
809 | if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
|
---|
810 | $sth->execute($pool->addr, $city);
|
---|
811 | }
|
---|
812 | } else { # (real netblock)
|
---|
813 | for (my $i=1; $i<=$#poolip_list; $i++) {
|
---|
814 | $sth->execute($poolip_list[$i]->addr, $city);
|
---|
815 | }
|
---|
816 | }
|
---|
817 | };
|
---|
818 | if ($@) {
|
---|
819 | $msg = $@." '".$sth->errstr."'";
|
---|
820 | eval { $dbh->rollback; };
|
---|
821 | return ('FAIL',$msg);
|
---|
822 | } else {
|
---|
823 | return ('OK',"OK");
|
---|
824 | }
|
---|
825 | } # end initPool()
|
---|
826 |
|
---|
827 |
|
---|
828 | ## IPDB::deleteBlock()
|
---|
829 | # Removes an allocation from the database, including deleting IPs
|
---|
830 | # from poolips and recombining entries in freeblocks if possible
|
---|
831 | # Also handles "deleting" a static IP allocation, and removal of a master
|
---|
832 | # Requires a database handle, the block to delete, and the type of block
|
---|
833 | sub deleteBlock {
|
---|
834 | my ($dbh,undef,$type) = @_;
|
---|
835 | my $cidr = new NetAddr::IP $_[1];
|
---|
836 |
|
---|
837 | my $sth;
|
---|
838 |
|
---|
839 | # Magic variables used for odd allocation cases.
|
---|
840 | my $container;
|
---|
841 | my $con_type;
|
---|
842 |
|
---|
843 | # To contain the error message, if any.
|
---|
844 | my $msg = "Unknown error deallocating $type $cidr";
|
---|
845 | # Enable transactions and exception-on-errors... but only for this sub
|
---|
846 | local $dbh->{AutoCommit} = 0;
|
---|
847 | local $dbh->{RaiseError} = 1;
|
---|
848 |
|
---|
849 | # First case. The "block" is a static IP
|
---|
850 | # Note that we still need some additional code in the odd case
|
---|
851 | # of a netblock-aligned contiguous group of static IPs
|
---|
852 | if ($type =~ /^.i$/) {
|
---|
853 |
|
---|
854 | eval {
|
---|
855 | $msg = "Unable to deallocate $disp_alloctypes{$type} $cidr";
|
---|
856 | $sth = $dbh->prepare("update poolips set custid=?,available='y',".
|
---|
857 | "city=(select city from allocations where cidr >>= ?".
|
---|
858 | " order by masklen(cidr) desc limit 1),".
|
---|
859 | "description='',notes='',circuitid='' where ip=?");
|
---|
860 | $sth->execute($defcustid, "$cidr", "$cidr");
|
---|
861 | $dbh->commit;
|
---|
862 | };
|
---|
863 | if ($@) {
|
---|
864 | eval { $dbh->rollback; };
|
---|
865 | return ('FAIL',$msg);
|
---|
866 | } else {
|
---|
867 | return ('OK',"OK");
|
---|
868 | }
|
---|
869 |
|
---|
870 | } elsif ($type eq 'mm') { # end alloctype =~ /.i/
|
---|
871 |
|
---|
872 | $msg = "Unable to delete master block $cidr";
|
---|
873 | eval {
|
---|
874 | $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
|
---|
875 | $sth->execute;
|
---|
876 | $sth = $dbh->prepare("delete from freeblocks where cidr <<= '$cidr'");
|
---|
877 | $sth->execute;
|
---|
878 | $dbh->commit;
|
---|
879 | };
|
---|
880 | if ($@) {
|
---|
881 | eval { $dbh->rollback; };
|
---|
882 | return ('FAIL', $msg);
|
---|
883 | } else {
|
---|
884 | return ('OK',"OK");
|
---|
885 | }
|
---|
886 |
|
---|
887 | } else { # end alloctype master block case
|
---|
888 |
|
---|
889 | ## This is a big block; but it HAS to be done in a chunk. Any removal
|
---|
890 | ## of a netblock allocation may result in a larger chunk of free
|
---|
891 | ## contiguous IP space - which may in turn be combined into a single
|
---|
892 | ## netblock rather than a number of smaller netblocks.
|
---|
893 |
|
---|
894 | eval {
|
---|
895 |
|
---|
896 | if ($type eq 'rm') {
|
---|
897 | $msg = "Unable to remove routing allocation $cidr";
|
---|
898 | $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
|
---|
899 | $sth->execute;
|
---|
900 | # Make sure block getting deleted is properly accounted for.
|
---|
901 | $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
|
---|
902 | " where cidr='$cidr'");
|
---|
903 | $sth->execute;
|
---|
904 | # Set up query to start compacting free blocks.
|
---|
905 | $sth = $dbh->prepare("select cidr from freeblocks where ".
|
---|
906 | "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
|
---|
907 |
|
---|
908 | } else { # end alloctype routing case
|
---|
909 |
|
---|
910 | # Magic. We need to get information about the containing block (if any)
|
---|
911 | # so as to make sure that the freeblocks we insert get the correct "type".
|
---|
912 | $sth = $dbh->prepare("select cidr,type from allocations where cidr >> '$cidr'");
|
---|
913 | $sth->execute;
|
---|
914 | ($container, $con_type) = $sth->fetchrow_array;
|
---|
915 |
|
---|
916 | # Delete all allocations within the block being deleted. This is
|
---|
917 | # deliberate and correct, and removes the need to special-case
|
---|
918 | # removal of "container" blocks.
|
---|
919 | $sth = $dbh->prepare("delete from allocations where cidr <<='$cidr'");
|
---|
920 | $sth->execute;
|
---|
921 |
|
---|
922 | # Special case - delete pool IPs
|
---|
923 | if ($type =~ /^.[pd]$/) {
|
---|
924 | # We have to delete the IPs from the pool listing.
|
---|
925 | $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
|
---|
926 | $sth->execute;
|
---|
927 | }
|
---|
928 |
|
---|
929 | # Set up query for compacting free blocks.
|
---|
930 | if ($con_type && $con_type eq 'pc') {
|
---|
931 | # Clean up after "bad" allocations (blocks that are not formally
|
---|
932 | # contained which have nevertheless been allocated from a container block)
|
---|
933 | # We want to make certain that the freeblocks are properly "labelled"
|
---|
934 | $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= '$container' order by maskbits desc");
|
---|
935 | } else {
|
---|
936 | # Standard deallocation.
|
---|
937 | $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
|
---|
938 | "(select cidr from routed where cidr >>= '$cidr') ".
|
---|
939 | " and maskbits<=".$cidr->masklen.
|
---|
940 | " and routed='".(($type =~ /^(.)r$/) ? "$1" : 'y').
|
---|
941 | "' order by maskbits desc");
|
---|
942 | }
|
---|
943 |
|
---|
944 | } # end alloctype general case
|
---|
945 |
|
---|
946 | ## Deallocate legacy blocks stashed in the middle of a static IP pool
|
---|
947 | ## This may be expandable to an even more general case of contained netblock, or other pool types.
|
---|
948 |
|
---|
949 | # Find out if the block we're deallocating is within a DSL pool
|
---|
950 | my $sth2 = $dbh->prepare("SELECT cidr,city,type FROM allocations WHERE type LIKE '_p' AND cidr >>= ?");
|
---|
951 | $sth2->execute("$cidr");
|
---|
952 | my ($pool,$poolcity,$pooltype) = $sth2->fetchrow_array;
|
---|
953 |
|
---|
954 | if ($pool || $sth2->rows) {
|
---|
955 | # We've already deleted the block, now we have to stuff its IPs into the pool.
|
---|
956 | $pooltype =~ s/p$/i/; # change type to static IP
|
---|
957 | $sth2 = $dbh->prepare("INSERT INTO poolips (pool,ip,city,type,custid) values ".
|
---|
958 | "('$pool',?,'$poolcity','$pooltype','$defcustid')");
|
---|
959 | ##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
|
---|
960 | # don't insert .0
|
---|
961 | $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
|
---|
962 | foreach my $ip ($cidr->hostenum) {
|
---|
963 | $sth2->execute("$ip");
|
---|
964 | }
|
---|
965 | $cidr--;
|
---|
966 | # don't insert .255
|
---|
967 | $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
|
---|
968 | } else { # done returning IPs from a block to a static DSL pool
|
---|
969 |
|
---|
970 | # Now we look for larger-or-equal-sized free blocks in the same master (routed)
|
---|
971 | # (super)block. If there aren't any, we can't combine blocks anyway. If there
|
---|
972 | # are, we check to see if we can combine blocks.
|
---|
973 | # Execute the statement prepared in the if-else above.
|
---|
974 |
|
---|
975 | $sth->execute;
|
---|
976 |
|
---|
977 | # NetAddr::IP->compact() attempts to produce the smallest inclusive block
|
---|
978 | # from the caller and the passed terms.
|
---|
979 | # EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
|
---|
980 | # and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
|
---|
981 | # .64-.95, and .96-.128), you will get an array containing a single
|
---|
982 | # /25 as element 0 (.0-.127). Order is not important; you could have
|
---|
983 | # $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
|
---|
984 |
|
---|
985 | my (@together, @combinelist);
|
---|
986 | my $i=0;
|
---|
987 | while (my @data = $sth->fetchrow_array) {
|
---|
988 | my $testIP = new NetAddr::IP $data[0];
|
---|
989 | @together = $testIP->compact($cidr);
|
---|
990 | my $num = @together;
|
---|
991 | if ($num == 1) {
|
---|
992 | $cidr = $together[0];
|
---|
993 | $combinelist[$i++] = $testIP;
|
---|
994 | }
|
---|
995 | }
|
---|
996 |
|
---|
997 | # Clear old freeblocks entries - if any. They should all be within
|
---|
998 | # the $cidr determined above.
|
---|
999 | $sth = $dbh->prepare("delete from freeblocks where cidr <<='$cidr'");
|
---|
1000 | $sth->execute;
|
---|
1001 |
|
---|
1002 | # insert "new" freeblocks entry
|
---|
1003 | if ($type eq 'rm') {
|
---|
1004 | $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
|
---|
1005 | " values ('$cidr',".$cidr->masklen.",'<NULL>')");
|
---|
1006 | } else {
|
---|
1007 | # Magic hackery to insert "correct" data for deallocation of
|
---|
1008 | # non-contained blocks allocated from within a container.
|
---|
1009 | $type = 'pr' if $con_type && $con_type eq 'pc';
|
---|
1010 |
|
---|
1011 | $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
|
---|
1012 | " values ('$cidr',".$cidr->masklen.
|
---|
1013 | ",(select city from routed where cidr >>= '$cidr'),'".
|
---|
1014 | (($type =~ /^(.)r$/) ? "$1" : 'y')."')");
|
---|
1015 | }
|
---|
1016 | $sth->execute;
|
---|
1017 |
|
---|
1018 | } # done returning IPs to the appropriate place
|
---|
1019 |
|
---|
1020 | # If we got here, we've succeeded. Whew!
|
---|
1021 | $dbh->commit;
|
---|
1022 | }; # end eval
|
---|
1023 | if ($@) {
|
---|
1024 | $msg = $@;
|
---|
1025 | eval { $dbh->rollback; };
|
---|
1026 | return ('FAIL', $msg);
|
---|
1027 | } else {
|
---|
1028 | return ('OK',"OK");
|
---|
1029 | }
|
---|
1030 |
|
---|
1031 | } # end alloctype != netblock
|
---|
1032 |
|
---|
1033 | } # end deleteBlock()
|
---|
1034 |
|
---|
1035 |
|
---|
1036 | ## IPDB::getBlockData()
|
---|
1037 | # Return custid, type, city, and description for a block
|
---|
1038 | sub getBlockData {
|
---|
1039 | my $dbh = shift;
|
---|
1040 | my $block = shift;
|
---|
1041 |
|
---|
1042 | my $binfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM searchme".
|
---|
1043 | " WHERE cidr = ?", undef, ($block) );
|
---|
1044 | return $binfo;
|
---|
1045 | } # end getBlockData()
|
---|
1046 |
|
---|
1047 |
|
---|
1048 | ## IPDB::getNodeList()
|
---|
1049 | # Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
|
---|
1050 | sub getNodeList {
|
---|
1051 | my $dbh = shift;
|
---|
1052 |
|
---|
1053 | my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name FROM nodes ORDER BY node_type,node_id",
|
---|
1054 | { Slice => {} });
|
---|
1055 | return $ret;
|
---|
1056 | } # end getNodeList()
|
---|
1057 |
|
---|
1058 |
|
---|
1059 | ## IPDB::getNodeName()
|
---|
1060 | # Get node name from the ID
|
---|
1061 | sub getNodeName {
|
---|
1062 | my $dbh = shift;
|
---|
1063 | my $nid = shift;
|
---|
1064 |
|
---|
1065 | my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
|
---|
1066 | return $nname;
|
---|
1067 | } # end getNodeName()
|
---|
1068 |
|
---|
1069 |
|
---|
1070 | ## IPDB::getNodeInfo()
|
---|
1071 | # Get node name and ID associated with a block
|
---|
1072 | sub getNodeInfo {
|
---|
1073 | my $dbh = shift;
|
---|
1074 | my $block = shift;
|
---|
1075 |
|
---|
1076 | my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
|
---|
1077 | " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
|
---|
1078 | return ($nid, $nname);
|
---|
1079 | } # end getNodeInfo()
|
---|
1080 |
|
---|
1081 |
|
---|
1082 | ## IPDB::mailNotify()
|
---|
1083 | # Sends notification mail to recipients regarding an IPDB operation
|
---|
1084 | sub mailNotify {
|
---|
1085 | my $dbh = shift;
|
---|
1086 | my ($action,$subj,$message) = @_;
|
---|
1087 |
|
---|
1088 | return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
1089 |
|
---|
1090 | ##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
|
---|
1091 |
|
---|
1092 | # split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
|
---|
1093 | my @actionbits = split //, $action;
|
---|
1094 |
|
---|
1095 | # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
|
---|
1096 | # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
|
---|
1097 | # and "all events with this action"
|
---|
1098 | my @actionsets = ($action);
|
---|
1099 | ##fixme: ick, eww. really gotta find a better way to handle this...
|
---|
1100 | push @actionsets, ($actionbits[0].'.'.$actionbits[2],
|
---|
1101 | $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
|
---|
1102 |
|
---|
1103 | my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
|
---|
1104 |
|
---|
1105 | # get recip list from db
|
---|
1106 | my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
|
---|
1107 |
|
---|
1108 | my %reciplist;
|
---|
1109 | foreach (@actionsets) {
|
---|
1110 | $sth->execute($_);
|
---|
1111 | ##fixme - need to handle db errors
|
---|
1112 | my ($recipsub) = $sth->fetchrow_array;
|
---|
1113 | next if !$recipsub;
|
---|
1114 | foreach (split(/,/, $recipsub)) {
|
---|
1115 | $reciplist{$_}++;
|
---|
1116 | }
|
---|
1117 | }
|
---|
1118 |
|
---|
1119 | return if !%reciplist;
|
---|
1120 |
|
---|
1121 | foreach my $recip (keys %reciplist) {
|
---|
1122 | $mailer->mail("ipdb\@$domain");
|
---|
1123 | $mailer->to($recip);
|
---|
1124 | $mailer->data("From: \"$org_name IP Database\" <ipdb\@$domain>\n",
|
---|
1125 | "To: $recip\n",
|
---|
1126 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
1127 | "Subject: {IPDB} $subj\n",
|
---|
1128 | "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
|
---|
1129 | "Organization: $org_name\n",
|
---|
1130 | "\n$message\n");
|
---|
1131 | }
|
---|
1132 | $mailer->quit;
|
---|
1133 | }
|
---|
1134 |
|
---|
1135 | # Indicates module loaded OK. Required by Perl.
|
---|
1136 | 1;
|
---|