source: trunk/cgi-bin/ipdb-rpc.cgi@ 907

Last change on this file since 907 was 907, checked in by Kris Deugau, 7 years ago

/trunk

Followup to r906 to make sure local modules are loaded after modifying @INC

  • Property svn:executable set to *
  • Property svn:keywords set to Date Rev Author Id
File size: 14.4 KB
RevLine 
[600]1#!/usr/bin/perl
2# XMLRPC interface to manipulate most DNS DB entities
3###
4# $Id: ipdb-rpc.cgi 907 2017-08-15 17:56:25Z kdeugau $
5###
[837]6# Copyright (C) 2013,2014,2016 Kris Deugau <kdeugau@deepnet.cx>
[600]7
8use strict;
9use warnings;
10
11use DBI;
12use NetAddr::IP;
13use FCGI;
14use Frontier::Responder;
15
16use Sys::Syslog;
17
18# don't remove! required for GNU/FHS-ish install from tarball
19##uselib##
20
[906]21# push "the directory the script is in" into @INC
22use FindBin;
23use lib "$FindBin::RealBin/";
24
[600]25use MyIPDB;
[907]26use CustIDCK;
[600]27
28openlog "IPDB-rpc","pid","$IPDB::syslog_facility";
29
30##fixme: username source? can we leverage some other auth method?
31# we don't care except for logging here, and Frontier::Client needs
32# a patch that's not well-distributed to use HTTP AUTH.
33
34# Collect the username from HTTP auth. If undefined, we're in
35# a test environment, or called without a username.
36my $authuser;
37if (!defined($ENV{'REMOTE_USER'})) {
38 $authuser = '__temptest';
39} else {
40 $authuser = $ENV{'REMOTE_USER'};
41}
42
43# Why not a global DB handle? (And a global statement handle, as well...)
44# Use the connectDB function, otherwise we end up confusing ourselves
45my $ip_dbh;
46my $sth;
47my $errstr;
48($ip_dbh,$errstr) = connectDB_My;
49initIPDBGlobals($ip_dbh);
50
51my $methods = {
[668]52 # Internal core IPDB subs; no value in exposing them since the DB handle can't be used by the caller
53 #'ipdb._rpc'
54 # This one could be exposed, but the globals aren't automatically
55 # inherited by the caller anyway, and we call it just above locally.
56 #'ipdb.initIPDBGlobals'
57 #'ipdb.connectDB'
58 #'ipdb.finish'
59 #'ipdb.checkDBSanity'
60 'ipdb.addMaster' => \&rpc_addMaster,
61 'ipdb.touchMaster' => \&rpc_touchMaster,
62 'ipdb.listSummary' => \&rpc_listSummary,
63 'ipdb.listSubs' => \&rpc_listSubs,
64 'ipdb.listContainers' => \&rpc_listContainers,
65 'ipdb.listAllocations' => \&rpc_listAllocations,
66 'ipdb.listFree' => \&rpc_listFree,
67 'ipdb.listPool' => \&rpc_listPool,
68 'ipdb.getMasterList' => \&rpc_getMasterList,
69 'ipdb.getTypeList' => \&rpc_getTypeList,
70 'ipdb.getPoolSelect' => \&rpc_getPoolSelect,
71 'ipdb.findAllocateFrom' => \&rpc_findAllocateFrom,
72 'ipdb.ipParent' => \&rpc_ipParent,
73 'ipdb.subParent' => \&rpc_subParent,
74 'ipdb.blockParent' => \&rpc_blockParent,
75 'ipdb.getRoutedCity' => \&rpc_getRoutedCity,
76 'ipdb.allocateBlock' => \&rpc_allocateBlock,
77 # another internal sub; mainly a sub to make allocateBlock() a lot smaller
78 #'ipdb.initPool' => \&rpc_initPool
79 'ipdb.updateBlock' => \&rpc_updateBlock,
80 'ipdb.deleteBlock' => \&rpc_deleteBlock,
81 'ipdb.getBlockData' => \&rpc_getBlockData,
82 'ipdb.getBlockRDNS' => \&rpc_getBlockRDNS,
83 'ipdb.getNodeList' => \&rpc_getNodeList,
84 'ipdb.getNodeName' => \&rpc_getNodeName,
85 'ipdb.getNodeInfo' => \&rpc_getNodeInfo,
86 'ipdb.mailNotify' => \&rpc_mailNotify,
87
88# Subs not part of the core IPDB
89 'ipdb.getDispAlloctypes' => \&rpc_getDispAlloctypes,
90 'ipdb.getListAlloctypes' => \&rpc_getListAlloctypes,
91 'ipdb.getDefCustIDs' => \&rpc_getDefCustIDs,
92 'ipdb.getCityList' => \&rpc_getCityList,
[600]93 'ipdb.getAvailableStatics' => \&rpc_getAvailableStatics,
[852]94 'ipdb.getBackupList' => \&rpc_getBackupList,
[886]95
96# Should this even be core/upstream?
97 'ipdb.findAllocation' => \&rpc_findAllocation,
[600]98};
99
100my $reqcnt = 0;
101
[891]102my $req = FCGI::Request();
103
[600]104# main FCGI loop.
[891]105while ($req->Accept() >= 0) {
[661]106 # done here to a) prevent $ENV{'REMOTE_ADDR'} from being empty and b) to collect
107 # the right user for the individual call (since we may be running with FCGI)
108 syslog "debug", "$authuser active, $ENV{'REMOTE_ADDR'}";
109
[600]110 # don't *think* we need any of these...
111 # %disp_alloctypes, %def_custids, %list_alloctypes
112 # @citylist, @poplist
113 # @masterblocks, %allocated, %free, %bigfree, %routed (removed in /trunk)
114 # %IPDBacl
115 #initIPDBGlobals($ip_dbh);
116
117 my $res = Frontier::Responder->new(
118 methods => $methods
119 );
120
121 # "Can't do that" errors
122 if (!$ip_dbh) {
123 print "Content-type: text/xml\n\n".$res->{_decode}->encode_fault(5, $DBI::errstr);
124 } else {
125 print $res->answer;
126 }
[661]127 last if $reqcnt++ > $IPDB::maxfcgi;
[600]128} # while FCGI::accept
129
130exit 0;
131
132
133##
134## Private subs
135##
136
137# Check RPC ACL
138sub _aclcheck {
139 my $subsys = shift;
[661]140 return 1 if grep /$ENV{REMOTE_ADDR}/, @{$IPDB::rpcacl{$subsys}};
[600]141 warn "$subsys/$ENV{REMOTE_ADDR} not in ACL\n"; # a bit of logging
142 return 0;
143}
144
145sub _commoncheck {
146 my $argref = shift;
147 my $needslog = shift;
148
149 die "Missing remote system name\n" if !$argref->{rpcsystem};
150 die "Access denied\n" if !_aclcheck($argref->{rpcsystem});
151 if ($needslog) {
152 die "Missing remote username\n" if !$argref->{rpcuser};
153 }
154}
155
156# stripped-down copy from from main.cgi. should probably be moved to IPDB.pm
157sub _validateInput {
158 my $argref = shift;
159
[837]160 if (!$argref->{block}) {
161 $argref->{block} = $argref->{cidr} if $argref->{cidr};
162 die "Block/IP is required\n" if !$argref->{block};
163 }
[600]164
165 # Alloctype check.
[837]166 chomp $argref->{type};
[600]167
[837]168 die "Invalid allocation type\n" if (!grep /$argref->{type}/, keys %disp_alloctypes);
[600]169
170 # Arguably not quite correct, as the custID won't be checked for
171 # validity if there's a default on the type.
[837]172 if ($def_custids{$argref->{type}} eq '') {
[600]173 # Types without a default custID must have one passed in
174 die "Customer ID is required\n" if !$argref->{custid};
175 # Crosscheck with billing.
176 my $status = CustIDCK->custid_exist($argref->{custid});
177 die "Error verifying customer ID: $CustIDCK::ErrMsg\n" if $CustIDCK::Error;
178 die "Customer ID not valid\n" if !$status;
179 } else {
180 # Types that have a default will use it unless one is specified.
181 if ((!$argref->{custid}) || ($argref->{custid} ne 'STAFF')) {
[837]182 $argref->{custid} = $def_custids{$argref->{type}};
[600]183 }
184 }
185} # end validateInput()
186
187
188##
189## RPC method subs
190##
191
[668]192# Core IPDB subs
[600]193# Prefixed with rpc_ to not conflict with subs in IPDB.pm
194
[668]195# These are deep internals and don't make much sense to expose, since RPC
196# by definition does not access the backing DB directly.
197#sub _rpc {}
198#sub initIPDBGlobals {}
199#sub connectDB {}
200#sub finish {}
201#sub checkDBSanity {}
[600]202
[668]203sub rpc_addMaster {}
204sub rpc_touchMaster {}
205sub rpc_listSummary {}
206sub rpc_listSubs {}
207sub rpc_listContainers {}
208sub rpc_listAllocations {}
209sub rpc_listFree {}
[866]210
211
212sub rpc_listPool {
213 my %args = @_;
214
215 _commoncheck(\%args, 'y');
216
217 $args{include_desc} = 0 if !$args{include_desc};
218
[869]219 my $pid;
[866]220 # convert passed pool from CIDR to an ID, maybe
221 if ($args{pool} !~ /^\d+$/) {
222 die "Invalid pool argument" if $args{pool} !~ m{^\d+\.\d+\.\d+\.\d+/\d+$};
223 die "VRF is required\n" if !$args{vrf}; # VRF name may not be empty
224 ($pid) = $ip_dbh->selectrow_array("SELECT a.id FROM allocations a JOIN allocations m ON a.master_id=m.id".
225 " WHERE a.cidr = ? AND m.vrf = ?", undef, $args{pool}, $args{vrf});
[869]226 } else {
227 $pid = $args{pool};
[866]228 }
229
230 return listPool($ip_dbh, $pid, $args{include_desc});
231} # rpc_listPool()
232
233
[668]234sub rpc_getMasterList {}
235sub rpc_getTypeList {}
236sub rpc_getPoolSelect {}
237sub rpc_findAllocateFrom {}
238sub rpc_ipParent {}
239sub rpc_subParent {}
240sub rpc_blockParent {}
241sub rpc_getRoutedCity {}
[600]242
243sub rpc_allocateBlock {
244 my %args = @_;
245
246 _commoncheck(\%args, 'y');
247
248 _validateInput(\%args);
249
250 # Not required for update, delete
251 die "City is required\n" if !$args{city};
[837]252 die "Customer ID is required\n" if !$args{custid};
253 die "Allocation type is required\n" if !$args{type};
[600]254
[837]255 if ($args{type} =~ /^.i$/) {
256 die "Pool ID or VRF to allocate from is required\n" if !$args{parent} && !$args{vrf};
257 } else {
258 die "Free block to allocate from is required\n" if !$args{fbid};
259 }
[600]260
[870]261 $args{user} = $args{rpcuser};
[837]262 my ($code,$msg) = allocateBlock($ip_dbh, %args);
263
[600]264 if ($code eq 'OK' || $code eq 'WARN') {
[837]265 if ($args{type} =~ /^.i$/) {
[600]266 $msg =~ s|/32||;
[837]267 mailNotify($ip_dbh, "a$args{type}", "ADDED: $disp_alloctypes{$args{type}} allocation",
268 "$disp_alloctypes{$args{type}} $msg allocated to customer $args{custid}\n".
[891]269 "Description: $args{desc}\n\nAllocated by: $args{rpcsystem}/$args{rpcuser}\n")
270 unless $args{nomail};
[600]271 } else {
272 my $netblock = new NetAddr::IP $args{block};
[837]273 mailNotify($ip_dbh, "a$args{type}", "ADDED: $disp_alloctypes{$args{type}} allocation",
274 "$disp_alloctypes{$args{type}} $args{block} allocated to customer $args{custid}\n".
[891]275 "Description: $args{desc}\n\nAllocated by: $args{rpcsystem}/$args{rpcuser}\n")
276 unless $args{nomail};
[600]277 }
278 syslog "notice", "$args{rpcsystem}/$args{rpcuser} allocated '$args{block}' to '$args{custid}' as ".
[837]279 "'$args{type}' ($msg)";
[600]280 } else {
281 syslog "err", "Allocation of '$args{block}' to '$args{custid}' as ".
[837]282 "'$args{type}' by $args{rpcsystem}/$args{rpcuser} failed: '$msg'";
[600]283 die "$msg\n";
284 }
285 return $msg;
286} # rpc_allocateBlock()
[668]287
288# another internal sub; mainly a sub to make allocateBlock() a lot smaller
289#sub rpc_initPool {}
[838]290
291
292sub rpc_updateBlock {
293 my %args = @_;
294
295 _commoncheck(\%args, 'y');
296
297 _validateInput(\%args);
298
299 # Allow caller to send a CIDR instead of the block ID.
300 $args{origblock} = $args{block};
301 if ($args{block} =~ m{^(?:\d+\.){3}\d+(?:/32)?$}) {
302 # updating a static IP. retrieve the IP ID based on either the parent or VRF.
303 die "Pool ID or VRF is required\n" if !$args{parent} && !$args{vrf};
304 ($args{block}) = $ip_dbh->selectrow_array(
[851]305 "SELECT id FROM poolips WHERE ip = ? AND ".($args{parent} ? "parent_id = ?" : "vrf = ?"),
306 undef, $args{block}, ($args{parent} ? $args{parent} : $args{vrf}) );
[838]307 }
308
309 my $binfo = getBlockData($ip_dbh, $args{block}, $args{type});
310
311 # set assignIP_on_update to simplify some calling situations. better to use allocateBlock if possible though.
312 my ($code,$msg) = updateBlock($ip_dbh, %args, assignIP_on_update => 1);
313 if ($code eq 'FAIL') {
[851]314 syslog "err", "$args{rpcsystem}/$args{rpcuser} could not update block/IP $args{block} ($binfo->{block}): '$msg'";
[838]315 die "$msg\n";
316 }
[851]317 syslog "notice", "$args{rpcsystem}/$args{rpcuser} updated $args{block} ($binfo->{block})";
[838]318
319 return $msg;
320} # rpc_updateBlock()
321
322
[850]323sub rpc_deleteBlock {
324 my %args = @_;
325
326 _commoncheck(\%args, 'y');
327
[866]328 if (!$args{block}) {
329 $args{block} = $args{cidr} if $args{cidr};
330 die "Block/IP is required\n" if !$args{block};
331 }
[850]332
333 if ($args{block} =~ m{^(?:\d+\.){3}\d+(?:/32)?$}) {
334 # deleting a static IP. retrieve the IP ID based on either the parent or VRF.
335 die "Pool ID or VRF is required\n" if !$args{parent} && !$args{vrf};
336 ($args{block}) = $ip_dbh->selectrow_array(
337 "SELECT id FROM poolips WHERE ip = ? AND ".($args{parent} ? "parent_id = ?" : "vrf = ?"),
338 undef, $args{block}, ($args{parent} ? $args{parent} : $args{vrf}) );
339 }
340
341 # snag block info for log
342 my $blockinfo = getBlockData($ip_dbh, $args{block}, $args{type});
[876]343 my ($code,$msg) = deleteBlock($ip_dbh, $args{block}, $args{type}, $args{delforward}, $args{rpcuser});
[850]344
345 my $authuser = "$args{rpcsystem}/$args{rpcuser}";
346 if ($code eq 'OK' || $code =~ /^WARN/) {
347 syslog "notice", "$authuser deallocated '$blockinfo->{type}'-type netblock ID $args{block} ".
348 "($blockinfo->{block}), $blockinfo->{custid}, $blockinfo->{city}, desc='$blockinfo->{description}'";
349 mailNotify($ip_dbh, 'da', "REMOVED: $disp_alloctypes{$blockinfo->{type}} $blockinfo->{block}",
350# $args{block} useful? do we care about the block ID here?
351 "$disp_alloctypes{$blockinfo->{type}} $blockinfo->{block} deallocated by $authuser\n".
352 "CustID: $blockinfo->{custid}\nCity: $blockinfo->{city}\n".
[891]353 "Description: $blockinfo->{description}\n")
354 unless $args{nomail};
[850]355 } else {
356 if ($args{type} =~ /^.i$/) {
357 syslog "err", "$authuser could not deallocate static IP ID $args{block} ($blockinfo->{block}): '$msg'";
358 } else {
359 syslog "err", "$authuser could not deallocate netblock ID $args{block} ($blockinfo->{block}): '$msg'";
360 }
361 }
362
363 return $msg;
364} # rpc_deleteBlock()
365
366
[668]367sub rpc_getBlockData {}
368sub rpc_getBlockRDNS {}
369sub rpc_getNodeList {}
370sub rpc_getNodeName {}
371sub rpc_getNodeInfo {}
372sub rpc_mailNotify {}
373
374
375##
376## Subs not part of the core IPDB
377##
378
379# Subs to send back IPDB globals
380
381#our %disp_alloctypes;
382sub rpc_getDispAlloctypes {
383 my %args = @_;
384 _commoncheck(\%args, 'n');
385 return \%disp_alloctypes;
386}
387
388#our %list_alloctypes;
389sub rpc_getListAlloctypes {
390 my %args = @_;
391 _commoncheck(\%args, 'n');
392 return \%list_alloctypes;
393}
394
395#our %def_custids;
396sub rpc_getDefCustIDs {
397 my %args = @_;
398 _commoncheck(\%args, 'n');
399 return \%def_custids;
400}
401
402#our @citylist;
403sub rpc_getCityList {
404 my %args = @_;
405 _commoncheck(\%args, 'n');
406 return \@citylist;
407}
408
409#our @poplist;
410sub rpc_getPOPList {
411 my %args = @_;
412 _commoncheck(\%args, 'n');
413 return \@poplist;
414}
415
416# not sure how useful it is to expose this on RPC
417#our %IPDBacl;
418sub rpc_getIPDBacl {
419 my %args = @_;
420 _commoncheck(\%args, 'n');
421 return \%IPDBacl;
422}
423
424# Operations not provided directly by the core IPDB
425
426# Get a list of available static IPs of the given type
427# Not a core IPDB sub since there's little use for this format.
428sub rpc_getAvailableStatics {
429 my %args = @_;
430
431 _commoncheck(\%args, 'n');
432
433 my ($base,undef) = split //, $args{type};
434 $base .= "_";
435 my @params = ($base);
436
437 my $sql = "SELECT poolips.id,poolips.ip,poolips.parent_id,poolips.pool ".
438 "FROM poolips JOIN allocations ON poolips.parent_id=allocations.id WHERE poolips.type LIKE ?";
439 if ($base ne 'd_' && $args{city}) {
440 $sql .= " AND allocations.city=?";
441 push @params, $args{city};
442 }
443 $sql .= " AND poolips.available='y'";
444
445 my $ret = $ip_dbh->selectall_arrayref($sql, { Slice => {} }, (@params) );
446 die $ip_dbh->errstr if !$ret;
447
448 return $ret;
449} # rpc_getAvailableStatics()
[852]450
451
452sub rpc_getBackupList {
453 my %args = @_;
454
455 _commoncheck(\%args, 'n');
456
457 # grab the whole waffle.
458 my $sql = "SELECT backup_id, bkbrand, bkmodel, bktype, bkport, bksrc, bkuser, bkvpass, bkepass, ip FROM backuplist";
459 my $result = $ip_dbh->selectall_arrayref($sql, { Slice => {} });
460 die $ip_dbh->errstr if !$result;
461
462 return $result;
463} # rpc_getBackupList()
[885]464
465
466sub rpc_findAllocation {
467 my %args = @_;
468
469 _commoncheck(\%args, 'n');
470
471 die "IP to search for required\n" if !$args{ip} || $args{ip} !~ /^\d+\.\d+\.\d+\.\d+$/;
472
[890]473 my $sql = q(SELECT s.cidr,s.custid,s.type,s.description,a.dispname
474 FROM searchme s
475 JOIN alloctypes a ON s.type = a.type
476 WHERE cidr >>= ?);
[885]477 # first, check if it's even on our network
[890]478 my $isours = $ip_dbh->selectall_arrayref($sql." AND s.type = 'mm'", undef, $args{ip});
[885]479 die $ip_dbh->errstr."\n" if $ip_dbh->err; # do we care?
480 die "IP not on our network\n" if !@$isours;
481
482 # now, find the specific allocation
[890]483 my $result = $ip_dbh->selectall_arrayref($sql." AND NOT s.type LIKE '_m' ORDER BY cidr DESC",
[885]484 { Slice => {} }, $args{ip});
485 die $ip_dbh->errstr."\n" if $ip_dbh->err;
486
487 return $result;
488} # rpc_findAllocation()
Note: See TracBrowser for help on using the repository browser.