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