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

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

/branches/stable

Bugfix; allow the real error message to actually show up for
errors adding a master block.

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