source: branches/stable/cgi-bin/main.cgi@ 181

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

/branches/stable

Backported SQL cleanup from /trunk r173

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