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

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

/trunk

Merge /branches/acl r221, 222, 223, 225, 226 back to trunk

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