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

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

/branches/stable

Merge ACL support from /branches/acl up to r241

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 47.6 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-19 19:42:43 +0000 (Tue, 19 Apr 2005) $
7# SVN revision $Rev: 242 $
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','Description/Name');
609
610 # Snag the allocations for this block
611 $sth = $ip_dbh->prepare("select cidr,city,type,custid,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,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], $data[4]);
627 # If the allocation is a pool, allow listing of the IPs in the pool.
628 if ($data[2] =~ /^.[pd]$/) {
629 $row[0] .= ' &nbsp; <a href="/ip/cgi-bin/main.cgi?action=listpool'.
630 "&pool=$data[0]\">List IPs</a>";
631 }
632
633 printRow(\@row, 'color1') if ($count%2 == 0);
634 printRow(\@row, 'color2') if ($count%2 != 0);
635 $count++;
636 }
637
638 print "</table>\n";
639
640 # If the routed block has no allocations, by definition it only has
641 # one free block, and therefore may be deleted.
642 if ($count == 0) {
643 print qq(<hr width="60%"><center><div class="heading">No allocations in ).
644 qq($master.</div></center>\n).
645 ($IPDBacl{$authuser} =~ /d/ ?
646 qq(<form action="/ip/cgi-bin/main.cgi" method=POST>\n).
647 qq(<input type=hidden name=action value="delete">\n).
648 qq(<input type=hidden name=block value="$master">\n).
649 qq(<input type=hidden name=alloctype value="rm">\n).
650 qq(<input type=submit value=" Remove this block ">\n).
651 qq(</form>\n) :
652 '');
653 }
654
655 print qq(<hr width="60%">\n<center><div class="heading">Free blocks within routed ).
656 qq(submaster $master</div></center>\n);
657
658 startTable('CIDR block','Range');
659
660 # Snag the free blocks. We don't really *need* to be pedantic about avoiding
661 # unrouted free blocks, but it's better to let the database do the work if we can.
662 $count = 0;
663 $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
664 " order by cidr");
665 $sth->execute();
666 while (my @data = $sth->fetchrow_array()) {
667 # cidr,routed
668 my $cidr = new NetAddr::IP $data[0];
669 # Include some HairyPerl(TM) to prefix subblocks with "Sub "
670 my @row = ((($data[1] ne 'y' && $data[1] ne 'n') ? 'Sub ' : '').
671 ($IPDBacl{$authuser} =~ /a/ ? qq(<a href="/ip/cgi-bin/main.cgi?action=assign&block=$cidr&fbtype=$data[1]">$cidr</a>) : $cidr),
672 $cidr->range);
673 printRow(\@row, 'color1') if ($count%2 == 0);
674 printRow(\@row, 'color2') if ($count%2 != 0);
675 $count++;
676 }
677
678 print "</table>\n";
679} # showRBlock
680
681
682# List the IPs used in a pool
683sub listPool {
684
685 my $cidr = new NetAddr::IP $webvar{pool};
686
687 my ($pooltype,$poolcity);
688
689 # Snag pool info for heading
690 $sth = $ip_dbh->prepare("select type,city from allocations where cidr='$cidr'");
691 $sth->execute;
692 $sth->bind_columns(\$pooltype, \$poolcity);
693 $sth->fetch() || carp $sth->errstr;
694
695 print qq(<center><div class="heading">Listing pool IPs for $cidr<br>\n).
696 qq(($disp_alloctypes{$pooltype} in $poolcity)</div></center><br>\n);
697 # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
698 if ($pooltype =~ /^.d$/) {
699 print qq(<div class="indent"><b>Reserved IPs:</b><br>\n);
700 print qq(<div class="indent"><table><tr class=color1><td>Network IP:</td><td>).
701 $cidr->addr."</td></tr>\n";
702 $cidr++;
703 print "<tr class=color2><td>Gateway:</td><td>".$cidr->addr."</td></tr>\n";
704 $cidr--; $cidr--;
705 print "<tr class=color1><td>Broadcast:</td><td>".$cidr->addr."</td></tr>\n".
706 "<tr><td>Netmask:</td><td>".$cidr->mask."</td></tr>\n".
707 "</table></div></div>\n";
708 }
709
710# probably have to add an "edit IP allocation" link here somewhere.
711
712 startTable('IP','Customer ID','Available?','Description','');
713 $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
714 " from poolips where pool='$webvar{pool}' order by ip");
715 $sth->execute;
716 my $count = 0;
717 while (my @data = $sth->fetchrow_array) {
718 # pool,ip,custid,city,ptype,available,notes,description,circuitid
719 # ip,custid,available,description,type
720 # If desc is "null", make it not null. <g>
721 if ($data[3] eq '') {
722 $data[3] = '&nbsp;';
723 }
724 # Some nice hairy Perl to decide whether to allow unassigning each IP
725 # -> if $data[2] (aka poolips.available) == 'n' then we print the unassign link
726 # else we print a blank space
727 my @row = ( qq(<a href="/ip/cgi-bin/main.cgi?action=edit&block=$data[0]">$data[0]</a>),
728 $data[1],$data[2],$data[3],
729 ( (($data[2] eq 'n') && ($IPDBacl{$authuser} =~ /d/)) ?
730 ("<a href=\"/ip/cgi-bin/main.cgi?action=delete&block=$data[0]&".
731 "alloctype=$data[4]\">Unassign this IP</a>") :
732 ("&nbsp;") )
733 );
734 printRow(\@row, 'color1') if($count%2==0);
735 printRow(\@row, 'color2') if($count%2!=0);
736 $count++;
737 }
738 print "</table>\n";
739
740} # end listPool
741
742
743# Show "Add new allocation" page. Note that the actual page may
744# be one of two templates, and the lists come from the database.
745sub assignBlock {
746
747 if ($IPDBacl{$authuser} !~ /a/) {
748 printError("You shouldn't have been able to get here. Access denied.");
749 return;
750 }
751
752 my $html;
753
754 # New special case- block to assign is specified
755 if ($webvar{block} ne '') {
756 open HTML, "../fb-assign.html"
757 or croak "Could not open fb-assign.html: $!";
758 $html = join('',<HTML>);
759 close HTML;
760 my $block = new NetAddr::IP $webvar{block};
761 $html =~ s|\$\$BLOCK\$\$|$block|g;
762 $html =~ s|\$\$MASKBITS\$\$|$block->masklen|;
763 my $typelist = '';
764
765 # This is a little dangerous, as it's *theoretically* possible to
766 # get fbtype='n' (aka a non-routed freeblock). However, should
767 # someone manage to get there, they get what they deserve.
768 if ($webvar{fbtype} ne 'y') {
769 # Snag the type of the block from the database. We have no
770 # convenient way to pass this in from the calling location. :/
771 $sth = $ip_dbh->prepare("select type from allocations where cidr >>='$block'");
772 $sth->execute;
773 my @data = $sth->fetchrow_array;
774 $data[0] =~ s/c$/r/; # Munge the type into the correct form
775 $typelist = "$list_alloctypes{$data[0]}<input type=hidden name=alloctype value=$data[0]>\n";
776 } else {
777 $typelist .= qq(<select name="alloctype">\n);
778 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 500 ".
779 "and type not like '_i' and type not like '_r' order by listorder");
780 $sth->execute;
781 my @data = $sth->fetchrow_array;
782 $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
783 while (my @data = $sth->fetchrow_array) {
784 $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
785 }
786 $typelist .= "</select>\n";
787 }
788 $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
789 } else {
790 open HTML, "../assign.html"
791 or croak "Could not open assign.html: $!";
792 $html = join('',<HTML>);
793 close HTML;
794 my $masterlist = "<select name=allocfrom><option selected>-</option>\n";
795 foreach my $master (@masterblocks) {
796 $masterlist .= "<option>$master</option>\n";
797 }
798 $masterlist .= "</select>\n";
799 $html =~ s|\$\$MASTERLIST\$\$|$masterlist|g;
800 my $pops = '';
801 foreach my $pop (@poplist) {
802 $pops .= "<option>$pop</option>\n";
803 }
804 $html =~ s|\$\$POPLIST\$\$|$pops|g;
805 my $typelist = '';
806 $sth = $ip_dbh->prepare("select type,listname from alloctypes where listorder < 900 order by listorder");
807 $sth->execute;
808 my @data = $sth->fetchrow_array;
809 $typelist .= "<option value='$data[0]' selected>$data[1]</option>\n";
810 while (my @data = $sth->fetchrow_array) {
811 $typelist .= "<option value='$data[0]'>$data[1]</option>\n";
812 }
813 $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
814 }
815 my $cities = '';
816 foreach my $city (@citylist) {
817 $cities .= "<option>$city</option>\n";
818 }
819 $html =~ s|\$\$ALLCITIES\$\$|$cities|g;
820
821 print $html;
822
823} # assignBlock
824
825
826# Take info on requested IP assignment and see what we can provide.
827sub confirmAssign {
828 if ($IPDBacl{$authuser} !~ /a/) {
829 printError("You shouldn't have been able to get here. Access denied.");
830 return;
831 }
832
833 my $cidr;
834 my $alloc_from;
835
836 # Going to manually validate some items.
837 # custid and city are automagic.
838 return if !validateInput();
839
840# Several different cases here.
841# Static IP vs netblock
842# + Different flavours of static IP
843# + Different flavours of netblock
844
845 if ($webvar{alloctype} =~ /^.i$/) {
846 my ($base,undef) = split //, $webvar{alloctype}; # split into individual chars
847 my ($sql,$city);
848 # Check for pools in Subury, North Bay, or Toronto if DSL or server pool.
849 # Anywhere else is invalid and shouldn't be in the db in the first place.
850 # ... aside from #^%#$%#@#^%^^!!!! legacy data. GRRR.
851 # Note that we want to retain the requested city to relate to customer info.
852 if ($base =~ /^[ds]$/) {
853 $city = "(allocations.city='Sudbury' or allocations.city='North Bay' or ".
854 "allocations.city='Toronto')";
855 } else {
856 $city = "allocations.city='$webvar{pop}'";
857 }
858
859# Ewww. But it works.
860 $sth = $ip_dbh->prepare("SELECT (SELECT city FROM allocations WHERE cidr=poolips.pool), ".
861 "poolips.pool, COUNT(*) FROM poolips,allocations WHERE poolips.available='y' AND ".
862 "poolips.pool=allocations.cidr AND $city AND poolips.type LIKE '".$base."_' ".
863 "GROUP BY pool");
864 $sth->execute;
865 my $optionlist;
866 while (my @data = $sth->fetchrow_array) {
867 # city,pool cidr,free IP count
868 if ($data[2] > 0) {
869 $optionlist .= "<option value='$data[1]'>$data[1] [$data[2] free IP(s)] in $data[0]</option>\n";
870 }
871 }
872 $cidr = "Single static IP";
873 $alloc_from = "<select name=alloc_from>".$optionlist."</select>\n";
874
875 } else { # end show pool options
876
877 if ($webvar{fbassign} eq 'y') {
878 $cidr = new NetAddr::IP $webvar{block};
879 $webvar{maskbits} = $cidr->masklen;
880 } else { # done with direct freeblocks assignment
881
882 if (!$webvar{maskbits}) {
883 printError("Please specify a CIDR mask length.");
884 return;
885 }
886 my $sql;
887 my $city;
888 my $failmsg;
889 if ($webvar{alloctype} eq 'rm') {
890 if ($webvar{allocfrom} ne '-') {
891 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
892 " and cidr <<= '$webvar{allocfrom}' order by maskbits desc";
893 } else {
894 $sql = "select * from freeblocks where maskbits<=$webvar{maskbits} and routed='n'".
895 " order by maskbits desc";
896 }
897 $failmsg = "No suitable free block found.<br>\nWe do not have a free".
898 " routeable block of that size.<br>\nYou will have to either route".
899 " a set of smaller netblocks or a single smaller netblock.";
900 } else {
901##fixme
902# This section needs serious Pondering.
903 # Pools of most types get assigned to the POP they're "routed from"
904 # This includes WAN blocks and other netblock "containers"
905 # This does NOT include cable pools.
906 if ($webvar{alloctype} =~ /^.[pc]$/) {
907 if (($webvar{city} !~ /^(Sudbury|North Bay|Toronto)$/) && ($webvar{alloctype} eq 'dp')) {
908 printError("You must chose Sudbury, North Bay, or Toronto for DSL pools.");
909 return;
910 }
911 $city = $webvar{city};
912 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
913 " superblock from one of the<br>\nmaster blocks in Sudbury or chose a smaller".
914 " block size for the pool.";
915 } else {
916 $city = $webvar{pop};
917 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
918 " superblock to $webvar{pop}<br>\nfrom one of the master blocks in Sudbury or".
919 " chose a smaller blocksize.";
920 }
921 if ($webvar{allocfrom} ne '-') {
922 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
923 " and cidr <<= '$webvar{allocfrom}' and routed='".
924 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."' order by maskbits desc,cidr";
925 } else {
926 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
927 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y').
928 "' order by maskbits desc,cidr";
929 }
930 }
931 $sth = $ip_dbh->prepare($sql);
932 $sth->execute;
933 my @data = $sth->fetchrow_array();
934 if ($data[0] eq "") {
935 printError($failmsg);
936 return;
937 }
938 $cidr = new NetAddr::IP $data[0];
939 } # check for freeblocks assignment or IPDB-controlled assignment
940
941 $alloc_from = qq($cidr<input type=hidden name=alloc_from value="$cidr">);
942
943 # If the block to be allocated is smaller than the one we found,
944 # figure out the "real" block to be allocated.
945 if ($cidr->masklen() ne $webvar{maskbits}) {
946 my $maskbits = $cidr->masklen();
947 my @subblocks;
948 while ($maskbits++ < $webvar{maskbits}) {
949 @subblocks = $cidr->split($maskbits);
950 }
951 $cidr = $subblocks[0];
952 }
953 } # if ($webvar{alloctype} =~ /^.i$/)
954
955 open HTML, "../confirm.html"
956 or croak "Could not open confirm.html: $!";
957 my $html = join '', <HTML>;
958 close HTML;
959
960### gotta fix this in final
961 # Stick in customer info as necessary - if it's blank, it just ends
962 # up as blank lines ignored in the rendering of the page
963 my $custbits;
964 $html =~ s|\$\$CUSTBITS\$\$|$custbits|g;
965###
966
967 # Stick in the allocation data
968 $html =~ s|\$\$ALLOC_TYPE\$\$|$webvar{alloctype}|g;
969 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$webvar{alloctype}}|g;
970 $html =~ s|\$\$ALLOC_FROM\$\$|$alloc_from|g;
971 $html =~ s|\$\$CIDR\$\$|$cidr|g;
972 $webvar{city} = desanitize($webvar{city});
973 $html =~ s|\$\$CITY\$\$|$webvar{city}|g;
974 $html =~ s|\$\$CUSTID\$\$|$webvar{custid}|g;
975 $webvar{circid} = desanitize($webvar{circid});
976 $html =~ s|\$\$CIRCID\$\$|$webvar{circid}|g;
977 $webvar{desc} = desanitize($webvar{desc});
978 $html =~ s|\$\$DESC\$\$|$webvar{desc}|g;
979 $webvar{notes} = desanitize($webvar{notes});
980 $html =~ s|\$\$NOTES\$\$|$webvar{notes}|g;
981 $html =~ s|\$\$ACTION\$\$|insert|g;
982
983 print $html;
984
985} # end confirmAssign
986
987
988# Do the work of actually inserting a block in the database.
989sub insertAssign {
990 if ($IPDBacl{$authuser} !~ /a/) {
991 printError("You shouldn't have been able to get here. Access denied.");
992 return;
993 }
994 # Some things are done more than once.
995 return if !validateInput();
996
997 # $code is "success" vs "failure", $msg contains OK for a
998 # successful netblock allocation, the IP allocated for static
999 # IP, or the error message if an error occurred.
1000 my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
1001 $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
1002 $webvar{circid});
1003
1004 if ($code eq 'OK') {
1005 if ($webvar{alloctype} =~ /^.i$/) {
1006 print qq(<div class="center"><div class="heading">The IP $msg has been allocated to customer $webvar{custid}</div></div>);
1007 # Notify tech@example.com
1008 mailNotify('tech@example.com',"ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
1009 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
1010 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
1011 } else {
1012 print qq(<div class="center"><div class="heading">The block $webvar{fullcidr} was ).
1013 "sucessfully added as: $disp_alloctypes{$webvar{alloctype}}</div></div>";
1014 }
1015 syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
1016 "'$webvar{alloctype}'";
1017 } else {
1018 syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
1019 "'$webvar{alloctype}' by $authuser failed: '$msg'";
1020 printError("Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
1021 " failed:<br>\n$msg\n");
1022 }
1023
1024} # end insertAssign()
1025
1026
1027# Does some basic checks on common input data to make sure nothing
1028# *really* weird gets in to the database through this script.
1029# Does NOT do complete input validation!!!
1030sub validateInput {
1031 if ($webvar{city} eq '-') {
1032 printError("Please choose a city.");
1033 return;
1034 }
1035
1036 # Alloctype check.
1037 chomp $webvar{alloctype};
1038 if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
1039 # Danger! Danger! alloctype should ALWAYS be set by a dropdown. Anyone
1040 # managing to call things in such a way as to cause this deserves a cryptic error.
1041 printError("Invalid alloctype");
1042 return;
1043 }
1044
1045 # CustID check
1046 # We have different handling for customer allocations and "internal" or "our" allocations
1047 if ($def_custids{$webvar{alloctype}} eq '') {
1048 if (!$webvar{custid}) {
1049 printError("Please enter a customer ID.");
1050 return;
1051 }
1052 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
1053 # Force uppercase for now...
1054 $webvar{custid} =~ tr/a-z/A-Z/;
1055 # Crosscheck with ... er... something.
1056 my $status = CustIDCK->custid_exist($webvar{custid});
1057 if ($CustIDCK::Error) {
1058 printError("Error verifying customer ID: ".$CustIDCK::ErrMsg);
1059 return;
1060 }
1061 if (!$status) {
1062 printError("Customer ID not valid. Make sure the Customer ID ".
1063 "is correct.<br>\nUse STAFF for staff static IPs, and 6750400 for any other ".
1064 "non-customer assignments.");
1065 return;
1066 }
1067#"Please enter a valid customer ID- this must be a 7- or 10-digit number, or STAFF for
1068#static IPs for staff.");
1069 }
1070# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
1071 } else {
1072 # New! Improved! And now Loaded From The Database!!
1073 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
1074 $webvar{custid} = $def_custids{$webvar{alloctype}};
1075 }
1076 }
1077
1078 # Check POP location
1079 my $flag;
1080 if ($webvar{alloctype} eq 'rm') {
1081 $flag = 'for a routed netblock';
1082 foreach (@poplist) {
1083 if (/^$webvar{city}$/) {
1084 $flag = 'n';
1085 last;
1086 }
1087 }
1088 } else {
1089 $flag = 'n';
1090 if ($webvar{pop} =~ /^-$/) {
1091 $flag = 'to route the block from/through';
1092 }
1093 }
1094 if ($flag ne 'n') {
1095 printError("Please choose a valid POP location $flag. Valid ".
1096 "POP locations are currently:<br>\n".join (" - ", @poplist));
1097 return;
1098 }
1099
1100 return 'OK';
1101} # end validateInput
1102
1103
1104# Displays details of a specific allocation in a form
1105# Allows update/delete
1106# action=edit
1107sub edit {
1108
1109 my $sql;
1110
1111 # Two cases: block is a netblock, or block is a static IP from a pool
1112 # because I'm lazy, we'll try to make the SELECT's bring out identical)ish) data
1113 if ($webvar{block} =~ /\/32$/) {
1114 $sql = "select ip,custid,type,city,circuitid,description,notes from poolips where ip='$webvar{block}'";
1115 } else {
1116 $sql = "select cidr,custid,type,city,circuitid,description,notes from allocations where cidr='$webvar{block}'"
1117 }
1118
1119 # gotta snag block info from db
1120 $sth = $ip_dbh->prepare($sql);
1121 $sth->execute;
1122 my @data = $sth->fetchrow_array;
1123
1124 # Clean up extra whitespace on alloc type
1125 $data[2] =~ s/\s//;
1126
1127 open (HTML, "../editDisplay.html")
1128 or croak "Could not open editDisplay.html :$!";
1129 my $html = join('', <HTML>);
1130
1131 # We can't let the city be changed here; this block is a part of
1132 # a larger routed allocation and therefore by definition can't be moved.
1133 # block and city are static.
1134##fixme
1135# Needs thinking. Have to allow changes to city to correct errors, no?
1136 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1137
1138 if ($IPDBacl{$authuser} =~ /c/) {
1139 $html =~ s/\$\$CUSTID\$\$/<input type=text name=custid value="$data[1]" maxlength=15 class="regular">/;
1140
1141# Screw it. Changing allocation types gets very ugly VERY quickly- especially
1142# with the much longer list of allocation types.
1143# We'll just show what type of block it is.
1144
1145# this has now been Requested, so here goes.
1146
1147##fixme The check here should be built from the database
1148 if ($data[2] =~ /^.[ne]$/) {
1149 # Block that can be changed
1150 my $blockoptions = "<select name=alloctype><option".
1151 (($data[2] eq 'me') ? ' selected' : '') ." value='me'>Dialup netblock</option>\n<option".
1152 (($data[2] eq 'de') ? ' selected' : '') ." value='de'>Dynamic DSL netblock</option>\n<option".
1153 (($data[2] eq 'ce') ? ' selected' : '') ." value='ce'>Dynamic cable netblock</option>\n<option".
1154 (($data[2] eq 'we') ? ' selected' : '') ." value='we'>Dynamic wireless netblock</option>\n<option".
1155 (($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
1156 (($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<option".
1157 (($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
1158 "</select>\n";
1159 $html =~ s/\$\$TYPESELECT\$\$/$blockoptions/g;
1160 } else {
1161 $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}<input type=hidden name=alloctype value="$data[2]">/g;
1162 }
1163 $html =~ s/\$\$CITY\$\$/<input type=text name=city value="$data[3]">/g;
1164 $html =~ s/\$\$CIRCID\$\$/<input type="text" name="circid" value="$data[4]" maxlength=64 size=64 class="regular">/g;
1165 $html =~ s/\$\$DESC\$\$/<input type="text" name="desc" value="$data[5]" maxlength=64 size=64 class="regular">/g;
1166 $html =~ s|\$\$NOTES\$\$|<textarea rows="8" cols="64" name="notes" class="regular">$data[6]</textarea>|g;
1167 } else {
1168 $html =~ s/\$\$CUSTID\$\$/$data[1]/g;
1169 $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}/g;
1170 $html =~ s/\$\$CITY\$\$/$data[3]/g;
1171 $html =~ s/\$\$CIRCID\$\$/$data[4]/g;
1172 $html =~ s/\$\$DESC\$\$/$data[5]/g;
1173 $html =~ s/\$\$NOTES\$\$/$data[6]/g;
1174 }
1175
1176 # More ACL trickery - we can live with forms that don't submit,
1177 # but we can't leave the extra table rows there, and we *really*
1178 # can't leave the submit buttons there.
1179 my $updok = '';
1180 my $i=2;
1181 if ($IPDBacl{$authuser} =~ /c/) {
1182 $updok = qq(<tr class="color$i"><td colspan=2 class=regular><div class="center">).
1183 qq(<input type="submit" value=" Update this block " class="regular">).
1184 "</div></td></tr></form>\n";
1185 $i--;
1186 }
1187 $html =~ s/\$\$UPDOK\$\$/$updok/g;
1188
1189 my $delok = '';
1190 if ($IPDBacl{$authuser} =~ /d/) {
1191 $delok = qq(<form method="POST" action="main.cgi">
1192 <tr class="color$i"><td colspan=2 class="regular"><div class=center>
1193 <input type="hidden" name="action" value="delete">
1194 <input type="hidden" name="block" value="$webvar{block}">
1195 <input type="hidden" name="alloctype" value="$data[2]">
1196 <input type=submit value=" Delete this block ">
1197 </div></td></tr>);
1198 }
1199 $html =~ s/\$\$DELOK\$\$/$delok/;
1200
1201 print $html;
1202
1203} # edit()
1204
1205
1206# Stuff new info about a block into the db
1207# action=update
1208sub update {
1209
1210 # Make sure incoming data is in correct format - custID among other things.
1211 return if !validateInput;
1212
1213 # SQL transaction wrapper
1214 eval {
1215 # Relatively simple SQL transaction here.
1216 my $sql;
1217 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
1218 $sql = "update poolips set custid='$webvar{custid}',notes='$webvar{notes}',".
1219 "circuitid='$webvar{circid}',description='$webvar{desc}',city='$webvar{city}' ".
1220 "where ip='$webvar{block}'";
1221 } else {
1222 $sql = "update allocations set custid='$webvar{custid}',".
1223 "description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',".
1224 "type='$webvar{alloctype}',circuitid='$webvar{circid}' where cidr='$webvar{block}'";
1225 }
1226 # Log the details of the change.
1227 syslog "debug", $sql;
1228 $sth = $ip_dbh->prepare($sql);
1229 $sth->execute;
1230 $ip_dbh->commit;
1231 };
1232 if ($@) {
1233 my $msg = $@;
1234 carp "Transaction aborted because $msg";
1235 eval { $ip_dbh->rollback; };
1236 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
1237 printError("Could not update block/IP $webvar{block}: $msg");
1238 return;
1239 }
1240
1241 # If we get here, the operation succeeded.
1242 syslog "notice", "$authuser updated $webvar{block}";
1243 open (HTML, "../updated.html")
1244 or croak "Could not open updated.html :$!";
1245 my $html = join('', <HTML>);
1246
1247 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
1248 $webvar{city} = desanitize($webvar{city});
1249 $html =~ s/\$\$CITY\$\$/$webvar{city}/g;
1250 $html =~ s/\$\$ALLOCTYPE\$\$/$webvar{alloctype}/g;
1251 $html =~ s/\$\$TYPEFULL\$\$/$disp_alloctypes{$webvar{alloctype}}/g;
1252 $html =~ s/\$\$CUSTID\$\$/$webvar{custid}/g;
1253 $webvar{circid} = desanitize($webvar{circid});
1254 $html =~ s/\$\$CIRCID\$\$/$webvar{circid}/g;
1255 $webvar{desc} = desanitize($webvar{desc});
1256 $html =~ s/\$\$DESC\$\$/$webvar{desc}/g;
1257 $webvar{notes} = desanitize($webvar{notes});
1258 $html =~ s/\$\$NOTES\$\$/$webvar{notes}/g;
1259
1260 print $html;
1261
1262} # update()
1263
1264
1265# Delete an allocation.
1266sub remove {
1267 if ($IPDBacl{$authuser} !~ /d/) {
1268 printError("You shouldn't have been able to get here. Access denied.");
1269 return;
1270 }
1271
1272 #show confirm screen.
1273 open HTML, "../confirmRemove.html"
1274 or croak "Could not open confirmRemove.html :$!";
1275 my $html = join('', <HTML>);
1276 close HTML;
1277
1278 # Serves'em right for getting here...
1279 if (!defined($webvar{block})) {
1280 printError("Error 332");
1281 return;
1282 }
1283
1284 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype);
1285
1286 if ($webvar{alloctype} eq 'rm') {
1287 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr='$webvar{block}'");
1288 $sth->execute();
1289
1290# This feels... extreme.
1291 croak $sth->errstr() if($sth->errstr());
1292
1293 $sth->bind_columns(\$cidr,\$city);
1294 $sth->execute();
1295 $sth->fetch || croak $sth->errstr();
1296 $custid = "N/A";
1297 $alloctype = $webvar{alloctype};
1298 $circid = "N/A";
1299 $desc = "N/A";
1300 $notes = "N/A";
1301
1302 } elsif ($webvar{alloctype} eq 'mm') {
1303 $cidr = $webvar{block};
1304 $city = "N/A";
1305 $custid = "N/A";
1306 $alloctype = $webvar{alloctype};
1307 $circid = "N/A";
1308 $desc = "N/A";
1309 $notes = "N/A";
1310 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
1311
1312 # Unassigning a static IP
1313 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid from poolips".
1314 " where ip='$webvar{block}'");
1315 $sth->execute();
1316# croak $sth->errstr() if($sth->errstr());
1317
1318 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid);
1319 $sth->fetch() || croak $sth->errstr;
1320
1321 } else { # done with alloctype=~ /^.i$/
1322
1323 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes from ".
1324 "allocations where cidr='$webvar{block}'");
1325 $sth->execute();
1326# croak $sth->errstr() if($sth->errstr());
1327
1328 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc, \$notes);
1329 $sth->fetch() || carp $sth->errstr;
1330 } # end cases for different alloctypes
1331
1332 # Munge everything into HTML
1333 $html =~ s|Please confirm|Please confirm <b>removal</b> of|;
1334 $html =~ s|\$\$BLOCK\$\$|$cidr|g;
1335 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$alloctype}|g;
1336 $html =~ s|\$\$ALLOCTYPE\$\$|$alloctype|g;
1337 $html =~ s|\$\$CITY\$\$|$city|g;
1338 $html =~ s|\$\$CUSTID\$\$|$custid|g;
1339 $html =~ s|\$\$CIRCID\$\$|$circid|g;
1340 $html =~ s|\$\$DESC\$\$|$desc|g;
1341 $html =~ s|\$\$NOTES\$\$|$notes|g;
1342
1343 $html =~ s|\$\$ACTION\$\$|finaldelete|g;
1344
1345 # Set the warning text.
1346 if ($alloctype =~ /^.[pd]$/) {
1347 $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>|;
1348 } else {
1349 $html =~ s|<!--warn-->|<tr bgcolor="black"><td colspan="2"><div class="red">Warning: clicking confirm will remove this record entirely.</div></td></tr>|;
1350 }
1351
1352 print $html;
1353} # end edit()
1354
1355
1356# Delete an allocation. Return it to the freeblocks table; munge
1357# data as necessary to keep as few records as possible in freeblocks
1358# to prevent weirdness when allocating blocks later.
1359# Remove IPs from pool listing if necessary
1360sub finalDelete {
1361 if ($IPDBacl{$authuser} !~ /d/) {
1362 printError("You shouldn't have been able to get here. Access denied.");
1363 return;
1364 }
1365
1366 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
1367
1368 if ($code eq 'OK') {
1369 print "<div class=heading align=center>Success! $webvar{block} deallocated.</div>\n";
1370 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}";
1371 # Notify tech@ when a block/IP is deallocated
1372 mailNotify('tech@example.com',"REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
1373 "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n");
1374 } else {
1375 if ($webvar{alloctype} =~ /^.i$/) {
1376 syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
1377 printError("Could not deallocate static IP $webvar{block}: $msg");
1378 } else {
1379 syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
1380 printError("Could not deallocate netblock $webvar{block}: $msg");
1381 }
1382 }
1383
1384} # finalDelete
1385
1386
1387sub exitError {
1388 my $errStr = $_[0];
1389 printHeader('','');
1390 print qq(<center><p class="regular"> $errStr </p>
1391<input type="button" value="Back" onclick="history.go(-1)">
1392</center>
1393);
1394 printFooter();
1395 exit;
1396} # errorExit
1397
1398
1399# Just in case we manage to get here.
1400exit 0;
Note: See TracBrowser for help on using the repository browser.