diff options
author | Sean Dague | 2008-04-15 14:24:15 +0000 |
---|---|---|
committer | Sean Dague | 2008-04-15 14:24:15 +0000 |
commit | 6f8ff326307ae1522e2f3163596b0bf1cdd2157f (patch) | |
tree | 4517fcd0560e9cf05ad170c0032fc9a60e7a01e4 | |
parent | From: dirk husemann <hud@zurich.ibm.com> (diff) | |
download | opensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.zip opensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.tar.gz opensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.tar.bz2 opensim-SC-6f8ff326307ae1522e2f3163596b0bf1cdd2157f.tar.xz |
From: Dr Scofield <hud@zurich.ibm.com>
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...
Diffstat (limited to '')
-rw-r--r-- | OpenSim/Framework/Communications/Capabilities/Caps.cs | 1 | ||||
-rw-r--r-- | OpenSim/Region/Environment/Modules/AsteriskVoiceModule.cs | 288 | ||||
-rw-r--r-- | bin/OpenSim.ini.example | 16 | ||||
-rw-r--r-- | share/python/asterisk/asterisk-opensim.cfg | 16 | ||||
-rw-r--r-- | share/python/asterisk/asterisk-opensim.py | 231 | ||||
-rw-r--r-- | share/python/asterisk/create-region.sql | 4 | ||||
-rw-r--r-- | share/python/asterisk/create-table.sql | 62 | ||||
-rw-r--r-- | share/python/asterisk/create-user.sql | 5 | ||||
-rw-r--r-- | share/python/asterisk/test-client.py | 28 |
9 files changed, 651 insertions, 0 deletions
diff --git a/OpenSim/Framework/Communications/Capabilities/Caps.cs b/OpenSim/Framework/Communications/Capabilities/Caps.cs index 46f50ad..a65a3f1 100644 --- a/OpenSim/Framework/Communications/Capabilities/Caps.cs +++ b/OpenSim/Framework/Communications/Capabilities/Caps.cs | |||
@@ -201,6 +201,7 @@ namespace OpenSim.Region.Capabilities | |||
201 | { | 201 | { |
202 | //Console.WriteLine("caps request " + request); | 202 | //Console.WriteLine("caps request " + request); |
203 | string result = LLSDHelpers.SerialiseLLSDReply(m_capsHandlers.CapsDetails); | 203 | string result = LLSDHelpers.SerialiseLLSDReply(m_capsHandlers.CapsDetails); |
204 | //m_log.DebugFormat("[CAPS] CapsRequest {0}", result); | ||
204 | return result; | 205 | return result; |
205 | } | 206 | } |
206 | 207 | ||
diff --git a/OpenSim/Region/Environment/Modules/AsteriskVoiceModule.cs b/OpenSim/Region/Environment/Modules/AsteriskVoiceModule.cs new file mode 100644 index 0000000..52b9c3e --- /dev/null +++ b/OpenSim/Region/Environment/Modules/AsteriskVoiceModule.cs | |||
@@ -0,0 +1,288 @@ | |||
1 | /* | ||
2 | * Copyright (c) Contributors, http://opensimulator.org/ | ||
3 | * See CONTRIBUTORS.TXT for a full list of copyright holders. | ||
4 | * | ||
5 | * Redistribution and use in source and binary forms, with or without | ||
6 | * modification, are permitted provided that the following conditions are met: | ||
7 | * * Redistributions of source code must retain the above copyright | ||
8 | * notice, this list of conditions and the following disclaimer. | ||
9 | * * Redistributions in binary form must reproduce the above copyright | ||
10 | * notice, this list of conditions and the following disclaimer in the | ||
11 | * documentation and/or other materials provided with the distribution. | ||
12 | * * Neither the name of the OpenSim Project nor the | ||
13 | * names of its contributors may be used to endorse or promote products | ||
14 | * derived from this software without specific prior written permission. | ||
15 | * | ||
16 | * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY | ||
17 | * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | ||
18 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
19 | * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY | ||
20 | * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | ||
21 | * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | ||
22 | * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | ||
23 | * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
24 | * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | ||
25 | * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
26 | */ | ||
27 | |||
28 | using System; | ||
29 | using System.Collections; | ||
30 | using System.Collections.Generic; | ||
31 | using libsecondlife; | ||
32 | using Nini.Config; | ||
33 | using Nwc.XmlRpc; | ||
34 | using OpenSim.Framework; | ||
35 | using OpenSim.Framework.Communications.Cache; | ||
36 | using OpenSim.Framework.Servers; | ||
37 | using OpenSim.Region.Capabilities; | ||
38 | using Caps = OpenSim.Region.Capabilities.Caps; | ||
39 | using OpenSim.Region.Environment.Interfaces; | ||
40 | using OpenSim.Region.Environment.Scenes; | ||
41 | |||
42 | namespace OpenSim.Region.Environment.Modules | ||
43 | { | ||
44 | public class AsteriskVoiceModule : IRegionModule | ||
45 | { | ||
46 | private static readonly log4net.ILog m_log = | ||
47 | log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | ||
48 | |||
49 | private Scene m_scene; | ||
50 | private IConfig m_config; | ||
51 | private string m_asterisk; | ||
52 | private string m_asterisk_password; | ||
53 | private string m_asterisk_salt; | ||
54 | private int m_asterisk_timeout; | ||
55 | private string m_sipDomain; | ||
56 | private string m_confDomain; | ||
57 | |||
58 | private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; | ||
59 | private static readonly string m_provisionVoiceAccountRequestPath = "0008/"; | ||
60 | |||
61 | public void Initialise(Scene scene, IConfigSource config) | ||
62 | { | ||
63 | m_scene = scene; | ||
64 | m_config = config.Configs["AsteriskVoice"]; | ||
65 | |||
66 | if (null == m_config) | ||
67 | { | ||
68 | m_log.Info("[ASTERISKVOICE] no config found, plugin disabled"); | ||
69 | return; | ||
70 | } | ||
71 | |||
72 | if (!m_config.GetBoolean("enabled", false)) | ||
73 | { | ||
74 | m_log.Info("[ASTERISKVOICE] plugin disabled by configuration"); | ||
75 | return; | ||
76 | } | ||
77 | m_log.Info("[ASTERISKVOICE] plugin enabled"); | ||
78 | |||
79 | try { | ||
80 | m_sipDomain = m_config.GetString("sip_domain", String.Empty); | ||
81 | m_log.InfoFormat("[ASTERISKVOICE] using SIP domain {0}", m_sipDomain); | ||
82 | |||
83 | m_confDomain = m_config.GetString("conf_domain", String.Empty); | ||
84 | m_log.InfoFormat("[ASTERISKVOICE] using conf domain {0}", m_confDomain); | ||
85 | |||
86 | m_asterisk = m_config.GetString("asterisk_frontend", String.Empty); | ||
87 | m_asterisk_password = m_config.GetString("asterisk_password", String.Empty); | ||
88 | m_asterisk_timeout = m_config.GetInt("asterisk_timeout", 3000); | ||
89 | m_asterisk_salt = m_config.GetString("asterisk_salt", "Wuffwuff"); | ||
90 | if (String.IsNullOrEmpty(m_asterisk)) throw new Exception("missing asterisk_frontend config parameter"); | ||
91 | if (String.IsNullOrEmpty(m_asterisk_password)) throw new Exception("missing asterisk_password config parameter"); | ||
92 | m_log.InfoFormat("[ASTERISKVOICE] using asterisk front end {0}", m_asterisk); | ||
93 | |||
94 | scene.EventManager.OnRegisterCaps += OnRegisterCaps; | ||
95 | } | ||
96 | catch (Exception e) | ||
97 | { | ||
98 | m_log.ErrorFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.Message); | ||
99 | m_log.DebugFormat("[ASTERISKVOICE] plugin initialization failed: {0}", e.ToString()); | ||
100 | return; | ||
101 | } | ||
102 | } | ||
103 | |||
104 | public void PostInitialise() | ||
105 | { | ||
106 | } | ||
107 | |||
108 | public void Close() | ||
109 | { | ||
110 | } | ||
111 | |||
112 | public string Name | ||
113 | { | ||
114 | get { return "AsteriskVoiceModule"; } | ||
115 | } | ||
116 | |||
117 | public bool IsSharedModule | ||
118 | { | ||
119 | get { return false; } | ||
120 | } | ||
121 | |||
122 | public void OnRegisterCaps(LLUUID agentID, Caps caps) | ||
123 | { | ||
124 | m_log.DebugFormat("[ASTERISKVOICE] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); | ||
125 | string capsBase = "/CAPS/" + caps.CapsObjectPath; | ||
126 | caps.RegisterHandler("ParcelVoiceInfoRequest", | ||
127 | new RestStreamHandler("POST", capsBase + m_parcelVoiceInfoRequestPath, | ||
128 | delegate(string request, string path, string param) | ||
129 | { | ||
130 | return ParcelVoiceInfoRequest(request, path, param, | ||
131 | agentID, caps); | ||
132 | })); | ||
133 | caps.RegisterHandler("ProvisionVoiceAccountRequest", | ||
134 | new RestStreamHandler("POST", capsBase + m_provisionVoiceAccountRequestPath, | ||
135 | delegate(string request, string path, string param) | ||
136 | { | ||
137 | return ProvisionVoiceAccountRequest(request, path, param, | ||
138 | agentID, caps); | ||
139 | })); | ||
140 | } | ||
141 | |||
142 | /// <summary> | ||
143 | /// Callback for a client request for ParcelVoiceInfo | ||
144 | /// </summary> | ||
145 | /// <param name="request"></param> | ||
146 | /// <param name="path"></param> | ||
147 | /// <param name="param"></param> | ||
148 | /// <param name="agentID"></param> | ||
149 | /// <param name="caps"></param> | ||
150 | /// <returns></returns> | ||
151 | public string ParcelVoiceInfoRequest(string request, string path, string param, | ||
152 | LLUUID agentID, Caps caps) | ||
153 | { | ||
154 | // we need to do: | ||
155 | // - send channel_uri: as "sip:regionID@m_sipDomain" | ||
156 | try | ||
157 | { | ||
158 | m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: request: {0}, path: {1}, param: {2}", | ||
159 | request, path, param); | ||
160 | |||
161 | |||
162 | // setup response to client | ||
163 | Hashtable creds = new Hashtable(); | ||
164 | creds["channel_uri"] = String.Format("sip:{0}@{1}", | ||
165 | m_scene.RegionInfo.RegionID.ToString(), m_sipDomain); | ||
166 | |||
167 | string regionName = m_scene.RegionInfo.RegionName; | ||
168 | ScenePresence avatar = m_scene.GetScenePresence(agentID); | ||
169 | if (null == m_scene.LandChannel) throw new Exception("land data not yet available"); | ||
170 | LandData land = m_scene.GetLandData(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); | ||
171 | |||
172 | LLSDParcelVoiceInfoResponse parcelVoiceInfo = | ||
173 | new LLSDParcelVoiceInfoResponse(regionName, land.localID, creds); | ||
174 | |||
175 | string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); | ||
176 | |||
177 | |||
178 | // update region on asterisk-opensim frontend | ||
179 | Hashtable requestData = new Hashtable(); | ||
180 | requestData["admin_password"] = m_asterisk_password; | ||
181 | requestData["region"] = m_scene.RegionInfo.RegionID.ToString(); | ||
182 | if (!String.IsNullOrEmpty(m_confDomain)) | ||
183 | { | ||
184 | requestData["region"] += String.Format("@{0}", m_confDomain); | ||
185 | } | ||
186 | |||
187 | ArrayList SendParams = new ArrayList(); | ||
188 | SendParams.Add(requestData); | ||
189 | XmlRpcRequest updateAccountRequest = new XmlRpcRequest("region_update", SendParams); | ||
190 | XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); | ||
191 | Hashtable responseData = (Hashtable)updateAccountResponse.Value; | ||
192 | |||
193 | if (!responseData.ContainsKey("success")) throw new Exception("region_update call failed"); | ||
194 | |||
195 | bool success = Convert.ToBoolean((string)responseData["success"]); | ||
196 | if (!success) throw new Exception("region_update failed"); | ||
197 | |||
198 | |||
199 | m_log.DebugFormat("[ASTERISKVOICE][PARCELVOICE]: {0}", r); | ||
200 | return r; | ||
201 | } | ||
202 | catch (Exception e) | ||
203 | { | ||
204 | m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0}, retry later", e.Message); | ||
205 | m_log.DebugFormat("[ASTERISKVOICE][CAPS][PARCELVOICE]: {0} failed", e.ToString()); | ||
206 | |||
207 | return "<llsd>undef</llsd>"; | ||
208 | } | ||
209 | |||
210 | return null; | ||
211 | } | ||
212 | |||
213 | /// <summary> | ||
214 | /// Callback for a client request for Voice Account Details | ||
215 | /// </summary> | ||
216 | /// <param name="request"></param> | ||
217 | /// <param name="path"></param> | ||
218 | /// <param name="param"></param> | ||
219 | /// <param name="agentID"></param> | ||
220 | /// <param name="caps"></param> | ||
221 | /// <returns></returns> | ||
222 | public string ProvisionVoiceAccountRequest(string request, string path, string param, | ||
223 | LLUUID agentID, Caps caps) | ||
224 | { | ||
225 | // we need to | ||
226 | // - get user data from UserProfileCacheService | ||
227 | // - generate nonce for user voice account password | ||
228 | // - issue XmlRpc request to asterisk opensim front end: | ||
229 | // + user: base 64 encoded user name (otherwise SL | ||
230 | // client is unhappy) | ||
231 | // + password: nonce | ||
232 | // - the XmlRpc call to asteris-opensim was successful: | ||
233 | // send account details back to client | ||
234 | try | ||
235 | { | ||
236 | m_log.DebugFormat("[ASTERISKVOICE][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", | ||
237 | request, path, param); | ||
238 | |||
239 | // get user data & prepare voice account response | ||
240 | string voiceUser = "x" + Convert.ToBase64String(agentID.GetBytes()); | ||
241 | voiceUser = voiceUser.Replace('+', '-').Replace('/', '_'); | ||
242 | |||
243 | CachedUserInfo userInfo = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(agentID); | ||
244 | if (null == userInfo) throw new Exception("cannot get user details"); | ||
245 | |||
246 | // we generate a nonce everytime | ||
247 | string voicePassword = "$1$" + Util.Md5Hash(DateTime.UtcNow.ToLongTimeString() + m_asterisk_salt); | ||
248 | LLSDVoiceAccountResponse voiceAccountResponse = | ||
249 | new LLSDVoiceAccountResponse(voiceUser, voicePassword); | ||
250 | string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); | ||
251 | m_log.DebugFormat("[CAPS][PROVISIONVOICE]: {0}", r); | ||
252 | |||
253 | |||
254 | // update user account on asterisk frontend | ||
255 | Hashtable requestData = new Hashtable(); | ||
256 | requestData["admin_password"] = m_asterisk_password; | ||
257 | requestData["username"] = voiceUser; | ||
258 | if (!String.IsNullOrEmpty(m_sipDomain)) | ||
259 | { | ||
260 | requestData["username"] += String.Format("@{0}", m_sipDomain); | ||
261 | } | ||
262 | requestData["password"] = voicePassword; | ||
263 | |||
264 | ArrayList SendParams = new ArrayList(); | ||
265 | SendParams.Add(requestData); | ||
266 | XmlRpcRequest updateAccountRequest = new XmlRpcRequest("account_update", SendParams); | ||
267 | XmlRpcResponse updateAccountResponse = updateAccountRequest.Send(m_asterisk, m_asterisk_timeout); | ||
268 | Hashtable responseData = (Hashtable)updateAccountResponse.Value; | ||
269 | |||
270 | if (!responseData.ContainsKey("success")) throw new Exception("account_update call failed"); | ||
271 | |||
272 | bool success = Convert.ToBoolean((string)responseData["success"]); | ||
273 | if (!success) throw new Exception("account_update failed"); | ||
274 | |||
275 | return r; | ||
276 | } | ||
277 | catch (Exception e) | ||
278 | { | ||
279 | m_log.ErrorFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0}, retry later", e.Message); | ||
280 | m_log.DebugFormat("[ASTERISKVOICE][CAPS][PROVISIONVOICE]: {0} failed", e.ToString()); | ||
281 | |||
282 | return "<llsd>undef</llsd>"; | ||
283 | } | ||
284 | |||
285 | return null; | ||
286 | } | ||
287 | } | ||
288 | } | ||
diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 6a04947..4e99740 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example | |||
@@ -173,6 +173,22 @@ account_management_server = https://www.bhr.vivox.com/api2 | |||
173 | ; Global SIP Server for conference calls | 173 | ; Global SIP Server for conference calls |
174 | sip_domain = testserver.com | 174 | sip_domain = testserver.com |
175 | 175 | ||
176 | [AsteriskVoice] | ||
177 | ; PLEASE NOTE that we don't have voice support in OpenSim quite yet - these configuration options are stubs | ||
178 | enabled = false | ||
179 | ; SIP account server domain | ||
180 | sip_domain = testserver.com | ||
181 | ; SIP conf server domain | ||
182 | conf_domain = testserver.com | ||
183 | ; URL of the asterisk opensim frontend | ||
184 | asterisk_frontend = http://testserver.com:49153/ | ||
185 | ; password for the asterisk frontend XmlRpc calls | ||
186 | asterisk_password = bah-humbug | ||
187 | ; timeout for XmlRpc calls to asterisk front end (in ms) | ||
188 | asterisk_timeout = 3000 | ||
189 | ; salt for asterisk nonces | ||
190 | asterisk_salt = paluempalum | ||
191 | |||
176 | ; Uncomment the following to control the progression of daytime | 192 | ; Uncomment the following to control the progression of daytime |
177 | ; in the Sim. The defaults are what is shown below | 193 | ; in the Sim. The defaults are what is shown below |
178 | ;[Sun] | 194 | ;[Sun] |
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 @@ | |||
1 | [xmlrpc] | ||
2 | baseurl = http://127.0.0.1:53263/ | ||
3 | debug = true | ||
4 | |||
5 | [mysql] | ||
6 | server = localhost | ||
7 | database = asterisk | ||
8 | user = asterisk | ||
9 | password = asterisk | ||
10 | debug = true | ||
11 | |||
12 | [mysql-templates] | ||
13 | tables = create-table.sql | ||
14 | user = create-user.sql | ||
15 | region = create-region.sql | ||
16 | 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 @@ | |||
1 | #!/usr/bin/python | ||
2 | # -*- encoding: utf-8 -*- | ||
3 | |||
4 | from __future__ import with_statement | ||
5 | |||
6 | import base64 | ||
7 | import ConfigParser | ||
8 | import optparse | ||
9 | import MySQLdb | ||
10 | import re | ||
11 | import SimpleXMLRPCServer | ||
12 | import socket | ||
13 | import sys | ||
14 | import uuid | ||
15 | |||
16 | class AsteriskOpenSimServerException(Exception): | ||
17 | pass | ||
18 | |||
19 | class AsteriskOpenSimServer(SimpleXMLRPCServer.SimpleXMLRPCServer): | ||
20 | '''Subclassed SimpleXMLRPCServer to be able to muck around with the socket options. | ||
21 | ''' | ||
22 | |||
23 | def __init__(self, config): | ||
24 | baseURL = config.get('xmlrpc', 'baseurl') | ||
25 | match = reURLParser.match(baseURL) | ||
26 | if not match: | ||
27 | raise AsteriskOpenSimServerException('baseURL "%s" is not a well-formed URL' % (baseURL)) | ||
28 | |||
29 | host = 'localhost' | ||
30 | port = 80 | ||
31 | path = None | ||
32 | if match.group('host'): | ||
33 | host = match.group('host') | ||
34 | port = int(match.group('port')) | ||
35 | else: | ||
36 | host = match.group('hostonly') | ||
37 | |||
38 | self.__host = host | ||
39 | self.__port = port | ||
40 | |||
41 | SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self,(host, port)) | ||
42 | |||
43 | def host(self): | ||
44 | return self.__host | ||
45 | |||
46 | def port(self): | ||
47 | return self.__port | ||
48 | |||
49 | def server_bind(self): | ||
50 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | ||
51 | SimpleXMLRPCServer.SimpleXMLRPCServer.server_bind(self) | ||
52 | |||
53 | |||
54 | class AsteriskFrontend(object): | ||
55 | '''AsteriskFrontend serves as an XmlRpc function dispatcher. | ||
56 | ''' | ||
57 | |||
58 | def __init__(self, config, db): | ||
59 | '''Constructor to take note of the AsteriskDB object. | ||
60 | ''' | ||
61 | self.__db = db | ||
62 | try: | ||
63 | self.__debug = config.getboolean('dispatcher', 'debug') | ||
64 | except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): | ||
65 | self.__debug = False | ||
66 | |||
67 | def account_update(self, request): | ||
68 | '''update (or create) the SIP account data in the Asterisk RealTime DB. | ||
69 | |||
70 | OpenSim's AsteriskVoiceModule will call this method each | ||
71 | time it receives a ProvisionVoiceAccount request. | ||
72 | ''' | ||
73 | print '[asterisk-opensim] account_update: new request' | ||
74 | |||
75 | for p in ['admin_password', 'username', 'password']: | ||
76 | if p not in request: | ||
77 | print '[asterisk-opensim] account_update: failed: missing password' | ||
78 | return { 'success': 'false', 'error': 'missing parameter "%s"' % (p)} | ||
79 | |||
80 | # turn base64 binary UUID into proper UUID | ||
81 | user = request['username'].partition('@')[0] | ||
82 | user = user.lstrip('x').replace('-','+').replace('_','/') | ||
83 | user = uuid.UUID(bytes = base64.standard_b64decode(user)) | ||
84 | |||
85 | if self.__debug: print '[asterisk-opensim]: account_update: user %s' % user | ||
86 | |||
87 | error = self.__db.AccountUpdate(user = user, password = request['password']) | ||
88 | if error: | ||
89 | print '[asterisk-opensim]: DB.AccountUpdate failed' | ||
90 | return { 'success': 'false', 'error': error} | ||
91 | |||
92 | print '[asterisk-opensim] account_update: done' | ||
93 | return { 'success': 'true'} | ||
94 | |||
95 | |||
96 | def region_update(self, request): | ||
97 | '''update (or create) a VoIP conference call for a region. | ||
98 | |||
99 | OpenSim's AsteriskVoiceModule will call this method each time it | ||
100 | receives a ParcelVoiceInfo request. | ||
101 | ''' | ||
102 | print '[asterisk-opensim] region_update: new request' | ||
103 | |||
104 | for p in ['admin_password', 'region']: | ||
105 | if p not in request: | ||
106 | print '[asterisk-opensim] region_update: failed: missing password' | ||
107 | return { 'success': 'false', 'error': 'missing parameter "%s"' % (p)} | ||
108 | |||
109 | region = request['region'].partition('@')[0] | ||
110 | if self.__debug: print '[asterisk-opensim]: region_update: region %s' % user | ||
111 | |||
112 | error = self.__db.RegionUpdate(region = region) | ||
113 | if error: | ||
114 | print '[asterisk-opensim]: DB.RegionUpdate failed' | ||
115 | return { 'success': 'false', 'error': error} | ||
116 | |||
117 | print '[asterisk-opensim] region_update: done' | ||
118 | return { 'success': 'true' } | ||
119 | |||
120 | class AsteriskDBException(Exception): | ||
121 | pass | ||
122 | |||
123 | class AsteriskDB(object): | ||
124 | '''AsteriskDB maintains the connection to Asterisk's MySQL database. | ||
125 | ''' | ||
126 | def __init__(self, config): | ||
127 | # configure from config object | ||
128 | self.__server = config.get('mysql', 'server') | ||
129 | self.__database = config.get('mysql', 'database') | ||
130 | self.__user = config.get('mysql', 'user') | ||
131 | self.__password = config.get('mysql', 'password') | ||
132 | |||
133 | try: | ||
134 | self.__debug = config.getboolean('mysql', 'debug') | ||
135 | self.__debug_t = config.getboolean('mysql-templates', 'debug') | ||
136 | except ConfigParser.NoOptionError: | ||
137 | self.__debug = False | ||
138 | |||
139 | self.__tablesTemplate = self.__loadTemplate(config, 'tables') | ||
140 | self.__userTemplate = self.__loadTemplate(config, 'user') | ||
141 | self.__regionTemplate = self.__loadTemplate(config, 'region') | ||
142 | |||
143 | self.__mysql = MySQLdb.connect(host = self.__server, db = self.__database, | ||
144 | user = self.__user, passwd = self.__password) | ||
145 | if self.__assertDBExists(): | ||
146 | raise AsteriskDBException('could not initialize DB') | ||
147 | |||
148 | def __loadTemplate(self, config, templateName): | ||
149 | template = config.get('mysql-templates', templateName) | ||
150 | t = '' | ||
151 | with open(template, 'r') as templateFile: | ||
152 | for line in templateFile: | ||
153 | line = line.rstrip('\n') | ||
154 | t += line | ||
155 | return t.split(';') | ||
156 | |||
157 | |||
158 | def __assertDBExists(self): | ||
159 | '''Assert that DB tables exist. | ||
160 | ''' | ||
161 | try: | ||
162 | cursor = self.__mysql.cursor() | ||
163 | for sql in self.__tablesTemplate[:]: | ||
164 | if not sql: continue | ||
165 | sql = sql % { 'database': self.__database } | ||
166 | if self.__debug: print 'AsteriskDB.__assertDBExists: %s' % sql | ||
167 | cursor.execute(sql) | ||
168 | cursor.fetchall() | ||
169 | cursor.close() | ||
170 | except MySQLdb.Error, e: | ||
171 | if self.__debug: print 'AsteriskDB.__assertDBExists: Error %d: %s' % (e.args[0], e.args[1]) | ||
172 | return e.args[1] | ||
173 | return None | ||
174 | |||
175 | def AccountUpdate(self, user, password): | ||
176 | print 'AsteriskDB.AccountUpdate: user %s' % (user) | ||
177 | try: | ||
178 | cursor = self.__mysql.cursor() | ||
179 | for sql in self.__userTemplate[:]: | ||
180 | if not sql: continue | ||
181 | sql = sql % { 'database': self.__database, 'username': user, 'password': password } | ||
182 | if self.__debug_t: print 'AsteriskDB.AccountUpdate: sql: %s' % sql | ||
183 | cursor.execute(sql) | ||
184 | cursor.fetchall() | ||
185 | cursor.close() | ||
186 | except MySQLdb.Error, e: | ||
187 | if self.__debug: print 'AsteriskDB.RegionUpdate: Error %d: %s' % (e.args[0], e.args[1]) | ||
188 | return e.args[1] | ||
189 | return None | ||
190 | |||
191 | def RegionUpdate(self, region): | ||
192 | print 'AsteriskDB.RegionUpdate: region %s' % (region) | ||
193 | try: | ||
194 | cursor = self.__mysql.cursor() | ||
195 | for sql in self.__regionTemplate[:]: | ||
196 | if not sql: continue | ||
197 | sql = sql % { 'database': self.__database, 'regionname': region } | ||
198 | if self.__debug_t: print 'AsteriskDB.RegionUpdate: sql: %s' % sql | ||
199 | cursor.execute(sql) | ||
200 | res = cursor.fetchall() | ||
201 | except MySQLdb.Error, e: | ||
202 | if self.__debug: print 'AsteriskDB.RegionUpdate: Error %d: %s' % (e.args[0], e.args[1]) | ||
203 | return e.args[1] | ||
204 | return None | ||
205 | |||
206 | |||
207 | reURLParser = re.compile(r'^http://((?P<host>[^/]+):(?P<port>\d+)|(?P<hostonly>[^/]+))/', re.IGNORECASE) | ||
208 | |||
209 | # main | ||
210 | if __name__ == '__main__': | ||
211 | |||
212 | parser = optparse.OptionParser() | ||
213 | parser.add_option('-c', '--config', dest = 'config', help = 'config file', metavar = 'CONFIG') | ||
214 | (options, args) = parser.parse_args() | ||
215 | |||
216 | if not options.config: | ||
217 | parser.error('missing option config') | ||
218 | sys.exit(1) | ||
219 | |||
220 | config = ConfigParser.ConfigParser() | ||
221 | config.readfp(open(options.config)) | ||
222 | |||
223 | server = AsteriskOpenSimServer(config) | ||
224 | server.register_introspection_functions() | ||
225 | server.register_instance(AsteriskFrontend(config, AsteriskDB(config))) | ||
226 | |||
227 | # get cracking | ||
228 | print '[asterisk-opensim] server ready on %s:%d' % (server.host(), server.port()) | ||
229 | server.serve_forever() | ||
230 | |||
231 | 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 @@ | |||
1 | USE %(database)s; | ||
2 | REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(regionname)s', 1, 'Answer', ''); | ||
3 | REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(regionname)s', 2, 'Wait', '1'); | ||
4 | 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 @@ | |||
1 | USE %(database)s; | ||
2 | CREATE TABLE IF NOT EXISTS `ast_sipfriends` ( | ||
3 | `id` int(11) NOT NULL auto_increment, | ||
4 | `name` varchar(80) NOT NULL default '', | ||
5 | `host` varchar(31) NOT NULL default 'dynamic', | ||
6 | `nat` varchar(5) NOT NULL default 'route', | ||
7 | `type` enum('user','peer','friend') NOT NULL default 'friend', | ||
8 | `accountcode` varchar(20) default NULL, | ||
9 | `amaflags` varchar(13) default NULL, | ||
10 | `callgroup` varchar(10) default NULL, | ||
11 | `callerid` varchar(80) default NULL, | ||
12 | `call-limit` int(11) NOT NULL default '0', | ||
13 | `cancallforward` char(3) default 'no', | ||
14 | `canreinvite` char(3) default 'no', | ||
15 | `context` varchar(80) default 'pre_outgoing', | ||
16 | `defaultip` varchar(15) default NULL, | ||
17 | `dtmfmode` varchar(7) default NULL, | ||
18 | `fromuser` varchar(80) default NULL, | ||
19 | `fromdomain` varchar(80) default NULL, | ||
20 | `insecure` varchar(4) default NULL, | ||
21 | `language` char(2) default NULL, | ||
22 | `mailbox` varchar(50) default NULL, | ||
23 | `md5secret` varchar(80) default NULL, | ||
24 | `deny` varchar(95) default NULL, | ||
25 | `permit` varchar(95) default NULL, | ||
26 | `mask` varchar(95) default NULL, | ||
27 | `musiconhold` varchar(100) default NULL, | ||
28 | `pickupgroup` varchar(10) default NULL, | ||
29 | `qualify` char(3) default NULL, | ||
30 | `regexten` varchar(80) default NULL, | ||
31 | `restrictcid` char(3) default NULL, | ||
32 | `rtptimeout` char(3) default NULL, | ||
33 | `rtpholdtimeout` char(3) default NULL, | ||
34 | `secret` varchar(80) default NULL, | ||
35 | `setvar` varchar(100) default NULL, | ||
36 | `disallow` varchar(100) default 'all', | ||
37 | `allow` varchar(100) default 'g729', | ||
38 | `fullcontact` varchar(80) NOT NULL default '', | ||
39 | `ipaddr` varchar(15) NOT NULL default '', | ||
40 | `port` smallint(5) unsigned NOT NULL default '0', | ||
41 | `regserver` varchar(100) default NULL, | ||
42 | `regseconds` int(11) NOT NULL default '0', | ||
43 | `username` varchar(80) NOT NULL default '', | ||
44 | `user` varchar(255) NOT NULL, | ||
45 | `placement` varchar(255) NOT NULL, | ||
46 | `description` varchar(255) NOT NULL, | ||
47 | `delay` int(4) NOT NULL default '0', | ||
48 | `sortorder` int(11) NOT NULL default '1', | ||
49 | PRIMARY KEY (`id`), | ||
50 | UNIQUE KEY `name` (`name`) | ||
51 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; | ||
52 | |||
53 | CREATE TABLE IF NOT EXISTS `extensions_table` ( | ||
54 | `id` int(11) NOT NULL auto_increment, | ||
55 | `context` varchar(20) NOT NULL default '', | ||
56 | `exten` varchar(36) NOT NULL default '', | ||
57 | `priority` tinyint(4) NOT NULL default '0', | ||
58 | `app` varchar(20) NOT NULL default '', | ||
59 | `appdata` varchar(128) NOT NULL default '', | ||
60 | PRIMARY KEY (`context`,`exten`,`priority`), | ||
61 | KEY `id` (`id`) | ||
62 | ) 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 @@ | |||
1 | USE %(database)s; | ||
2 | REPLACE INTO ast_sipfriends (port,context,disallow,allow,type,secret,host,name) VALUES ('5060','avatare','all','ulaw','friend','%(password)s','dynamic','%(username)s'); | ||
3 | REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(username)s', 1, 'Answer', ''); | ||
4 | REPLACE INTO `extensions_table` (context,exten,priority,app,appdata) VALUES ('avatare', '%(username)s', 2, 'Wait', '1'); | ||
5 | 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 @@ | |||
1 | #!/usr/bin/python | ||
2 | # -*- encoding: utf-8 -*- | ||
3 | |||
4 | import xmlrpclib | ||
5 | |||
6 | # XML-RPC URL (http_listener_port) | ||
7 | asteriskServerURL = 'http://127.0.0.1:53263' | ||
8 | |||
9 | # instantiate server object | ||
10 | asteriskServer = xmlrpclib.Server(asteriskServerURL) | ||
11 | |||
12 | try: | ||
13 | # invoke admin_alert: requires password and message | ||
14 | res = asteriskServer.region_update({ | ||
15 | 'admin_password': 'c00lstuff', | ||
16 | 'region' : '941ae087-a7da-43b4-900b-9fe48387ae57@secondlife.zurich.ibm.com' | ||
17 | }) | ||
18 | print res | ||
19 | |||
20 | res = asteriskServer.account_update({ | ||
21 | 'admin_password': 'c00lstuff', | ||
22 | 'username' : '0780d90b-1939-4152-a283-8d1261fb1b68@secondlife.zurich.ibm.com', | ||
23 | 'password' : '$1$dd02c7c2232759874e1c205587017bed' | ||
24 | }) | ||
25 | print res | ||
26 | except Exception, e: | ||
27 | print e | ||
28 | |||