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

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

/branches/stable

Add Toronto to list of cities DSL pools can be in.

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 45.3 KB
RevLine 
[4]1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
3# Started munging from noc.vianet's old IPDB 04/22/2004
[8]4###
5# SVN revision info
6# $Date: 2005-03-22 17:15:10 +0000 (Tue, 22 Mar 2005) $
7# SVN revision $Rev: 206 $
8# Last update by $Author: kdeugau $
9###
[4]10
11use strict;
12use warnings;
13use CGI::Carp qw(fatalsToBrowser);
14use DBI;
15use CommonWeb qw(:ALL);
[158]16use MyIPDB;
[56]17use CustIDCK;
[4]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
[125]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;
[158]40($ip_dbh,$errstr) = connectDB_My;
[125]41if (!$ip_dbh) {
[185]42 printAndExit("Database error: $errstr\n");
[125]43}
44initIPDBGlobals($ip_dbh);
[4]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
[99]53# Global variables
[4]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
[125]72 print "<div type=heading align=center>Adding $cidr as master block....</div>\n";
[4]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
[159]88 $sth = $ip_dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
89 " values ('$webvar{cidr}',".$cidr->masklen.",'<NULL>','n')");
[4]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; };
[17]99 syslog "err", "Could not add master block '$webvar{cidr}' to database: '$@'";
[125]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}";
[4]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}
[125]165## Finally! Done with that NASTY "case" emulation!
[4]166
167
168
[125]169# Clean up IPDB globals, DB handle, etc.
170finish($ip_dbh);
[200]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)
[204]174 if $authuser =~ /kdeugau|jodyh|jipp/;
[200]175
[125]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;
[4]181
182
[125]183
[4]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);
[174]211
212 # Need to assemble SQL query in this order to avoid breaking things.
213 $sql = "select cidr,custid,type,city,description from searchme";
[4]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. :/
[174]224 $sql = "select cidr,custid,type,city,description from searchme where custid ilike '%$query%'";
[4]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).
[174]233 $sql = "select cidr,custid,type,city,description from searchme where description ilike '%$query%'";
[4]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>
[174]250 $sql = "select cidr,custid,type,city,description from searchme where cidr='$query'";
[4]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
[174]255 $sql = "select cidr,custid,type,city,description from searchme where ".
256 "text(cidr) like '$net%' and text(cidr) like '%$maskbits'";
[4]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;
[174]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'");
[4]268 $sth->execute;
269 while (my @data = $sth->fetchrow_array()) {
270 my $cidr = new NetAddr::IP $data[0];
[174]271 queryResults("select cidr,custid,type,city,description from searchme where ".
272 "cidr='$cidr'", $webvar{page}, 1);
[4]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";
[174]276 $sql = "select cidr,custid,type,city,description from searchme where ".
277 "text(cidr) like '$query%'";
[4]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...
[125]283 printError("Invalid query.");
[4]284 }
285 } else {
286 # This shouldn't happen, but if it does, whoever gets it deserves what they get...
[125]287 printError("Invalid searchfor.");
[4]288 }
289} # viewBy
290
[9]291
[4]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
[134]304ELEMENT: foreach my $element (@$rowRef) {
305 if (!defined($element)) {
306 print "<td></td>\n";
307 next ELEMENT;
308 }
[4]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) {
[192]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>),
[98]336 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
[4]337 # Allow listing of pool if desired/required.
[159]338 if ($data[2] =~ /^.[pd]$/) {
[4]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 {
[53]363 print qq(<a href="/ip/cgi-bin/main.cgi?page=$i&input=$webvar{input}&action=search&searchfor=$webvar{searchfor}">$i</a>&nbsp;\n);
[4]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
[125]394sub showSummary {
395 # this is horrible-ugly-bad and will Go Away real soon now(TM)
[4]396 print "Content-type: text/html\n\n";
397
398 startTable('Master netblock', 'Routed netblocks', 'Allocated netblocks',
399 'Free netblocks', 'Largest free block');
400
[125]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();
[4]412 }
413
[125]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();
[4]420 }
421
[125]422 # Count the free blocks.
[194]423 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
424 "(routed='y' or routed='n')");
[125]425 foreach my $master (@masterblocks) {
426 $sth->execute("$master");
427 $sth->bind_columns(\$free{"$master"});
428 $sth->fetch();
[4]429 }
430
[125]431 # Find the largest free block in each master
[194]432 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
433 "(routed='y' or routed='n') order by maskbits limit 1");
[125]434 foreach my $master (@masterblocks) {
435 $sth->execute("$master");
436 $sth->bind_columns(\$bigfree{"$master"});
437 $sth->fetch();
438 }
439
440 # Print the data.
[4]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"},
[160]445 ( ($bigfree{"$master"} eq '') ? ("&lt;NONE&gt;") : ("/".$bigfree{"$master"}) )
[4]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
[125]470 my %allocated;
471 my %free;
472 my %routed;
473 my %bigfree;
474
[4]475 my $master = new NetAddr::IP $webvar{block};
476 my @localmasters;
477
[125]478 # Fetch only the blocks relevant to this master
[159]479 $sth = $ip_dbh->prepare("select cidr,city from routed where cidr <<= '$master' order by cidr");
[4]480 $sth->execute();
481
482 my $i=0;
483 while (my @data = $sth->fetchrow_array()) {
484 my $cidr = new NetAddr::IP $data[0];
[125]485 $localmasters[$i++] = $cidr;
486 $free{"$cidr"} = 0;
487 $allocated{"$cidr"} = 0;
488 $bigfree{"$cidr"} = 128;
[4]489 # Retain the routing destination
[159]490 $routed{"$cidr"} = $data[1];
[4]491 }
492
[125]493 # Check if there were actually any blocks routed from this master
[4]494 if ($i > 0) {
495 startTable('Routed block','Routed to','Allocated blocks',
496 'Free blocks','Largest free block');
497
[125]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();
[4]504 }
505
[125]506 # Count the free blocks.
[194]507 $sth = $ip_dbh->prepare("select count(*) from freeblocks where cidr <<= ? and ".
508 "(routed='y' or routed='n')");
[125]509 foreach my $master (@localmasters) {
510 $sth->execute("$master");
511 $sth->bind_columns(\$free{"$master"});
512 $sth->fetch();
[4]513 }
514
[125]515 # Get the size of the largest free block
[194]516 $sth = $ip_dbh->prepare("select maskbits from freeblocks where cidr <<= ? and ".
517 "(routed='y' or routed='n') order by maskbits limit 1");
[125]518 foreach my $master (@localmasters) {
519 $sth->execute("$master");
520 $sth->bind_columns(\$bigfree{"$master"});
521 $sth->fetch();
[4]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;
[125]557 $sth = $ip_dbh->prepare("select cidr from freeblocks where cidr <<='$master' and ".
558 "routed='n' order by cidr");
[4]559 $sth->execute();
560 while (my @data = $sth->fetchrow_array()) {
561 my $cidr = new NetAddr::IP $data[0];
[125]562 my @row = ("$cidr", $cidr->range);
563 printRow(\@row, 'color1' ) if($count%2==0);
564 printRow(\@row, 'color2' ) if($count%2!=0);
565 $count++;
[4]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
[159]584 $sth = $ip_dbh->prepare("select city from routed where cidr='$master'");
[4]585 $sth->execute;
586 my @data = $sth->fetchrow_array;
587
588 print qq(<center><div class="heading">Summarizing allocated blocks for ).
[159]589 qq($master ($data[0]):</div></center><br>\n);
[4]590
[125]591 startTable('CIDR allocation','Customer Location','Type','CustID','Description/Name');
592
593 # Snag the allocations for this block
[159]594 $sth = $ip_dbh->prepare("select cidr,city,type,custid,description".
595 " from allocations where cidr <<= '$master' order by cidr");
[4]596 $sth->execute();
597
598 my $count=0;
599 while (my @data = $sth->fetchrow_array()) {
[159]600 # cidr,city,type,custid,description, as per the SELECT
[4]601 my $cidr = new NetAddr::IP $data[0];
602
603 # Clean up extra spaces that are borking things.
[159]604# $data[2] =~ s/\s+//g;
[4]605
[192]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>),
[159]609 $data[1], $disp_alloctypes{$data[2]}, $data[3], $data[4]);
[4]610 # If the allocation is a pool, allow listing of the IPs in the pool.
[159]611 if ($data[2] =~ /^.[pd]$/) {
[4]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).
[192]631 qq(<input type=hidden name=alloctype value="rm">\n).
[4]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;
[192]644 $sth = $ip_dbh->prepare("select cidr,routed from freeblocks where cidr <<= '$master'".
645 " order by cidr");
[4]646 $sth->execute();
647 while (my @data = $sth->fetchrow_array()) {
[192]648 # cidr,routed
[4]649 my $cidr = new NetAddr::IP $data[0];
[192]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>),
[24]653 $cidr->range);
[125]654 printRow(\@row, 'color1') if ($count%2 == 0);
655 printRow(\@row, 'color2') if ($count%2 != 0);
656 $count++;
[4]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
[159]669 my ($pooltype,$poolcity);
670
[4]671 # Snag pool info for heading
[159]672 $sth = $ip_dbh->prepare("select type,city from allocations where cidr='$cidr'");
[4]673 $sth->execute;
[159]674 $sth->bind_columns(\$pooltype, \$poolcity);
675 $sth->fetch() || carp $sth->errstr;
[4]676
677 print qq(<center><div class="heading">Listing pool IPs for $cidr<br>\n).
[159]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>).
[4]683 $cidr->addr."</td></tr>\n";
[159]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".
[4]688 "<tr><td>Netmask:</td><td>".$cidr->mask."</td></tr>\n".
689 "</table></div></div>\n";
[159]690 }
[4]691
692# probably have to add an "edit IP allocation" link here somewhere.
693
694 startTable('IP','Customer ID','Available?','Description','');
[159]695 $sth = $ip_dbh->prepare("select ip,custid,available,description,type".
696 " from poolips where pool='$webvar{pool}' order by ip");
[4]697 $sth->execute;
698 my $count = 0;
699 while (my @data = $sth->fetchrow_array) {
[75]700 # pool,ip,custid,city,ptype,available,notes,description,circuitid
[159]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;';
[4]705 }
706 # Some nice hairy Perl to decide whether to allow unassigning each IP
[159]707 # -> if $data[2] (aka poolips.available) == 'n' then we print the unassign link
[4]708 # else we print a blank space
[159]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>") :
[4]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
[125]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.
[4]727sub assignBlock {
728 printHeader('');
729
[24]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|;
[98]741 my $typelist = '';
[192]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";
[98]765 }
766 $html =~ s|\$\$TYPELIST\$\$|$typelist|g;
[24]767 } else {
768 open HTML, "../assign.html"
[4]769 or croak "Could not open assign.html: $!";
[24]770 $html = join('',<HTML>);
[91]771 close HTML;
[32]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;
[91]778 my $pops = '';
779 foreach my $pop (@poplist) {
780 $pops .= "<option>$pop</option>\n";
781 }
782 $html =~ s|\$\$POPLIST\$\$|$pops|g;
[98]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;
[24]792 }
[91]793 my $cities = '';
794 foreach my $city (@citylist) {
795 $cities .= "<option>$city</option>\n";
796 }
797 $html =~ s|\$\$ALLCITIES\$\$|$cities|g;
[4]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.
[125]813 return if !validateInput();
[4]814
815# Several different cases here.
816# Static IP vs netblock
817# + Different flavours of static IP
818# + Different flavours of netblock
819
[159]820 if ($webvar{alloctype} =~ /^.i$/) {
[4]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.
[159]827##fixme This needs thought.
828##SELECT DISTINCT pool, Count(*) FROM poolips where available='y' GROUP BY pool;
[4]829 if ($base =~ /^[ds]$/) {
830 $sql = "select * from poolips where available='y' and".
[206]831 " type='$webvar{alloctype}' and (city='Sudbury' or city='North Bay' or city='Toronto')";
[4]832 } else {
833 $sql = "select * from poolips where available='y' and".
[164]834 " type='$webvar{alloctype}' and city='$webvar{pop}'";
[4]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 }
[86]845 $sth = $ip_dbh->prepare("select city from allocations where cidr=?");
[4]846 foreach my $key (keys %ipcount) {
[86]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";
[4]850 }
851 $cidr = "Single static IP";
852 $alloc_from = "<select name=alloc_from>".$optionlist."</select>\n";
853
854 } else { # end show pool options
[24]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}) {
[125]862 printError("Please specify a CIDR mask length.");
863 return;
[24]864 }
865 my $sql;
866 my $city;
867 my $failmsg;
[192]868 if ($webvar{alloctype} eq 'rm') {
[32]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 }
[24]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.";
[4]879 } else {
[125]880##fixme
881# This section needs serious Pondering.
[192]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]$/) {
[206]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.");
[125]887 return;
888 }
[39]889 $city = $webvar{city};
[24]890 $failmsg = "No suitable free block found.<br>\nYou will have to route another".
[125]891 " superblock from one of the<br>\nmaster blocks in Sudbury or chose a smaller".
[24]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".
[101]896 " superblock to $webvar{pop}<br>\nfrom one of the master blocks in Sudbury or".
[24]897 " chose a smaller blocksize.";
898 }
[32]899 if ($webvar{allocfrom} ne '-') {
[159]900 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[192]901 " and cidr <<= '$webvar{allocfrom}' and routed='".
902 (($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y')."' order by maskbits desc,cidr";
[32]903 } else {
[159]904 $sql = "select cidr from freeblocks where city='$city' and maskbits<=$webvar{maskbits}".
[192]905 " and routed='".(($webvar{alloctype} =~ /^(.)r$/) ? "$1" : 'y').
906 "' order by maskbits desc,cidr";
[32]907 }
[4]908 }
[24]909 $sth = $ip_dbh->prepare($sql);
910 $sth->execute;
911 my @data = $sth->fetchrow_array();
912 if ($data[0] eq "") {
[125]913 printError($failmsg);
914 return;
[24]915 }
916 $cidr = new NetAddr::IP $data[0];
917 } # check for freeblocks assignment or IPDB-controlled assignment
[4]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 }
[159]931 } # if ($webvar{alloctype} =~ /^.i$/)
[4]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;
[98]947 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$webvar{alloctype}}|g;
[4]948 $html =~ s|\$\$ALLOC_FROM\$\$|$alloc_from|g;
949 $html =~ s|\$\$CIDR\$\$|$cidr|g;
[82]950 $webvar{city} = desanitize($webvar{city});
[4]951 $html =~ s|\$\$CITY\$\$|$webvar{city}|g;
952 $html =~ s|\$\$CUSTID\$\$|$webvar{custid}|g;
[83]953 $webvar{circid} = desanitize($webvar{circid});
[75]954 $html =~ s|\$\$CIRCID\$\$|$webvar{circid}|g;
[4]955 $webvar{desc} = desanitize($webvar{desc});
[89]956 $html =~ s|\$\$DESC\$\$|$webvar{desc}|g;
[4]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('');
[125]970 return if !validateInput();
[4]971
[125]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});
[4]978
[125]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>);
[122]982 # Notify tech@example.com
[203]983 mailNotify('tech@example.com',"ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
[125]984 "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
[122]985 "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
[125]986 } else {
987 print qq(<div class="center"><div class="heading">The block $webvar{fullcidr} was ).
[192]988 "sucessfully added as: $disp_alloctypes{$webvar{alloctype}}</div></div>";
[122]989 }
[125]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'";
[192]995 printError("Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
[159]996 " failed:<br>\n$msg\n");
[125]997 }
[122]998
[4]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 '-') {
[125]1007 printError("Please choose a city.");
1008 return;
[4]1009 }
[140]1010
1011 # Alloctype check.
[4]1012 chomp $webvar{alloctype};
[140]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
[4]1021 # We have different handling for customer allocations and "internal" or "our" allocations
[140]1022 if ($webvar{alloctype} =~ /^(cn|.i)$/) {
[4]1023 if (!$webvar{custid}) {
[125]1024 printError("Please enter a customer ID.");
1025 return;
[4]1026 }
[116]1027 if ($webvar{custid} !~ /^(?:\d{10}|\d{7}|STAFF)(?:-\d\d?)?$/) {
[56]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});
[125]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 }
[56]1042#"Please enter a valid customer ID- this must be a 7- or 10-digit number, or STAFF for
1043#static IPs for staff.");
[4]1044 }
[56]1045# print "<!-- [ In validateInput(). Insert customer ID cross-check here. ] -->\n";
[140]1046 } else {
[168]1047 # New! Improved! And now Loaded From The Database!!
[56]1048 if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
[168]1049 $webvar{custid} = $def_custids{$webvar{alloctype}};
[56]1050 }
[4]1051 }
[125]1052
1053 # Check POP location
1054 my $flag;
[192]1055 if ($webvar{alloctype} eq 'rm') {
[125]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';
[4]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$/) {
[162]1090 $sql = "select ip,custid,type,city,circuitid,description,notes from poolips where ip='$webvar{block}'";
[4]1091 } else {
[75]1092 $sql = "select cidr,custid,type,city,circuitid,description,notes from allocations where cidr='$webvar{block}'"
[4]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
[159]1103##fixme LEGACY CODE
[4]1104 # Postfix "i" on pool IP types
[97]1105 if ($data[2] =~ /^[cdsmw]$/) {
[4]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
[35]1125# this has now been Requested, so here goes.
[4]1126
[192]1127##fixme The check here should be built from the database
1128 if ($data[2] =~ /^.[ne]$/) {
[35]1129 # Block that can be changed
1130 my $blockoptions = "<select name=alloctype><option".
[192]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".
[35]1135 (($data[2] eq 'cn') ? ' selected' : '') ." value='cn'>Customer netblock</option>\n<option".
[192]1136 (($data[2] eq 'en') ? ' selected' : '') ." value='en'>End-use netblock</option>\n<option".
[133]1137 (($data[2] eq 'in') ? ' selected' : '') ." value='in'>Internal netblock</option>\n".
[35]1138 "</select>\n";
1139 $html =~ s/\$\$TYPESELECT\$\$/$blockoptions/g;
1140 } else {
[98]1141 $html =~ s/\$\$TYPESELECT\$\$/$disp_alloctypes{$data[2]}<input type=hidden name=alloctype value="$data[2]">/g;
[35]1142 }
1143
[4]1144 # These can be modified, although CustID changes may get ignored.
1145 $html =~ s/\$\$CUSTID\$\$/$data[1]/g;
[75]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;
[4]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;
[159]1168 if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
[75]1169 $sql = "update poolips set custid='$webvar{custid}',notes='$webvar{notes}',".
1170 "circuitid='$webvar{circid}',description='$webvar{desc}' ".
[4]1171 "where ip='$webvar{block}'";
1172 } else {
1173 $sql = "update allocations set custid='$webvar{custid}',".
[35]1174 "description='$webvar{desc}',notes='$webvar{notes}',city='$webvar{city}',".
[75]1175 "type='$webvar{alloctype}',circuitid='$webvar{circid}' where cidr='$webvar{block}'";
[4]1176 }
[159]1177 # Log the details of the change.
1178 syslog "debug", $sql;
[4]1179 $sth = $ip_dbh->prepare($sql);
1180 $sth->execute;
1181 $ip_dbh->commit;
1182 };
1183 if ($@) {
[163]1184 my $msg = $@;
1185 carp "Transaction aborted because $msg";
[4]1186 eval { $ip_dbh->rollback; };
[163]1187 syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
1188 printError("Could not update block/IP $webvar{block}: $msg");
[125]1189 return;
[4]1190 }
1191
1192 # If we get here, the operation succeeded.
1193 syslog "notice", "$authuser updated $webvar{block}";
1194 open (HTML, "../updated.html")
[125]1195 or croak "Could not open updated.html :$!";
[4]1196 my $html = join('', <HTML>);
1197
1198 $html =~ s/\$\$BLOCK\$\$/$webvar{block}/g;
[89]1199 $webvar{city} = desanitize($webvar{city});
[4]1200 $html =~ s/\$\$CITY\$\$/$webvar{city}/g;
1201 $html =~ s/\$\$ALLOCTYPE\$\$/$webvar{alloctype}/g;
[98]1202 $html =~ s/\$\$TYPEFULL\$\$/$disp_alloctypes{$webvar{alloctype}}/g;
[4]1203 $html =~ s/\$\$CUSTID\$\$/$webvar{custid}/g;
[89]1204 $webvar{circid} = desanitize($webvar{circid});
[75]1205 $html =~ s/\$\$CIRCID\$\$/$webvar{circid}/g;
[89]1206 $webvar{desc} = desanitize($webvar{desc});
[4]1207 $html =~ s/\$\$DESC\$\$/$webvar{desc}/g;
[89]1208 $webvar{notes} = desanitize($webvar{notes});
[4]1209 $html =~ s/\$\$NOTES\$\$/$webvar{notes}/g;
1210
1211 print $html;
1212
1213} # update()
1214
1215
1216# Delete an allocation.
[125]1217sub remove {
[4]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})) {
[125]1227 printError("Error 332");
1228 return;
[4]1229 }
1230
[75]1231 my ($cidr, $custid, $type, $city, $circid, $desc, $notes, $alloctype);
[4]1232
[192]1233 if ($webvar{alloctype} eq 'rm') {
[4]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};
[75]1245 $circid = "N/A";
[4]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};
[75]1254 $circid = "N/A";
[4]1255 $desc = "N/A";
1256 $notes = "N/A";
[192]1257 } elsif ($webvar{alloctype} =~ /^.i$/) { # done with alloctype=[rm]m
[4]1258
1259 # Unassigning a static IP
[163]1260 my $sth = $ip_dbh->prepare("select ip,custid,city,type,notes,circuitid from poolips".
[4]1261 " where ip='$webvar{block}'");
1262 $sth->execute();
1263# croak $sth->errstr() if($sth->errstr());
1264
[75]1265 $sth->bind_columns(\$cidr, \$custid, \$city, \$alloctype, \$notes, \$circid);
[4]1266 $sth->fetch() || croak $sth->errstr;
1267
[159]1268 } else { # done with alloctype=~ /^.i$/
[4]1269
[75]1270 my $sth = $ip_dbh->prepare("select cidr,custid,type,city,circuitid,description,notes from ".
[4]1271 "allocations where cidr='$webvar{block}'");
1272 $sth->execute();
1273# croak $sth->errstr() if($sth->errstr());
1274
[75]1275 $sth->bind_columns(\$cidr, \$custid, \$alloctype, \$city, \$circid, \$desc, \$notes);
1276 $sth->fetch() || carp $sth->errstr;
[4]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;
[98]1282 $html =~ s|\$\$TYPEFULL\$\$|$disp_alloctypes{$alloctype}|g;
[4]1283 $html =~ s|\$\$ALLOCTYPE\$\$|$alloctype|g;
1284 $html =~ s|\$\$CITY\$\$|$city|g;
1285 $html =~ s|\$\$CUSTID\$\$|$custid|g;
[75]1286 $html =~ s|\$\$CIRCID\$\$|$circid|g;
[4]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.
[159]1293 if ($alloctype =~ /^.[pd]$/) {
[4]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
[125]1310 my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
[4]1311
[125]1312 if ($code eq 'OK') {
[4]1313 print "<div class=heading align=center>Success! $webvar{block} deallocated.</div>\n";
[125]1314 syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block}";
[205]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");
[125]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");
[4]1325 }
[102]1326 }
1327
[4]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.