FreeSwitchVoiceModule.cs 39 KB

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