From 6f8ff326307ae1522e2f3163596b0bf1cdd2157f Mon Sep 17 00:00:00 2001 From: Sean Dague Date: Tue, 15 Apr 2008 14:24:15 +0000 Subject: From: Dr Scofield ansgar and i have been working on an asterisk voice module that will allow us to couple opensim with an asterisk VoIP gateway. the patch below consists of * AsteriskVoiceModule region module: alternative to the plain-vanilla VoiceModule, will make XmlRpc calls out to an asterisk-opensim frontend * asterisk-opensim.py frontend, living in share/python/asterisk, takes XmlRpc calls from the AsteriskVoiceModule * account_update: to update/create a new SIP account (on ProvisionVoiceAccountRequest) * region_update: to update/create a new "region" conference call (on ParcelVoiceInfo) * a asterisk-opensim test client, living in share/python/asterisk, to exercise astersik-opensim.py this still does not give us voice in OpenSim, but it's another step on this path... --- share/python/asterisk/asterisk-opensim.cfg | 16 ++ share/python/asterisk/asterisk-opensim.py | 231 +++++++++++++++++++++++++++++ share/python/asterisk/create-region.sql | 4 + share/python/asterisk/create-table.sql | 62 ++++++++ share/python/asterisk/create-user.sql | 5 + share/python/asterisk/test-client.py | 28 ++++ 6 files changed, 346 insertions(+) create mode 100644 share/python/asterisk/asterisk-opensim.cfg create mode 100644 share/python/asterisk/asterisk-opensim.py create mode 100644 share/python/asterisk/create-region.sql create mode 100644 share/python/asterisk/create-table.sql create mode 100644 share/python/asterisk/create-user.sql create mode 100644 share/python/asterisk/test-client.py (limited to 'share') diff --git a/share/python/asterisk/asterisk-opensim.cfg b/share/python/asterisk/asterisk-opensim.cfg new file mode 100644 index 0000000..174dd7a --- /dev/null +++ b/share/python/asterisk/asterisk-opensim.cfg @@ -0,0 +1,16 @@ +[xmlrpc] +baseurl = http://127.0.0.1:53263/ +debug = true + +[mysql] +server = localhost +database = asterisk +user = asterisk +password = asterisk +debug = true + +[mysql-templates] +tables = create-table.sql +user = create-user.sql +region = create-region.sql +debug = true diff --git a/share/python/asterisk/asterisk-opensim.py b/share/python/asterisk/asterisk-opensim.py new file mode 100644 index 0000000..aad72eb --- /dev/null +++ b/share/python/asterisk/asterisk-opensim.py @@ -0,0 +1,231 @@ +#!/usr/bin/python +# -*- encoding: utf-8 -*- + +from __future__ import with_statement + +import base64 +import ConfigParser +import optparse +import MySQLdb +import re +import SimpleXMLRPCServer +import socket +import sys +import uuid + +class AsteriskOpenSimServerException(Exception): + pass + +class AsteriskOpenSimServer(SimpleXMLRPCServer.SimpleXMLRPCServer): + '''Subclassed SimpleXMLRPCServer to be able to muck around with the socket options. + ''' + + def __init__(self, config): + baseURL = config.get('xmlrpc', 'baseurl') + match = reURLParser.match(baseURL) + if not match: + raise AsteriskOpenSimServerException('baseURL "%s" is not a well-formed URL' % (baseURL)) + + host = 'localhost' + port = 80 + path = None + if match.group('host'): + host = match.group('host') + port = int(match.group('port')) + else: + host = match.group('hostonly') + + self.__host = host + self.__port = port + + SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self,(host, port)) + + def host(self): + return self.__host + + def port(self): + return self.__port + + def server_bind(self): + self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self) + + +class AsteriskFrontend(object): + '''AsteriskFrontend serves as an XmlRpc function dispatcher. + ''' + + def __init__(self, config, db): + '''Constructor to take note of the AsteriskDB object. + ''' + self.__db = db + try: + self.__debug = config.getboolean('dispatcher', 'debug') + except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): + self.__debug = False + + def account_update(self, request): + '''update (or create) the SIP account data in the Asterisk RealTime DB. + + OpenSim's AsteriskVoiceModule will call this method each + time it receives a ProvisionVoiceAccount request. + ''' + print '[asterisk-opensim] account_update: new request' + + for p in ['admin_password', 'username', 'password']: + if p not in request: + print '[asterisk-opensim] account_update: failed: missing password' + return { 'success': 'false', 'error': 'missing parameter "%s"' % (p)} + + # turn base64 binary UUID into proper UUID + user = request['username'].partition('@')[0] + user = user.lstrip('x').replace('-','+').replace('_','/') + user = uuid.UUID(bytes = base64.standard_b64decode(user)) + + if self.__debug: print '[asterisk-opensim]: account_update: user %s' % user + + error = self.__db.AccountUpdate(user = user, password = request['password']) + if error: + print '[asterisk-opensim]: DB.AccountUpdate failed' + return { 'success': 'false', 'error': error} + + print '[asterisk-opensim] account_update: done' + return { 'success': 'true'} + + + def region_update(self, request): + '''update (or create) a VoIP conference call for a region. + + OpenSim's AsteriskVoiceModule will call this method each time it + receives a ParcelVoiceInfo request. + ''' + print '[asterisk-opensim] region_update: new request' + + for p in ['admin_password', 'region']: + if p not in request: + print '[asterisk-opensim] region_update: failed: missing password' + return { 'success': 'false', 'error': 'missing parameter "%s"' % (p)} + + region = request['region'].partition('@')[0] + if self.__debug: print '[asterisk-opensim]: region_update: region %s' % user + + error = self.__db.RegionUpdate(region = region) + if error: + print '[asterisk-opensim]: DB.RegionUpdate failed' + return { 'success': 'false', 'error': error} + + print '[asterisk-opensim] region_update: done' + return { 'success': 'true' } + +class AsteriskDBException(Exception): + pass + +class AsteriskDB(object): + '''AsteriskDB maintains the connection to Asterisk's MySQL database. + ''' + def __init__(self, config): + # configure from config object + self.__server = config.get('mysql', 'server') + self.__database = config.get('mysql', 'database') + self.__user = config.get('mysql', 'user') + self.__password = config.get('mysql', 'password') + + try: + self.__debug = config.getboolean('mysql', 'debug') + self.__debug_t = config.getboolean('mysql-templates', 'debug') + except ConfigParser.NoOptionError: + self.__debug = False + + self.__tablesTemplate = self.__loadTemplate(config, 'tables') + self.__userTemplate = self.__loadTemplate(config, 'user') + self.__regionTemplate = self.__loadTemplate(config, 'region') + + self.__mysql = MySQLdb.connect(host = self.__server, db = self.__database, + user = self.__user, passwd = self.__password) + if self.__assertDBExists(): + raise AsteriskDBException('could not initialize DB') + + def __loadTemplate(self, config, templateName): + template = config.get('mysql-templates', templateName) + t = '' + with open(template, 'r') as templateFile: + for line in templateFile: + line = line.rstrip('\n') + t += line + return t.split(';') + + + def __assertDBExists(self): + '''Assert that DB tables exist. + ''' + try: + cursor = self.__mysql.cursor() + for sql in self.__tablesTemplate[:]: + if not sql: continue + sql = sql % { 'database': self.__database } + if self.__debug: print 'AsteriskDB.__assertDBExists: %s' % sql + cursor.execute(sql) + cursor.fetchall() + cursor.close() + except MySQLdb.Error, e: + if self.__debug: print 'AsteriskDB.__assertDBExists: Error %d: %s' % (e.args[0], e.args[1]) + return e.args[1] + return None + + def AccountUpdate(self, user, password): + print 'AsteriskDB.AccountUpdate: user %s' % (user) + try: + cursor = self.__mysql.cursor() + for sql in self.__userTemplate[:]: + if not sql: continue + sql = sql % { 'database': self.__database, 'username': user, 'password': password } + if self.__debug_t: print 'AsteriskDB.AccountUpdate: sql: %s' % sql + cursor.execute(sql) + cursor.fetchall() + cursor.close() + except MySQLdb.Error, e: + if self.__debug: print 'AsteriskDB.RegionUpdate: Error %d: %s' % (e.args[0], e.args[1]) + return e.args[1] + return None + + def RegionUpdate(self, region): + print 'AsteriskDB.RegionUpdate: region %s' % (region) + try: + cursor = self.__mysql.cursor() + for sql in self.__regionTemplate[:]: + if not sql: continue + sql = sql % { 'database': self.__database, 'regionname': region } + if self.__debug_t: print 'AsteriskDB.RegionUpdate: sql: %s' % sql + cursor.execute(sql) + res = cursor.fetchall() + except MySQLdb.Error, e: + if self.__debug: print 'AsteriskDB.RegionUpdate: Error %d: %s' % (e.args[0], e.args[1]) + return e.args[1] + return None + + +reURLParser = re.compile(r'^http://((?P[^/]+):(?P\d+)|(?P[^/]+))/', re.IGNORECASE) + +# main +if __name__ == '__main__': + + parser = optparse.OptionParser() + parser.add_option('-c', '--config', dest = 'config', help = 'config file', metavar = 'CONFIG') + (options, args) = parser.parse_args() + + if not options.config: + parser.error('missing option config') + sys.exit(1) + + config = ConfigParser.ConfigParser() + config.readfp(open(options.config)) + + server = AsteriskOpenSimServer(config) + server.register_introspection_functions() + server.register_instance(AsteriskFrontend(config, AsteriskDB(config))) + + # get cracking + print '[asterisk-opensim] server ready on %s:%d' % (server.host(), server.port()) + server.serve_forever() + + sys.exit(0) diff --git a/share/python/asterisk/create-region.sql b/share/python/asterisk/create-region.sql new file mode 100644 index 0000000..a11e77a --- /dev/null +++ b/share/python/asterisk/create-region.sql @@ -0,0 +1,4 @@ +USE %(database)s; +REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(regionname)s', 1, 'Answer', ''); +REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(regionname)s', 2, 'Wait', '1'); +REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(regionname)s', 3, 'Meetme', '%(regionname)s|Acdi'); \ No newline at end of file diff --git a/share/python/asterisk/create-table.sql b/share/python/asterisk/create-table.sql new file mode 100644 index 0000000..4fe190f --- /dev/null +++ b/share/python/asterisk/create-table.sql @@ -0,0 +1,62 @@ +USE %(database)s; +CREATE TABLE IF NOT EXISTS `ast_sipfriends` ( + `id` int(11) NOT NULL auto_increment, + `name` varchar(80) NOT NULL default '', + `host` varchar(31) NOT NULL default 'dynamic', + `nat` varchar(5) NOT NULL default 'route', + `type` enum('user','peer','friend') NOT NULL default 'friend', + `accountcode` varchar(20) default NULL, + `amaflags` varchar(13) default NULL, + `callgroup` varchar(10) default NULL, + `callerid` varchar(80) default NULL, + `call-limit` int(11) NOT NULL default '0', + `cancallforward` char(3) default 'no', + `canreinvite` char(3) default 'no', + `context` varchar(80) default 'pre_outgoing', + `defaultip` varchar(15) default NULL, + `dtmfmode` varchar(7) default NULL, + `fromuser` varchar(80) default NULL, + `fromdomain` varchar(80) default NULL, + `insecure` varchar(4) default NULL, + `language` char(2) default NULL, + `mailbox` varchar(50) default NULL, + `md5secret` varchar(80) default NULL, + `deny` varchar(95) default NULL, + `permit` varchar(95) default NULL, + `mask` varchar(95) default NULL, + `musiconhold` varchar(100) default NULL, + `pickupgroup` varchar(10) default NULL, + `qualify` char(3) default NULL, + `regexten` varchar(80) default NULL, + `restrictcid` char(3) default NULL, + `rtptimeout` char(3) default NULL, + `rtpholdtimeout` char(3) default NULL, + `secret` varchar(80) default NULL, + `setvar` varchar(100) default NULL, + `disallow` varchar(100) default 'all', + `allow` varchar(100) default 'g729', + `fullcontact` varchar(80) NOT NULL default '', + `ipaddr` varchar(15) NOT NULL default '', + `port` smallint(5) unsigned NOT NULL default '0', + `regserver` varchar(100) default NULL, + `regseconds` int(11) NOT NULL default '0', + `username` varchar(80) NOT NULL default '', + `user` varchar(255) NOT NULL, + `placement` varchar(255) NOT NULL, + `description` varchar(255) NOT NULL, + `delay` int(4) NOT NULL default '0', + `sortorder` int(11) NOT NULL default '1', + PRIMARY KEY (`id`), + UNIQUE KEY `name` (`name`) +) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; + +CREATE TABLE IF NOT EXISTS `extensions_table` ( + `id` int(11) NOT NULL auto_increment, + `context` varchar(20) NOT NULL default '', + `exten` varchar(36) NOT NULL default '', + `priority` tinyint(4) NOT NULL default '0', + `app` varchar(20) NOT NULL default '', + `appdata` varchar(128) NOT NULL default '', + PRIMARY KEY (`context`,`exten`,`priority`), + KEY `id` (`id`) +) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; \ No newline at end of file diff --git a/share/python/asterisk/create-user.sql b/share/python/asterisk/create-user.sql new file mode 100644 index 0000000..68b8147 --- /dev/null +++ b/share/python/asterisk/create-user.sql @@ -0,0 +1,5 @@ +USE %(database)s; +REPLACE INTO ast_sipfriends (port,context,disallow,allow,type,secret,host,name) VALUES ('5060','avatare','all','ulaw','friend','%(password)s','dynamic','%(username)s'); +REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(username)s', 1, 'Answer', ''); +REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(username)s', 2, 'Wait', '1'); +REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(username)s', 3, 'Dial', 'SIP/%(username)s,60'); \ No newline at end of file diff --git a/share/python/asterisk/test-client.py b/share/python/asterisk/test-client.py new file mode 100644 index 0000000..d1872cd --- /dev/null +++ b/share/python/asterisk/test-client.py @@ -0,0 +1,28 @@ +#!/usr/bin/python +# -*- encoding: utf-8 -*- + +import xmlrpclib + +# XML-RPC URL (http_listener_port) +asteriskServerURL = 'http://127.0.0.1:53263' + +# instantiate server object +asteriskServer = xmlrpclib.Server(asteriskServerURL) + +try: + # invoke admin_alert: requires password and message + res = asteriskServer.region_update({ + 'admin_password': 'c00lstuff', + 'region' : '941ae087-a7da-43b4-900b-9fe48387ae57@secondlife.zurich.ibm.com' + }) + print res + + res = asteriskServer.account_update({ + 'admin_password': 'c00lstuff', + 'username' : '0780d90b-1939-4152-a283-8d1261fb1b68@secondlife.zurich.ibm.com', + 'password' : '$1$dd02c7c2232759874e1c205587017bed' + }) + print res +except Exception, e: + print e + -- cgit v1.1