source: trunk/cgi-bin/main.cgi @ 916

Last change on this file since 916 was 916, checked in by Kris Deugau, 4 years ago

/trunk

Continue adding a generalized block-notice system. See #17 and #23, sort of.
Add a retrieval sub for block notices to IPDB.pm
Wrap the new module sub in a local sub in main.cgi, since the primary

web-UI actions will be called from a number of places

Update the block assignment templates and call the new local sub for

block assignment

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author
File size: 60.6 KB
Line 
1#!/usr/bin/perl
2# ipdb/cgi-bin/main.cgi
3###
4# SVN revision info
5# $Date: 2018-05-01 17:29:29 +0000 (Tue, 01 May 2018) $
6# SVN revision $Rev: 916 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004-2016 - 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;
19use Frontier::Client;
20
21use Sys::Syslog;
22
23# don't remove!  required for GNU/FHS-ish install from tarball
24##uselib##
25
26# push "the directory the script is in" into @INC
27use FindBin;
28use lib "$FindBin::RealBin/";
29
30use CustIDCK;
31use MyIPDB;
32
33openlog "IPDB","pid","$IPDB::syslog_facility";
34
35## Environment.  Collect some things, process some things, set some things...
36
37# Collect the username from HTTP auth.  If undefined, we're in
38# a test environment, or called without a username.
39my $authuser;
40if (!defined($ENV{'REMOTE_USER'})) {
41  $authuser = '__temptest';
42} else {
43  $authuser = $ENV{'REMOTE_USER'};
44}
45
46# anyone got a better name?  :P
47my $thingroot = $ENV{SCRIPT_FILENAME};
48$thingroot =~ s|cgi-bin/main.cgi||;
49
50syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";
51
52##fixme there *must* be a better order to do things in so this can go back where it was
53# CGI fiddling done here so we can declare %webvar so we can alter $webvar{action}
54# to show the right page on DB errors.
55# Set up the CGI object...
56my $q = new CGI::Simple;
57# ... and get query-string params as well as POST params if necessary
58$q->parse_query_string;
59
60# Convenience;  saves changing all references to %webvar
61##fixme:  tweak for handling <select multiple='y' size=3> (list with multiple selection)
62my %webvar = $q->Vars;
63
64# Why not a global DB handle?  (And a global statement handle, as well...)
65# Use the connectDB function, otherwise we end up confusing ourselves
66my $ip_dbh;
67my $errstr;
68($ip_dbh,$errstr) = connectDB_My;
69if (!$ip_dbh) {
70  $webvar{action} = "dberr";
71} else {
72  initIPDBGlobals($ip_dbh);
73}
74
75# Set up some globals
76$ENV{HTML_TEMPLATE_ROOT} = $thingroot;
77my @templatepath = [ "localtemplates", "templates" ];
78
79my $header = HTML::Template->new(filename => "header.tmpl", path => @templatepath);
80my $footer = HTML::Template->new(filename => "footer.tmpl", path => @templatepath);
81my $utilbar = HTML::Template->new(filename => "utilbar.tmpl", loop_context_vars => 1, global_vars => 1,
82        path => @templatepath);
83
84print "Content-type: text/html\n\n";
85
86$header->param(version => $IPDB::VERSION);
87$header->param(addperm => $IPDBacl{$authuser} =~ /a/);
88$header->param(webpath => $IPDB::webpath);
89
90$utilbar->param(webpath => $IPDB::webpath);
91
92print $header->output;
93
94##fixme:  whine and complain when the user is not present in the ACL hash above
95
96#main()
97my $aclerr;
98
99if(!defined($webvar{action})) {
100  $webvar{action} = "index";    #shuts up the warnings.
101}
102
103my $page;
104if (-e "$ENV{HTML_TEMPLATE_ROOT}/templates/$webvar{action}.tmpl") {
105  $page = HTML::Template->new(filename => "$webvar{action}.tmpl", loop_context_vars => 1, global_vars => 1,
106        path => @templatepath);
107} else {
108  $page = HTML::Template->new(filename => "dunno.tmpl", die_on_bad_params => 0,
109        path => @templatepath);
110}
111
112if($webvar{action} eq 'index') {
113  showSummary();
114} elsif ($webvar{action} eq 'showvrf') {
115  showVRF();
116
117} elsif ($webvar{action} eq 'addvrf') {
118  if ($IPDBacl{$authuser} !~ /s/) {
119    $aclerr = 'addvrf';
120  }
121
122  # Retrieve the list of DNS locations if we've got a place to grab them from
123  if ($IPDB::rpc_url) {
124    my %rpcargs = (
125        rpcuser => $authuser,
126        group => 1,     # bleh
127        defloc => '',
128        );
129    my $result = IPDB::_rpc('getLocDropdown', %rpcargs);
130    $page->param(loclist => $result);
131  }
132
133} elsif ($webvar{action} eq 'newvrf') {
134  if ($IPDBacl{$authuser} !~ /s/) {
135    $aclerr = 'addvrf';
136  } else {
137    my ($code,$msg) = addVRF($ip_dbh, $webvar{vrf}, comment => $webvar{comment}, location => $webvar{loc});
138
139    if ($code eq 'FAIL') {
140      syslog "err", "Could not add VRF '$webvar{vrf}' to database: '$msg'";
141      $page->param(err => $msg);
142      $page->param(vrf => $webvar{vrf});
143    } else {
144      $page->param(vrf => $msg);
145      if ($code eq 'WARN') {
146        $IPDB::errstr =~ s/\n\n/<br>\n/g;
147        $IPDB::errstr =~ s/:\n/:<br>\n/g;
148        $page->param(warn => $IPDB::errstr);
149      }
150      syslog "info", "$authuser added VRF $webvar{vrf}";
151    }
152
153  } # ACL check
154
155} elsif ($webvar{action} eq 'delvrf') {
156  if ($IPDBacl{$authuser} !~ /s/) {
157    $aclerr = 'delvrf';
158  }
159
160  my $vrf = getVRF($ip_dbh, $webvar{vrf});
161
162  $page->param(vrf => $webvar{vrf});
163  $page->param(vrfcomment => $vrf->{comment});
164
165} elsif ($webvar{action} eq 'finaldelvrf') {
166  if ($IPDBacl{$authuser} !~ /s/) {
167    $aclerr = 'finaldelvrf';
168  }
169
170  my $vrf = getVRF($ip_dbh, $webvar{vrf});
171  $page->param(vrf => $webvar{vrf});
172  $page->param(vrfcomment => $vrf->{comment});
173
174  my ($code,$msg) = deleteVRF($ip_dbh, $webvar{vrf}, $authuser);
175
176  if ($code eq 'FAIL') {
177    $page->param(failmsg => $msg);
178  }
179
180} elsif ($webvar{action} eq 'addmaster') {
181  if ($IPDBacl{$authuser} !~ /a/) {
182    $aclerr = 'addmaster';
183  }
184
185  my $vrf = getVRF($ip_dbh, $webvar{vrf});
186
187  # Retrieve the list of DNS locations if we've got a place to grab them from
188  if ($IPDB::rpc_url) {
189    my %rpcargs = (
190        rpcuser => $authuser,
191        group => 1,     # bleh
192        defloc => $vrf->{location},
193        );
194    my $result = IPDB::_rpc('getLocDropdown', %rpcargs);
195    $page->param(loclist => $result);
196  }
197
198  # we don't have a netblock;  pass 0 for the block ID
199  # Tree navigation
200  my $crumbs = getBreadCrumbs($ip_dbh, 0, $webvar{vrf});
201  my @rcrumbs = reverse (@$crumbs);
202  $utilbar->param(breadcrumb => \@rcrumbs);
203
204  $page->param(vrf => $webvar{vrf});
205
206} elsif ($webvar{action} eq 'newmaster') {
207
208  if ($IPDBacl{$authuser} !~ /a/) {
209    $aclerr = 'addmaster';
210  } else {
211    my $cidr = new NetAddr::IP $webvar{cidr};
212    $page->param(cidr => "$cidr");
213
214    my ($code,$msg) = addMaster($ip_dbh, $webvar{cidr}, (vrf => $webvar{vrf}, rdns => $webvar{rdns}, 
215        rwhois => $webvar{rwhois}, defloc => $webvar{loc}, user => $authuser) );
216
217    if ($code eq 'FAIL') {
218      syslog "err", "Could not add master block '$webvar{cidr}' to database: '$msg'";
219      $page->param(err => $msg);
220    } else {
221      $page->param(parent => $msg);
222      if ($code eq 'WARN') {
223        $IPDB::errstr =~ s/\n\n/<br>\n/g;
224        $IPDB::errstr =~ s/:\n/:<br>\n/g;
225        $page->param(warn => $IPDB::errstr);
226      }
227      syslog "info", "$authuser added master block $webvar{cidr}";
228    }
229
230    # we don't have a netblock;  pass 0 for the block ID
231    # Tree navigation
232    my $crumbs = getBreadCrumbs($ip_dbh, 0, $webvar{vrf});
233    my @rcrumbs = reverse (@$crumbs);
234    $utilbar->param(breadcrumb => \@rcrumbs);
235
236  } # ACL check
237
238} # end add new master
239
240elsif ($webvar{action} eq 'showsubs') {
241  showSubs();
242}
243
244elsif($webvar{action} eq 'listpool') {
245  showPool();
246}
247
248# Not modified or added;  just shuffled
249elsif($webvar{action} eq 'assign') {
250  assignBlock();
251}
252elsif($webvar{action} eq 'confirm') {
253  confirmAssign();
254}
255elsif($webvar{action} eq 'insert') {
256  insertAssign();
257}
258elsif($webvar{action} eq 'edit') {
259  edit();
260}
261elsif($webvar{action} eq 'update') {
262  update();
263}
264elsif($webvar{action} eq 'split') {
265  prepSplit();
266}
267elsif($webvar{action} eq 'dosplit') {
268  doSplit();
269}
270elsif($webvar{action} eq 'merge') {
271  prepMerge();
272}
273elsif($webvar{action} eq 'confmerge') {
274  confMerge();
275}
276elsif($webvar{action} eq 'domerge') {
277  doMerge();
278}
279elsif($webvar{action} eq 'delete') {
280  remove();
281}
282elsif($webvar{action} eq 'finaldelete') {
283  finalDelete();
284}
285elsif ($webvar{action} eq 'nodesearch') {
286  my $nodelist = getNodeList($ip_dbh);
287  $page->param(nodelist => $nodelist);
288}
289
290# DB failure.  Can't do much here, really.
291elsif ($webvar{action} eq 'dberr') {
292  $page->param(errmsg => $errstr);
293}
294
295# Default is an error.  It shouldn't be possible to get here unless you're
296# randomly feeding in values for webvar{action}.
297else {
298  my $rnd = rand 500;
299  my $boing = sprintf("%.2f", rand 500);
300  my @excuses = (
301        "Aether cloudy.  Ask again later about $webvar{action}.",
302        "The gods are unhappy with your sacrificial $webvar{action}.",
303        "Because one of $webvar{action}'s legs are both the same",
304        "<b>wibble</b><br>Can't $webvar{action}, the grue will get me!<br>Can't $webvar{action}, the grue will get me!",
305        "Hey, man, you've had your free $webvar{action}.  Next one's gonna...  <i>cost</i>....",
306        "I ain't done $webvar{action}",
307        "Oooo, look!  A flying $webvar{action}!",
308        "$webvar{action} too evil, avoiding.",
309        "Rocks fall, $webvar{action} dies.",
310        "Bit bucket must be emptied before I can $webvar{action}..."
311        );
312  $page->param(dunno => $excuses[$rnd/50.0]);
313}
314## Finally! Done with that NASTY "case" emulation!
315
316
317# Switch to a different template if we've tripped on an ACL error.
318# Note that this should only be exercised in development, when
319# deeplinked, or when being attacked;  normal ACL handling should
320# remove the links a user is not allowed to click on.
321if ($aclerr) {
322  $page = HTML::Template->new(filename => "aclerror.tmpl", path => @templatepath);
323  $page->param(ipdbfunc => $aclmsg{$aclerr});
324}
325
326# Clean up IPDB globals, DB handle, etc.
327finish($ip_dbh);
328
329## Do all our printing here so we can generate errors and stick them into the slots in the templates.
330
331# can't do this yet, too many blowups
332#print "Content-type: text/html\n\n", $header->output;
333$page->param(webpath => $IPDB::webpath);
334print $utilbar->output;
335print $page->output;
336
337# include the admin tools link in the output?
338$footer->param(adminlink => ($IPDBacl{$authuser} =~ /A/));
339$footer->param(webpath => $IPDB::webpath);
340print $footer->output;
341
342# Just in case something waaaayyy down isn't in place
343# properly... we exit explicitly.
344exit 0;
345
346
347# Initial display:  Show list of VRFs
348sub showSummary {
349  my $vrflist = listVRF($ip_dbh);
350
351  if ($IPDB::masterswithvrfs == 2) {
352    $page = HTML::Template->new(filename => "index2.tmpl", loop_context_vars => 1, global_vars => 1,
353        path => @templatepath);
354    # alternate layout;  put master blocks on the front summary page instead of "out"/"down" a
355    # layer in the browse tree.  Leaving the manual include of showvrf.tmpl for reference;  not
356    # sure why setting webpath here didn't seem to make it to the output.
357#    my $vrfinfo = HTML::Template->new(filename => "showvrf.tmpl", path => @templatepath);
358    foreach my $vrf (@$vrflist) {
359      my $masterlist = listSummary($ip_dbh, $vrf->{vrf});
360      $vrf->{masterlist} = $masterlist;
361      $vrf->{addmaster} = ($IPDBacl{$authuser} =~ /s/);
362      $vrf->{maydel} = ($IPDBacl{$authuser} =~ /s/);
363      $vrf->{sub} = 1;
364#      $vrfinfo->param(vrf => $vrf->{vrf});
365#      $vrfinfo->param(masterlist => $masterlist);
366#      $vrfinfo->param(addmaster => ($IPDBacl{$authuser} =~ /s/) );
367#      $vrfinfo->param(maydel => ($IPDBacl{$authuser} =~ /s/) );
368#      $vrfinfo->param(sub => 1);
369#      $vrfinfo->param(webpath => $IPDB::webpath);
370#      $vrf->{vrfinfo} = $vrfinfo->output;
371    }
372  }
373
374  $page->param(vrflist => $vrflist);
375
376  # Only systems/network should be allowed to add VRFs - or maybe higher?
377  $page->param(addvrf => ($IPDBacl{$authuser} =~ /s/) );
378
379} # showSummary
380
381
382# Show IP blocks in a VRF
383sub showVRF {
384  my $masterlist = listSummary($ip_dbh, $webvar{vrf});
385  $page->param(vrf => $webvar{vrf});
386  $page->param(masterlist => $masterlist);
387
388  # we don't have a netblock;  pass 0 for the block ID
389  # Tree navigation
390  my $crumbs = getBreadCrumbs($ip_dbh, 0, $webvar{vrf});
391  my @rcrumbs = reverse (@$crumbs);
392  $utilbar->param(breadcrumb => \@rcrumbs);
393
394  $page->param(maydel => ($IPDBacl{$authuser} =~ /s/) );
395  $page->param(addmaster => ($IPDBacl{$authuser} =~ /s/) );
396} # showVRF
397
398
399# Display blocks immediately within a given parent
400sub showSubs {
401  # Which layout?
402  if ($IPDB::sublistlayout == 2) {
403
404    # 2-part layout;  mixed containers and end-use allocations and free blocks.
405    # Containers have a second line for the subblock metadata.
406    # We need to load an alternate template for this case.
407    $page = HTML::Template->new(filename => "showsubs2.tmpl", loop_context_vars => 1, global_vars => 1,
408        path => @templatepath);
409
410    $page->param(maydel => ($IPDBacl{$authuser} =~ /d/));
411
412    my $sublist = listSubs($ip_dbh, parent => $webvar{parent});
413    $page->param(sublist => $sublist);
414
415  } else {
416
417    # 3-part layout;  containers, end-use allocations, and free blocks
418
419    my $contlist = listContainers($ip_dbh, parent => $webvar{parent});
420    $page->param(contlist => $contlist);
421
422    my $alloclist = listAllocations($ip_dbh, parent => $webvar{parent});
423    $page->param(alloclist => $alloclist);
424
425    # only show "delete" button if we have no container or usage allocations
426    $page->param(maydel => ($IPDBacl{$authuser} =~ /d/) && !(@$contlist || @$alloclist));
427
428  }
429
430  # Common elements
431  my $pinfo = getBlockData($ip_dbh, $webvar{parent});
432  $page->param(blockpctfree => sprintf("%0.1f", $pinfo->{nfree}/2**(32-$pinfo->{masklen}) * 100 ) );
433
434##fixme:  do we add a wrapper to not show the edit link for master blocks?
435#$page->param(editme => 1) unless $pinfo->{type} ne 'mm';
436
437  my $crumbs = getBreadCrumbs($ip_dbh, $pinfo->{parent_id}, $pinfo->{vrf});
438  my @rcrumbs = reverse (@$crumbs);
439  $utilbar->param(breadcrumb => \@rcrumbs);
440
441  $page->param(self_id => $webvar{parent});
442  $page->param(block => $pinfo->{block});
443  $page->param(mayadd => ($IPDBacl{$authuser} =~ /a/));
444
445  my $flist = listFree($ip_dbh, parent => $webvar{parent});
446  $page->param(freelist => $flist);
447} # showSubs
448
449
450# List the IPs used in a pool
451sub showPool {
452
453  my $poolinfo = getBlockData($ip_dbh, $webvar{pool});
454  my $cidr = new NetAddr::IP $poolinfo->{block};
455  $page->param(vlan => $poolinfo->{vlan});
456  $page->param(poolpctfree => sprintf("%0.1f", $poolinfo->{nfree}/2**(32-$poolinfo->{masklen}) * 100 ) );
457
458  # Tree navigation
459  my $crumbs = getBreadCrumbs($ip_dbh, $poolinfo->{parent_id});
460  my @rcrumbs = reverse (@$crumbs);
461  $utilbar->param(breadcrumb => \@rcrumbs);
462
463  $page->param(block => $cidr);
464  $page->param(netip => $cidr->addr);
465  $cidr++;
466  $page->param(gate => $cidr->addr);
467  $cidr--;  $cidr--;
468  $page->param(bcast => $cidr->addr);
469  $page->param(mask => $cidr->mask);
470
471  $page->param(disptype => $disp_alloctypes{$poolinfo->{type}});
472  $page->param(city => $poolinfo->{city});
473
474  # Only display net/gw/bcast if it's a "real" netblock and not a PPP(oE) lunacy
475  $page->param(realblock => $poolinfo->{type} =~ /^.d$/);
476
477# probably have to add an "edit IP allocation" link here somewhere.
478
479  # this will cascade into the IP list below
480  $page->param(maydel => $IPDBacl{$authuser} =~ /d/);
481
482  my $plist = listPool($ip_dbh, $webvar{pool}, 1);
483  $page->param(poolips => $plist);
484} # end showPool
485
486
487# Show "Add new allocation" page.  Note that the actual page may
488# be one of two templates, and the lists come from the database.
489sub assignBlock {
490
491  if ($IPDBacl{$authuser} !~ /a/) {
492    $aclerr = 'addblock';
493    return;
494  }
495
496  # hack pthbttt eww
497  $webvar{parent} = 0 if !$webvar{parent};
498  $webvar{block} = '' if !$webvar{block};
499
500  $page->param(allocfrom => $webvar{block});    # fb-assign flag, if block is set, we're in fb-assign
501
502  if ($webvar{fbid} || $webvar{fbtype}) {
503
504    # Common case, according to reported usage.  Block to assign is specified.
505    my $block = new NetAddr::IP $webvar{block};
506
507    my ($rdns,$cached) = getBlockRDNS($ip_dbh, id => $webvar{parent}, type => $webvar{fbtype}, user => $authuser);
508    $page->param(rdns => $rdns) if $rdns;
509    $page->param(parent => $webvar{parent});
510    $page->param(fbid => $webvar{fbid});
511    # visual flag that we're working IPDB-local, not off more authoritative data in dnsadmin
512    $page->param(cached => $cached);
513
514    my $pinfo = getBlockData($ip_dbh, $webvar{parent});
515
516    # retrieve any notices
517    blocknotices($webvar{parent});
518
519    my @cities;
520    foreach my $city (@citylist) {
521      my %row = (city => $city, sel => ($pinfo->{city} eq $city) );
522      push (@cities, \%row);
523    }
524    $page->param(preselected => 1);
525    $page->param(citylist => \@cities);
526
527    # Tree navigation
528    my $crumbs = getBreadCrumbs($ip_dbh, $webvar{parent});
529    my @rcrumbs = reverse (@$crumbs);
530    $utilbar->param(breadcrumb => \@rcrumbs);
531
532    $webvar{fbtype} = '' if !$webvar{fbtype};
533    if ($webvar{fbtype} eq 'i') {
534      my $ipinfo = getBlockData($ip_dbh, $webvar{block}, 'i');
535      $page->param(
536        fbip => 1,
537        block => $ipinfo->{block},
538        fbdisptype => $list_alloctypes{$ipinfo->{type}},
539        type => $ipinfo->{type},
540        allocfrom => $pinfo->{block},
541        );
542    } else {
543      # get "primary" alloctypes, since these are all that can correctly be assigned if we're in this branch
544      my $tlist = getTypeList($ip_dbh, 'n');
545      $tlist->[0]->{sel} = 1;
546      $page->param(typelist => $tlist, block => $block);
547    }
548
549  } else {
550
551    # Uncommon case, according to reported usage.  Block to assign needs to be found based on criteria.
552    my $mlist = getMasterList($ip_dbh, 'c');
553    $page->param(masterlist => $mlist);
554
555    my @pops;
556    foreach my $pop (@citylist) {
557      my %row = (pop => $pop);
558      push (@pops, \%row);
559    }
560    $page->param(pops => \@pops);
561
562    my @cities;
563    foreach my $city (@citylist) {
564      my %row = (city => $city);
565      push (@cities, \%row);
566    }
567    $page->param(citylist => \@cities);
568
569    # get all standard alloctypes
570    my $tlist = getTypeList($ip_dbh, 'a');
571    $tlist->[0]->{sel} = 1;
572    $page->param(typelist => $tlist);
573  }
574
575## node hack
576  my $nlist = getNodeList($ip_dbh);
577  $page->param(nodelist => $nlist);
578## end node hack
579
580  $page->param(nocling => $IPDBacl{$authuser} =~ /s/);
581
582} # assignBlock
583
584
585# Take info on requested IP assignment and see what we can provide.
586sub confirmAssign {
587  if ($IPDBacl{$authuser} !~ /a/) {
588    $aclerr = 'addblock';
589    return;
590  }
591
592  my $cidr;
593  my $resv;   # Reserved for expansion.
594  my $alloc_from;
595  my $fbid = $webvar{fbid};
596  my $p_id = $webvar{parent};
597
598  # Going to manually validate some items.
599  # custid and city are automagic.
600  return if !validateInput();
601
602  # make sure this is defined
603  $webvar{fbassign} = 'n' if !$webvar{fbassign};
604
605# Several different cases here.
606# Static IP vs netblock
607#  + Different flavours of static IP
608#  + Different flavours of netblock
609
610  if ($webvar{alloctype} =~ /^.i$/ && $webvar{fbassign} ne 'y') {
611    if (!$webvar{pop}) {
612      $page->param(err => "Please select a location/POP site to allocate from.");
613      return;
614    }
615    my $plist = getPoolSelect($ip_dbh, $webvar{alloctype}, $webvar{pop});
616    $page->param(staticip => 1);
617    $page->param(poollist => $plist) if $plist;
618    $cidr = "Single static IP";
619##fixme:  need to handle "no available pools"
620
621  } else { # end show pool options
622
623    if ($webvar{fbassign} && $webvar{fbassign} eq 'y') {
624
625      # Tree navigation
626      my $crumbs = getBreadCrumbs($ip_dbh, $webvar{parent});
627      my @rcrumbs = reverse (@$crumbs);
628      $utilbar->param(breadcrumb => \@rcrumbs);
629
630      $cidr = new NetAddr::IP $webvar{block};
631      $alloc_from = new NetAddr::IP $webvar{allocfrom};
632      $webvar{maskbits} = $cidr->masklen;
633      # Some additional checks are needed for reserving free space
634      if ($webvar{reserve}) {
635        if ($cidr == $alloc_from) {
636# We could still squirm and fiddle to try to find a way to reserve space, but the storage model for
637# IPDB means that all continguous free space is kept in the smallest number of strict CIDR netblocks
638# possible.  (In theory.)  If the request and the freeblock are the same, it is theoretically impossible
639# to reserve an equivalent-sized block either ahead or behind the requested one, because the pair
640# together would never be a strict CIDR block.
641          $page->param(warning => "Can't reserve space for expansion;  free block and requested allocation are the same.");
642          delete $webvar{reserve};
643        } else {
644          # Find which new free block will match the reqested block.
645          # Take the requested mask, shift by one
646          my $tmpmask = $webvar{maskbits};
647          $tmpmask--;
648          # find the subnets with that mask in the selected free block
649          my @pieces = $alloc_from->split($tmpmask);
650          foreach my $slice (@pieces) {
651            if ($slice->contains($cidr)) {
652              # For the subnet that contains the requested block, split that in two,
653              # and flag/cache the one that's not the requested block.
654              my @bits = $slice->split($webvar{maskbits});
655              if ($bits[0] == $cidr) {
656                $resv = $bits[1];
657              } else {
658                $resv = $bits[0];
659              }
660            }
661          }
662        }
663      } # reserve block check
664
665    } else { # done with direct freeblocks assignment
666
667      if (!$webvar{maskbits}) {
668        $page->param(err => "Please specify a CIDR mask length.");
669        return;
670      }
671
672##fixme ick, ew, bleh.  gotta handle the failure message generation better.  push it into findAllocateFrom()?
673      my $failmsg = "No suitable free block found.<br>\n";
674      if ($webvar{alloctype} eq 'rm') {
675        $failmsg .= "We do not have a free routeable block of that size.<br>\n".
676                "You will have to either route a set of smaller netblocks or a single smaller netblock.";
677      } else {
678        if ($webvar{alloctype} =~ /^.[pc]$/) {
679          $failmsg .= "You will have to route another superblock from one of the<br>\n".
680                "master blocks or chose a smaller block size for the pool.";
681        } else {
682          if (!$webvar{pop}) {
683            $page->param(err => 'Please select a POP to route the block from/through.');
684            return;
685          }
686          $failmsg .= "You will have to route another superblock to $webvar{pop}<br>\n".
687                "from one of the master blocks";
688          if ($webvar{reserve}) {
689            $failmsg .= ', choose a smaller blocksize, or uncheck "Reserve space for expansion".';
690          } else {
691            $failmsg .= " or chose a smaller blocksize.";
692          }
693        }
694      }
695
696      # if requesting extra space "reserved for expansion", we need to find a free
697      # block at least double the size of the request.
698      if ($webvar{reserve}) {
699        $webvar{maskbits}--;
700      }
701
702      ($fbid,$cidr,$p_id) = findAllocateFrom($ip_dbh, $webvar{maskbits}, $webvar{alloctype},
703        $webvar{city}, $webvar{pop}, (master => $webvar{allocfrom}, allowpriv => $webvar{allowpriv}) );
704      if (!$cidr) {
705        $page->param(err => $failmsg);
706        return;
707      }
708      $cidr = new NetAddr::IP $cidr;
709
710      $alloc_from = "$cidr";
711
712      # when autofinding a block to allocate from, use the first piece of the found
713      # block for the allocation, and the next piece for the "reserved for expansion".
714      if ($webvar{reserve}) {
715        # reset the mask to the real requested one, now that we've got a
716        # block large enough for the request plus reserve
717        $webvar{maskbits}++;
718        ($cidr,$resv) = $cidr->split($webvar{maskbits});
719      }
720
721      # If the block to be allocated is smaller than the one we found,
722      # figure out the "real" block to be allocated.
723      if ($cidr->masklen() ne $webvar{maskbits}) {
724        my $maskbits = $cidr->masklen();
725        # we reset $cidr each time around the loop to better allow for the huge
726        # address space of IPv6;  many allocation schemes in v6 will break NetAddr::IP's
727        # hard limit of 65536 subnets from a split()
728        while ($maskbits++ < $webvar{maskbits}) {
729          $cidr = ($cidr->split($maskbits))[0];
730        }
731      }
732    } # check for freeblocks assignment or IPDB-controlled assignment
733
734    # Generate the IP list for the new allocation in case someone wants to set per-IP rDNS right away.
735    # We don't do this on the previous page because we don't know how big a block or even what IP range
736    # it's for (if following the "normal" allocation process)
737    if ($IPDBacl{$authuser} =~ /c/
738        && $cidr->masklen != $cidr->bits
739        && ($cidr->bits - $cidr->masklen) <= $IPDB::maxrevlist
740        # config flag for "all block types" OR "not-a-pool-or-IP type"
741        && ($IPDB::revlistalltypes || $webvar{alloctype} !~ /^.[dpi]/)
742        # safety against trying to retrieve and display more than 1k (10 bits, /22 v4) worth of individual IPs
743        # ever.  If you really need to manage a long list of IPs like that all in one place, you can use the DNS
744        # management tool.  Even a /26 is a bit much, really.
745        && ($cidr->bits - $cidr->masklen) <= 10
746        # do we want to allow v6 at all?
747        #&& ! $cidr->{isv6}
748        ) {
749      my @list;
750      foreach my $ip (@{$cidr->splitref()}) {
751        my %row;
752        $row{r_ip} = $ip->addr;
753        $row{iphost} = '';
754        push @list, \%row;
755      }
756      $page->param(r_iplist => \@list);
757      # We don't use this here, because these IPs should already be bare.
758      # ... or should we be paranoid?  Make it a config option?
759      #getRDNSbyIP($ip_dbh, type => $webvar{alloctype}, range => "$cidr", user => $authuser) );
760    }
761  } # if ($webvar{alloctype} =~ /^.i$/)
762
763## node hack
764  if ($webvar{node} && $webvar{node} ne '-') {
765    my $nodename = getNodeName($ip_dbh, $webvar{node});
766    $page->param(nodename => $nodename);
767    $page->param(nodeid => $webvar{node});
768  }
769## end node hack
770
771  # flag DNS info if we can't publish the entry remotely
772  my $pinfo = getBlockData($ip_dbh, $webvar{parent});
773  $page->param(dnslocal => 1) unless ($pinfo->{revpartial} || $pinfo->{revavail});
774
775  # retrieve any notices
776  blocknotices($webvar{parent});
777
778  # reserve for expansion
779  $page->param(reserve => $webvar{reserve});
780  # probably just preventing a little log noise doing this;  could just set the param
781  # all the time since it won't be shown if the reserve param above isn't set.
782#  if ($webvar{reserve}) {
783    $page->param(resvblock => $resv);
784#  }
785
786  # Stick in the allocation data
787  $page->param(alloc_type => $webvar{alloctype});
788  $page->param(typefull => $q->escapeHTML($disp_alloctypes{$webvar{alloctype}}));
789  $page->param(alloc_from => $alloc_from);
790  $page->param(parent => $p_id);
791  $page->param(fbid => $fbid);
792  $page->param(cidr => $cidr);
793  $page->param(rdns => $webvar{rdns});
794  $page->param(vrf => $webvar{vrf});
795  $page->param(vlan => $webvar{vlan});
796  $page->param(city => $q->escapeHTML($webvar{city}));
797  $page->param(custid => $webvar{custid});
798  $page->param(circid => $q->escapeHTML($webvar{circid}));
799  $page->param(desc => $q->escapeHTML($webvar{desc}));
800
801##fixme: find a way to have the displayed copy have <br> substitutions
802# for newlines, and the <input> value have either encoded or bare newlines.
803# Also applies to privdata.
804  $page->param(notes => $q->escapeHTML($webvar{notes},'y'));
805
806  # Check to see if user is allowed to do anything with sensitive data
807  if ($IPDBacl{$authuser} =~ /s/) {
808    $page->param(nocling => 1);
809    $page->param(privdata => $q->escapeHTML($webvar{privdata},'y'));
810
811    $page->param(backupfields => $webvar{backupfields});
812    $page->param(bkbrand => $webvar{bkbrand});
813    $page->param(bkmodel => $webvar{bkmodel});
814    $page->param(bktype  => $webvar{bktype});
815    $page->param(bksrc   => $webvar{bksrc});
816    $page->param(bkuser  => $webvar{bkuser});
817    # these two could use virtually any character
818    $page->param(bkvpass => $q->escapeHTML($webvar{bkvpass}));
819    $page->param(bkepass => $q->escapeHTML($webvar{bkepass}));
820    $page->param(bkport  => $webvar{bkport});
821    $page->param(bkip    => $webvar{bkip});
822  }
823
824  # Yay!  This now has it's very own little home.
825  $page->param(billinguser => $webvar{userid})
826        if $webvar{userid};
827
828  syslog "debug", "billinguser used ($authuser): alloc_from $alloc_from, type $webvar{alloctype}" if $webvar{userid};
829
830##fixme:  this is only needed iff confirm.tmpl and
831# confirmRemove.tmpl are merged (quite possible, just
832# a little tedious)
833  $page->param(action => "insert");
834
835} # end confirmAssign
836
837
838# Do the work of actually inserting a block in the database.
839sub insertAssign {
840  if ($IPDBacl{$authuser} !~ /a/) {
841    $aclerr = 'addblock';
842    return;
843  }
844  # Some things are done more than once.
845  return if !validateInput();
846
847##fixme: permission check
848  if (!defined($webvar{privdata})) {
849    $webvar{privdata} = '';
850  }
851
852  # $code is "success" vs "failure", $msg contains OK for a
853  # successful netblock allocation, the IP allocated for static
854  # IP, or the error message if an error occurred.
855
856##fixme:  consider just passing \%webvar to allocateBlock()?
857  # collect per-IP rDNS fields.  only copy over the ones that actually have something in them.
858  my %iprev;
859  foreach (keys %webvar) {
860    $iprev{$_} = $webvar{$_} if /host_[\d.a-fA-F:]+/ && $webvar{$_};
861  }
862
863  # Easier to see and cosmetically fiddle the list like this
864  my %insert_args = (
865        cidr            => $webvar{fullcidr},
866        fbid            => $webvar{fbid},
867        reserve         => $webvar{reserve},
868        parent          => $webvar{parent},
869        custid          => $webvar{custid},
870        type            => $webvar{alloctype},
871        city            => $webvar{city}, 
872        desc            => $webvar{desc},
873        notes           => $webvar{notes},
874        circid          => $webvar{circid},
875        privdata        => $webvar{privdata},
876        nodeid          => $webvar{node},
877        rdns            => $webvar{rdns},
878        vrf             => $webvar{vrf},
879        vlan            => $webvar{vlan},
880        user            => $authuser,
881        );
882
883##fixme: permission check
884  # fill in backup data, if present/allowed
885  if ($webvar{backupfields}) {
886    $insert_args{backup} = 1;
887    for my $bkfield (@IPDB::backupfields) {
888      $insert_args{"bk$bkfield"} = ($webvar{"bk$bkfield"} ? $webvar{"bk$bkfield"} : '');
889    }
890  }
891
892  my $pinfo = getBlockData($ip_dbh, $webvar{parent});
893
894  # clean up a minor mess with guided allocation of static IPs
895  if ($webvar{alloctype} =~ /^.i$/) {
896    $insert_args{alloc_from} = $pinfo->{block};
897  }
898
899  my ($code,$msg) = allocateBlock($ip_dbh, %insert_args, iprev => \%iprev);
900
901  if ($code eq 'OK') {
902    # breadcrumbs lite!  provide at least a link to the parent of the block we just allocated.
903    $page->param(parentid => $webvar{parent});
904    $page->param(parentblock => $pinfo->{block});
905
906    if ($webvar{alloctype} =~ /^.i$/) {
907      $msg =~ s|/32||;
908      $page->param(staticip => $msg);
909      $page->param(custid => $webvar{custid});
910      $page->param(billinguser => $webvar{billinguser});
911      $page->param(billinglink => $IPDB::billinglink);
912      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
913        "$disp_alloctypes{$webvar{alloctype}} $msg allocated to customer $webvar{custid}\n".
914        "Description: $webvar{desc}\n".
915        ($webvar{rdns} ? "DNS name: $webvar{rdns}\n" : '').
916        "\nAllocated by: $authuser\n");
917    } else {
918      my $netblock = new NetAddr::IP $webvar{fullcidr};
919      $page->param(fullcidr => $webvar{fullcidr});
920      $page->param(alloctype => $disp_alloctypes{$webvar{alloctype}});
921      $page->param(custid => $webvar{custid});
922
923      # Full breadcrumbs
924      my $crumbs = getBreadCrumbs($ip_dbh, $webvar{parent});
925      my @rcrumbs = reverse (@$crumbs);
926      $utilbar->param(breadcrumb => \@rcrumbs);
927
928      if ($webvar{alloctype} eq 'pr' && $webvar{billinguser}) {
929        $page->param(billinguser => $webvar{billinguser});
930        $page->param(billinglink => $IPDB::billinglink);
931        $page->param(custid => $webvar{custid});
932        $page->param(netaddr => $netblock->addr);
933        $page->param(masklen => $netblock->masklen);
934      }
935      syslog "debug", "billinguser used ($authuser): allocated $netblock, type $webvar{alloctype}" if $webvar{billinguser};
936      mailNotify($ip_dbh, "a$webvar{alloctype}", "ADDED: $disp_alloctypes{$webvar{alloctype}} allocation",
937        "$disp_alloctypes{$webvar{alloctype}} $webvar{fullcidr} allocated to customer $webvar{custid}\n".
938        "Description: $webvar{desc}\n".
939        ($webvar{rdns} ? "DNS name/pattern: $webvar{rdns}\n" : '').
940        "\nAllocated by: $authuser\n");
941    }
942    syslog "notice", "$authuser allocated '$webvar{fullcidr}' to '$webvar{custid}' as ".
943        "'$webvar{alloctype}' ($msg)";
944  } else {
945    syslog "err", "Allocation of '$webvar{fullcidr}' to '$webvar{custid}' as ".
946        "'$webvar{alloctype}' by $authuser failed: '$msg'";
947    $page->param(err => "Allocation of $webvar{fullcidr} as '$disp_alloctypes{$webvar{alloctype}}' failed:");
948    $page->param(errmsg => $msg);
949  }
950
951} # end insertAssign()
952
953
954# Does some basic checks on common input data to make sure nothing
955# *really* weird gets in to the database through this script.
956# Does NOT do complete input validation!!!
957sub validateInput {
958  if ($webvar{city} eq '-') {
959    $page->param(err => 'Please choose a city');
960    return;
961  }
962
963  # Alloctype check.
964  chomp $webvar{alloctype};
965  if (!grep /$webvar{alloctype}/, keys %disp_alloctypes) {
966    # Danger! Danger!  alloctype should ALWAYS be set by a dropdown.  Anyone
967    # managing to call things in such a way as to cause this deserves a cryptic error.
968    $page->param(err => 'Invalid alloctype');
969    return;
970  }
971
972  # CustID check
973  # We have different handling for customer allocations and "internal" or "our" allocations
974  if ($def_custids{$webvar{alloctype}} eq '') {
975    if (!$webvar{custid}) {
976      $page->param(err => 'Please enter a customer ID.');
977      return;
978    }
979    # Crosscheck with billing.
980    my $status = CustIDCK->custid_exist($webvar{custid});
981    if ($CustIDCK::Error) {
982      $page->param(err => "Error verifying customer ID: ".$CustIDCK::ErrMsg);
983      return;
984    }
985    if (!$status) {
986      $page->param(err => "Customer ID not valid.  Make sure the Customer ID ".
987        "is correct.<br>\nUse STAFF for staff static IPs, and $IPDB::defcustid for any other ".
988        "non-customer assignments.");
989      return;
990    }
991#    print "<!-- [ In validateInput().  Insert customer ID cross-check here. ] -->\n";
992  } else {
993    # New!  Improved!  And now Loaded From The Database!!
994    if ((!$webvar{custid}) || ($webvar{custid} ne 'STAFF')) {
995      $webvar{custid} = $def_custids{$webvar{alloctype}};
996    }
997  }
998
999## hmmm....  is this even useful?
1000if (0) {
1001  # Check POP location
1002  my $flag;
1003  if ($webvar{alloctype} eq 'rm') {
1004    $flag = 'for a routed netblock';
1005    foreach (@poplist) {
1006      if (/^$webvar{city}$/) {
1007        $flag = 'n';
1008        last;
1009      }
1010    }
1011  } else {
1012    $flag = 'n';
1013##fixme:  hook to force-set POP or city on certain alloctypes
1014# if ($webvar{alloctype =~ /foo,bar,bz/ { $webvar{pop} = 'blah'; }
1015    if ($webvar{pop} && $webvar{pop} =~ /^-$/) {
1016      $flag = 'to route the block from/through';
1017    }
1018  }
1019
1020  # if the alloctype has a restricted city/POP list as determined above,
1021  # and the reqested city/POP does not match that list, complain
1022  if ($flag ne 'n') {
1023    $page->param(err => "Please choose a valid POP location $flag.  Valid ".
1024        "POP locations are currently:<br>\n".join (" - ", @poplist));
1025    return;
1026  }
1027}
1028
1029  # VRF.  Not a full validity check, just a basic sanity check.
1030  if ($webvar{vrf}) {
1031    # Trim leading and trailing whitespace first
1032    $webvar{vrf} =~ s/^\s+//;
1033    $webvar{vrf} =~ s/\s+$//;
1034    if ($webvar{vrf} !~ /^[\w\d_.-]{1,32}$/) {
1035      $page->param(err => "VRF values may only contain alphanumerics, and may not be more than 32 characters");
1036      return;
1037    }
1038  }
1039
1040  # VLAN.  Should we allow/use VLAN names, or just the numeric ID?
1041  if ($webvar{vlan}) {
1042    # Trim leading and trailing whitespace first
1043    $webvar{vlan} =~ s/^\s+//;
1044    $webvar{vlan} =~ s/\s+$//;
1045    # Then any surrounding a comma
1046    $webvar{vlan} =~ s/\s*,\s*/,/g;
1047    # ...  ve make it ze configurable thingy!
1048    if ($IPDB::numeric_vlan) {
1049      if ($webvar{vlan} !~ /^[\d,-]+$/) {
1050        $page->param(err => "VLANs must be numeric");
1051        return;
1052      }
1053    } else {
1054      if ($webvar{vlan} !~ /^[\w\d_.,-]+$/) {
1055        $page->param(err => "VLANs must be alphanumeric");
1056        return;
1057      }
1058    }
1059  }
1060
1061  # Backup fields.  Minimal sanity checks.
1062  # Bypass if the user isn't authorized for backup data, or if the checkbox is unchecked
1063  if ($IPDBacl{$authuser} =~ /s/ && defined($webvar{backupfields})) {
1064    for my $bkfield (qw(brand model)) {
1065      if (!$webvar{"bk$bkfield"}) {
1066        $page->param(err => "Backup $bkfield must be filled in if IP/netblock is flagged for backup");
1067        return;
1068      }
1069      if ($webvar{"bk$bkfield"} !~ /^[a-zA-Z0-9\s_.-]+$/) {
1070        $page->param(err => "Invalid characters in backup $bkfield");
1071        return;
1072      }
1073    }
1074    for my $bkfield (qw(type src user)) {  # no spaces in these!
1075      if ($webvar{"bk$bkfield"} && $webvar{"bk$bkfield"} !~ /^[a-zA-Z0-9_.-]+$/) {
1076        $page->param(err => "Invalid characters in backup $bkfield");
1077        return;
1078      }
1079    }
1080    if ($webvar{bkport}) {
1081      $webvar{bkport} =~ s/^\s+//g;
1082      $webvar{bkport} =~ s/\s+$//g;
1083      if ($webvar{bkport} !~ /^\d+$/) {
1084        $page->param(err => "Backup port must be numeric");
1085        return;
1086      }
1087    }
1088##fixme:  code review:  should normalize $webvar{cidr} variants so we can
1089# check for non-/32 allocations having the backup IP field filled in here,
1090# instead of failing on the allocation or update attempt
1091    if ($webvar{bkip}) {
1092      $webvar{bkip} =~ s/^\s+//g;
1093      $webvar{bkip} =~ s/\s+$//g;
1094      if ($webvar{bkip} !~ /^[\da-fA-F:.]+$/) {
1095        $page->param(err => "Backup IP must be an IP");
1096        return;
1097      }
1098    }
1099  } # backup
1100
1101  return 'OK';
1102} # end validateInput
1103
1104
1105# Displays details of a specific allocation in a form
1106# Allows update/delete
1107# action=edit
1108sub edit {
1109
1110  # snag block info from db
1111  my $blockinfo = getBlockData($ip_dbh, $webvar{id}, $webvar{basetype});
1112  my $cidr = new NetAddr::IP $blockinfo->{block};
1113  $page->param(id       => $webvar{id});
1114  $page->param(basetype => $webvar{basetype});
1115
1116  # Tree navigation
1117  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
1118  my @rcrumbs = reverse (@$crumbs);
1119  $utilbar->param(breadcrumb => \@rcrumbs);
1120
1121  # Show link to IP list for pools
1122  $page->param(ispool => 1) if $blockinfo->{type} =~ /^.[dp]$/;
1123
1124  # Clean up extra whitespace on alloc type.  Mainly a legacy-data cleanup.
1125  $blockinfo->{type} =~ s/\s//;
1126
1127##fixme:  The case of "allocation larger than a /24" (or any similar case
1128# where the allocation is larger than the zone(s) in DNS) doesn't work well.
1129# Best solution may just be to add a warning that the entry shown may not be
1130# correct/complete.
1131  if ($blockinfo->{revavail} || $blockinfo->{revpartial}) {
1132    $page->param(showrev => ($blockinfo->{revavail} || $blockinfo->{revpartial}) );
1133    $page->param(v6 => $cidr->{isv6});
1134    $page->param(dnslink => $IPDB::dnsadmin_url);
1135
1136    # get the DNSAdmin zone ID(s) for this allocation.
1137    # Multiple zones should be rare, but are NOT impossible!
1138    my $revlist = getRevID($ip_dbh, user => $authuser, cidr => $blockinfo->{block},
1139        location => $blockinfo->{location});
1140    $page->param(revlist => $revlist) if $revlist;
1141
1142    my $cached;
1143    # Get rDNS info;  duplicates a bit of getBlockData but also does the RPC call if possible
1144    ($blockinfo->{rdns},$cached) = getBlockRDNS($ip_dbh, id => $webvar{id}, type => $blockinfo->{type}, user => $authuser);
1145    $page->param(rdns     => $blockinfo->{rdns});
1146    # visual flag that we're working IPDB-local, not off more authoritative data in dnsadmin
1147    $page->param(cached   => $cached);
1148
1149    # Limit the per-IP rDNS list based on CIDR length;  larger ones just take up too much space.
1150    # Also, don't show on IP pools;  the individual IPs will have a space for rDNS
1151    # Don't show on single IPs;  these use the "pattern" field
1152    if ($IPDBacl{$authuser} =~ /c/
1153        && $cidr->masklen != $cidr->bits
1154        && ($cidr->bits - $cidr->masklen) <= $IPDB::maxrevlist
1155        # config flag for "all block types" OR "not-a-pool-or-IP type"
1156        && ($IPDB::revlistalltypes || $blockinfo->{type} !~ /^.[dpi]/)
1157        # safety against trying to retrieve and display more than 1k (10 bits, /22 v4) worth of individual IPs
1158        # ever.  If you really need to manage a long list of IPs like that all in one place, you can use the DNS
1159        # management tool.  Even a /26 is a bit much, really.
1160        && ($cidr->bits - $cidr->masklen) <= 10
1161        # do we want to allow v6 at all?
1162        #&& ! $cidr->{isv6}
1163        ) {
1164      $page->param(r_iplist => getRDNSbyIP($ip_dbh, id => $webvar{id}, type => $blockinfo->{type},
1165          range => $blockinfo->{block}, user => $authuser) );
1166    }
1167  } # rDNS availability check
1168
1169  # backup data
1170  if ($blockinfo->{hasbk}) {
1171    $page->param(hasbackup => $blockinfo->{hasbk});
1172    for my $bkfield (@IPDB::backupfields) {
1173      $page->param("bk$bkfield" => $blockinfo->{"bk$bkfield"});
1174    }
1175    $page->param(bktelnet => 1) if $blockinfo->{bktype} eq 'telnet';
1176    $page->param(bkssh => 1) if $blockinfo->{bktype} eq 'SSH';
1177  }
1178
1179  # consider extending this to show time as well as date
1180  my ($lastmod,undef) = split /\s+/, $blockinfo->{lastmod};
1181  $page->param(lastmod  => $lastmod);
1182
1183  $page->param(block    => $blockinfo->{block});
1184  $page->param(city     => $blockinfo->{city});
1185  $page->param(custid   => $blockinfo->{custid});
1186
1187##fixme The check here should be built from the database
1188# Need to expand to support pool types too
1189  if ($blockinfo->{type} =~ /^.[ne]$/ && $IPDBacl{$authuser} =~ /c/) {
1190    $page->param(changetype => 1);
1191    $page->param(alloctype => [
1192                { selme => ($blockinfo->{type} eq 'me'), type => "me", disptype => "Dialup netblock" },
1193                { selme => ($blockinfo->{type} eq 'de'), type => "de", disptype => "Dynamic DSL netblock" },
1194                { selme => ($blockinfo->{type} eq 'ce'), type => "ce", disptype => "Dynamic cable netblock" },
1195                { selme => ($blockinfo->{type} eq 'we'), type => "we", disptype => "Dynamic wireless netblock" },
1196                { selme => ($blockinfo->{type} eq 'cn'), type => "cn", disptype => "Customer netblock" },
1197                { selme => ($blockinfo->{type} eq 'en'), type => "en", disptype => "End-use netblock" },
1198                { selme => ($blockinfo->{type} eq 'in'), type => "in", disptype => "Internal netblock" },
1199                ]
1200        );
1201  } else {
1202    $page->param(disptype => $disp_alloctypes{$blockinfo->{type}});
1203    $page->param(type => $blockinfo->{type});
1204  }
1205
1206## node hack
1207  my ($nodeid,$nodename) = getNodeInfo($ip_dbh, $blockinfo->{block});
1208#  $page->param(havenodeid => $nodeid);
1209  $page->param(nodename => $nodename);
1210
1211##fixme:  this whole hack needs cleanup and generalization for all alloctypes
1212##fixme:  arguably a bug that presence of a nodeid implies it can be changed..
1213  if ($IPDBacl{$authuser} =~ /c/) {
1214    my $nlist = getNodeList($ip_dbh);
1215    if ($nodeid) {
1216      foreach (@{$nlist}) {
1217        $$_{selme} = ($$_{node_id} == $nodeid);
1218      }
1219    }
1220    $page->param(nodelist => $nlist);
1221  }
1222## end node hack
1223
1224#  $page->param(vrf      => $blockinfo->{vrf});
1225  $page->param(vlan     => $blockinfo->{vlan});
1226
1227  # Reserved-for-expansion
1228  $page->param(reserve  => $blockinfo->{reserve});
1229  $page->param(reserve_id => $blockinfo->{reserve_id});
1230  my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
1231  $page->param(newblock => $newblock);
1232
1233  # not happy with the upside-down logic, but...
1234  $page->param(swipable => $blockinfo->{type} !~ /.i/);
1235  $page->param(swip     => $blockinfo->{swip} ne 'n') if $blockinfo->{swip};
1236
1237  $page->param(circid   => $blockinfo->{circuitid});
1238  $page->param(desc     => $blockinfo->{description});
1239  $page->param(notes    => $blockinfo->{notes});
1240
1241  # Check to see if we can display sensitive data
1242  $page->param(nocling  => $IPDBacl{$authuser} =~ /s/);
1243  $page->param(privdata => $blockinfo->{privdata});
1244
1245  # ACL trickery - these two template booleans control the presence of all form/input tags
1246  $page->param(maychange => $IPDBacl{$authuser} =~ /c/);
1247  $page->param(maydel => $IPDBacl{$authuser} =~ /d/);
1248
1249  # Need to find internal knobs to twist to actually vary these.  (Ab)use "change" flag for now
1250  $page->param(maymerge => ($IPDBacl{$authuser} =~ /m/ && $blockinfo->{type} !~ /^.i$/));
1251
1252  if ($IPDBacl{$authuser} =~ /c/ && $blockinfo->{type} !~ /^.i$/) {
1253    if ($blockinfo->{type} =~ /^.p$/) {
1254      # PPP pools
1255      $page->param(maysplit => 1) if $cidr->masklen+1 < $cidr->bits;
1256    } elsif ($blockinfo->{type} =~ /.d/) {
1257      # Non-PPP pools
1258      $page->param(maysplit => 1) if $cidr->masklen+2 < $cidr->bits;
1259    } else {
1260      # Standard netblocks.  Arguably allowing splitting these down to single IPs
1261      # doesn't make much sense, but forcing users to apply allocation types
1262      # "properly" is worse than herding cats.
1263      $page->param(maysplit => 1) if $cidr->masklen < $cidr->bits;
1264    }
1265  }
1266
1267} # edit()
1268
1269
1270# Stuff new info about a block into the db
1271# action=update
1272sub update {
1273  if ($IPDBacl{$authuser} !~ /c/) {
1274    $aclerr = 'updateblock';
1275    return;
1276  }
1277
1278  # Collect existing block info here, since we need it for the breadcrumb nav
1279  my $binfo = getBlockData($ip_dbh, $webvar{block}, $webvar{basetype});
1280  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
1281  my @rcrumbs = reverse (@$crumbs);
1282  $utilbar->param(breadcrumb => \@rcrumbs);
1283
1284  # Make sure incoming data is in correct format - custID among other things.
1285  return if !validateInput;
1286
1287  $webvar{swip} = 'n' if !$webvar{swip};
1288
1289  my %updargs = (
1290        custid          => $webvar{custid},
1291        city            => $webvar{city},
1292        description     => $webvar{desc},
1293        notes           => $webvar{notes},
1294        circuitid       => $webvar{circid},
1295        block           => $webvar{block},
1296        type            => $webvar{alloctype},
1297        swip            => $webvar{swip},
1298        rdns            => $webvar{rdns},
1299        vrf             => $webvar{vrf},
1300        vlan            => $webvar{vlan},
1301        user            => $authuser,
1302        );
1303
1304  # Check to see if user is allowed to do anything with sensitive data
1305  if ($IPDBacl{$authuser} =~ /s/) {
1306    $updargs{privdata} = $webvar{privdata};
1307    for my $bkfield (@IPDB::backupfields) {
1308      $updargs{"bk$bkfield"} = $webvar{"bk$bkfield"};
1309    }
1310    $updargs{backup} = $webvar{backupfields};
1311  } else {
1312    # If the user doesn't have permissions to monkey with NOC-things, pass
1313    # a flag so we don't treat it as "backup data removed"
1314    $updargs{ignorebk} = 1;
1315  }
1316
1317  # Semioptional values
1318  $updargs{node} = $webvar{node} if $webvar{node};
1319
1320  # collect per-IP rDNS fields.  only copy over the ones that actually have something in them.
1321  my %iprev;
1322  foreach (keys %webvar) {
1323    $iprev{$_} = $webvar{$_} if /host_[\d.a-fA-F:]+/ && $webvar{$_};
1324  }
1325
1326  # and now IPv6
1327##fixme:  how to remove an entry?  maybe treat empty host as "delete meeeee!"?
1328  if ($webvar{v6list}) {
1329    my @v6lines = split /\n/, $webvar{v6list};
1330    foreach (@v6lines) {
1331      s/^\s+//;
1332      s/\s+$//;
1333      next if /^$/;
1334      my ($ip,$name) = split /,/;
1335      $iprev{"host_$ip"} = $name;
1336    }
1337  }
1338
1339  # Merge with reserved freeblock
1340  $updargs{fbmerge} = $webvar{expandme} if $webvar{expandme};
1341
1342  my ($code,$msg) = updateBlock($ip_dbh, %updargs, iprev => \%iprev);
1343
1344  if ($code eq 'FAIL') {
1345    syslog "err", "$authuser could not update block/IP $webvar{block} ($binfo->{block}): '$msg'";
1346    $page->param(err => "Could not update block/IP $binfo->{block}: $msg");
1347    return;
1348  }
1349
1350  # If we get here, the operation succeeded.
1351  syslog "notice", "$authuser updated $webvar{block} ($binfo->{block})";
1352##fixme:  log details of the change?  old way is in the .debug stream anyway.
1353##fixme:  need to wedge something in to allow "update:field" notifications
1354## hmm.  how to tell what changed?  O_o
1355mailNotify($ip_dbh, 's:swi', "SWIPed: $disp_alloctypes{$webvar{alloctype}} $binfo->{block}",
1356        "$binfo->{block} had SWIP status changed to \"Yes\" by $authuser") if $webvar{swip} eq 'on';
1357
1358## node hack
1359  if ($webvar{node} && $webvar{node} ne '-') {
1360    my $nodename = getNodeName($ip_dbh, $webvar{node});
1361    $page->param(nodename => $nodename);
1362  }
1363## end node hack
1364
1365  # Link back to browse-routed or list-pool page on "Update complete" page.
1366  my $pblock = getBlockData($ip_dbh, $binfo->{parent_id});
1367  $page->param(backid => $binfo->{parent_id});
1368  $page->param(backblock => $pblock->{block});
1369  $page->param(backpool => ($webvar{basetype} eq 'i'));
1370
1371  # Do some HTML fiddling here instead of using ESCAPE=HTML in the template,
1372  # because otherwise we can't convert \n to <br>.  *sigh*
1373  $webvar{notes} = $q->escapeHTML($webvar{notes});      # escape first...
1374  $webvar{notes} =~ s/\n/<br>\n/;                       # ... then convert newlines
1375  $webvar{privdata} = ($webvar{privdata} ? $q->escapeHTML($webvar{privdata}) : "&nbsp;");
1376  $webvar{privdata} =~ s/\n/<br>\n/;
1377
1378  if ($webvar{expandme}) {
1379    # this is fugly but still faster than hitting the DB again with getBlockData()
1380    my $tmp = new NetAddr::IP $binfo->{block};
1381    my $fb = new NetAddr::IP $binfo->{reserve};
1382    my @newblock = $tmp->compact($fb);
1383    $page->param(cidr => $newblock[0]);
1384  } else {
1385    $page->param(cidr => $binfo->{block});
1386  }
1387  $page->param(rdns => $webvar{rdns});
1388  $page->param(city => $webvar{city});
1389  $page->param(disptype => $disp_alloctypes{$webvar{alloctype}});
1390  $page->param(custid => $webvar{custid});
1391  $page->param(swip => $webvar{swip} eq 'on' ? 'Yes' : 'No');
1392  $page->param(circid => $webvar{circid});
1393  $page->param(desc => $webvar{desc});
1394  $page->param(notes => $webvar{notes});
1395  if ($IPDBacl{$authuser} =~ /s/) {
1396    $page->param(nocling  => 1);
1397    $page->param(privdata => $webvar{privdata});
1398    if ($webvar{backupfields} && $webvar{backupfields} eq 'on') {
1399      $page->param(hasbackup => 1);
1400      for my $bkfield (@IPDB::backupfields) {
1401        $page->param("bk$bkfield" => $webvar{"bk$bkfield"});
1402      }
1403    }
1404  }
1405
1406} # update()
1407
1408
1409sub prepSplit {
1410  if ($IPDBacl{$authuser} !~ /c/) {
1411    $aclerr = 'splitblock';
1412    return;
1413  }
1414
1415  my $blockinfo = getBlockData($ip_dbh, $webvar{block});
1416
1417  # Tree navigation
1418  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
1419  my @rcrumbs = reverse (@$crumbs);
1420  $utilbar->param(breadcrumb => \@rcrumbs);
1421
1422  if ($blockinfo->{type} =~ /^.i$/) {
1423    $page->param(err => "Can't split a single IP allocation");
1424    return;
1425  }
1426
1427  # Info about current allocation
1428  $page->param(oldblock => $blockinfo->{block});
1429  $page->param(block => $webvar{block});
1430
1431# Note that there are probably different rules that should be followed to restrict splitting IPv6 blocks;
1432# strictly speaking it will be exceptionally rare to see smaller than a /64 assigned to a customer, since that
1433# breaks auto-addressing schemes.
1434
1435  # Generate possible splits
1436  my $block = new NetAddr::IP $blockinfo->{block};
1437  my $oldmask = $block->masklen;
1438  if ($blockinfo->{type} =~ /^.d$/) {
1439    # Non-PPP pools
1440    $page->param(ispool => 1);
1441    if ($oldmask+2 >= $block->bits) {
1442      $page->param(err => "Can't split a standard netblock pool any further");
1443      return;
1444    }
1445    # Allow splitting down to v4 /30 (which results in one usable IP;  dubiously useful)
1446    $page->param(sp4mask => $oldmask+2) if $oldmask+2 <= $block->bits-2;
1447  } elsif ($blockinfo->{type} =~ /.p/) {
1448    $page->param(ispool => 1);
1449    # Allow splitting PPP pools down to v4 /31
1450    $page->param(sp4mask => $oldmask+2) if $oldmask+2 <= $block->bits-1;
1451  } else {
1452    # Allow splitting all other non-pool netblocks down to single IPs, which...
1453    # arguably should be *aggregated* in a pool.  Except where they shouldn't.
1454    $page->param(sp4mask => $oldmask+2) if $oldmask+2 <= $block->bits;
1455  }
1456  # set the split-in-half mask
1457  $page->param(sp2mask => $oldmask+1);
1458
1459  # Generate possible shrink targets
1460  my @keepers = $block->split($block->masklen+1);
1461  $page->param(newblockA => $keepers[0]);
1462  $page->param(newblockB => $keepers[1]);
1463} # prepSplit()
1464
1465
1466sub doSplit {
1467  if ($IPDBacl{$authuser} !~ /c/) {
1468    $aclerr = 'splitblock';
1469    return;
1470  }
1471
1472##fixme:  need consistent way to identify "this thing that is this thing" with only the ID
1473# also applies to other locations
1474  my $blockinfo = getBlockData($ip_dbh, $webvar{block});
1475
1476  # Tree navigation
1477  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
1478  my @rcrumbs = reverse (@$crumbs);
1479  $utilbar->param(breadcrumb => \@rcrumbs);
1480
1481  if ($blockinfo->{type} =~ /^.i$/) {
1482    $page->param(err => "Can't split a single IP allocation");
1483    return;
1484  }
1485
1486  if ($webvar{subact} eq 'split') {
1487    $page->param(issplit => 1);
1488    my $block = new NetAddr::IP $blockinfo->{block};
1489    my $newblocks = splitBlock($ip_dbh, id => $webvar{block}, basetype => 'b', newmask => $webvar{split},
1490        user => $authuser);
1491    if ($newblocks) {
1492      $page->param(newblocks => $newblocks);
1493    } else {
1494      $page->param(err => $IPDB::errstr);
1495    }
1496
1497  } elsif ($webvar{subact} eq 'shrink') {
1498    $page->param(nid => $webvar{block});
1499    $page->param(newblock => $webvar{shrink});
1500    my $newfree = shrinkBlock($ip_dbh, $webvar{block}, $webvar{shrink});
1501    if ($newfree) {
1502      $page->param(newfb => $newfree);
1503    } else {
1504      $page->param(err => $IPDB::errstr);
1505    }
1506
1507  } else {
1508    # Your llama is on fire.
1509    $page->param(err => "Missing form field that shouldn't be missing.");
1510    return;
1511  }
1512
1513  # common bits
1514  $page->param(cidr => $blockinfo->{block});
1515  # and the backlink to the parent container
1516  my $pinfo = getBlockData($ip_dbh, $blockinfo->{parent_id});
1517  $page->param(backid => $blockinfo->{parent_id});
1518  $page->param(backblock => $pinfo->{block});
1519} # doSplit()
1520
1521
1522# Set up for merge
1523sub prepMerge {
1524  if ($IPDBacl{$authuser} !~ /m/) {
1525    $aclerr = 'mergeblock';
1526    return;
1527  }
1528
1529  my $binfo = getBlockData($ip_dbh, $webvar{block});
1530
1531  # Tree navigation
1532  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
1533  my @rcrumbs = reverse (@$crumbs);
1534  $utilbar->param(breadcrumb => \@rcrumbs);
1535
1536  $page->param(block => $webvar{block});
1537  $page->param(ispool => $binfo->{type} =~ /.[dp]/);
1538  $page->param(ismaster => $binfo->{type} eq 'mm');
1539  $page->param(oldblock => $binfo->{block});
1540  $page->param(oldtype => $disp_alloctypes{$binfo->{type}});
1541  $page->param(typelist => getTypeList($ip_dbh, 'n', $binfo->{type}));  # down the rabbit hole we go...
1542
1543  # Strings for scope;  do this way so we don't have to edit them many places
1544  $page->param(vis_keepall => $merge_display{keepall});
1545  $page->param(vis_mergepeer => $merge_display{mergepeer});
1546  $page->param(vis_clearpeer => $merge_display{clearpeer});
1547  $page->param(vis_clearall => $merge_display{clearall});
1548
1549} # prepMerge()
1550
1551
1552# Show what will be merged, present warnings about data loss
1553sub confMerge {
1554  if ($IPDBacl{$authuser} !~ /m/) {
1555    $aclerr = 'mergeblock';
1556    return;
1557  }
1558
1559  if (!$webvar{newmask} || $webvar{newmask} !~ /^\d+$/) {
1560    $page->param(err => 'New netmask required');
1561    return;
1562  }
1563
1564  $page->param(block => $webvar{block});
1565  my $binfo = getBlockData($ip_dbh, $webvar{block});
1566  my $pinfo = getBlockData($ip_dbh, $binfo->{parent_id});
1567  my $minfo = getBlockData($ip_dbh, $binfo->{master_id});
1568  my $block = new NetAddr::IP $binfo->{block};
1569
1570  # Tree navigation
1571  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
1572  my @rcrumbs = reverse (@$crumbs);
1573  $utilbar->param(breadcrumb => \@rcrumbs);
1574
1575  $page->param(oldblock => $binfo->{block});
1576  $page->param(oldtype => $disp_alloctypes{$binfo->{type}});
1577  $page->param(ismaster => $binfo->{type} eq 'mm');
1578  $page->param(ispool => $webvar{alloctype} =~ /.[dp]/);
1579  $page->param(isleaf => $webvar{alloctype} =~ /.[enr]/);
1580  $page->param(newtype => $webvar{alloctype});
1581  $page->param(newdisptype => $disp_alloctypes{$webvar{alloctype}});
1582  my $newblock = new NetAddr::IP $block->addr."/$webvar{newmask}";
1583  $newblock = $newblock->network;
1584  $page->param(newmask => $webvar{newmask});
1585  $page->param(newblock => "$newblock");
1586
1587  # get list of allocations and freeblocks to be merged
1588  my $malloc_list = listForMerge($ip_dbh, $binfo->{parent_id}, $newblock, 'a');
1589  $page->param(mergealloc => $malloc_list);
1590
1591  $page->param(vis_scope => $merge_display{$webvar{scope}});
1592  $page->param(scope => $webvar{scope});
1593} # confMerge()
1594
1595
1596# Make it so
1597sub doMerge {
1598  if ($IPDBacl{$authuser} !~ /m/) {
1599    $aclerr = 'mergeblock';
1600    return;
1601  }
1602
1603  if (!$webvar{newmask} || $webvar{newmask} !~ /^\d+$/) {
1604    $page->param(err => 'New netmask required');
1605    return;
1606  }
1607
1608  $page->param(block => $webvar{block});
1609  my $binfo = getBlockData($ip_dbh, $webvar{block});
1610  my $pinfo = getBlockData($ip_dbh, $binfo->{parent_id});
1611  my $block = new NetAddr::IP $binfo->{block};
1612
1613  # Tree navigation
1614  my $crumbs = getBreadCrumbs($ip_dbh, $binfo->{parent_id});
1615  my @rcrumbs = reverse (@$crumbs);
1616  $utilbar->param(breadcrumb => \@rcrumbs);
1617
1618  $page->param(oldblock => $binfo->{block});
1619  $page->param(oldtype => $disp_alloctypes{$binfo->{type}});
1620  $page->param(newdisptype => $disp_alloctypes{$webvar{newtype}});
1621  my $newblock = new NetAddr::IP $block->addr."/$webvar{newmask}";
1622  $newblock = $newblock->network;
1623  $page->param(newblock => $newblock);
1624  $page->param(vis_scope => $merge_display{$webvar{scope}});
1625
1626  my $mlist = mergeBlocks($ip_dbh, $webvar{block}, %webvar, user => $authuser);
1627
1628  if ($mlist) {
1629    #(newtype => $webvar{newtype}, newmask => $webvar{newmask}));
1630    # Slice off first entry (the new parent - note this may be a new allocation,
1631    # not the same ID that was "merged"!
1632    my $parent = shift @$mlist;
1633    $page->param(backpool => $webvar{newtype} =~ /.[dp]/);
1634    if ($webvar{newtype} =~ /.[enr]/) {
1635      $page->param(backleaf => 1);
1636      $page->param(backid => $binfo->{parent_id});
1637      $page->param(backblock => $pinfo->{block});
1638    } else {
1639      $page->param(backid => $parent->{id});
1640      $page->param(backblock => $parent->{block});
1641    }
1642    $page->param(mergelist => $mlist);
1643  } else {
1644    $page->param(err => "Merge failed: $IPDB::errstr");
1645  }
1646} # doMerge()
1647
1648
1649# Delete an allocation.
1650sub remove {
1651  if ($IPDBacl{$authuser} !~ /d/) {
1652    $aclerr = 'delblock';
1653    return;
1654  }
1655
1656  # Serves'em right for getting here...
1657  if (!defined($webvar{block})) {
1658    $page->param(err => "Can't delete a block that doesn't exist");
1659    return;
1660  }
1661
1662  my $blockdata;
1663  $blockdata = getBlockData($ip_dbh, $webvar{block}, $webvar{basetype});
1664
1665  # Tree navigation
1666  my $crumbs = getBreadCrumbs($ip_dbh, $blockdata->{parent_id});
1667  my @rcrumbs = reverse (@$crumbs);
1668  $utilbar->param(breadcrumb => \@rcrumbs);
1669
1670  if ($blockdata->{parent_id} == 0) {   # $webvar{alloctype} eq 'mm'
1671    $blockdata->{city} = "N/A";
1672    $blockdata->{custid} = "N/A";
1673    $blockdata->{circuitid} = "N/A";
1674    $blockdata->{description} = "N/A";
1675    $blockdata->{notes} = "N/A";
1676    $blockdata->{privdata} = "N/A";
1677  } # end cases for different alloctypes
1678
1679  $page->param(blockid => $webvar{block});
1680  $page->param(basetype => $webvar{basetype});
1681
1682  $page->param(block => $blockdata->{block});
1683  $page->param(rdns => $blockdata->{rdns});
1684
1685  # maybe need to apply more magic here?
1686  # most allocations we *do* want to autodelete the forward as well as reverse;  for a handful we don't.
1687  # -> all real blocks (nb: pool IPs need extra handling)
1688  # -> NOC/private-IP (how to ID?)
1689  # -> anything with a pattern matching $IPDB::domain?
1690  if ($blockdata->{type} !~ /^.i$/) {
1691    $page->param(autodel => 1);
1692  }
1693
1694  $page->param(disptype => $disp_alloctypes{$blockdata->{type}});
1695  $page->param(city => $blockdata->{city});
1696  $page->param(custid => $blockdata->{custid});
1697  $page->param(circid => $blockdata->{circuitid});
1698  $page->param(desc => $blockdata->{description});
1699  $blockdata->{notes} = $q->escapeHTML($blockdata->{notes});
1700  $blockdata->{notes} =~ s/\n/<br>\n/;
1701  $page->param(notes => $blockdata->{notes});
1702  $blockdata->{privdata} = $q->escapeHTML($blockdata->{privdata});
1703  $blockdata->{privdata} = '&nbsp;' if !$blockdata->{privdata};
1704  $blockdata->{privdata} =~ s/\n/<br>\n/;
1705  $page->param(privdata => $blockdata->{privdata}) if $IPDBacl{$authuser} =~ /s/;
1706  $page->param(delpool => $blockdata->{type} =~ /^.[pd]$/);
1707
1708} # end remove()
1709
1710
1711# Delete an allocation.  Return it to the freeblocks table;  munge
1712# data as necessary to keep as few records as possible in freeblocks
1713# to prevent weirdness when allocating blocks later.
1714# Remove IPs from pool listing if necessary
1715sub finalDelete {
1716  if ($IPDBacl{$authuser} !~ /d/) {
1717    $aclerr = 'delblock';
1718    return;
1719  }
1720
1721  # need to retrieve block data before deleting so we can notify on that
1722  my $blockinfo = getBlockData($ip_dbh, $webvar{block}, $webvar{basetype});
1723  my $pinfo = getBlockData($ip_dbh, $blockinfo->{parent_id}, 'b');
1724
1725  # Tree navigation
1726  my $crumbs = getBreadCrumbs($ip_dbh, $blockinfo->{parent_id});
1727  my @rcrumbs = reverse (@$crumbs);
1728  $utilbar->param(breadcrumb => \@rcrumbs);
1729
1730  my ($code,$msg) = deleteBlock($ip_dbh, $webvar{block}, $webvar{basetype}, $webvar{delforward}, $authuser);
1731
1732  $page->param(block => $blockinfo->{block});
1733  $page->param(bdisp => $q->escapeHTML($disp_alloctypes{$blockinfo->{type}}));
1734  $page->param(delparent_id => $blockinfo->{parent_id});
1735  if ($pinfo) {
1736    $page->param(delparent => $pinfo->{block});
1737    $page->param(pdisp => $q->escapeHTML($disp_alloctypes{$pinfo->{type}}));
1738  }
1739  $page->param(returnpool => ($webvar{basetype} eq 'i') );
1740  if ($code =~ /^WARN(POOL|MERGE)/) {
1741    my ($pid,$pcidr) = split /,/, $msg;
1742    my $real_pinfo = getBlockData($ip_dbh, $pid, 'b');
1743    $page->param(parent_id => $pid);
1744    $page->param(parent => $pcidr);
1745    $page->param(real_disp => $q->escapeHTML($disp_alloctypes{$real_pinfo->{type}}));
1746    $page->param(mergeip => $code eq 'WARNPOOL');
1747  }
1748  if ($code eq 'WARN') {
1749    $msg =~ s/\n/<br>\n/g;
1750    $page->param(genwarn => $msg);
1751  }
1752  if ($code eq 'OK' || $code =~ /^WARN/) {
1753    syslog "notice", "$authuser deallocated '".$blockinfo->{type}."'-type netblock ID $webvar{block} ".
1754        "($blockinfo->{block}), $blockinfo->{custid}, $blockinfo->{city}, desc='$blockinfo->{description}'";
1755    mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$blockinfo->{type}} $blockinfo->{block}",
1756# $webvar{block} useful?  do we care about the block ID here?
1757        "$disp_alloctypes{$blockinfo->{type}} $blockinfo->{block} deallocated by $authuser\n".
1758        "CustID: $blockinfo->{custid}\nCity: $blockinfo->{city}\n".
1759        "Description: $blockinfo->{description}\n");
1760  } else {
1761    $page->param(failmsg => $msg);
1762    if ($webvar{alloctype} =~ /^.i$/) {
1763      syslog "err", "$authuser could not deallocate static IP $webvar{block} ($blockinfo->{block}): '$msg'";
1764    } else {
1765      syslog "err", "$authuser could not deallocate netblock $webvar{block} ($blockinfo->{block}): '$msg'";
1766      $page->param(netblock => 1);
1767    }
1768  }
1769
1770} # finalDelete
1771
1772# Retrive and lightly preprocess any block notices.
1773sub blocknotices {
1774  my $blockid = shift;
1775  # retrieve any notices
1776  my $nlist = getBlockNotices($ip_dbh, $blockid);
1777  my @notices;
1778  foreach (@$nlist) {
1779    push @notices, $_->{notice} if $_->{notice};
1780  }
1781  my $blockmsg = join("<br>\n", @notices);
1782  $page->param(blockmsg => $blockmsg);
1783}
Note: See TracBrowser for help on using the repository browser.