source: branches/htmlform/cgi-bin/main.cgi @ 456

Last change on this file since 456 was 456, checked in by Kris Deugau, 12 years ago

/branches/htmlform

Convert assign.html to template; page seems to still have
validation problems. See #3.

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