Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 1 | #!/usr/bin/python3 |
| 2 | # -*- mode: python-mode; py-indent-tabs-mode: nil -*- |
| 3 | """ |
| 4 | /* |
| 5 | * Copyright (C) 2018 sysmocom s.f.m.c. GmbH |
| 6 | * |
| 7 | * All Rights Reserved |
| 8 | * |
| 9 | * This program is free software; you can redistribute it and/or modify |
| 10 | * it under the terms of the GNU General Public License as published by |
| 11 | * the Free Software Foundation; either version 3 of the License, or |
| 12 | * (at your option) any later version. |
| 13 | * |
| 14 | * This program is distributed in the hope that it will be useful, |
| 15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 17 | * GNU General Public License for more details. |
| 18 | * |
| 19 | * You should have received a copy of the GNU General Public License along |
| 20 | * with this program; if not, write to the Free Software Foundation, Inc., |
| 21 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. |
| 22 | */ |
| 23 | """ |
| 24 | |
Max | f7255fa | 2018-11-28 11:25:15 +0100 | [diff] [blame] | 25 | __version__ = "0.0.4" # bump this on every non-trivial change |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 26 | |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 27 | import argparse, os, logging, logging.handlers |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 28 | import hashlib |
| 29 | import json |
| 30 | import configparser |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 31 | from functools import partial |
| 32 | from distutils.version import StrictVersion as V # FIXME: use NormalizedVersion from PEP-386 when available |
| 33 | from twisted.internet import defer, reactor |
| 34 | from treq import post, collect |
| 35 | from osmopy.trap_helper import debug_init, get_type, get_r, p_h, make_params, comm_proc |
| 36 | from osmopy.twisted_ipa import CTRL, IPAFactory, __version__ as twisted_ipa_version |
| 37 | from osmopy.osmo_ipa import Ctrl |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 38 | |
| 39 | # we don't support older versions of TwistedIPA module |
| 40 | assert V(twisted_ipa_version) > V('0.4') |
| 41 | |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 42 | |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 43 | def handle_reply(f, log, resp): |
| 44 | """ |
| 45 | Reply handler: process raw CGI server response, function f to run for each command |
| 46 | """ |
Max | ec3944e | 2018-11-27 17:43:45 +0100 | [diff] [blame] | 47 | decoded = json.loads(resp.decode('utf-8')) |
Max | f7255fa | 2018-11-28 11:25:15 +0100 | [diff] [blame] | 48 | comm_proc(decoded.get('commands'), f, log) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 49 | |
| 50 | def gen_hash(params, skey): |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 51 | inp = '' |
| 52 | for key in ['time_stamp', 'position_validity', 'admin_status', 'policy_status']: |
| 53 | inp += str(params.get(key)) |
| 54 | inp += skey |
| 55 | for key in ['bsc_id', 'lat', 'lon', 'position_validity']: |
| 56 | inp += str(params.get(key)) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 57 | m = hashlib.md5() |
Max | 25a8297 | 2018-11-28 11:55:19 +0100 | [diff] [blame] | 58 | m.update(inp.encode('utf-8')) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 59 | res = m.hexdigest() |
| 60 | #print('HASH: \nparams="%r"\ninput="%s" \nres="%s"' %(params, input, res)) |
| 61 | return res |
| 62 | |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 63 | class Trap(CTRL): |
| 64 | """ |
| 65 | TRAP handler (agnostic to factory's client object) |
| 66 | """ |
| 67 | def ctrl_TRAP(self, data, op_id, v): |
| 68 | """ |
| 69 | Parse CTRL TRAP and dispatch to appropriate handler after normalization |
| 70 | """ |
| 71 | self.factory.log.debug('TRAP %s' % v) |
| 72 | t_type = get_type(v) |
| 73 | p = p_h(v) |
| 74 | method = getattr(self, 'handle_' + t_type.replace('-', ''), lambda *_: "Unhandled %s trap" % t_type) |
| 75 | method(p(1), p(3), p(5), p(7), get_r(v)) |
| 76 | |
| 77 | def ctrl_SET_REPLY(self, data, _, v): |
| 78 | """ |
| 79 | Debug log for replies to our commands |
| 80 | """ |
| 81 | self.factory.log.debug('SET REPLY %s' % v) |
| 82 | |
| 83 | def ctrl_ERROR(self, data, op_id, v): |
| 84 | """ |
| 85 | We want to know if smth went wrong |
| 86 | """ |
| 87 | self.factory.log.debug('CTRL ERROR [%s] %s' % (op_id, v)) |
| 88 | |
| 89 | def connectionMade(self): |
| 90 | """ |
| 91 | Logging wrapper, calling super() is necessary not to break reconnection logic |
| 92 | """ |
| 93 | self.factory.log.info("Connected to CTRL@%s:%d" % (self.factory.host, self.factory.port)) |
| 94 | super(CTRL, self).connectionMade() |
| 95 | |
| 96 | @defer.inlineCallbacks |
| 97 | def handle_locationstate(self, net, bsc, bts, trx, data): |
| 98 | """ |
| 99 | Handle location-state TRAP: parse trap content, build CGI Request and use treq's routines to post it while setting up async handlers |
| 100 | """ |
| 101 | params = make_params(bsc, data) |
| 102 | self.factory.log.debug('location-state@%s.%s.%s.%s (%s) => %s' % (net, bsc, bts, trx, params['time_stamp'], data)) |
| 103 | params['h'] = gen_hash(params, self.factory.secret_key) |
Max | ec3944e | 2018-11-27 17:43:45 +0100 | [diff] [blame] | 104 | d = post(self.factory.location, params) |
| 105 | d.addCallback(collect, partial(handle_reply, self.transport.write, self.factory.log)) # treq's collect helper is handy to get all reply content at once |
Max | a07e553 | 2018-11-27 17:42:07 +0100 | [diff] [blame] | 106 | d.addErrback(lambda e, bsc: self.factory.log.critical("HTTP POST error %s while trying to register BSC %s on %s" % (e, bsc, self.factory.location)), bsc) # handle HTTP errors |
| 107 | # Ensure that we run only limited number of requests in parallel: |
| 108 | yield self.factory.semaphore.acquire() |
| 109 | yield d # we end up here only if semaphore is available which means it's ok to fire the request without exceeding the limit |
| 110 | self.factory.semaphore.release() |
| 111 | |
| 112 | def handle_notificationrejectionv1(self, net, bsc, bts, trx, data): |
| 113 | """ |
| 114 | Handle notification-rejection-v1 TRAP: just an example to show how more message types can be handled |
| 115 | """ |
| 116 | self.factory.log.debug('notification-rejection-v1@bsc-id %s => %s' % (bsc, data)) |
| 117 | |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 118 | |
| 119 | class TrapFactory(IPAFactory): |
| 120 | """ |
| 121 | Store CGI information so TRAP handler can use it for requests |
| 122 | """ |
| 123 | location = None |
| 124 | log = None |
| 125 | semaphore = None |
| 126 | client = None |
| 127 | host = None |
| 128 | port = None |
| 129 | secret_key = None |
| 130 | def __init__(self, host, port, proto, semaphore, log, location, secret_key): |
| 131 | self.host = host # for logging only, |
| 132 | self.port = port # seems to be no way to get it from ReconnectingClientFactory |
| 133 | self.log = log |
| 134 | self.semaphore = semaphore |
| 135 | self.location = location |
| 136 | self.secret_key = secret_key |
| 137 | level = self.log.getEffectiveLevel() |
| 138 | self.log.setLevel(logging.WARNING) # we do not need excessive debug from lower levels |
| 139 | super(TrapFactory, self).__init__(proto, self.log) |
| 140 | self.log.setLevel(level) |
| 141 | self.log.debug("Using IPA %s, CGI server: %s" % (Ctrl.version, self.location)) |
| 142 | |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 143 | |
| 144 | if __name__ == '__main__': |
| 145 | p = argparse.ArgumentParser(description='Proxy between given GCI service and Osmocom CTRL protocol.') |
| 146 | p.add_argument('-v', '--version', action='version', version=("%(prog)s v" + __version__)) |
| 147 | p.add_argument('-a', '--addr-ctrl', default='localhost', help="Adress to use for CTRL interface, defaults to localhost") |
| 148 | p.add_argument('-p', '--port-ctrl', type=int, default=4250, help="Port to use for CTRL interface, defaults to 4250") |
| 149 | p.add_argument('-n', '--num-max-conn', type=int, default=5, help="Max number of concurrent HTTP requests to CGI server") |
Max | 5baba8c | 2018-11-26 16:42:59 +0100 | [diff] [blame] | 150 | p.add_argument('-d', '--debug', action='store_true', help="Enable debug log") # keep in sync with debug_init call below |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 151 | p.add_argument('-l', '--location', help="Location URL of the CGI server") |
| 152 | p.add_argument('-s', '--secret-key', help="Secret key used to generate verification token") |
| 153 | p.add_argument('-c', '--config-file', help="Path Config file. Cmd line args override values in config file") |
| 154 | args = p.parse_args() |
| 155 | |
Max | f0f8a35 | 2018-12-05 13:49:13 +0100 | [diff] [blame^] | 156 | log = debug_init('CTRL2CGI', args.debug) |
Pau Espin Pedrol | 10fbb40 | 2018-07-11 14:05:13 +0200 | [diff] [blame] | 157 | |
| 158 | location_cfgfile = None |
| 159 | secret_key_cfgfile = None |
| 160 | port_ctrl_cfgfile = None |
| 161 | addr_ctrl_cfgfile = None |
| 162 | num_max_conn_cfgfile = None |
| 163 | if args.config_file: |
| 164 | config = configparser.ConfigParser() |
| 165 | config.read(args.config_file) |
| 166 | if 'main' in config: |
| 167 | location_cfgfile = config['main'].get('location', None) |
| 168 | secret_key_cfgfile = config['main'].get('secret_key', None) |
| 169 | addr_ctrl_cfgfile = config['main'].get('addr_ctrl', None) |
| 170 | port_ctrl_cfgfile = config['main'].get('port_ctrl', None) |
| 171 | num_max_conn_cfgfile = config['main'].get('num_max_conn', None) |
| 172 | location = args.location if args.location is not None else location_cfgfile |
| 173 | secret_key = args.secret_key if args.secret_key is not None else secret_key_cfgfile |
| 174 | addr_ctrl = args.addr_ctrl if args.addr_ctrl is not None else addr_ctrl_cfgfile |
| 175 | port_ctrl = args.port_ctrl if args.port_ctrl is not None else port_ctrl_cfgfile |
| 176 | num_max_conn = args.num_max_conn if args.num_max_conn is not None else num_max_conn_cfgfile |
| 177 | |
| 178 | log.info("CGI proxy %s starting with PID %d ..." % (__version__, os.getpid())) |
| 179 | reactor.connectTCP(addr_ctrl, port_ctrl, TrapFactory(addr_ctrl, port_ctrl, Trap, defer.DeferredSemaphore(num_max_conn), log, location, secret_key)) |
| 180 | reactor.run() |