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

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

/branches/stable

Squash a buglet that caused Dynamic-route DSL updates to lose
the customer ID. CustID checks are now formally done on any
type with a blank default CustID.

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