source: branches/new-search-20050223/cgi-bin/main.cgi@ 208

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

/branches/new-search-20050223

Final cleanup. This should be mergeable back to trunk "soon".
Cleanup includes:

-> Removing a little bit of leftover devel code in search.cgi
-> Expanding a little on docu-comments in search.cgi
-> Removing the viewBy() and queryResults() subs from main.cgi,

as well as the $webvar{action} check that ran the search there.

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