[PATCH] openbsc[master]: Add simple CTRL2SOAP proxy

Max gerrit-no-reply at lists.osmocom.org
Thu Feb 23 13:11:45 UTC 2017


Review at  https://gerrit.osmocom.org/1875

Add simple CTRL2SOAP proxy

Add python client which converts TRAP messages into SOAP requests and
perform corresponding actions.

It can be used as follows

./soap.py -d -w http://example.com/soapservice/htdocs/wsdl/test.wsdl -l 'http://localhost:8000/soapservice/SoapServer.php'

In this case the location of SOAP server from test.wsdl is ignored and
requests are dospatched to localhost instead. See ./soap.py -h for
additional options.

Change-Id: I82844ec7a302bac30d6daee9ebca2188fd48ca46
Related: SYS#3028
---
A openbsc/contrib/soap.py
1 file changed, 140 insertions(+), 0 deletions(-)


  git pull ssh://gerrit.osmocom.org:29418/openbsc refs/changes/75/1875/1

diff --git a/openbsc/contrib/soap.py b/openbsc/contrib/soap.py
new file mode 100755
index 0000000..19b4fe5
--- /dev/null
+++ b/openbsc/contrib/soap.py
@@ -0,0 +1,140 @@
+#!/usr/bin/python3
+# -*- mode: python-mode; py-indent-tabs-mode: nil -*-
+"""
+/*
+ * Copyright (C) 2016 sysmocom s.f.m.c. GmbH
+ *
+ * All Rights Reserved
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+"""
+
+from twisted.internet import reactor
+from twisted_ipa import CTRL, IPAFactory
+from ipa import Ctrl
+from treq import post, collect
+from suds.client import Client
+from suds.plugin import MessagePlugin
+from functools import partial
+import argparse, logging, datetime
+
+# keys from OpenBSC openbsc/src/libbsc/bsc_rf_ctrl.c, values SOAP-specific
+oper = { 'inoperational' : 0, 'operational' : 1 }
+admin = { 'locked' : 0, 'unlocked' : 1 }
+policy = { 'off' : 0, 'on' : 1, 'grace' : 2, 'unknown' : 3 }
+# keys from OpenBSC openbsc/src/libbsc/bsc_vty.c
+fix = { 'invalid' : 0, 'fix2d' : 1, 'fix3d' : 3 }
+
+class Trap(CTRL):
+    """
+    TRAP handler (agnostic to client object)
+    """
+    def ctrl_TRAP(self, data, op_id, v):
+        """
+        Parse CTRL TRAP and dispatch to appropriate handler after normalization
+        """
+        (l, r) = v.split()
+        loc = l.split('.')
+        t_type = loc[-1]
+        p = partial(lambda a, i: a[i] if len(a) > i else None, loc) # parse helper
+        method = getattr(self, 'handle_' + t_type.replace('-', ''), lambda: "Unhandled %s trap" % t_type)
+        method(p(1), p(3), p(5), p(7), r) # we expect net.0.bsc.666.bts.2.trx.1 format for trap prefix
+
+    def handle_locationstate(self, net, bsc, bts, trx, data):
+        """
+        Handle location-state TRAP: parse trap content, build SOAP context and use treq's routines to post it while setting up async handlers
+        """
+        def cback(c, r):
+            """
+            Callback function: takes c (SOAP client's RequestContext) and server's reply, sends set of parsed ctrl commands (in a 'fire and forget' way)
+            """
+            def commands(c, f):
+                """
+                Process OpenBscCommands format from .wsdl
+                """
+                for t in c:
+                    (_, m) = Ctrl().cmd(*t.split())
+                    f(m)
+            def keyvals(k, f):
+                """
+                Process OpenBscKeyVal format from .wsdl
+                """
+                for _, m in list(map(lambda x, y: Ctrl().cmd(x.rstrip(), y), k[0].key, k[0].value)):
+                    f(m)
+            # The 2 options below are mutually exclusive as the information in the reply is duplicated:
+            commands(c.process_reply(r).commands, self.transport.write)
+            #keyvals(c.process_reply(r).keysvals, self.transport.write)
+        (ts, fx, lat, lon, height, opr, adm, pol, mcc, mnc) = data.split(',')
+        tstamp = datetime.datetime.fromtimestamp(float(ts)).strftime('%Y-%m-%d')
+        self.dbg('location-state@%s.%s.%s.%s (%s) [%s/%s] => %s' % (net, bsc, bts, trx, tstamp, mcc, mnc, data))
+        ctx = self.factory.soap.service.registerOpenBscLocationAclSupport(bsc, float(lon), float(lat), fix.get(fx, 0), tstamp, oper.get(opr, 2), admin.get(adm, 2), policy.get(pol, 3))
+        handler = partial(cback, ctx) # make closure with context by partial parameter application
+        post(self.factory.location, ctx.envelope).addCallback(collect, handler) # treq's collect helper is handy to get all reply content at once
+
+    def handle_notificationrejectionv1(self, net, bsc, bts, trx, data):
+        """
+        Handle notification-rejection-v1 TRAP
+        """
+        self.dbg('notification-rejection-v1 at bsc-id %s => %s' % (bsc, data))
+
+
+class Filter(MessagePlugin):
+    """
+    Workarounds for broken .php SOAP server
+    """
+    def received(self, c):
+        c.reply = c.reply.replace(b'xsd:OpenBscCommands', b'ns1:OpenBscCommands')
+        c.reply = c.reply.replace(b'xsd:OpenBscKeyVal', b'ns1:OpenBscKeyVal')
+        c.reply = c.reply.replace(b'<item>', b'')
+        c.reply = c.reply.replace(b'value></item>', b'value>')
+        c.reply = c.reply.replace(b'item', b'command')
+
+
+class TrapFactory(IPAFactory):
+    """
+    Store SOAP client object so TRAP handler can use it for requests
+    """
+    location = None
+    soap = None
+    def __init__(self, proto=None, debug=False, wsdl=None, location=None):
+        self.location = location.encode()
+        self.soap = Client(wsdl, location=location, nosend=True, plugins=[Filter()]) # make async SOAP client
+        if debug:
+            print(self.soap)
+        super(TrapFactory, self).__init__(proto, debug)
+
+
+if __name__ == '__main__':
+    p = argparse.ArgumentParser("SOAP-CTRL proxy")
+    p.add_argument('-v', '--version', action='version', version='%(prog)s v0.1')
+    p.add_argument('-p', '--port', type=int, default=4250, help="Port to use for CTRL interface, defaults to 4250")
+    p.add_argument('-c', '--ctrl', default='localhost', help="Adress to use for CTRL interface, defaults to localhost")
+    p.add_argument('-w', '--wsdl', required=True, help="WSDL URL for SOAP")
+    p.add_argument('-s', '--size', type=int, default=5, help="Size of thread pool")
+    p.add_argument('-d', '--debug', action='store_true', help="Enable debug log")
+    p.add_argument('-l', '--location', help="Override location found in WSDL file")
+    args = p.parse_args()
+
+    logging.basicConfig(level=logging.ERROR)
+    if args.debug:
+        logging.getLogger('suds.client').setLevel(logging.DEBUG)
+        logging.getLogger('suds.transport').setLevel(logging.DEBUG)
+        logging.getLogger('suds.xsd').setLevel(logging.DEBUG)
+        logging.getLogger('suds.umx').setLevel(logging.DEBUG)
+
+    reactor.suggestThreadPoolSize(args.size)
+    reactor.connectTCP(args.ctrl, args.port, TrapFactory(Trap, args.debug, args.wsdl, args.location))
+    reactor.run()

-- 
To view, visit https://gerrit.osmocom.org/1875
To unsubscribe, visit https://gerrit.osmocom.org/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I82844ec7a302bac30d6daee9ebca2188fd48ca46
Gerrit-PatchSet: 1
Gerrit-Project: openbsc
Gerrit-Branch: master
Gerrit-Owner: Max <msuraev at sysmocom.de>


More information about the gerrit-log mailing list