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

Last change on this file since 244 was 244, checked in by Kris Deugau, 19 years ago

/branches/stable

Semi-temporary change to allow SWIPing of existing netblocks.
SWIP process to be replaced with RWHOIS as soon as that can
be considered to be operating "correctly".

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