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