1
0

FreeSwitchVoiceModule.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. using (HttpWebResponse fwdrsp = (HttpWebResponse)forwardreq.GetResponse())
  477. {
  478. Encoding encoding = Util.UTF8;
  479. using (Stream s = fwdrsp.GetResponseStream())
  480. {
  481. using (StreamReader fwdresponsestream = new StreamReader(s))
  482. {
  483. fwdresponsestr = fwdresponsestream.ReadToEnd();
  484. fwdresponsecontenttype = fwdrsp.ContentType;
  485. fwdresponsecode = (int)fwdrsp.StatusCode;
  486. }
  487. }
  488. }
  489. response["content_type"] = fwdresponsecontenttype;
  490. response["str_response_string"] = fwdresponsestr;
  491. response["int_response_code"] = fwdresponsecode;
  492. return response;
  493. }
  494. public Hashtable FreeSwitchSLVoiceGetPreloginHTTPHandler(Hashtable request)
  495. {
  496. m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceGetPreloginHTTPHandler called");
  497. Hashtable response = new Hashtable();
  498. response["content_type"] = "text/xml";
  499. response["keepalive"] = false;
  500. response["str_response_string"] = String.Format(
  501. "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
  502. "<VCConfiguration>\r\n"+
  503. "<DefaultRealm>{0}</DefaultRealm>\r\n" +
  504. "<DefaultSIPProxy>{1}</DefaultSIPProxy>\r\n"+
  505. "<DefaultAttemptUseSTUN>{2}</DefaultAttemptUseSTUN>\r\n"+
  506. "<DefaultEchoServer>{3}</DefaultEchoServer>\r\n"+
  507. "<DefaultEchoPort>{4}</DefaultEchoPort>\r\n"+
  508. "<DefaultWellKnownIP>{5}</DefaultWellKnownIP>\r\n"+
  509. "<DefaultTimeout>{6}</DefaultTimeout>\r\n"+
  510. "<UrlResetPassword>{7}</UrlResetPassword>\r\n"+
  511. "<UrlPrivacyNotice>{8}</UrlPrivacyNotice>\r\n"+
  512. "<UrlEulaNotice/>\r\n"+
  513. "<App.NoBottomLogo>false</App.NoBottomLogo>\r\n"+
  514. "</VCConfiguration>",
  515. m_freeSwitchRealm, m_freeSwitchSIPProxy, m_freeSwitchAttemptUseSTUN,
  516. m_freeSwitchEchoServer, m_freeSwitchEchoPort,
  517. m_freeSwitchDefaultWellKnownIP, m_freeSwitchDefaultTimeout,
  518. m_freeSwitchUrlResetPassword, "");
  519. response["int_response_code"] = 200;
  520. //m_log.DebugFormat("[FreeSwitchVoice] FreeSwitchSLVoiceGetPreloginHTTPHandler return {0}",response["str_response_string"]);
  521. return response;
  522. }
  523. public Hashtable FreeSwitchSLVoiceBuddyHTTPHandler(Hashtable request)
  524. {
  525. m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceBuddyHTTPHandler called");
  526. Hashtable response = new Hashtable();
  527. response["int_response_code"] = 200;
  528. response["str_response_string"] = string.Empty;
  529. response["content-type"] = "text/xml";
  530. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  531. if (!requestBody.ContainsKey("auth_token"))
  532. return response;
  533. string auth_token = (string)requestBody["auth_token"];
  534. //string[] auth_tokenvals = auth_token.Split(':');
  535. //string username = auth_tokenvals[0];
  536. int strcount = 0;
  537. string[] ids = new string[strcount];
  538. int iter = -1;
  539. lock (m_UUIDName)
  540. {
  541. strcount = m_UUIDName.Count;
  542. ids = new string[strcount];
  543. foreach (string s in m_UUIDName.Keys)
  544. {
  545. iter++;
  546. ids[iter] = s;
  547. }
  548. }
  549. StringBuilder resp = new StringBuilder();
  550. 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\">");
  551. resp.Append(string.Format(@"<level0>
  552. <status>OK</status>
  553. <cookie_name>lib_session</cookie_name>
  554. <cookie>{0}</cookie>
  555. <auth_token>{0}</auth_token>
  556. <body>
  557. <buddies>",auth_token));
  558. /*
  559. <cookie_name>lib_session</cookie_name>
  560. <cookie>{0}:{1}:9303959503950::</cookie>
  561. <auth_token>{0}:{1}:9303959503950::</auth_token>
  562. */
  563. for (int i=0;i<ids.Length;i++)
  564. {
  565. DateTime currenttime = DateTime.Now;
  566. string dt = currenttime.ToString("yyyy-MM-dd HH:mm:ss.0zz");
  567. resp.Append(
  568. string.Format(@"<level3>
  569. <bdy_id>{1}</bdy_id>
  570. <bdy_data></bdy_data>
  571. <bdy_uri>sip:{0}@{2}</bdy_uri>
  572. <bdy_nickname>{0}</bdy_nickname>
  573. <bdy_username>{0}</bdy_username>
  574. <bdy_domain>{2}</bdy_domain>
  575. <bdy_status>A</bdy_status>
  576. <modified_ts>{3}</modified_ts>
  577. <b2g_group_id></b2g_group_id>
  578. </level3>", ids[i], i ,m_freeSwitchRealm, dt));
  579. }
  580. resp.Append("</buddies><groups></groups></body></level0></response>");
  581. response["str_response_string"] = resp.ToString();
  582. // Regex normalizeEndLines = new Regex(@"(\r\n|\n)", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
  583. //
  584. // m_log.DebugFormat(
  585. // "[FREESWITCH]: FreeSwitchSLVoiceBuddyHTTPHandler() response {0}",
  586. // normalizeEndLines.Replace((string)response["str_response_string"],""));
  587. return response;
  588. }
  589. public Hashtable FreeSwitchSLVoiceWatcherHTTPHandler(Hashtable request)
  590. {
  591. m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceWatcherHTTPHandler called");
  592. Hashtable response = new Hashtable();
  593. response["int_response_code"] = 200;
  594. response["content-type"] = "text/xml";
  595. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  596. string auth_token = (string)requestBody["auth_token"];
  597. //string[] auth_tokenvals = auth_token.Split(':');
  598. //string username = auth_tokenvals[0];
  599. StringBuilder resp = new StringBuilder();
  600. 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\">");
  601. // 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
  602. // give an OK response, then viewer 2 engages in an continuous viv_signin.php, viv_buddy.php, viv_watcher.php loop
  603. // Viewer 1 appeared happy to ignore the lack of reply and still works with this reply.
  604. //
  605. // However, really we need to fill in whatever watcher data should be here (whatever that is).
  606. resp.Append(string.Format(@"<level0>
  607. <status>OK</status>
  608. <cookie_name>lib_session</cookie_name>
  609. <cookie>{0}</cookie>
  610. <auth_token>{0}</auth_token>
  611. <body/></level0></response>", auth_token));
  612. response["str_response_string"] = resp.ToString();
  613. // Regex normalizeEndLines = new Regex(@"(\r\n|\n)", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.Multiline);
  614. //
  615. // m_log.DebugFormat(
  616. // "[FREESWITCH]: FreeSwitchSLVoiceWatcherHTTPHandler() response {0}",
  617. // normalizeEndLines.Replace((string)response["str_response_string"],""));
  618. return response;
  619. }
  620. public Hashtable FreeSwitchSLVoiceSigninHTTPHandler(Hashtable request)
  621. {
  622. m_log.Debug("[FreeSwitchVoice]: FreeSwitchSLVoiceSigninHTTPHandler called");
  623. // string requestbody = (string)request["body"];
  624. // string uri = (string)request["uri"];
  625. // string contenttype = (string)request["content-type"];
  626. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  627. //string pwd = (string) requestBody["pwd"];
  628. string userid = (string) requestBody["userid"];
  629. string avatarName = string.Empty;
  630. int pos = -1;
  631. lock (m_UUIDName)
  632. {
  633. if (m_UUIDName.ContainsKey(userid))
  634. {
  635. avatarName = m_UUIDName[userid];
  636. foreach (string s in m_UUIDName.Keys)
  637. {
  638. pos++;
  639. if (s == userid)
  640. break;
  641. }
  642. }
  643. }
  644. //m_log.DebugFormat("[FreeSwitchVoice]: AUTH, URI: {0}, Content-Type:{1}, Body{2}", uri, contenttype,
  645. // requestbody);
  646. Hashtable response = new Hashtable();
  647. response["str_response_string"] = string.Format(@"<response xsi:schemaLocation=""/xsd/signin.xsd"">
  648. <level0>
  649. <status>OK</status>
  650. <body>
  651. <code>200</code>
  652. <cookie_name>lib_session</cookie_name>
  653. <cookie>{0}:{1}:9303959503950::</cookie>
  654. <auth_token>{0}:{1}:9303959503950::</auth_token>
  655. <primary>1</primary>
  656. <account_id>{1}</account_id>
  657. <displayname>{2}</displayname>
  658. <msg>auth successful</msg>
  659. </body>
  660. </level0>
  661. </response>", userid, pos, avatarName);
  662. response["int_response_code"] = 200;
  663. // m_log.DebugFormat("[FreeSwitchVoice]: Sending FreeSwitchSLVoiceSigninHTTPHandler response");
  664. return response;
  665. }
  666. public Hashtable ParseRequestBody(string body)
  667. {
  668. Hashtable bodyParams = new Hashtable();
  669. // split string
  670. string [] nvps = body.Split(new Char [] {'&'});
  671. foreach (string s in nvps)
  672. {
  673. if (s.Trim() != "")
  674. {
  675. string [] nvp = s.Split(new Char [] {'='});
  676. bodyParams.Add(HttpUtility.UrlDecode(nvp[0]), HttpUtility.UrlDecode(nvp[1]));
  677. }
  678. }
  679. return bodyParams;
  680. }
  681. private string ChannelUri(Scene scene, LandData land)
  682. {
  683. string channelUri = null;
  684. string landUUID;
  685. string landName;
  686. // Create parcel voice channel. If no parcel exists, then the voice channel ID is the same
  687. // as the directory ID. Otherwise, it reflects the parcel's ID.
  688. lock (m_ParcelAddress)
  689. {
  690. if (m_ParcelAddress.ContainsKey(land.GlobalID.ToString()))
  691. {
  692. m_log.DebugFormat("[FreeSwitchVoice]: parcel id {0}: using sip address {1}",
  693. land.GlobalID, m_ParcelAddress[land.GlobalID.ToString()]);
  694. return m_ParcelAddress[land.GlobalID.ToString()];
  695. }
  696. }
  697. if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0)
  698. {
  699. landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name);
  700. landUUID = land.GlobalID.ToString();
  701. m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
  702. landName, land.LocalID, landUUID);
  703. }
  704. else
  705. {
  706. landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName);
  707. landUUID = scene.RegionInfo.RegionID.ToString();
  708. m_log.DebugFormat("[FreeSwitchVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}",
  709. landName, land.LocalID, landUUID);
  710. }
  711. // slvoice handles the sip address differently if it begins with confctl, hiding it from the user in the friends list. however it also disables
  712. // 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.
  713. channelUri = String.Format("sip:conf-{0}@{1}", "x" + Convert.ToBase64String(Encoding.ASCII.GetBytes(landUUID)), m_freeSwitchRealm);
  714. lock (m_ParcelAddress)
  715. {
  716. if (!m_ParcelAddress.ContainsKey(land.GlobalID.ToString()))
  717. {
  718. m_ParcelAddress.Add(land.GlobalID.ToString(),channelUri);
  719. }
  720. }
  721. return channelUri;
  722. }
  723. private static bool CustomCertificateValidation(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
  724. {
  725. return true;
  726. }
  727. public Hashtable FreeSwitchConfigHTTPHandler(Hashtable request)
  728. {
  729. Hashtable response = new Hashtable();
  730. response["str_response_string"] = string.Empty;
  731. response["content_type"] = "text/plain";
  732. response["keepalive"] = false;
  733. response["int_response_code"] = 500;
  734. Hashtable requestBody = ParseRequestBody((string)request["body"]);
  735. string section = (string) requestBody["section"];
  736. if (section == "directory")
  737. {
  738. string eventCallingFunction = (string)requestBody["Event-Calling-Function"];
  739. m_log.DebugFormat(
  740. "[FreeSwitchVoice]: Received request for config section directory, event calling function '{0}'",
  741. eventCallingFunction);
  742. response = m_FreeswitchService.HandleDirectoryRequest(requestBody);
  743. }
  744. else if (section == "dialplan")
  745. {
  746. m_log.DebugFormat("[FreeSwitchVoice]: Received request for config section dialplan");
  747. response = m_FreeswitchService.HandleDialplanRequest(requestBody);
  748. }
  749. else
  750. m_log.WarnFormat("[FreeSwitchVoice]: Unknown section {0} was requested from config.", section);
  751. return response;
  752. }
  753. }
  754. public class MonoCert : ICertificatePolicy
  755. {
  756. #region ICertificatePolicy Members
  757. public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem)
  758. {
  759. return true;
  760. }
  761. #endregion
  762. }
  763. }