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