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

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

/trunk

Updates to RPC findAllocation() to provide more details to the caller
in one shot

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