source: trunk/cgi-bin/main.cgi@ 231

Last change on this file since 231 was 231, checked in by Kris Deugau, 20 years ago

/trunk

Missing backport: update to fix display issue relating to
container netblocks from /branches/stable r194

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 44.4 KB
RevLine 
[4]1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
3# Started munging from noc.vianet's old IPDB 04/22/2004
[8]4###
5# SVN revision info
6# $Date: 2005-04-15 21:10:52 +0000 (Fri, 15 Apr 2005) $
7# SVN revision $Rev: 231 $
8# Last update by $Author: kdeugau $
9###
[4]10
11use strict;
12use warnings;
13use CGI::Carp qw(fatalsToBrowser);
14use DBI;
15use CommonWeb qw(:ALL);
[142]16use MyIPDB;
[4]17use POSIX qw(ceil);
18use NetAddr::IP;
19
20use Sys::Syslog;
21
22openlog "IPDB","pid","local2";
23
24# Collect the username from HTTP auth. If undefined, we're in a test environment.
25my $authuser;
26if (!defined($ENV{'REMOTE_USER'})) {
27 $authuser = '__temptest';
28} else {
29 $authuser = $ENV{'REMOTE_USER'};
30}
31
32syslog "debug", "$authuser active";
33
[106]34# Why not a global DB handle? (And a global statement handle, as well...)
35# Use the connectDB function, otherwise we end up confusing ourselves
36my $ip_dbh;
37my $sth;
38my $errstr;
[142]39($ip_dbh,$errstr) = connectDB_My;
[106]40if (!$ip_dbh) {
[184]41 printAndExit("Database error: $errstr\n");
[106]42}
43initIPDBGlobals($ip_dbh);
[4]44
45#prototypes
46sub viewBy($$); # feed it the category and query
47sub queryResults($$$); # args is the sql, the page# and the rowCount
48# Needs rewrite/rename
49sub countRows($); # returns first element of first row of passed SQL
50 # Only usage passes "select count(*) ..."
51
[106]52# Global variables
[4]53my $RESULTS_PER_PAGE = 50;
54my %webvar = parse_post();
55cleanInput(\%webvar);
56
57
58#main()
59
60if(!defined($webvar{action})) {
61 $webvar{action} = "<NULL>"; #shuts up the warnings.
62}
63
64if($webvar{action} eq 'index') {
65 showSummary();
66} elsif ($webvar{action} eq 'newmaster') {
67 printHeader('');
68
69 my $cidr = new NetAddr::IP $webvar{cidr};
70
[115]71 print "<div type=heading align=center>Adding $cidr as master block....</div>\n";
[4]72
73 # Allow transactions, and raise an exception on errors so we can catch it later.
74 # Use local to make sure these get "reset" properly on exiting this block
75 local $ip_dbh->{AutoCommit} = 0;
76 local $ip_dbh->{RaiseError} = 1;
77
78 # Wrap the SQL in a transaction
79 eval {
80 $sth = $ip_dbh->prepare("insert into masterblocks values ('$webvar{cidr}')");
81 $sth->execute;
82
83# Unrouted blocks aren't associated with a city (yet). We don't rely on this
84# elsewhere though; legacy data may have traps and pitfalls in it to break this.
85# Thus the "routed" flag.
86
[157]87 $sth = $ip_dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
88 " values ('$webvar{cidr}',".$cidr->masklen.",'<NULL>','n')");
[4]89 $sth->execute;
90
91 # If we get here, everything is happy. Commit changes.
92 $ip_dbh->commit;
93 }; # end eval
94
95 if ($@) {
96 carp "Transaction aborted because $@";
97 eval { $ip_dbh->rollback; };
[17]98 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$@'";
[106]99 printError("Could not add master block $webvar{cidr} to database: $@");
100 } else {
[115]101 print "<div type=heading align=center>Success!</div>\n";
[106]102 syslog "info", "$authuser added master block $webvar{cidr}";
[4]103 }
104
105} # end add new master
106
107elsif($webvar{action} eq 'showmaster') {
108 showMaster();
109}
110elsif($webvar{action} eq 'showrouted') {
111 showRBlock();
112}
113elsif($webvar{action} eq 'listpool') {
114 listPool();
115}
116elsif($webvar{action} eq 'search') {
117 printHeader('');
118 if (!$webvar{input}) {
119 # No search term. Display everything.
120 viewBy('all', '');
121 } else {
122 # Search term entered. Display matches.
123 # We should really sanitize $webvar{input}, no?
124 viewBy($webvar{searchfor}, $webvar{input});
125 }
126}
127
128# Not modified or added; just shuffled
129elsif($webvar{action} eq 'assign') {
130 assignBlock();
131}
132elsif($webvar{action} eq 'confirm') {
133 confirmAssign();
134}
135elsif($webvar{action} eq 'insert') {
136 insertAssign();
137}
138elsif($webvar{action} eq 'edit') {
139 edit();
140}
141elsif($webvar{action} eq 'update') {
142 update();
143}
144elsif($webvar{action} eq 'delete') {
145 remove();
146}
147elsif($webvar{action} eq 'finaldelete') {
148 finalDelete();
149}
150
151# Default is an error. It shouldn't be possible to easily get here.
152# The only way I can think of offhand is to just call main.cgi bare-
153# which is not in any way guaranteed to provide anything useful.
154else {
155 printHeader('');
156 my $rnd = rand 500;
157 my $boing = sprintf("%.2f", rand 500);
158 my @excuses = ("Aether cloudy. Ask again later.","The gods are unhappy with your sacrifice.",
159 "Because one of it's legs are both the same", "*wibble*",
160 "Hey! Stop pushing my buttons!", "I ain't done nuttin'", "9",
161 "8", "9", "10", "11", "12", "13", "14", "15", "16", "17");
162 printAndExit("Error $boing: ".$excuses[$rnd/30.0]);
163}
[111]164## Finally! Done with that NASTY "case" emulation!
[4]165
166
167
[106]168# Clean up IPDB globals, DB handle, etc.
[111]169finish($ip_dbh);
[199]170
171print qq(<div align=right style="position: absolute; right: 30px;">).
172 qq(<a href="/ip/cgi-bin/admin.cgi">Admin tools</a></div><br>\n)
[214]173 if $authuser =~ /kdeugau|jodyh|jipp/;
[199]174
[111]175# We print the footer here, so we don't have to do it elsewhere.
176printFooter;
[106]177# Just in case something waaaayyy down isn't in place
178# properly... we exit explicitly.
179exit;
[4]180
181
[111]182
[4]183sub viewBy($$) {
184 my ($category,$query) = @_;
185
186 # Local variables
187 my $sql;
188
189#print "<pre>\n";
190
191#print "start querysub: query '$query'\n";
192# this may happen with more than one subcategory. Unlikely, but possible.
193
194 # Calculate start point for LIMIT clause
195 my $offset = ($webvar{page}-1)*$RESULTS_PER_PAGE;
196
197# Possible cases:
198# 1) Partial IP/subnet. Treated as "first-three-octets-match" in old IPDB,
199# I should be able to handle it similarly here.
200# 2a) CIDR subnet. Treated more or less as such in old IPDB.
201# 2b) CIDR netmask. Not sure how it's treated.
202# 3) Customer ID. Not handled in old IPDB
203# 4) Description.
204# 5) Invalid data which might be interpretable as an IP or something, but
205# which probably shouldn't be for reasons of sanity.
206
207 if ($category eq 'all') {
208
209 print qq(<div class="heading">Showing all netblock and static-IP allocations</div><br>\n);
[173]210
211 # Need to assemble SQL query in this order to avoid breaking things.
212 $sql = "select cidr,custid,type,city,description from searchme";
[4]213 my $count = countRows("select count(*) from ($sql) foo");
214 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
215 queryResults($sql, $webvar{page}, $count);
216
217 } elsif ($category eq 'cust') {
218
219 print qq(<div class="heading">Searching for Customer IDs containing '$query'</div><br>\n);
220
221 # Query for a customer ID. Note that we can't restrict to "numeric-only"
222 # as we have non-numeric custIDs in the legacy data. :/
[173]223 $sql = "select cidr,custid,type,city,description from searchme where custid ilike '%$query%'";
[4]224 my $count = countRows("select count(*) from ($sql) foo");
225 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
226 queryResults($sql, $webvar{page}, $count);
227
228 } elsif ($category eq 'desc') {
229
230 print qq(<div class="heading">Searching for descriptions containing '$query'</div><br>\n);
231 # Query based on description (includes "name" from old DB).
[173]232 $sql = "select cidr,custid,type,city,description from searchme where description ilike '%$query%'";
[4]233 my $count = countRows("select count(*) from ($sql) foo");
234 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
235 queryResults($sql, $webvar{page}, $count);
236
237 } elsif ($category =~ /ipblock/) {
238
239 # Query is for a partial IP, a CIDR block in some form, or a flat IP.
240 print qq(<div class="heading">Searching for IP-based matches on '$query'</div><br>\n);
241
242 $query =~ s/\s+//g;
243 if ($query =~ /\//) {
244 # 209.91.179/26 should show all /26 subnets in 209.91.179
245 my ($net,$maskbits) = split /\//, $query;
246 if ($query =~ /^(\d{1,3}\.){3}\d{1,3}\/\d{2}$/) {
247 # /0->/9 are silly to worry about right now. I don't think
248 # we'll be getting a class A anytime soon. <g>
[173]249 $sql = "select cidr,custid,type,city,description from searchme where cidr='$query'";
[4]250 queryResults($sql, $webvar{page}, 1);
251 } else {
252 print "Finding all blocks with netmask /$maskbits, leading octet(s) $net<br>\n";
253 # Partial match; beginning of subnet and maskbits are provided
[173]254 $sql = "select cidr,custid,type,city,description from searchme where ".
255 "text(cidr) like '$net%' and text(cidr) like '%$maskbits'";
[4]256 my $count = countRows("select count(*) from ($sql) foo");
257 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
258 queryResults($sql, $webvar{page}, $count);
259 }
260 } elsif ($query =~ /^(\d{1,3}\.){3}\d{1,3}$/) {
261 # Specific IP address match
262 my $sfor = new NetAddr::IP $query;
[173]263# We do this convoluted roundabout way of finding things in order
264# to bring up matches for single IPs that are within a static block;
265# we want to show both the "container" block and the static IP itself.
266 $sth = $ip_dbh->prepare("select cidr from searchme where cidr >>= '$sfor'");
[4]267 $sth->execute;
268 while (my @data = $sth->fetchrow_array()) {
269 my $cidr = new NetAddr::IP $data[0];
[173]270 queryResults("select cidr,custid,type,city,description from searchme where ".
271 "cidr='$cidr'", $webvar{page}, 1);
[4]272 }
273 } elsif ($query =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.?$/) {
274 print "Finding matches where the first three octets are $query<br>\n";
[173]275 $sql = "select cidr,custid,type,city,description from searchme where ".
276 "text(cidr) like '$query%'";
[4]277 my $count = countRows("select count(*) from ($sql) foo");
278 $sql .= " order by cidr limit $RESULTS_PER_PAGE offset $offset";
279 queryResults($sql, $webvar{page}, $count);
280 } else {
281 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
[111]282 printError("Invalid query.");
[4]283 }
284 } else {
285 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
[111]286 printError("Invalid searchfor.");
[4]287 }
288} # viewBy
289
[9]290
[4]291# args are: a reference to an array with the row to be printed and the
292# class(stylesheet) to use for formatting.
293# if ommitting the class - call the sub as &printRow(\@array)
294sub printRow {
295 my ($rowRef,$class) = @_;
296
297 if (!$class) {
298 print "<tr>\n";
299 } else {
300 print "<tr class=\"$class\">\n";
301 }
302
[135]303ELEMENT: foreach my $element (@$rowRef) {
304 if (!defined($element)) {
305 print "<td></td>\n";
306 next ELEMENT;
307 }
[4]308 $element =~ s|\n|</br>|g;
309 print "<td>$element</td>\n";
310 }
311 print "</tr>";
312} # printRow
313
314
315# Display certain types of search query. Note that this can't be
316# cleanly reused much of anywhere else as the data isn't neatly tabulated.
317# This is tied to the search sub tightly enough I may just gut it and provide
318# more appropriate tables directly as needed.
319sub queryResults($$$) {
320 my ($sql, $pageNo, $rowCount) = @_;
321 my $offset = 0;
322 $offset = $1 if($sql =~ m/.*limit\s+(.*),.*/);
323
324 my $sth = $ip_dbh->prepare($sql);
325 $sth->execute();
326
327 startTable('Allocation','CustID','Type','City','Description/Name');
328 my $count = 0;
329
330 while (my @data = $sth->fetchrow_array) {
[187]331 # cidr,custid,type,city,description
332 # Prefix subblocks with "Sub "
333 my @row = ( (($data[2] =~ /^.r$/) ? 'Sub ' : '').
[186]334 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
[106]335 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
[4]336 # Allow listing of pool if desired/required.
[157]337 if ($data[2] =~ /^.[pd]$/) {
[4]338 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
339 "&pool=$data[0]\">List IPs</a>";
340 }
341 printRow(\@row, 'color1', 1) if ($count%2==0);
342 printRow(\@row, 'color2', 1) if ($count%2!=0);
343 $count++;
344 }
345
346 # Have to think on this call, it's primarily to clean up unfetched rows from a select.
347 # In this context it's probably a good idea.
348 $sth->finish();
349
350 my $upper = $offset+$count;
351 print "<tr><td colspan=10 bgcolor=white class=regular>Records found: $rowCount<br><i>Displaying: $offset - $upper</i></td></tr>\n";
352 print "</table></center>\n";
353
354 # print the page thing..
355 if ($rowCount > $RESULTS_PER_PAGE) {
356 my $pages = ceil($rowCount/$RESULTS_PER_PAGE);
357 print qq(<div class="center"> Page: );
358 for (my $i = 1; $i <= $pages; $i++) {
359 if ($i == $pageNo) {
360 print "<b>$i&nbsp;</b>\n";
361 } else {
[61]362 print qq(<a href="/ip/cgi-bin/main.cgi?page=$i&input=$webvar{input}&action=search&searchfor=$webvar{searchfor}">$i</a>&nbsp;\n);
[4]363 }
364 }
365 print "</div>";
366 }
367} # queryResults
368
369
370# Prints table headings. Accepts any number of arguments;
371# each argument is a table heading.
372sub startTable {
373 print qq(<center><table width="98%" cellspacing="0" class="center"><tr>);
374
375 foreach(@_) {
376 print qq(<td class="heading">$_</td>);
377 }
378 print "</tr>\n";
379} # startTable
380
381
382# Return first element of passed SQL query
383sub countRows($) {
384 my $sth = $ip_dbh->prepare($_[0]);
385 $sth->execute();
386 my @a = $sth->fetchrow_array();
387 $sth->finish();
388 return $a[0];
389}
390
391
392# Initial display: Show master blocks with total allocated subnets, total free subnets
[118]393sub showSummary {
394 # this is horrible-ugly-bad and will Go Away real soon now(TM)
[4]395 print "Content-type: text/html\n\n";
396
397 startTable('Master netblock', 'Routed netblocks', 'Allocated netblocks',
398 'Free netblocks', 'Largest free block');
399
[106]400 my %allocated;
401 my %free;
402 my %routed;
403 my %bigfree;
404
[118]405 # Count the allocations.
406 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
407 foreach my $master (@masterblocks) {
408 $sth->execute("$master");
409 $sth->bind_columns(\$allocated{"$master"});
410 $sth->fetch();
[4]411 }
412
[118]413 # Count routed blocks
414 $sth = $ip_dbh->prepare("select count(*) from routed where cidr <<= ?");
415 foreach my $master (@masterblocks) {
416 $sth->execute("$master");
417 $sth->bind_columns(\$routed{"$master"});
418 $sth->fetch();
[4]419 }
420
[118]421 # Count the free blocks.
[231]422 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
423 "(routed='y' or routed='n')");
[118]424 foreach my $master (@masterblocks) {
425 $sth->execute("$master");
426 $sth->bind_columns(\$free{"$master"});
427 $sth->fetch();
[4]428 }
429
[118]430 # Find the largest free block in each master
[231]431 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
432 "(routed='y' or routed='n') order by maskbits limit 1");
[118]433 foreach my $master (@masterblocks) {
434 $sth->execute("$master");
435 $sth->bind_columns(\$bigfree{"$master"});
436 $sth->fetch();
437 }
438
439 # Print the data.
[4]440 my $count=0;
441 foreach my $master (@masterblocks) {
442 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showmaster&block=$master\">$master</a>",
443 $routed{"$master"}, $allocated{"$master"}, $free{"$master"},
[161]444 ( ($bigfree{"$master"} eq '') ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
[4]445 );
446
447 printRow(\@row, 'color1' ) if($count%2==0);
448 printRow(\@row, 'color2' ) if($count%2!=0);
449 $count++;
450 }
451 print "</table>\n";
452 print qq(<a href="/ip/addmaster.shtml">Add new master block</a><br><br>\n);
453 print "Note: Free blocks noted here include both routed and unrouted blocks.\n";
454
455} # showSummary
456
457
458# Display detail on master
459# Alrighty then! We're showing routed blocks within a single master this time.
460# We should be able to steal code from showSummary(), and if I'm really smart
461# I'll figger a way to munge the two together. (Once I've done that, everything
462# else should follow. YMMV.)
463sub showMaster {
464 printHeader('');
465
466 print qq(<center><div class="heading">Summarizing routed blocks for ).
467 qq($webvar{block}:</div></center><br>\n);
468
[106]469 my %allocated;
470 my %free;
471 my %routed;
472 my %bigfree;
473
[4]474 my $master = new NetAddr::IP $webvar{block};
475 my @localmasters;
476
[118]477 # Fetch only the blocks relevant to this master
[157]478 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr <<= '$master' order by cidr");
[4]479 $sth->execute();
480
481 my $i=0;
482 while (my @data = $sth->fetchrow_array()) {
483 my $cidr = new NetAddr::IP $data[0];
[118]484 $localmasters[$i++] = $cidr;
485 $free{"$cidr"} = 0;
486 $allocated{"$cidr"} = 0;
487 $bigfree{"$cidr"} = 128;
[4]488 # Retain the routing destination
[157]489 $routed{"$cidr"} = $data[1];
[4]490 }
491
[118]492 # Check if there were actually any blocks routed from this master
[4]493 if ($i > 0) {
494 startTable('Routed block','Routed to','Allocated blocks',
495 'Free blocks','Largest free block');
496
[118]497 # Count the allocations
498 $sth = $ip_dbh->prepare("select count(*) from allocations where cidr <<= ?");
499 foreach my $master (@localmasters) {
500 $sth->execute("$master");
501 $sth->bind_columns(\$allocated{"$master"});
502 $sth->fetch();
[4]503 }
504
[118]505 # Count the free blocks.
[231]506 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
507 "(routed='y' or routed='n')");
[118]508 foreach my $master (@localmasters) {
509 $sth->execute("$master");
510 $sth->bind_columns(\$free{"$master"});
511 $sth->fetch();
[4]512 }
513
[118]514 # Get the size of the largest free block
[231]515 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
516 "(routed='y' or routed='n') order by maskbits limit 1");
[118]517 foreach my $master (@localmasters) {
518 $sth->execute("$master");
519 $sth->bind_columns(\$bigfree{"$master"});
520 $sth->fetch();
[4]521 }
522
523 # Print the data.
524 my $count=0;
525 foreach my $master (@localmasters) {
526 my @row = ("<a href=\"/ip/cgi-bin/main.cgi?action=showrouted&block=$master\">$master</a>",
527 $routed{"$master"}, $allocated{"$master"},
528 $free{"$master"},
529 ( ($bigfree{"$master"} eq 128) ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
530 );
531 printRow(\@row, 'color1' ) if($count%2==0);
532 printRow(\@row, 'color2' ) if($count%2!=0);
533 $count++;
534 }
535 } else {
536 # If a master block has no routed blocks, then by definition it has no
537 # allocations, and can be deleted.
538 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
539 qq($master.</div>\n).
540 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
541 qq(<input type=hidden name=action value="delete">\n).
542 qq(<input type=hidden name=block value="$master">\n).
543 qq(<input type=hidden name=alloctype value="mm">\n).
544 qq(<input type=submit value=" Remove this master ">\n).
545 qq(</form></center>\n);
546
547 } # end check for existence of routed blocks in master
548
549 print qq(</table>\n<hr width="60%">\n).
550 qq(<center><div class="heading">Unrouted blocks in $master:</div></center><br>\n);
551
552 startTable('Netblock','Range');
553
554 # Snag the free blocks.
555 my $count = 0;
[118]556 $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr <<='$master' and ".
557 "routed='n' order by cidr");
[4]558 $sth->execute();
559 while (my @data = $sth->fetchrow_array()) {
560 my $cidr = new NetAddr::IP $data[0];
[118]561 my @row = ("$cidr", $cidr->range);
562 printRow(\@row, 'color1' ) if($count%2==0);
563 printRow(\@row, 'color2' ) if($count%2!=0);
564 $count++;
[4]565 }
566
567 print "</table>\n";
568} # showMaster
569
570
571# Display details of a routed block
572# Alrighty then! We're showing allocations within a routed block this time.
573# We should be able to steal code from showSummary() and showMaster(), and if
574# I'm really smart I'll figger a way to munge all three together. (Once I've
575# done that, everything else should follow. YMMV.
576# This time, we check the database before spewing, because we may
577# not have anything useful to spew.
578sub showRBlock {
579 printHeader('');
580
581 my $master = new NetAddr::IP $webvar{block};
582
[157]583 $sth = $ip_dbh->prepare("select city from routed where cidr='$master'");
[4]584 $sth->execute;
585 my @data = $sth->fetchrow_array;
586
587 print qq(<center><div class="heading">Summarizing allocated blocks for ).
[157]588 qq($master ($data[0]):</div></center><br>\n);
[4]589
[118]590 startTable('CIDR allocation','Customer Location','Type','CustID','Description/Name');
591
592 # Snag the allocations for this block
[157]593 $sth = $ip_dbh->prepare("select cidr,city,type,custid,description".
594 " from allocations where cidr <<= '$master' order by cidr");
[4]595 $sth->execute();
596
597 my $count=0;
598 while (my @data = $sth->fetchrow_array()) {
[157]599 # cidr,city,type,custid,description, as per the SELECT
[4]600 my $cidr = new NetAddr::IP $data[0];
601
602 # Clean up extra spaces that are borking things.
[157]603# $data[2] =~ s/\s+//g;
[4]604
[187]605 # Prefix subblocks with "Sub "
606 my @row = ( (($data[2] =~ /^.r$/) ? 'Sub ' : '').
[186]607 qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
[157]608 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
[4]609 # If the allocation is a pool, allow listing of the IPs in the pool.
[157]610 if ($data[2] =~ /^.[pd]$/) {
[4]611 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
612 "&pool=$data[0]\">List IPs</a>";
613 }
614
615 printRow(\@row, 'color1') if ($count%2 == 0);
616 printRow(\@row, 'color2') if ($count%2 != 0);
617 $count++;
618 }
619
620 print "</table>\n";
621
622 # If the routed block has no allocations, by definition it only has
623 # one free block, and therefore may be deleted.
624 if ($count == 0) {
625 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
626 qq($master.</div></center>\n).
627 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
628 qq(<input type=hidden name=action value="delete">\n).
629 qq(<input type=hidden name=block value="$master">\n).
[187]630 qq(<input type=hidden name=alloctype value="rm">\n).
[4]631 qq(<input type=submit value=" Remove this block ">\n).
632 qq(</form>\n);
633 }
634
635 print qq(<hr width="60%">\n<center><div class="heading">Free blocks within routed ).
636 qq(submaster $master</div></center>\n);
637
638 startTable('CIDR block','Range');
639
640 # Snag the free blocks. We don't really *need* to be pedantic about avoiding
641 # unrouted free blocks, but it's better to let the database do the work if we can.
642 $count = 0;
[186]643 $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
644 " order by cidr");
[4]645 $sth->execute();
646 while (my @data = $sth->fetchrow_array()) {
[186]647 # cidr,routed
[4]648 my $cidr = new NetAddr::IP $data[0];
[187]649 # Include some HairyPerl(TM) to prefix subblocks with "Sub "
650 my @row = ((($data[1] ne 'y' && $data[1] ne 'n') ? 'Sub ' : '').
651 qq(<a href="/ip/cgi-bin/main.cgi?action=assign&block=$cidr&fbtype=$data[1]">$cidr</a>),
[21]652 $cidr->range);
[118]653 printRow(\@row, 'color1') if ($count%2 == 0);
654 printRow(\@row, 'color2') if ($count%2 != 0);
655 $count++;
[4]656 }
657
658 print "</table>\n";
659} # showRBlock
660
661
662# List the IPs used in a pool
663sub listPool {
664 printHeader('');
665
666 my $cidr = new NetAddr::IP $webvar{pool};
667
[157]668 my ($pooltype,$poolcity);
669
[4]670 # Snag pool info for heading
[157]671 $sth = $ip_dbh->prepare("select type,city from allocations where cidr='$cidr'");
[4]672 $sth->execute;
[157]673 $sth->bind_columns(\$pooltype, \$poolcity);
674 $sth->fetch() || carp $sth->errstr;
[4]675
676 print qq(<center><div class="heading">Listing pool IPs for $cidr<br>\n).
[157]677 qq(($disp_alloctypes{$pooltype} in $poolcity)</div></center><br>\n);
678 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
679 if ($pooltype =~ /^.d$/) {
680 print qq(<div class="indent"><b>Reserved IPs:</b><br>\n);
681 print qq(<div class="indent"><table><tr class=color1><td>Network IP:</td><td>).
[4]682 $cidr->addr."</td></tr>\n";
[157]683 $cidr++;
684 print "<tr class=color2><td>Gateway:</td><td>".$cidr->addr."</td></tr>\n";
685 $cidr--; $cidr--;
686 print "<tr class=color1><td>Broadcast:</td><td>".$cidr->addr."</td></tr>\n".
[4]687 "<tr><td>Netmask:</td><td>".$cidr->mask."</td></tr>\n".
688 "</table></div></div>\n";
[157]689 }
[4]690
691# probably have to add an "edit IP allocation" link here somewhere.
692
693 startTable('IP','Customer ID','Available?','Description','');
[157]694 $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
695 " from poolips where pool='$webvar{pool}' order by ip");
[4]696 $sth->execute;
697 my $count = 0;
698 while (my @data = $sth->fetchrow_array) {
[74]699 # pool,ip,custid,city,ptype,available,notes,description,circuitid
[157]700 # ip,custid,available,description,type
701 # If desc is "null", make it not null. <g>
702 if ($data[3] eq '') {
703 $data[3] = '&nbsp;';
[4]704 }
705 # Some nice hairy Perl to decide whether to allow unassigning each IP
[157]706 # -> if $data[2] (aka poolips.available) == 'n' then we print the unassign link
[4]707 # else we print a blank space
[157]708 my @row = ( qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
709 $data[1],$data[2],$data[3],
710 ( ($data[2] eq 'n') ?
711 ("<a href=\"/ip/cgi-bin/main.cgi?action=delete&block=$data[0]&".
712 "alloctype=$data[4]\">Unassign this IP</a>") :
[4]713 ("&nbsp;") )
714 );
715 printRow(\@row, 'color1') if($count%2==0);
716 printRow(\@row, 'color2') if($count%2!=0);
717 $count++;
718 }
719 print "</table>\n";
720
721} # end listPool
722
723
[106]724# Show "Add new allocation" page. Note that the actual page may
725# be one of two templates, and the lists come from the database.
[4]726sub assignBlock {
727 printHeader('');
728
[21]729 my $html;
730
731 # New special case- block to assign is specified
732 if ($webvar{block} ne '') {
733 open HTML, "../fb-assign.html"
734 or croak "Could not open fb-assign.html: $!";
735 $html = join('',<HTML>);
736 close HTML;
737 my $block = new NetAddr::IP $webvar{block};
738 $html =~ s|\$\$BLOCK\$\$|$block|g;
739 $html =~ s|\$\$MASKBITS\$\$|$block->masklen|;
[106]740 my $typelist = '';
[187]741
742 # This is a little dangerous, as it's *theoretically* possible to
743 # get fbtype='n' (aka a non-routed freeblock). However, should
744 # someone manage to get there, they get what they deserve.
745 if ($webvar{fbtype} ne 'y') {
746 # Snag the type of the block from the database. We have no
747 # convenient way to pass this in from the calling location. :/
748 $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
749 $sth->execute;
750 my @data = $sth->fetchrow_array;
751 $data[0] =~ s/c$/r/; # Munge the type into the correct form
[191]752 $typelist = "$list_alloctypes{$data[0]}<input type=hidden name=alloctype value=$data[0]>\n";
[187]753 } else {
754 $typelist .= qq(<select name="alloctype">\n);
755 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
[191]756 "and type not like '_i' and type not like '_r' order by listorder");
[187]757 $sth->execute;
758 my @data = $sth->fetchrow_array;
759 $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
760 while (my @data = $sth->fetchrow_array) {
761 $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
762 }
763 $typelist .= "</select>\n";
[106]764 }
765 $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
[21]766 } else {
767 open HTML, "../assign.html"
[4]768 or croak "Could not open assign.html: $!";
[21]769 $html = join('',<HTML>);
[92]770 close HTML;
[31]771 my $masterlist = "<select name=allocfrom><option selected>-</option>\n";
772 foreach my $master (@masterblocks) {
773 $masterlist .= "<option>$master</option>\n";
774 }
775 $masterlist .= "</select>\n";
776 $html =~ s|\$\$MASTERLIST\$\$|$masterlist|g;
[92]777 my $pops = '';
778 foreach my $pop (@poplist) {
779 $pops .= "<option>$pop</option>\n";
780 }
781 $html =~ s|\$\$POPLIST\$\$|$pops|g;
[106]782 my $typelist = '';
783 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 900 order by listorder");
784 $sth->execute;
785 my @data = $sth->fetchrow_array;
786 $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
787 while (my @data = $sth->fetchrow_array) {
788 $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
789 }
790 $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
[21]791 }
[92]792 my $cities = '';
793 foreach my $city (@citylist) {
794 $cities .= "<option>$city</option>\n";
795 }
796 $html =~ s|\$\$ALLCITIES\$\$|$cities|g;
[4]797
798 print $html;
799
800} # assignBlock
801
802
803# Take info on requested IP assignment and see what we can provide.
804sub confirmAssign {
805 printHeader('');
806
807 my $cidr;
808 my $alloc_from;
809
810 # Going to manually validate some items.
811 # custid and city are automagic.
[111]812 return if !validateInput();
[4]813
814# Several different cases here.
815# Static IP vs netblock
816# + Different flavours of static IP
817# + Different flavours of netblock
818
[157]819 if ($webvar{alloctype} =~ /^.i$/) {
[4]820 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
[214]821 my ($sql,$city);
822 # Check for pools in Subury, North Bay, or Toronto if DSL or server pool.
823 # Anywhere else is invalid and shouldn't be in the db in the first place.
[4]824 # ... aside from #^%#$%#@#^%^^!!!! legacy data. GRRR.
825 # Note that we want to retain the requested city to relate to customer info.
826 if ($base =~ /^[ds]$/) {
[214]827 $city = "(allocations.city='Sudbury' or allocations.city='North Bay' or ".
828 "allocations.city='Toronto')";
[4]829 } else {
[214]830 $city = "allocations.city='$webvar{pop}'";
[4]831 }
832
[214]833# Ewww. But it works.
834 $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
835 "poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
836 "poolips.pool=allocations.cidr AND $city AND poolips.type LIKE '".$base."_' ".
837 "GROUP BY pool");
[4]838 $sth->execute;
839 my $optionlist;
840 while (my @data = $sth->fetchrow_array) {
[214]841 # city,pool cidr,free IP count
842 if ($data[2] > 0) {
843 $optionlist .= "<option value='$data[1]'>$data[1] [$data[2] free IP(s)] in $data[0]</option>\n";
844 }
[4]845 }
846 $cidr = "Single static IP";
847 $alloc_from = "<select name=alloc_from>".$optionlist."</select>\n";
848
849 } else { # end show pool options
[21]850
851 if ($webvar{fbassign} eq 'y') {
852 $cidr = new NetAddr::IP $webvar{block};
853 $webvar{maskbits} = $cidr->masklen;
854 } else { # done with direct freeblocks assignment
855
856 if (!$webvar{maskbits}) {
[111]857 printError("Please specify a CIDR mask length.");
858 return;
[21]859 }
860 my $sql;
861 my $city;
862 my $failmsg;
[187]863 if ($webvar{alloctype} eq 'rm') {
[31]864 if ($webvar{allocfrom} ne '-') {
865 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
866 " and cidr <<= '$webvar{allocfrom}' order by maskbits desc";
867 } else {
868 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
869 " order by maskbits desc";
870 }
[21]871 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
872 " routeable block of that size.<br>\nYou will have to either route".
873 " a set of smaller netblocks or a single smaller netblock.";
[4]874 } else {
[118]875##fixme
876# This section needs serious Pondering.
[214]877 # Pools of most types get assigned to the POP they're "routed from"
[187]878 # This includes WAN blocks and other netblock "containers"
[214]879 # This does NOT include cable pools.
880 if ($webvar{alloctype} =~ /^.[pc]$/) {
881 if (($webvar{city} !~ /^(Sudbury|North Bay|Toronto)$/) && ($webvar{alloctype} eq 'dp')) {
882 printError("You must chose Sudbury, North Bay, or Toronto for DSL pools.");
[111]883 return;
884 }
[37]885 $city = $webvar{city};
[21]886 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[118]887 " superblock from one of the<br>\nmaster blocks in Sudbury or chose a smaller".
[21]888 " block size for the pool.";
889 } else {
890 $city = $webvar{pop};
891 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[106]892 " superblock to $webvar{pop}<br>\nfrom one of the master blocks in Sudbury or".
[21]893 " chose a smaller blocksize.";
894 }
[31]895 if ($webvar{allocfrom} ne '-') {
[157]896 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[186]897 " and cidr <<= '$webvar{allocfrom}' and routed='".
[189]898 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."' order by maskbits desc,cidr";
[31]899 } else {
[157]900 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[189]901 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y').
902 "' order by maskbits desc,cidr";
[31]903 }
[4]904 }
[21]905 $sth = $ip_dbh->prepare($sql);
906 $sth->execute;
907 my @data = $sth->fetchrow_array();
908 if ($data[0] eq "") {
[111]909 printError($failmsg);
910 return;
[21]911 }
912 $cidr = new NetAddr::IP $data[0];
913 } # check for freeblocks assignment or IPDB-controlled assignment
[4]914
915 $alloc_from = qq($cidr<input type=hidden name=alloc_from value="$cidr">);
916
917 # If the block to be allocated is smaller than the one we found,
918 # figure out the "real" block to be allocated.
919 if ($cidr->masklen() ne $webvar{maskbits}) {
920 my $maskbits = $cidr->masklen();
921 my @subblocks;
922 while ($maskbits++ < $webvar{maskbits}) {
923 @subblocks = $cidr->split($maskbits);
924 }
925 $cidr = $subblocks[0];
926 }
[157]927 } # if ($webvar{alloctype} =~ /^.i$/)
[4]928
929 open HTML, "../confirm.html"
930 or croak "Could not open confirm.html: $!";
931 my $html = join '', <HTML>;
932 close HTML;
933
934### gotta fix this in final
935 # Stick in customer info as necessary - if it's blank, it just ends
936 # up as blank lines ignored in the rendering of the page
937 my $custbits;
938 $html =~ s|\$\$CUSTBITS\$\$|$custbits|g;
939###
940
941 # Stick in the allocation data
942 $html =~ s|\$\$ALLOC_TYPE\$\$|$webvar{alloctype}|g;
[106]943 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$webvar{alloctype}}|g;
[4]944 $html =~ s|\$\$ALLOC_FROM\$\$|$alloc_from|g;
945 $html =~ s|\$\$CIDR\$\$|$cidr|g;
[87]946 $webvar{city} = desanitize($webvar{city});
[4]947 $html =~ s|\$\$CITY\$\$|$webvar{city}|g;
948 $html =~ s|\$\$CUSTID\$\$|$webvar{custid}|g;
[87]949 $webvar{circid} = desanitize($webvar{circid});
[74]950 $html =~ s|\$\$CIRCID\$\$|$webvar{circid}|g;
[4]951 $webvar{desc} = desanitize($webvar{desc});
[92]952 $html =~ s|\$\$DESC\$\$|$webvar{desc}|g;
[4]953 $webvar{notes} = desanitize($webvar{notes});
954 $html =~ s|\$\$NOTES\$\$|$webvar{notes}|g;
955 $html =~ s|\$\$ACTION\$\$|insert|g;
956
957 print $html;
958
959} # end confirmAssign
960
961
962# Do the work of actually inserting a block in the database.
963sub insertAssign {
964 # Some things are done more than once.
965 printHeader('');
[111]966 return if !validateInput();
[4]967
[106]968 # $code is "success" vs "failure", $msg contains OK for a
969 # successful netblock allocation, the IP allocated for static
970 # IP, or the error message if an error occurred.
971 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
972 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
973 $webvar{circid});
[4]974
[111]975 if ($code eq 'OK') {
[106]976 if ($webvar{alloctype} =~ /^.i$/) {
977 print qq(<div class="center"><div class="heading">The IP $msg has been allocated to customer $webvar{custid}</div></div>);
978 # Notify tech@example.com
[214]979 mailNotify('tech@example.com',"ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
[111]980 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
981 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[106]982 } else {
983 print qq(<div class="center"><div class="heading">The block $webvar{fullcidr} was ).
[189]984 "sucessfully added as: $disp_alloctypes{$webvar{alloctype}}</div></div>";
[4]985 }
[106]986 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
987 "'$webvar{alloctype}'";
[111]988 } else {
989 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
990 "'$webvar{alloctype}' by $authuser failed: '$msg'";
[189]991 printError("Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
[157]992 " failed:<br>\n$msg\n");
[106]993 }
[4]994
995} # end insertAssign()
996
997
998# Does some basic checks on common input data to make sure nothing
999# *really* weird gets in to the database through this script.
1000# Does NOT do complete input validation!!!
1001sub validateInput {
1002 if ($webvar{city} eq '-') {
[111]1003 printError("Please choose a city.");
1004 return;
[4]1005 }
[138]1006
1007 # Alloctype check.
[4]1008 chomp $webvar{alloctype};
[138]1009 if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
1010 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
1011 # managing to call things in such a way as to cause this deserves a cryptic error.
1012 printError("Invalid alloctype");
1013 return;
1014 }
1015
1016 # CustID check
[4]1017 # We have different handling for customer allocations and "internal" or "our" allocations
[214]1018 if ($def_custids{$webvar{alloctype}} eq '') {
[4]1019 if (!$webvar{custid}) {
[111]1020 printError("Please enter a customer ID.");
1021 return;
[4]1022 }
[87]1023 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF|TEMP)(?:-\d\d?)?$/) {
[111]1024 printError("Please enter a valid customer ID- this must be a 7- or 10-digit number, or STAFF for static IPs for staff.");
1025 return;
[4]1026 }
1027 print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
[138]1028 } else {
[167]1029 # New! Improved! And now Loaded From The Database!!
1030 $webvar{custid} = $def_custids{$webvar{alloctype}};
[4]1031 }
[111]1032
1033 # Check POP location
1034 my $flag;
[187]1035 if ($webvar{alloctype} eq 'rm') {
[111]1036 $flag = 'for a routed netblock';
1037 foreach (@poplist) {
1038 if (/^$webvar{city}$/) {
1039 $flag = 'n';
1040 last;
1041 }
1042 }
1043 } else {
1044 $flag = 'n';
1045 if ($webvar{pop} =~ /^-$/) {
1046 $flag = 'to route the block from/through';
1047 }
1048 }
1049 if ($flag ne 'n') {
1050 printError("Please choose a valid POP location $flag. Valid ".
1051 "POP locations are currently:<br>\n".join (" - ", @poplist));
1052 return;
1053 }
1054
1055 return 'OK';
[4]1056} # end validateInput
1057
1058
1059# Displays details of a specific allocation in a form
1060# Allows update/delete
1061# action=edit
1062sub edit {
1063 printHeader('');
1064
1065 my $sql;
1066
1067 # Two cases: block is a netblock, or block is a static IP from a pool
1068 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
1069 if ($webvar{block} =~ /\/32$/) {
[166]1070 $sql = "select ip,custid,type,city,circuitid,description,notes from poolips where ip='$webvar{block}'";
[4]1071 } else {
[74]1072 $sql = "select cidr,custid,type,city,circuitid,description,notes from allocations where cidr='$webvar{block}'"
[4]1073 }
1074
1075 # gotta snag block info from db
1076 $sth = $ip_dbh->prepare($sql);
1077 $sth->execute;
1078 my @data = $sth->fetchrow_array;
1079
1080 # Clean up extra whitespace on alloc type
1081 $data[2] =~ s/\s//;
1082
[157]1083##fixme LEGACY CODE
[4]1084 # Postfix "i" on pool IP types
[72]1085 if ($data[2] =~ /^[cdsmw]$/) {
[4]1086 $data[2] .= "i";
1087 }
1088
1089 open (HTML, "../editDisplay.html")
1090 or croak "Could not open editDisplay.html :$!";
1091 my $html = join('', <HTML>);
1092
1093 # We can't let the city be changed here; this block is a part of
1094 # a larger routed allocation and therefore by definition can't be moved.
1095 # block and city are static.
1096##fixme
1097# Needs thinking. Have to allow changes to city to correct errors, no?
1098 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1099 $html =~ s/\$\$CITY\$\$/$data[3]/g;
1100
1101# Screw it. Changing allocation types gets very ugly VERY quickly- especially
1102# with the much longer list of allocation types.
1103# We'll just show what type of block it is.
1104
[33]1105# this has now been Requested, so here goes.
[4]1106
[187]1107##fixme The check here should be built from the database
1108 if ($data[2] =~ /^.[ne]$/) {
[33]1109 # Block that can be changed
1110 my $blockoptions = "<select name=alloctype><option".
[187]1111 (($data[2] eq 'me') ? ' selected' : '') ." value='me'>Dialup netblock</option>\n<option".
[228]1112 (($data[2] eq 'de') ? ' selected' : '') ." value='de'>Dynamic DSL netblock</option>\n<option".
1113 (($data[2] eq 'ce') ? ' selected' : '') ." value='ce'>Dynamic cable netblock</option>\n<option".
1114 (($data[2] eq 'we') ? ' selected' : '') ." value='we'>Dynamic wireless netblock</option>\n<option".
[33]1115 (($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
[187]1116 (($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<option".
[135]1117 (($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
[33]1118 "</select>\n";
1119 $html =~ s/\$\$TYPESELECT\$\$/$blockoptions/g;
1120 } else {
[106]1121 $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}<input type=hidden name=alloctype value="$data[2]">/g;
[33]1122 }
1123
[4]1124 # These can be modified, although CustID changes may get ignored.
1125 $html =~ s/\$\$CUSTID\$\$/$data[1]/g;
[74]1126 $html =~ s/\$\$TYPE\$\$/$data[2]/g;
1127 $html =~ s/\$\$CIRCID\$\$/$data[4]/g;
1128 $html =~ s/\$\$DESC\$\$/$data[5]/g;
1129 $html =~ s/\$\$NOTES\$\$/$data[6]/g;
[4]1130
1131 print $html;
1132
1133} # edit()
1134
1135
1136# Stuff new info about a block into the db
1137# action=update
1138sub update {
1139 printHeader('');
1140
1141 # Make sure incoming data is in correct format - custID among other things.
[228]1142 return if !validateInput;
[4]1143
1144 # SQL transaction wrapper
1145 eval {
1146 # Relatively simple SQL transaction here.
1147 my $sql;
[157]1148 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
[74]1149 $sql = "update poolips set custid='$webvar{custid}',notes='$webvar{notes}',".
[228]1150 "circuitid='$webvar{circid}',description='$webvar{desc}',city='$webvar{city}' ".
[4]1151 "where ip='$webvar{block}'";
1152 } else {
1153 $sql = "update allocations set custid='$webvar{custid}',".
[33]1154 "description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',".
[74]1155 "type='$webvar{alloctype}',circuitid='$webvar{circid}' where cidr='$webvar{block}'";
[4]1156 }
[157]1157 # Log the details of the change.
1158 syslog "debug", $sql;
[4]1159 $sth = $ip_dbh->prepare($sql);
1160 $sth->execute;
1161 $ip_dbh->commit;
1162 };
1163 if ($@) {
[166]1164 my $msg = $@;
1165 carp "Transaction aborted because $msg";
[4]1166 eval { $ip_dbh->rollback; };
[166]1167 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
1168 printError("Could not update block/IP $webvar{block}: $msg");
[111]1169 return;
[4]1170 }
1171
1172 # If we get here, the operation succeeded.
1173 syslog "notice", "$authuser updated $webvar{block}";
1174 open (HTML, "../updated.html")
[111]1175 or croak "Could not open updated.html :$!";
[4]1176 my $html = join('', <HTML>);
1177
1178 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
[92]1179 $webvar{city} = desanitize($webvar{city});
[4]1180 $html =~ s/\$\$CITY\$\$/$webvar{city}/g;
1181 $html =~ s/\$\$ALLOCTYPE\$\$/$webvar{alloctype}/g;
[106]1182 $html =~ s/\$\$TYPEFULL\$\$/$disp_alloctypes{$webvar{alloctype}}/g;
[4]1183 $html =~ s/\$\$CUSTID\$\$/$webvar{custid}/g;
[92]1184 $webvar{circid} = desanitize($webvar{circid});
[74]1185 $html =~ s/\$\$CIRCID\$\$/$webvar{circid}/g;
[92]1186 $webvar{desc} = desanitize($webvar{desc});
[4]1187 $html =~ s/\$\$DESC\$\$/$webvar{desc}/g;
[92]1188 $webvar{notes} = desanitize($webvar{notes});
[4]1189 $html =~ s/\$\$NOTES\$\$/$webvar{notes}/g;
1190
1191 print $html;
1192
1193} # update()
1194
1195
1196# Delete an allocation.
[106]1197sub remove {
[4]1198 printHeader('');
1199 #show confirm screen.
1200 open HTML, "../confirmRemove.html"
1201 or croak "Could not open confirmRemove.html :$!";
1202 my $html = join('', <HTML>);
1203 close HTML;
1204
1205 # Serves'em right for getting here...
1206 if (!defined($webvar{block})) {
[111]1207 printError("Error 332");
1208 return;
[4]1209 }
1210
[74]1211 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype);
[4]1212
[187]1213 if ($webvar{alloctype} eq 'rm') {
[4]1214 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
1215 $sth->execute();
1216
1217# This feels... extreme.
1218 croak $sth->errstr() if($sth->errstr());
1219
1220 $sth->bind_columns(\$cidr,\$city);
1221 $sth->execute();
1222 $sth->fetch || croak $sth->errstr();
1223 $custid = "N/A";
1224 $alloctype = $webvar{alloctype};
[74]1225 $circid = "N/A";
[4]1226 $desc = "N/A";
1227 $notes = "N/A";
1228
1229 } elsif ($webvar{alloctype} eq 'mm') {
1230 $cidr = $webvar{block};
1231 $city = "N/A";
1232 $custid = "N/A";
1233 $alloctype = $webvar{alloctype};
[74]1234 $circid = "N/A";
[4]1235 $desc = "N/A";
1236 $notes = "N/A";
[189]1237 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
[4]1238
1239 # Unassigning a static IP
[166]1240 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid from poolips".
[4]1241 " where ip='$webvar{block}'");
1242 $sth->execute();
1243# croak $sth->errstr() if($sth->errstr());
1244
[74]1245 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid);
[4]1246 $sth->fetch() || croak $sth->errstr;
1247
[157]1248 } else { # done with alloctype=~ /^.i$/
[4]1249
[74]1250 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes from ".
[4]1251 "allocations where cidr='$webvar{block}'");
1252 $sth->execute();
1253# croak $sth->errstr() if($sth->errstr());
1254
[74]1255 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc, \$notes);
1256 $sth->fetch() || carp $sth->errstr;
[4]1257 } # end cases for different alloctypes
1258
1259 # Munge everything into HTML
1260 $html =~ s|Please confirm|Please confirm <b>removal</b> of|;
1261 $html =~ s|\$\$BLOCK\$\$|$cidr|g;
[106]1262 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$alloctype}|g;
[4]1263 $html =~ s|\$\$ALLOCTYPE\$\$|$alloctype|g;
1264 $html =~ s|\$\$CITY\$\$|$city|g;
1265 $html =~ s|\$\$CUSTID\$\$|$custid|g;
[74]1266 $html =~ s|\$\$CIRCID\$\$|$circid|g;
[4]1267 $html =~ s|\$\$DESC\$\$|$desc|g;
1268 $html =~ s|\$\$NOTES\$\$|$notes|g;
1269
1270 $html =~ s|\$\$ACTION\$\$|finaldelete|g;
1271
1272 # Set the warning text.
[157]1273 if ($alloctype =~ /^.[pd]$/) {
[4]1274 $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.<br>Any IPs allocated from this pool will also be removed!</div></td></tr>|;
1275 } else {
1276 $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.</div></td></tr>|;
1277 }
1278
1279 print $html;
1280} # end edit()
1281
1282
1283# Delete an allocation. Return it to the freeblocks table; munge
1284# data as necessary to keep as few records as possible in freeblocks
1285# to prevent weirdness when allocating blocks later.
1286# Remove IPs from pool listing if necessary
1287sub finalDelete {
1288 printHeader('');
1289
[106]1290 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
[4]1291
[106]1292 if ($code eq 'OK') {
[4]1293 print "<div class=heading align=center>Success! $webvar{block} deallocated.</div>\n";
[106]1294 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}";
[214]1295 # Notify tech@ when a block/IP is deallocated
1296 mailNotify('tech@example.com',"REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1297 "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n");
[106]1298 } else {
1299 if ($webvar{alloctype} =~ /^.i$/) {
1300 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
[111]1301 printError("Could not deallocate static IP $webvar{block}: $msg");
[106]1302 } else {
1303 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
[111]1304 printError("Could not deallocate netblock $webvar{block}: $msg");
[4]1305 }
[106]1306 }
[4]1307
1308} # finalDelete
1309
1310
1311# Just in case we manage to get here.
1312exit 0;
Note: See TracBrowser for help on using the repository browser.