FreeSwitchVoiceModule.cs 38 KB

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