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

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

/trunk

Update FastCGI setup/call
Add nomail argument to add and update methods

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