FreeSwitchVoiceModule.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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 OpenSimulator 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. using System;
  28. using System.IO;
  29. using System.Net;
  30. using System.Net.Security;
  31. using System.Web;
  32. using System.Security.Cryptography.X509Certificates;
  33. using System.Text;
  34. using System.Xml;
  35. using System.Collections;
  36. using System.Collections.Generic;
  37. using System.Reflection;
  38. using OpenMetaverse;
  39. using OpenMetaverse.StructuredData;
  40. using log4net;
  41. using Nini.Config;
  42. using Nwc.XmlRpc;
  43. using OpenSim.Framework;
  44. using Mono.Addins;
  45. using OpenSim.Framework.Capabilities;
  46. using OpenSim.Framework.Servers;
  47. using OpenSim.Framework.Servers.HttpServer;
  48. using OpenSim.Region.Framework.Interfaces;
  49. using OpenSim.Region.Framework.Scenes;
  50. using Caps = OpenSim.Framework.Capabilities.Caps;
  51. using System.Text.RegularExpressions;
  52. using OpenSim.Server.Base;
  53. using OpenSim.Services.Interfaces;
  54. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  55. namespace OpenSim.Region.OptionalModules.Avatar.Voice.FreeSwitchVoice
  56. {
  57. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FreeSwitchVoiceModule")]
  58. public class FreeSwitchVoiceModule : ISharedRegionModule, IVoiceModule
  59. {
  60. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  61. // Capability string prefixes
  62. //private static readonly string m_chatSessionRequestPath = "0209/";
  63. // Control info
  64. private static bool m_Enabled = false;
  65. // FreeSwitch server is going to contact us and ask us all
  66. // sorts of things.
  67. // SLVoice client will do a GET on this prefix
  68. private static string m_freeSwitchAPIPrefix;
  69. // We need to return some information to SLVoice
  70. // figured those out via curl
  71. // http://vd1.vivox.com/api2/viv_get_prelogin.php
  72. //
  73. // need to figure out whether we do need to return ALL of
  74. // these...
  75. private static string m_freeSwitchRealm;
  76. private static string m_freeSwitchSIPProxy;
  77. private static bool m_freeSwitchAttemptUseSTUN;
  78. private static string m_freeSwitchEchoServer;
  79. private static int m_freeSwitchEchoPort;
  80. private static string m_freeSwitchDefaultWellKnownIP;
  81. private static int m_freeSwitchDefaultTimeout;
  82. private static string m_freeSwitchUrlResetPassword;
  83. private uint m_freeSwitchServicePort;
  84. private string m_openSimWellKnownHTTPAddress;
  85. // private string m_freeSwitchContext;
  86. private readonly Dictionary<string, string> m_UUIDName = new Dictionary<string, string>();
  87. private Dictionary<string, string> m_ParcelAddress = new Dictionary<string, string>();
  88. private IConfig m_Config;
  89. private IFreeswitchService m_FreeswitchService;
  90. public void Initialise(IConfigSource config)
  91. {
  92. m_Config = config.Configs["FreeSwitchVoice"];
  93. if (m_Config == null)
  94. return;
  95. if (!m_Config.GetBoolean("Enabled", false))
  96. return;
  97. try
  98. {
  99. string serviceDll = m_Config.GetString("LocalServiceModule",
  100. String.Empty);
  101. if (serviceDll == String.Empty)
  102. {
  103. m_log.Error("[FreeSwitchVoice]: No LocalServiceModule named in section FreeSwitchVoice. Not starting.");
  104. return;
  105. }
  106. Object[] args = new Object[] { config };
  107. m_FreeswitchService = ServerUtils.LoadPlugin<IFreeswitchService>(serviceDll, args);
  108. string jsonConfig = m_FreeswitchService.GetJsonConfig();
  109. //m_log.Debug("[FreeSwitchVoice]: Configuration string: " + jsonConfig);
  110. OSDMap map = (OSDMap)OSDParser.DeserializeJson(jsonConfig);
  111. m_freeSwitchAPIPrefix = map["APIPrefix"].AsString();
  112. m_freeSwitchRealm = map["Realm"].AsString();
  113. m_freeSwitchSIPProxy = map["SIPProxy"].AsString();
  114. m_freeSwitchAttemptUseSTUN = map["AttemptUseSTUN"].AsBoolean();
  115. m_freeSwitchEchoServer = map["EchoServer"].AsString();
  116. m_freeSwitchEchoPort = map["EchoPort"].AsInteger();
  117. m_freeSwitchDefaultWellKnownIP = map["DefaultWellKnownIP"].AsString();
  118. m_freeSwitchDefaultTimeout = map["DefaultTimeout"].AsInteger();
  119. m_freeSwitchUrlResetPassword = String.Empty;
  120. // m_freeSwitchContext = map["Context"].AsString();
  121. if (String.IsNullOrEmpty(m_freeSwitchRealm) ||
  122. String.IsNullOrEmpty(m_freeSwitchAPIPrefix))
  123. {
  124. m_log.Error("[FreeSwitchVoice]: Freeswitch service mis-configured. Not starting.");
  125. return;
  126. }
  127. // set up http request handlers for
  128. // - prelogin: viv_get_prelogin.php
  129. // - signin: viv_signin.php
  130. // - buddies: viv_buddy.php
  131. // - ???: viv_watcher.php
  132. // - signout: viv_signout.php
  133. MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix),
  134. FreeSwitchSLVoiceGetPreloginHTTPHandler);
  135. MainServer.Instance.AddHTTPHandler(String.Format("{0}/freeswitch-config", m_freeSwitchAPIPrefix), FreeSwitchConfigHTTPHandler);
  136. // RestStreamHandler h = new
  137. // RestStreamHandler("GET",
  138. // String.Format("{0}/viv_get_prelogin.php", m_freeSwitchAPIPrefix), FreeSwitchSLVoiceGetPreloginHTTPHandler);
  139. // MainServer.Instance.AddStreamHandler(h);
  140. MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_signin.php", m_freeSwitchAPIPrefix),
  141. FreeSwitchSLVoiceSigninHTTPHandler);
  142. MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_buddy.php", m_freeSwitchAPIPrefix),
  143. FreeSwitchSLVoiceBuddyHTTPHandler);
  144. MainServer.Instance.AddHTTPHandler(String.Format("{0}/viv_watcher.php", m_freeSwitchAPIPrefix),
  145. FreeSwitchSLVoiceWatcherHTTPHandler);
  146. m_log.InfoFormat("[FreeSwitchVoice]: using FreeSwitch server {0}", m_freeSwitchRealm);
  147. m_Enabled = true;
  148. m_log.Info("[FreeSwitchVoice]: plugin enabled");
  149. }
  150. catch (Exception e)
  151. {
  152. m_log.ErrorFormat("[FreeSwitchVoice]: plugin initialization failed: {0} {1}", e.Message, e.StackTrace);
  153. return;
  154. }
  155. }
  156. public void PostInitialise()
  157. {
  158. }
  159. public void AddRegion(Scene scene)
  160. {
  161. // We generate these like this: The region's external host name
  162. // as defined in Regions.ini is a good address to use. It's a
  163. // dotted quad (or should be!) and it can reach this host from
  164. // a client. The port is grabbed from the region's HTTP server.
  165. m_openSimWellKnownHTTPAddress = scene.RegionInfo.ExternalHostName;
  166. m_freeSwitchServicePort = MainServer.Instance.Port;
  167. if (m_Enabled)
  168. {
  169. // we need to capture scene in an anonymous method
  170. // here as we need it later in the callbacks
  171. scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps)
  172. {
  173. OnRegisterCaps(scene, agentID, caps);
  174. };
  175. }
  176. }
  177. public void RemoveRegion(Scene scene)
  178. {
  179. }
  180. public void RegionLoaded(Scene scene)
  181. {
  182. if (m_Enabled)
  183. {
  184. m_log.Info("[FreeSwitchVoice]: registering IVoiceModule with the scene");
  185. // register the voice interface for this module, so the script engine can call us
  186. scene.RegisterModuleInterface<IVoiceModule>(this);
  187. }
  188. }
  189. public void Close()
  190. {
  191. }
  192. public string Name
  193. {
  194. get { return "FreeSwitchVoiceModule"; }
  195. }
  196. public Type ReplaceableInterface
  197. {
  198. get { return null; }
  199. }
  200. // <summary>
  201. // implementation of IVoiceModule, called by osSetParcelSIPAddress script function
  202. // </summary>
  203. public void setLandSIPAddress(string SIPAddress,UUID GlobalID)
  204. {
  205. m_log.DebugFormat("[FreeSwitchVoice]: setLandSIPAddress parcel id {0}: setting sip address {1}",
  206. GlobalID, SIPAddress);
  207. lock (m_ParcelAddress)
  208. {
  209. if (m_ParcelAddress.ContainsKey(GlobalID.ToString()))
  210. {
  211. m_ParcelAddress[GlobalID.ToString()] = SIPAddress;
  212. }
  213. else
  214. {
  215. m_ParcelAddress.Add(GlobalID.ToString(), SIPAddress);
  216. }
  217. }
  218. }
  219. // <summary>
  220. // OnRegisterCaps is invoked via the scene.EventManager
  221. // everytime OpenSim hands out capabilities to a client
  222. // (login, region crossing). We contribute two capabilities to
  223. // the set of capabilities handed back to the client:
  224. // ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest.
  225. //
  226. // ProvisionVoiceAccountRequest allows the client to obtain
  227. // the voice account credentials for the avatar it is
  228. // controlling (e.g., user name, password, etc).
  229. //
  230. // ParcelVoiceInfoRequest is invoked whenever the client
  231. // changes from one region or parcel to another.
  232. //
  233. // Note that OnRegisterCaps is called here via a closure
  234. // delegate containing the scene of the respective region (see
  235. // Initialise()).
  236. // </summary>
  237. public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps)
  238. {
  239. m_log.DebugFormat(
  240. "[FreeSwitchVoice]: OnRegisterCaps() called with agentID {0} caps {1} in scene {2}",
  241. agentID, caps, scene.RegionInfo.RegionName);
  242. caps.RegisterSimpleHandler("ProvisionVoiceAccountRequest",
  243. new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  244. {
  245. ProvisionVoiceAccountRequest(httpRequest, httpResponse, agentID, scene);
  246. }));
  247. caps.RegisterSimpleHandler("ParcelVoiceInfoRequest",
  248. new SimpleStreamHandler("/" + UUID.Random(), delegate (IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  249. {
  250. ParcelVoiceInfoRequest(httpRequest, httpResponse, agentID, scene);
  251. }));
  252. //caps.RegisterHandler(
  253. // "ChatSessionRequest",
  254. // new RestStreamHandler(
  255. // "POST",
  256. // capsBase + m_chatSessionRequestPath,
  257. // (request, path, param, httpRequest, httpResponse)
  258. // => ChatSessionRequest(scene, request, path, param, agentID, caps),
  259. // "ChatSessionRequest",
  260. // agentID.ToString()));
  261. }
  262. /// <summary>
  263. /// Callback for a client request for Voice Account Details
  264. /// </summary>
  265. /// <param name="scene">current scene object of the client</param>
  266. /// <param name="request"></param>
  267. /// <param name="path"></param>
  268. /// <param name="param"></param>
  269. /// <param name="agentID"></param>
  270. /// <param name="caps"></param>
  271. /// <returns></returns>
  272. public void ProvisionVoiceAccountRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
  273. {
  274. if(request.HttpMethod != "POST")
  275. {
  276. response.StatusCode = (int)HttpStatusCode.NotFound;
  277. return;
  278. }
  279. m_log.DebugFormat(
  280. "[FreeSwitchVoice][PROVISIONVOICE]: ProvisionVoiceAccountRequest() request for {0}", agentID.ToString());
  281. response.StatusCode = (int)HttpStatusCode.OK;
  282. ScenePresence avatar = scene.GetScenePresence(agentID);
  283. if (avatar == null)
  284. {
  285. System.Threading.Thread.Sleep(2000);
  286. avatar = scene.GetScenePresence(agentID);
  287. if (avatar == null)
  288. {
  289. response.RawBuffer = Util.UTF8.GetBytes("<llsd>undef</llsd>");
  290. return;
  291. }
  292. }
  293. string avatarName = avatar.Name;
  294. try
  295. {
  296. //XmlElement resp;
  297. string agentname = "x" + Convert.ToBase64String(agentID.GetBytes());
  298. string password = "1234";//temp hack//new UUID(Guid.NewGuid()).ToString().Replace('-','Z').Substring(0,16);
  299. // XXX: we need to cache the voice credentials, as
  300. // FreeSwitch is later going to come and ask us for
  301. // those
  302. agentname = agentname.Replace('+', '-').Replace('/', '_');
  303. lock (m_UUIDName)
  304. {
  305. if (m_UUIDName.ContainsKey(agentname))
  306. {
  307. m_UUIDName[agentname] = avatarName;
  308. }
  309. else
  310. {
  311. m_UUIDName.Add(agentname, avatarName);
  312. }
  313. }
  314. string accounturl = String.Format("http://{0}:{1}{2}/", m_openSimWellKnownHTTPAddress,
  315. m_freeSwitchServicePort, m_freeSwitchAPIPrefix);
  316. // fast foward encode
  317. osUTF8 lsl = LLSDxmlEncode2.Start();
  318. LLSDxmlEncode2.AddMap(lsl);
  319. LLSDxmlEncode2.AddElem("username", agentname, lsl);
  320. LLSDxmlEncode2.AddElem("password", password, lsl);
  321. LLSDxmlEncode2.AddElem("voice_sip_uri_hostname", m_freeSwitchRealm, lsl);
  322. LLSDxmlEncode2.AddElem("voice_account_server_name", accounturl, lsl);
  323. LLSDxmlEncode2.AddEndMap(lsl);
  324. response.RawBuffer = LLSDxmlEncode2.EndToBytes(lsl);
  325. }
  326. catch (Exception e)
  327. {
  328. m_log.ErrorFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1}, retry later", avatarName, e.Message);
  329. m_log.DebugFormat("[FreeSwitchVoice][PROVISIONVOICE]: avatar \"{0}\": {1} failed", avatarName, e.ToString());
  330. response.RawBuffer = osUTF8.GetASCIIBytes("<llsd>undef</llsd>");
  331. }
  332. }
  333. /// <summary>
  334. /// Callback for a client request for ParcelVoiceInfo
  335. /// </summary>
  336. /// <param name="scene">current scene object of the client</param>
  337. /// <param name="request"></param>
  338. /// <param name="path"></param>
  339. /// <param name="param"></param>
  340. /// <param name="agentID"></param>
  341. /// <param name="caps"></param>
  342. /// <returns></returns>
  343. public void ParcelVoiceInfoRequest(IOSHttpRequest request, IOSHttpResponse response, UUID agentID, Scene scene)
  344. {
  345. if (request.HttpMethod != "POST")
  346. {
  347. response.StatusCode = (int)HttpStatusCode.NotFound;
  348. return;
  349. }
  350. response.StatusCode = (int)HttpStatusCode.OK;
  351. m_log.DebugFormat(
  352. "[FreeSwitchVoice][PARCELVOICE]: ParcelVoiceInfoRequest() on {0} for {1}",
  353. scene.RegionInfo.RegionName, agentID);
  354. ScenePresence avatar = scene.GetScenePresence(agentID);
  355. if(avatar == null)
  356. {
  357. response.RawBuffer = Util.UTF8.GetBytes("<llsd>undef</llsd>");
  358. return;
  359. }
  360. string avatarName = avatar.Name;
  361. // - check whether we have a region channel in our cache
  362. // - if not:
  363. // create it and cache it
  364. // - send it to the client
  365. // - send channel_uri: as "sip:regionID@m_sipDomain"
  366. try
  367. {
  368. string channelUri;
  369. if (null == scene.LandChannel)
  370. {
  371. m_log.ErrorFormat("region \"{0}\": avatar \"{1}\": land data not yet available",
  372. scene.RegionInfo.RegionName, avatarName);
  373. response.RawBuffer = Util.UTF8.GetBytes("<llsd>undef</llsd>");
  374. return;
  375. }
  376. // get channel_uri: check first whether estate
  377. // settings allow voice, then whether parcel allows
  378. // voice, if all do retrieve or obtain the parcel
  379. // voice channel
  380. LandData land = scene.GetLandData(avatar.AbsolutePosition);
  381. //m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}",
  382. // scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param);
  383. // TODO: EstateSettings don't seem to get propagated...
  384. if (!scene.RegionInfo.EstateSettings.AllowVoice)
  385. {
  386. m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings",
  387. scene.RegionInfo.RegionName);
  388. channelUri = String.Empty;
  389. }
  390. else
  391. if (!scene.RegionInfo.EstateSettings.TaxFree && (land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0)
  392. {
  393. // m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel",
  394. // scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName);
  395. channelUri = String.Empty;
  396. }
  397. else
  398. {
  399. channelUri = ChannelUri(scene, land);
  400. }
  401. // fast foward encode
  402. osUTF8 lsl = LLSDxmlEncode2.Start(512);
  403. LLSDxmlEncode2.AddMap(lsl);
  404. LLSDxmlEncode2.AddElem("parcel_local_id", land.LocalID, lsl);
  405. LLSDxmlEncode2.AddElem("region_name", scene.Name, lsl);
  406. LLSDxmlEncode2.AddMap("voice_credentials", lsl);
  407. LLSDxmlEncode2.AddElem("channel_uri", channelUri, lsl);
  408. //LLSDxmlEncode2.AddElem("channel_credentials", channel_credentials, lsl);
  409. LLSDxmlEncode2.AddEndMap(lsl);
  410. LLSDxmlEncode2.AddEndMap(lsl);
  411. response.RawBuffer= LLSDxmlEncode2.EndToBytes(lsl);
  412. }
  413. catch (Exception e)
  414. {
  415. m_log.ErrorFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later",
  416. scene.RegionInfo.RegionName, avatarName, e.Message);
  417. m_log.DebugFormat("[FreeSwitchVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed",
  418. scene.RegionInfo.RegionName, avatarName, e.ToString());
  419. response.RawBuffer = Util.UTF8.GetBytes("<llsd>undef</llsd>");
  420. }
  421. }
  422. /// <summary>
  423. /// Callback for a client request for ChatSessionRequest
  424. /// </summary>
  425. /// <param name="scene">current scene object of the client</param>
  426. /// <param name="request"></param>
  427. /// <param name="path"></param>
  428. /// <param name="param"></param>
  429. /// <param name="agentID"></param>
  430. /// <param name="caps"></param>
  431. /// <returns></returns>
  432. public string ChatSessionRequest(Scene scene, string request, string path, string param,
  433. UUID agentID, Caps caps)
  434. {
  435. ScenePresence avatar = scene.GetScenePresence(agentID);
  436. string avatarName = avatar.Name;
  437. m_log.DebugFormat("[FreeSwitchVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}",
  438. avatarName, request, path, param);
  439. return "<llsd>true</llsd>";
  440. }
  441. public Hashtable ForwardProxyRequest(Hashtable request)
  442. {
  443. m_log.Debug("[PROXYING]: -------------------------------proxying request");
  444. Hashtable response = new Hashtable();
  445. response["content_type"] = "text/xml";
  446. response["str_response_string"] = "";
  447. response["int_response_code"] = 200;
  448. string forwardaddress = "https://www.bhr.vivox.com/api2/";
  449. string body = (string)request["body"];
  450. string method = (string) request["http-method"];
  451. string contenttype = (string) request["content-type"];
  452. string uri = (string) request["uri"];
  453. uri = uri.Replace("/api/", "");
  454. forwardaddress += uri;
  455. string fwdresponsestr = "";
  456. int fwdresponsecode = 200;
  457. string fwdresponsecontenttype = "text/xml";
  458. HttpWebRequest forwardreq = (HttpWebRequest)WebRequest.Create(forwardaddress);
  459. forwardreq.Method = method;
  460. forwardreq.ContentType = contenttype;
  461. forwardreq.KeepAlive = false;
  462. forwardreq.ServerCertificateValidationCallback = CustomCertificateValidation;
  463. if (method == "POST")
  464. {
  465. byte[] contentreq = Util.UTF8.GetBytes(body);
  466. forwardreq.ContentLength = contentreq.Length;
  467. Stream reqStream = forwardreq.GetRequestStream();
  468. reqStream.Write(contentreq, 0, contentreq.Length);
  469. reqStream.Close();
  470. }
  471. using (HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse())
  472. {
  473. Encoding encoding = Util.UTF8;
  474. using (Stream s = fwdrsp.GetResponseStream())
  475. {
  476. using (StreamReader fwdresponsestream = new StreamReader(s))
  477. {
  478. fwdresponsestr = fwdresponsestream.ReadToEnd();
  479. fwdresponsecontenttype = fwdrsp.ContentType;
  480. fwdresponsecode = (int)fwdrsp.StatusCode;
  481. }
  482. }
  483. }
  484. response["content_type"] = fwdresponsecontenttype;
  485. response["str_response_string"] = fwdresponsestr;
  486. response["int_response_code"] = fwdresponsecode;
  487. return response;
  488. }
  489. public Hashtable FreeSwitchSLVoiceGetPreloginHTTPHandler(Hashtable request)
  490. {
  491. // m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler called");
  492. Hashtable response = new Hashtable();
  493. response["content_type"] = "text/xml";
  494. response["keepalive"] = false;
  495. response["str_response_string"] = String.Format(
  496. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
  497. "<VCConfiguration>\r\n"+
  498. "<DefaultRealm>{0}</DefaultRealm>\r\n" +
  499. "<DefaultSIPProxy>{1}</DefaultSIPProxy>\r\n"+
  500. "<DefaultAttemptUseSTUN>{2}</DefaultAttemptUseSTUN>\r\n"+
  501. "<DefaultEchoServer>{3}</DefaultEchoServer>\r\n"+
  502. "<DefaultEchoPort>{4}</DefaultEchoPort>\r\n"+
  503. "<DefaultWellKnownIP>{5}</DefaultWellKnownIP>\r\n"+
  504. "<DefaultTimeout>{6}</DefaultTimeout>\r\n"+
  505. "<UrlResetPassword>{7}</UrlResetPassword>\r\n"+
  506. "<UrlPrivacyNotice>{8}</UrlPrivacyNotice>\r\n"+
  507. "<UrlEulaNotice/>\r\n"+
  508. "<App.NoBottomLogo>false</App.NoBottomLogo>\r\n"+
  509. "</VCConfiguration>",
  510. m_freeSwitchRealm, m_freeSwitchSIPProxy, m_freeSwitchAttemptUseSTUN,
  511. m_freeSwitchEchoServer, m_freeSwitchEchoPort,
  512. m_freeSwitchDefaultWellKnownIP, m_freeSwitchDefaultTimeout,
  513. m_freeSwitchUrlResetPassword, "");
  514. response["int_response_code"] = 200;
  515. //m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler return {0}",response["str_response_string"]);
  516. return response;
  517. }
  518. public Hashtable FreeSwitchSLVoiceBuddyHTTPHandler(Hashtable request)
  519. {
  520. m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceBuddyHTTPHandler called");
  521. Hashtable response = new Hashtable();
  522. response["int_response_code"] = 200;
  523. response["str_response_string"] = string.Empty;
  524. response["content-type"] = "text/xml";
  525. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  526. if (!requestBody.ContainsKey("auth_token"))
  527. return response;
  528. string auth_token = (string)requestBody["auth_token"];
  529. //string[] auth_tokenvals = auth_token.Split(':');
  530. //string username = auth_tokenvals[0];
  531. int strcount = 0;
  532. string[] ids = new string[strcount];
  533. int iter = -1;
  534. lock (m_UUIDName)
  535. {
  536. strcount = m_UUIDName.Count;
  537. ids = new string[strcount];
  538. foreach (string s in m_UUIDName.Keys)
  539. {
  540. iter++;
  541. ids[iter] = s;
  542. }
  543. }
  544. StringBuilder resp = new StringBuilder();
  545. resp.Append("<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?><response xmlns=\"http://www.vivox.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"/xsd/buddy_list.xsd\">");
  546. resp.Append(string.Format(@"<level0>
  547. <status>OK</status>
  548. <cookie_name>lib_session</cookie_name>
  549. <cookie>{0}</cookie>
  550. <auth_token>{0}</auth_token>
  551. <body>
  552. <buddies>",auth_token));
  553. /*
  554. <cookie_name>lib_session</cookie_name>
  555. <cookie>{0}:{1}:9303959503950::</cookie>
  556. <auth_token>{0}:{1}:9303959503950::</auth_token>
  557. */
  558. for (int i=0;i<ids.Length;i++)
  559. {
  560. DateTime currenttime = DateTime.Now;
  561. string dt = currenttime.ToString("yyyy-MM-dd HH:mm:ss.0zz");
  562. resp.Append(
  563. string.Format(@"<level3>
  564. <bdy_id>{1}</bdy_id>
  565. <bdy_data></bdy_data>
  566. <bdy_uri>sip:{0}@{2}</bdy_uri>
  567. <bdy_nickname>{0}</bdy_nickname>
  568. <bdy_username>{0}</bdy_username>
  569. <bdy_domain>{2}</bdy_domain>
  570. <bdy_status>A</bdy_status>
  571. <modified_ts>{3}</modified_ts>
  572. <b2g_group_id></b2g_group_id>
  573. </level3>", ids[i], i ,m_freeSwitchRealm, dt));
  574. }
  575. resp.Append("</buddies><groups></groups></body></level0></response>");
  576. response["str_response_string"] = resp.ToString();
  577. // Regex normalizeEndLines = new Regex(@"(\r\n|\n)", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
  578. //
  579. // m_log.DebugFormat(
  580. // "[FREESWITCH]: FreeSwitchSLVoiceBuddyHTTPHandler() response {0}",
  581. // normalizeEndLines.Replace((string)response["str_response_string"],""));
  582. return response;
  583. }
  584. public Hashtable FreeSwitchSLVoiceWatcherHTTPHandler(Hashtable request)
  585. {
  586. m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceWatcherHTTPHandler called");
  587. Hashtable response = new Hashtable();
  588. response["int_response_code"] = 200;
  589. response["content-type"] = "text/xml";
  590. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  591. string auth_token = (string)requestBody["auth_token"];
  592. //string[] auth_tokenvals = auth_token.Split(':');
  593. //string username = auth_tokenvals[0];
  594. StringBuilder resp = new StringBuilder();
  595. resp.Append("<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?><response xmlns=\"http://www.vivox.com\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation= \"/xsd/buddy_list.xsd\">");
  596. // FIXME: This is enough of a response to stop viewer 2 complaining about a login failure and get voice to work. If we don't
  597. // give an OK response, then viewer 2 engages in an continuous viv_signin.php, viv_buddy.php, viv_watcher.php loop
  598. // Viewer 1 appeared happy to ignore the lack of reply and still works with this reply.
  599. //
  600. // However, really we need to fill in whatever watcher data should be here (whatever that is).
  601. resp.Append(string.Format(@"<level0>
  602. <status>OK</status>
  603. <cookie_name>lib_session</cookie_name>
  604. <cookie>{0}</cookie>
  605. <auth_token>{0}</auth_token>
  606. <body/></level0></response>", auth_token));
  607. response["str_response_string"] = resp.ToString();
  608. // Regex normalizeEndLines = new Regex(@"(\r\n|\n)", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
  609. //
  610. // m_log.DebugFormat(
  611. // "[FREESWITCH]: FreeSwitchSLVoiceWatcherHTTPHandler() response {0}",
  612. // normalizeEndLines.Replace((string)response["str_response_string"],""));
  613. return response;
  614. }
  615. public Hashtable FreeSwitchSLVoiceSigninHTTPHandler(Hashtable request)
  616. {
  617. //m_log.Debug("[FreeSwitchVoice] FreeSwitchSLVoiceSigninHTTPHandler called");
  618. // string requestbody = (string)request["body"];
  619. // string uri = (string)request["uri"];
  620. // string contenttype = (string)request["content-type"];
  621. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  622. //string pwd = (string) requestBody["pwd"];
  623. string userid = (string) requestBody["userid"];
  624. string avatarName = string.Empty;
  625. int pos = -1;
  626. lock (m_UUIDName)
  627. {
  628. if (m_UUIDName.ContainsKey(userid))
  629. {
  630. avatarName = m_UUIDName[userid];
  631. foreach (string s in m_UUIDName.Keys)
  632. {
  633. pos++;
  634. if (s == userid)
  635. break;
  636. }
  637. }
  638. }
  639. //m_log.DebugFormat("[FreeSwitchVoice]: AUTH, URI: {0}, Content-Type:{1}, Body{2}", uri, contenttype,
  640. // requestbody);
  641. Hashtable response = new Hashtable();
  642. response["str_response_string"] = string.Format(@"<response xsi:schemaLocation=""/xsd/signin.xsd"">
  643. <level0>
  644. <status>OK</status>
  645. <body>
  646. <code>200</code>
  647. <cookie_name>lib_session</cookie_name>
  648. <cookie>{0}:{1}:9303959503950::</cookie>
  649. <auth_token>{0}:{1}:9303959503950::</auth_token>
  650. <primary>1</primary>
  651. <account_id>{1}</account_id>
  652. <displayname>{2}</displayname>
  653. <msg>auth successful</msg>
  654. </body>
  655. </level0>
  656. </response>", userid, pos, avatarName);
  657. response["int_response_code"] = 200;
  658. // m_log.DebugFormat("[FreeSwitchVoice]: Sending FreeSwitchSLVoiceSigninHTTPHandler response");
  659. return response;
  660. }
  661. public Hashtable ParseRequestBody(string body)
  662. {
  663. Hashtable bodyParams = new Hashtable();
  664. // split string
  665. string [] nvps = body.Split(new Char [] {'&'});
  666. foreach (string s in nvps)
  667. {
  668. if (s.Trim() != "")
  669. {
  670. string [] nvp = s.Split(new Char [] {'='});
  671. bodyParams.Add(HttpUtility.UrlDecode(nvp[0]), HttpUtility.UrlDecode(nvp[1]));
  672. }
  673. }
  674. return bodyParams;
  675. }
  676. private string ChannelUri(Scene scene, LandData land)
  677. {
  678. string channelUri = null;
  679. string landUUID;
  680. string landName;
  681. // Create parcel voice channel. If no parcel exists, then the voice channel ID is the same
  682. // as the directory ID. Otherwise, it reflects the parcel's ID.
  683. lock (m_ParcelAddress)
  684. {
  685. if (m_ParcelAddress.ContainsKey(land.GlobalID.ToString()))
  686. {
  687. m_log.DebugFormat("[FreeSwitchVoice]: parcel id {0}: using sip address {1}",
  688. land.GlobalID, m_ParcelAddress[land.GlobalID.ToString()]);
  689. return m_ParcelAddress[land.GlobalID.ToString()];
  690. }
  691. }
  692. if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0)
  693. {
  694. landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name);
  695. landUUID = land.GlobalID.ToString();
  696. m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
  697. landName, land.LocalID, landUUID);
  698. }
  699. else
  700. {
  701. landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName);
  702. landUUID = scene.RegionInfo.RegionID.ToString();
  703. m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
  704. landName, land.LocalID, landUUID);
  705. }
  706. // slvoice handles the sip address differently if it begins with confctl, hiding it from the user in the friends list. however it also disables
  707. // the personal speech indicators as well unless some siren14-3d codec magic happens. we dont have siren143d so we'll settle for the personal speech indicator.
  708. channelUri = String.Format("sip:conf-{0}@{1}", "x" + Convert.ToBase64String(Encoding.ASCII.GetBytes(landUUID)), m_freeSwitchRealm);
  709. lock (m_ParcelAddress)
  710. {
  711. if (!m_ParcelAddress.ContainsKey(land.GlobalID.ToString()))
  712. {
  713. m_ParcelAddress.Add(land.GlobalID.ToString(),channelUri);
  714. }
  715. }
  716. return channelUri;
  717. }
  718. private static bool CustomCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
  719. {
  720. return true;
  721. }
  722. public Hashtable FreeSwitchConfigHTTPHandler(Hashtable request)
  723. {
  724. Hashtable response = new Hashtable();
  725. response["str_response_string"] = string.Empty;
  726. response["content_type"] = "text/plain";
  727. response["keepalive"] = false;
  728. response["int_response_code"] = 500;
  729. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  730. string section = (string) requestBody["section"];
  731. if (section == "directory")
  732. {
  733. string eventCallingFunction = (string)requestBody["Event-Calling-Function"];
  734. m_log.DebugFormat(
  735. "[FreeSwitchVoice]: Received request for config section directory, event calling function '{0}'",
  736. eventCallingFunction);
  737. response = m_FreeswitchService.HandleDirectoryRequest(requestBody);
  738. }
  739. else if (section == "dialplan")
  740. {
  741. m_log.DebugFormat("[FreeSwitchVoice]: Received request for config section dialplan");
  742. response = m_FreeswitchService.HandleDialplanRequest(requestBody);
  743. }
  744. else
  745. m_log.WarnFormat("[FreeSwitchVoice]: Unknown section {0} was requested from config.", section);
  746. return response;
  747. }
  748. }
  749. }