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

Last change on this file since 595 was 595, checked in by Kris Deugau, 8 years ago

/branches/stable

Hand-backport pieces of the allocate-from-routed-freeblock from /trunk
post-r553. Cherrypick merge not possible due to intermingled changes
relating to the database structure updates.
Includes a handful of harmless references to the new structure.
Will likely cause merge conflicts when the structure update is merged.

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 28.8 KB
Line 
1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
3###
4# SVN revision info
5# $Date: 2013-05-15 21:26:55 +0000 (Wed, 15 May 2013) $
6# SVN revision $Rev: 595 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2011 - Kris Deugau
10
11use strict;             
12use warnings;   
13use CGI::Carp qw(fatalsToBrowser);
14use CGI::Simple;
15use HTML::Template;
16use DBI;
17use POSIX qw(ceil);
18use NetAddr::IP;
19
20use Sys::Syslog;
21
22# don't remove!  required for GNU/FHS-ish install from tarball
23##uselib##
24
25use CustIDCK;
26use MyIPDB;
27
28openlog "IPDB","pid","$IPDB::syslog_facility";
29
30## Environment.  Collect some things, process some things, set some things...
31
32# Collect the username from HTTP auth.  If undefined, we're in
33# a test environment, or called without a username.
34my $authuser;
35if (!defined($ENV{'REMOTE_USER'})) {
36  $authuser = '__temptest';
37} else {
38  $authuser = $ENV{'REMOTE_USER'};
39}
40
41# anyone got a better name?  :P
42my $thingroot = $ENV{SCRIPT_FILENAME};
43$thingroot =~ s|cgi-bin/main.cgi||;
44
45syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";
46
47##fixme there *must* be a better order to do things in so this can go back where it was
48# CGI fiddling done here so we can declare %webvar so we can alter $webvar{action}
49# to show the right page on DB errors.
50# Set up the CGI object...
51my $q = new CGI::Simple;
52# ... and get query-string params as well as POST params if necessary
53$q->parse_query_string;
54
55# Convenience;  saves changing all references to %webvar
56##fixme:  tweak for handling <select multiple='y' size=3> (list with multiple selection)
57my %webvar = $q->Vars;
58
59# Why not a global DB handle?  (And a global statement handle, as well...)
60# Use the connectDB function, otherwise we end up confusing ourselves
61my $ip_dbh;
62my $errstr;
63($ip_dbh,$errstr) = connectDB_My;
64if (!$ip_dbh) {
65  $webvar{action} = "dberr";
66} else {
67  initIPDBGlobals($ip_dbh);
68}
69
70# Set up some globals
71$ENV{HTML_TEMPLATE_ROOT} = $thingroot."templates";
72
73my $header = HTML::Template->new(filename => "header.tmpl");
74my $footer = HTML::Template->new(filename => "footer.tmpl");
75
76$header->param(version => $IPDB::VERSION);
77$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
78$header->param(webpath => $IPDB::webpath);
79print "Content-type: text/html\n\n", $header->output;
80
81
82#main()
83my $aclerr;
84
85if(!defined($webvar{action})) {
86  $webvar{action} = "index";    #shuts up the warnings.
87}
88
89my $page;
90if (-e "$ENV{HTML_TEMPLATE_ROOT}/$webvar{action}.tmpl") {
91  $page = HTML::Template->new(filename => "$webvar{action}.tmpl", loop_context_vars => 1, global_vars => 1);
92} else {
93  $page = HTML::Template->new(filename => "dunno.tmpl");
94}
95
96if($webvar{action} eq 'index') {
97  showSummary();
98} elsif ($webvar{action} eq 'addmaster') {
99  if ($IPDBacl{$authuser} !~ /a/) {
100    $aclerr = 'addmaster';
101  }
102} elsif ($webvar{action} eq 'newmaster') {
103
104  if ($IPDBacl{$authuser} !~ /a/) {
105    $aclerr = 'addmaster';
106  } else {
107    my $cidr = new NetAddr::IP $webvar{cidr};
108    $page->param(cidr => "$cidr");
109
110    my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr});
111
112    if ($code eq 'FAIL') {
113      syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
114      $page->param(err => $msg);
115    } else {
116      syslog "info", "$authuser added master block $webvar{cidr}";
117    }
118
119  } # ACL check
120
121} # end add new master
122
123elsif($webvar{action} eq 'showmaster') {
124  showMaster();
125}
126elsif($webvar{action} eq 'showrouted') {
127  showRBlock();
128}
129elsif($webvar{action} eq 'listpool') {
130  showPool();
131}
132
133# Not modified or added;  just shuffled
134elsif($webvar{action} eq 'assign') {
135  assignBlock();
136}
137elsif($webvar{action} eq 'confirm') {
138  confirmAssign();
139}
140elsif($webvar{action} eq 'insert') {
141  insertAssign();
142}
143elsif($webvar{action} eq 'edit') {
144  edit();
145}
146elsif($webvar{action} eq 'update') {
147  update();
148}
149elsif($webvar{action} eq 'delete') {
150  remove();
151}
152elsif($webvar{action} eq 'finaldelete') {
153  finalDelete();
154}
155elsif ($webvar{action} eq 'nodesearch') {
156  my $nodelist = getNodeList($ip_dbh);
157  $page->param(nodelist => $nodelist);
158}
159
160# DB failure.  Can't do much here, really.
161elsif ($webvar{action} eq 'dberr') {
162  $page->param(errmsg => $errstr);
163}
164
165# Default is an error.  It shouldn't be possible to get here unless you're
166# randomly feeding in values for webvar{action}.
167else {
168  my $rnd = rand 500;
169  my $boing = sprintf("%.2f", rand 500);
170  my @excuses = (
171        "Aether cloudy.  Ask again later about $webvar{action}.",
172        "The gods are unhappy with your sacrificial $webvar{action}.",
173        "Because one of $webvar{action}'s legs are both the same",
174        "<b>wibble</b><br>Can't $webvar{action}, the grue will get me!<br>Can't $webvar{action}, the grue will get me!",
175        "Hey, man, you've had your free $webvar{action}.  Next one's gonna...  <i>cost</i>....",
176        "I ain't done $webvar{action}",
177        "Oooo, look!  A flying $webvar{action}!",
178        "$webvar{action} too evil, avoiding.",
179        "Rocks fall, $webvar{action} dies.",
180        "Bit bucket must be emptied before I can $webvar{action}..."
181        );
182  $page->param(dunno => $excuses[$rnd/50.0]);
183}
184## Finally! Done with that NASTY "case" emulation!
185
186
187# Switch to a different template if we've tripped on an ACL error.
188# Note that this should only be exercised in development, when
189# deeplinked, or when being attacked;  normal ACL handling should
190# remove the links a user is not allowed to click on.
191if ($aclerr) {
192  $page = HTML::Template->new(filename => "aclerror.tmpl");
193  $page->param(ipdbfunc => $aclmsg{$aclerr});
194}
195
196# Clean up IPDB globals, DB handle, etc.
197finish($ip_dbh);
198
199## Do all our printing here so we can generate errors and stick them into the slots in the templates.
200
201# can't do this yet, too many blowups
202#print "Content-type: text/html\n\n", $header->output;
203$page->param(webpath => $IPDB::webpath);
204print $page->output;
205
206# include the admin tools link in the output?
207$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
208$footer->param(webpath => $IPDB::webpath);
209print $footer->output;
210
211# Just in case something waaaayyy down isn't in place
212# properly... we exit explicitly.
213exit 0;
214
215
216# Initial display:  Show master blocks with total allocated subnets, total free subnets
217sub showSummary {
218  my $masterlist = listSummary($ip_dbh);
219  $page->param(masterlist => $masterlist);
220
221  $page->param(addmaster => ($IPDBacl{$authuser} =~ /a/) );
222} # showSummary
223
224
225# Display detail on master
226# Alrighty then!  We're showing routed blocks within a single master this time.
227# We should be able to steal code from showSummary(), and if I'm really smart
228# I'll figger a way to munge the two together.  (Once I've done that, everything
229# else should follow.  YMMV.)
230sub showMaster {
231
232  $page->param(master => $webvar{block});
233  $page->param(delmaster => ($IPDBacl{$authuser} =~ /d/));
234
235  my $rlist = listMaster($ip_dbh, $webvar{block});
236  $page->param(routedlist => $rlist);
237
238  my $flist = listFree($ip_dbh, $webvar{block});
239  $page->param(unrouted => $flist);
240  $page->param(mayadd => ($IPDBacl{$authuser} =~ /a/));
241} # showMaster
242
243
244# Display details of a routed block
245# Alrighty then!  We're showing allocations within a routed block this time.
246# We should be able to steal code from showSummary() and showMaster(), and if
247# I'm really smart I'll figger a way to munge all three together.  (Once I've
248# done that, everything else should follow.  YMMV.
249# This time, we check the database before spewing, because we may
250# not have anything useful to spew.
251sub showRBlock {
252
253  $page->param(master => $webvar{block});
254  $page->param(delrouted => $IPDBacl{$authuser} =~ /d/);
255
256  my $rcity = getRoutedCity($ip_dbh, $webvar{block});
257  $page->param(rcity => $rcity);
258
259  my $blist = listRBlock($ip_dbh, $webvar{block});
260  $page->param(blocklist => $blist);
261
262  my $flist = listFree($ip_dbh, $webvar{block}, 'y');
263  $page->param(unassigned => $flist);
264} # showRBlock
265
266
267# List the IPs used in a pool
268sub showPool {
269
270  my $cidr = new NetAddr::IP $webvar{pool};
271
272  $page->param(block => $webvar{pool});
273  $page->param(netip => $cidr->addr);
274  $cidr++;
275  $page->param(gate => $cidr->addr);
276  $cidr--;  $cidr--;
277  $page->param(bcast => $cidr->addr);
278  $page->param(mask => $cidr->mask);
279
280  # Snag pool info for heading
281  my $poolinfo = getBlockData($ip_dbh, $webvar{pool});
282
283  $page->param(disptype => $disp_alloctypes{$poolinfo->{type}});
284  $page->param(city => $poolinfo->{city});
285
286  # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
287  $page->param(realblock => $poolinfo->{type} =~ /^.d$/);
288
289# probably have to add an "edit IP allocation" link here somewhere.
290
291  my $plist = listPool($ip_dbh, $webvar{pool});
292  # technically slightly more efficient to check the ACL in an if () once outside the foreach
293  foreach (@{$plist}) {
294    $$_{maydel} = $IPDBacl{$authuser} =~ /d/;
295  }
296  $page->param(poolips => $plist);
297} # end showPool
298
299
300# Show "Add new allocation" page.  Note that the actual page may
301# be one of two templates, and the lists come from the database.
302sub assignBlock {
303
304  if ($IPDBacl{$authuser} !~ /a/) {
305    $aclerr = 'addblock';
306    return;
307  }
308
309  # hack pthbttt eww
310  $webvar{block} = '' if !$webvar{block};
311
312# hmm.  TMPL_IF block and TMPL_ELSE block on these instead?
313  $page->param(rowa => 'row'.($webvar{block} eq '' ? 1 : 0));
314  $page->param(rowb => 'row'.($webvar{block} eq '' ? 0 : 1));
315  $page->param(allocfrom => $webvar{block});    # fb-assign flag, if block is set, we're in fb-assign
316
317  if ($webvar{fbtype}) {
318
319    # Common case, according to reported usage.  Block to assign is specified.
320    my $block = new NetAddr::IP $webvar{block};
321
322    $webvar{fbtype} = '' if !$webvar{fbtype};
323    if ($webvar{fbtype} eq 'i') {
324      my $ipinfo = getBlockData($ip_dbh, $webvar{block}, 'i');
325      my $pinfo = getBlockData($ip_dbh, $webvar{parent});
326      $page->param(
327        fbip => 1,
328        block => $ipinfo->{block},
329        fbdisptype => $list_alloctypes{$ipinfo->{type}},
330        type => $ipinfo->{type},
331        allocfrom => $pinfo->{block},
332        );
333    } elsif ($webvar{fbtype} eq 'n') {
334      $page->param(
335        fbrouted => 1,
336        fbdisptype => $list_alloctypes{'rm'},
337        type => 'rm',
338        block => $block,
339        );
340    } else {
341      # get "primary" alloctypes, since these are all that can correctly be assigned if we're in this branch
342      my $tlist = getTypeList($ip_dbh, 'n');
343      $tlist->[0]->{sel} = 1;
344      $page->param(typelist => $tlist, block => $block);
345    }
346
347  } else {
348
349    # Uncommon case, according to reported usage.  Block to assign needs to be found based on criteria.
350    my $mlist = getMasterList($ip_dbh, 'c');
351    $page->param(masterlist => $mlist);
352
353    my @pops;
354    foreach my $pop (@citylist) {
355      my %row = (pop => $pop);
356      push (@pops, \%row);
357    }
358    $page->param(pops => \@pops);
359
360    # get all standard alloctypes
361    my $tlist = getTypeList($ip_dbh, 'a');
362    $tlist->[0]->{sel} = 1;
363    $page->param(typelist => $tlist);
364  }
365  my @cities;
366  foreach my $city (@citylist) {
367    my %row = (city => $city);
368    push (@cities, \%row);
369  }
370  $page->param(citylist => \@cities);
371
372## node hack
373  my $nlist = getNodeList($ip_dbh);
374  $page->param(nodelist => $nlist);
375## end node hack
376
377  $page->param(privdata => $IPDBacl{$authuser} =~ /s/);
378
379} # assignBlock
380
381
382# Take info on requested IP assignment and see what we can provide.
383sub confirmAssign {
384  if ($IPDBacl{$authuser} !~ /a/) {
385    $aclerr = 'addblock';
386    return;
387  }
388
389  my $cidr;
390  my $alloc_from;
391
392  # Going to manually validate some items.
393  # custid and city are automagic.
394  return if !validateInput();
395
396# Several different cases here.
397# Static IP vs netblock
398#  + Different flavours of static IP
399#  + Different flavours of netblock
400
401  if ($webvar{alloctype} =~ /^.i$/ && $webvar{fbassign} ne 'y') {
402    my $plist = getPoolSelect($ip_dbh, $webvar{alloctype}, $webvar{pop});
403    $page->param(staticip => 1);
404    $page->param(poollist => $plist) if $plist;
405    $cidr = "Single static IP";
406##fixme:  need to handle "no available pools"
407
408  } else { # end show pool options
409
410    if ($webvar{fbassign} && $webvar{fbassign} eq 'y') {
411      $cidr = new NetAddr::IP $webvar{block};
412      $alloc_from = new NetAddr::IP $webvar{allocfrom};
413      $webvar{maskbits} = $cidr->masklen;
414    } else { # done with direct freeblocks assignment
415
416      if (!$webvar{maskbits}) {
417        $page->param(err => "Please specify a CIDR mask length.");
418        return;
419      }
420
421##fixme ick, ew, bleh.  gotta handle the failure message generation better.  push it into findAllocateFrom()?
422      my $failmsg = "No suitable free block found.<br>\n";
423      if ($webvar{alloctype} eq 'rm') {
424        $failmsg .= "We do not have a free routeable block of that size.<br>\n".
425                "You will have to either route a set of smaller netblocks or a single smaller netblock.";
426      } else {
427        if ($webvar{alloctype} =~ /^.[pc]$/) {
428          $failmsg .= "You will have to route another superblock from one of the<br>\n".
429                "master blocks or chose a smaller block size for the pool.";
430        } else {
431          if (!$webvar{pop}) {
432            $page->param(err => 'Please select a POP to route the block from/through.');
433            return;
434          }
435          $failmsg .= "You will have to route another superblock to $webvar{pop}<br>\n".
436                "from one of the master blocks or chose a smaller blocksize.";
437        }
438      }
439
440      $cidr = findAllocateFrom($ip_dbh, $webvar{maskbits}, $webvar{alloctype}, $webvar{city}, $webvar{pop},
441        (master => $webvar{allocfrom}, allowpriv => $webvar{allowpriv}) );
442      if (!$cidr) {
443        $page->param(err => $failmsg);
444        return;
445      }
446      $cidr = new NetAddr::IP $cidr;
447
448# this chunk now specific to "guided" allocation;  freeblock-select can now slice-n-dice on its own.
449      $alloc_from = "$cidr";
450      # If the block to be allocated is smaller than the one we found,
451      # figure out the "real" block to be allocated.
452      if ($cidr->masklen() ne $webvar{maskbits}) {
453        my $maskbits = $cidr->masklen();
454        my @subblocks;
455        while ($maskbits++ < $webvar{maskbits}) {
456          @subblocks = $cidr->split($maskbits);
457        }
458        $cidr = $subblocks[0];
459      }
460    } # check for freeblocks assignment or IPDB-controlled assignment
461
462  } # if ($webvar{alloctype} =~ /^.i$/)
463
464## node hack
465  if ($webvar{node} && $webvar{node} ne '-') {
466    my $nodename = getNodeName($ip_dbh, $webvar{node});
467    $page->param(nodename => $nodename);
468    $page->param(nodeid => $webvar{node});
469  }
470## end node hack
471
472  # Stick in the allocation data
473  $page->param(alloc_type => $webvar{alloctype});
474  $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
475  $page->param(alloc_from => $alloc_from);
476  $page->param(cidr => $cidr);
477  $page->param(city => $q->escapeHTML($webvar{city}));
478  $page->param(custid => $webvar{custid});
479  $page->param(circid => $q->escapeHTML($webvar{circid}));
480  $page->param(desc => $q->escapeHTML($webvar{desc}));
481
482##fixme: find a way to have the displayed copy have <br> substitutions
483# for newlines, and the <input> value have either encoded or bare newlines.
484# Also applies to privdata.
485  $page->param(notes => $q->escapeHTML($webvar{notes},'y'));
486
487  # Check to see if user is allowed to do anything with sensitive data
488  my $privdata = '';
489  $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'))
490        if $IPDBacl{$authuser} =~ /s/;
491
492  # Yay!  This now has it's very own little home.
493  $page->param(billinguser => $webvar{userid})
494        if $webvar{userid};
495
496##fixme:  this is only needed iff confirm.tmpl and
497# confirmRemove.tmpl are merged (quite possible, just
498# a little tedious)
499  $page->param(action => "insert");
500
501} # end confirmAssign
502
503
504# Do the work of actually inserting a block in the database.
505sub insertAssign {
506  if ($IPDBacl{$authuser} !~ /a/) {
507    $aclerr = 'addblock';
508    return;
509  }
510  # Some things are done more than once.
511  return if !validateInput();
512
513  if (!defined($webvar{privdata})) {
514    $webvar{privdata} = '';
515  }
516  # $code is "success" vs "failure", $msg contains OK for a
517  # successful netblock allocation, the IP allocated for static
518  # IP, or the error message if an error occurred.
519
520  my ($code,$msg) = allocateBlock($ip_dbh, $webvar{fullcidr}, $webvar{alloc_from},
521        $webvar{custid}, $webvar{alloctype}, $webvar{city}, $webvar{desc}, $webvar{notes},
522        $webvar{circid}, $webvar{privdata}, $webvar{node});
523
524  if ($code eq 'OK' || $code eq 'WARN') {
525    if ($webvar{alloctype} =~ /^.i$/) {
526      $msg =~ s|/32||;
527      $page->param(staticip => $msg);
528      $page->param(custid => $webvar{custid});
529      $page->param(billinguser => $webvar{billinguser});
530      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
531        "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
532        "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
533    } else {
534      my $netblock = new NetAddr::IP $webvar{fullcidr};
535      $page->param(fullcidr => $webvar{fullcidr});
536      $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}});
537      $page->param(custid => $webvar{custid});
538      if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) {
539        $page->param(billinguser => $webvar{billinguser});
540        $page->param(custid => $webvar{custid});
541        $page->param(netaddr => $netblock->addr);
542        $page->param(masklen => $netblock->masklen);
543      }
544      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
545        "$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
546        "Description: $webvar{desc}\n\nAllocated by: $authuser\n");
547    }
548    syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
549        "'$webvar{alloctype}' ($msg)";
550  } else {
551    syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
552        "'$webvar{alloctype}' by $authuser failed: '$msg'";
553    $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}'".
554        " failed:<br>\n$msg\n");
555  }
556
557} # end insertAssign()
558
559
560# Does some basic checks on common input data to make sure nothing
561# *really* weird gets in to the database through this script.
562# Does NOT do complete input validation!!!
563sub validateInput {
564  if ($webvar{city} eq '-') {
565    $page->param(err => 'Please choose a city');
566    return;
567  }
568
569  # Alloctype check.
570  chomp $webvar{alloctype};
571  if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
572    # Danger! Danger!  alloctype should ALWAYS be set by a dropdown.  Anyone
573    # managing to call things in such a way as to cause this deserves a cryptic error.
574    $page->param(err => 'Invalid alloctype');
575    return;
576  }
577
578  # CustID check
579  # We have different handling for customer allocations and "internal" or "our" allocations
580  if ($def_custids{$webvar{alloctype}} eq '') {
581    if (!$webvar{custid}) {
582      $page->param(err => 'Please enter a customer ID.');
583      return;
584    }
585    # Crosscheck with billing.
586    my $status = CustIDCK->custid_exist($webvar{custid});
587    if ($CustIDCK::Error) {
588      $page->param(err => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
589      return;
590    }
591    if (!$status) {
592      $page->param(err => "Customer ID not valid.  Make sure the Customer ID ".
593        "is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
594        "non-customer assignments.");
595      return;
596    }
597#    print "<!-- [ In validateInput().  Insert customer ID cross-check here. ] -->\n";
598  } else {
599    # New!  Improved!  And now Loaded From The Database!!
600    if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
601      $webvar{custid} = $def_custids{$webvar{alloctype}};
602    }
603  }
604
605  # Check POP location
606  my $flag;
607  if ($webvar{alloctype} eq 'rm') {
608    $flag = 'for a routed netblock';
609    foreach (@poplist) {
610      if (/^$webvar{city}$/) {
611        $flag = 'n';
612        last;
613      }
614    }
615  } else {
616    $flag = 'n';
617##fixme:  hook to force-set POP or city on certain alloctypes
618# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
619    if ($webvar{pop} && $webvar{pop} =~ /^-$/) {
620      $flag = 'to route the block from/through';
621    }
622  }
623
624  # if the alloctype has a restricted city/POP list as determined above,
625  # and the reqested city/POP does not match that list, complain
626  if ($flag ne 'n') {
627    $page->param(err => "Please choose a valid POP location $flag.  Valid ".
628        "POP locations are currently:<br>\n".join (" - ", @poplist));
629    return;
630  }
631
632  return 'OK';
633} # end validateInput
634
635
636# Displays details of a specific allocation in a form
637# Allows update/delete
638# action=edit
639sub edit {
640
641  # snag block info from db
642  my $blockinfo = getBlockData($ip_dbh, $webvar{block});
643
644  # Clean up extra whitespace on alloc type.  Mainly a legacy-data cleanup.
645  $blockinfo->{type} =~ s/\s//;
646
647  $page->param(block => $webvar{block});
648
649  $page->param(custid   => $blockinfo->{custid});
650  $page->param(city     => $blockinfo->{city});
651  $page->param(circid   => $blockinfo->{circuitid});
652  $page->param(desc     => $blockinfo->{description});
653  $page->param(notes    => $blockinfo->{notes});
654
655##fixme The check here should be built from the database
656# Need to expand to support pool types too
657  if ($blockinfo->{type} =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) {
658    $page->param(changetype => 1);
659    $page->param(alloctype => [
660                { selme => ($blockinfo->{type} eq 'me'), type => "me", disptype => "Dialup netblock" },
661                { selme => ($blockinfo->{type} eq 'de'), type => "de", disptype => "Dynamic DSL netblock" },
662                { selme => ($blockinfo->{type} eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" },
663                { selme => ($blockinfo->{type} eq 'we'), type => "we", disptype => "Dynamic wireless netblock" },
664                { selme => ($blockinfo->{type} eq 'cn'), type => "cn", disptype => "Customer netblock" },
665                { selme => ($blockinfo->{type} eq 'en'), type => "en", disptype => "End-use netblock" },
666                { selme => ($blockinfo->{type} eq 'in'), type => "in", disptype => "Internal netblock" },
667                ]
668        );
669  } else {
670    $page->param(disptype => $disp_alloctypes{$blockinfo->{type}});
671    $page->param(type => $blockinfo->{type});
672  }
673
674## node hack
675  my ($nodeid,$nodename) = getNodeInfo($ip_dbh, $webvar{block});
676  $page->param(havenodeid => $nodeid);
677
678  if ($blockinfo->{type} eq 'fr' || $blockinfo->{type} eq 'bi') {
679    $page->param(typesupportsnodes => 1);
680    $page->param(nodename => $nodename);
681
682##fixme:  this whole hack needs cleanup and generalization for all alloctypes
683##fixme:  arguably a bug that presence of a nodeid implies it can be changed..
684#  but except for manual database changes, only the two types fr and bi can
685#  (currently) have a nodeid set in the first place.
686    if ($IPDBacl{$authuser} =~ /c/) {
687      my $nlist = getNodeList($ip_dbh);
688      foreach (@{$nlist}) {
689        $$_{selme} = ($$_{node_id} == $nodeid);
690      }
691      $page->param(nodelist => $nlist);
692    }
693  }
694## end node hack
695
696  my ($lastmod,undef) = split /\s+/, $blockinfo->{lastmod};
697  $page->param(lastmod => $lastmod);
698
699  # not happy with the upside-down logic, but...
700  $page->param(swipable => $blockinfo->{type} !~ /.i/);
701  $page->param(swip => $blockinfo->{swip} ne 'n') if $blockinfo->{swip};
702
703  # Check to see if we can display sensitive data
704  $page->param(nocling => $IPDBacl{$authuser} =~ /s/);
705  $page->param(privdata => $blockinfo->{privdata});
706
707  # ACL trickery - these two template booleans control the presence of all form/input tags
708  $page->param(maychange => $IPDBacl{$authuser} =~ /c/);
709  $page->param(maydel => $IPDBacl{$authuser} =~ /d/);
710
711} # edit()
712
713
714# Stuff new info about a block into the db
715# action=update
716sub update {
717  if ($IPDBacl{$authuser} !~ /c/) {
718    $aclerr = 'updateblock';
719    return;
720  }
721
722  # Make sure incoming data is in correct format - custID among other things.
723  return if !validateInput;
724
725  $webvar{swip} = 'n' if !$webvar{swip};
726
727  my %updargs = (
728        custid          => $webvar{custid},
729        city            => $webvar{city},
730        description     => $webvar{desc},
731        notes           => $webvar{notes},
732        circuitid       => $webvar{circid},
733        block           => $webvar{block},
734        type            => $webvar{alloctype},
735        swip            => $webvar{swip},
736        );
737
738  # Semioptional values
739  $updargs{privdata} = $webvar{privdata} if $IPDBacl{$authuser} =~ /s/;
740  $updargs{node} = $webvar{node} if $webvar{node};
741
742  my ($code,$msg) = updateBlock($ip_dbh, %updargs);
743
744  if ($code eq 'FAIL') {
745    syslog "err", "$authuser could not update block/IP '$webvar{block}': '$msg'";
746    $page->param(err => "Could not update block/IP $webvar{block}: $msg");
747    return;
748  }
749
750  # If we get here, the operation succeeded.
751  syslog "notice", "$authuser updated $webvar{block}";
752##fixme:  log details of the change?  old way is in the .debug stream anyway.
753##fixme:  need to wedge something in to allow "update:field" notifications
754## hmm.  how to tell what changed?  O_o
755mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
756        "$webvar{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';
757
758## node hack
759  if ($webvar{node} && $webvar{node} ne '-') {
760    my $nodename = getNodeName($ip_dbh, $webvar{node});
761    $page->param(nodename => $nodename);
762  }
763## end node hack
764
765  # Link back to browse-routed or list-pool page on "Update complete" page.
766  my $cblock;
767  if (my $pooltype = ($webvar{alloctype} =~ /^(.)i$/) ) {
768    $page->param(backpool => 1);
769    $cblock = ipParent($ip_dbh, $webvar{block});
770  } else {
771    $cblock = blockParent($ip_dbh, $webvar{block});
772  }
773  $page->param(backblock => $cblock->{cidr});
774
775  # Do some HTML fiddling here instead of using ESCAPE=HTML in the template,
776  # because otherwise we can't convert \n to <br>.  *sigh*
777  $webvar{notes} = $q->escapeHTML($webvar{notes});      # escape first...
778  $webvar{notes} =~ s/\n/<br>\n/;                       # ... then convert newlines
779  $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : "&nbsp;");
780  $webvar{privdata} =~ s/\n/<br>\n/;
781
782  $page->param(cidr => $webvar{block});
783  $page->param(city => $webvar{city});
784  $page->param(disptype => $disp_alloctypes{$webvar{alloctype}});
785  $page->param(custid => $webvar{custid});
786  $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No');
787  $page->param(circid => $webvar{circid});
788  $page->param(desc => $webvar{desc});
789  $page->param(notes => $webvar{notes});
790  $page->param(privdata => $webvar{privdata})
791        if $IPDBacl{$authuser} =~ /s/;
792
793} # update()
794
795
796# Delete an allocation.
797sub remove {
798  if ($IPDBacl{$authuser} !~ /d/) {
799    $aclerr = 'delblock';
800    return;
801  }
802
803  # Serves'em right for getting here...
804  if (!defined($webvar{block})) {
805    $page->param(err => "Can't delete a block that doesn't exist");
806    return;
807  }
808
809  my $blockdata;
810
811  if ($webvar{alloctype} eq 'rm') {
812
813    $blockdata->{block} = $webvar{block};
814    $blockdata->{city} = getRoutedCity($ip_dbh, $webvar{block});
815    $blockdata->{custid} = "N/A";
816    $blockdata->{type} = $webvar{alloctype};
817    $blockdata->{circuitid} = "N/A";
818    $blockdata->{description} = "N/A";
819    $blockdata->{notes} = "N/A";
820    $blockdata->{privdata} = "N/A";
821
822  } elsif ($webvar{alloctype} eq 'mm') {
823
824    $blockdata->{block} = $webvar{block};
825    $blockdata->{city} = "N/A";
826    $blockdata->{custid} = "N/A";
827    $blockdata->{type} = $webvar{alloctype};
828    $blockdata->{circuitid} = "N/A";
829    $blockdata->{description} = "N/A";
830    $blockdata->{notes} = "N/A";
831    $blockdata->{privdata} = "N/A";
832
833  } else {
834
835    $blockdata = getBlockData($ip_dbh, $webvar{block})
836
837  } # end cases for different alloctypes
838
839  $page->param(block => $blockdata->{block});
840  $page->param(disptype => $disp_alloctypes{$blockdata->{type}});
841  $page->param(type => $blockdata->{type});
842  $page->param(city => $blockdata->{city});
843  $page->param(custid => $blockdata->{custid});
844  $page->param(circid => $blockdata->{circuitid});
845  $page->param(desc => $blockdata->{description});
846  $blockdata->{notes} = $q->escapeHTML($blockdata->{notes});
847  $blockdata->{notes} =~ s/\n/<br>\n/;
848  $page->param(notes => $blockdata->{notes});
849  $blockdata->{privdata} = $q->escapeHTML($blockdata->{privdata});
850  $blockdata->{privdata} = '&nbsp;' if !$blockdata->{privdata};
851  $blockdata->{privdata} =~ s/\n/<br>\n/;
852  $page->param(privdata => $blockdata->{privdata}) if $IPDBacl{$authuser} =~ /s/;
853  $page->param(delpool => $blockdata->{type} =~ /^.[pd]$/);
854
855} # end remove()
856
857
858# Delete an allocation.  Return it to the freeblocks table;  munge
859# data as necessary to keep as few records as possible in freeblocks
860# to prevent weirdness when allocating blocks later.
861# Remove IPs from pool listing if necessary
862sub finalDelete {
863  if ($IPDBacl{$authuser} !~ /d/) {
864    $aclerr = 'delblock';
865    return;
866  }
867
868  # need to retrieve block data before deleting so we can notify on that
869  my $blockinfo = getBlockData($ip_dbh, $webvar{block});
870
871  my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{alloctype});
872
873  $page->param(block => $webvar{block});
874  if ($code eq 'OK') {
875    syslog "notice", "$authuser deallocated '$webvar{alloctype}'-type netblock $webvar{block} ".
876        $blockinfo->{custid}.", ".$blockinfo->{city}.", desc='".$blockinfo->{description}."'";
877    mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$webvar{alloctype}} $webvar{block}",
878        "$disp_alloctypes{$webvar{alloctype}} $webvar{block} deallocated by $authuser\n".
879        "CustID: ".$blockinfo->{custid}."\nCity: ".$blockinfo->{city}.
880        "\nDescription: ".$blockinfo->{description}."\n");
881  } else {
882    $page->param(failmsg => $msg);
883    if ($webvar{alloctype} =~ /^.i$/) {
884      syslog "err", "$authuser could not deallocate static IP '$webvar{block}': '$msg'";
885    } else {
886      syslog "err", "$authuser could not deallocate netblock '$webvar{block}': '$msg'";
887      $page->param(netblock => 1);
888    }
889  }
890
891} # finalDelete
Note: See TracBrowser for help on using the repository browser.