XMLRPCModule.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSim Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Net;
  31. using System.Reflection;
  32. using System.Threading;
  33. using OpenMetaverse;
  34. using log4net;
  35. using Nini.Config;
  36. using Nwc.XmlRpc;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Servers;
  39. using OpenSim.Region.Environment.Interfaces;
  40. using OpenSim.Region.Environment.Scenes;
  41. /*****************************************************
  42. *
  43. * XMLRPCModule
  44. *
  45. * Module for accepting incoming communications from
  46. * external XMLRPC client and calling a remote data
  47. * procedure for a registered data channel/prim.
  48. *
  49. *
  50. * 1. On module load, open a listener port
  51. * 2. Attach an XMLRPC handler
  52. * 3. When a request is received:
  53. * 3.1 Parse into components: channel key, int, string
  54. * 3.2 Look up registered channel listeners
  55. * 3.3 Call the channel (prim) remote data method
  56. * 3.4 Capture the response (llRemoteDataReply)
  57. * 3.5 Return response to client caller
  58. * 3.6 If no response from llRemoteDataReply within
  59. * RemoteReplyScriptTimeout, generate script timeout fault
  60. *
  61. * Prims in script must:
  62. * 1. Open a remote data channel
  63. * 1.1 Generate a channel ID
  64. * 1.2 Register primid,channelid pair with module
  65. * 2. Implement the remote data procedure handler
  66. *
  67. * llOpenRemoteDataChannel
  68. * llRemoteDataReply
  69. * remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval)
  70. * llCloseRemoteDataChannel
  71. *
  72. * **************************************************/
  73. namespace OpenSim.Region.Environment.Modules.Scripting.XMLRPC
  74. {
  75. public class XMLRPCModule : IRegionModule, IXMLRPC
  76. {
  77. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  78. private string m_name = "XMLRPCModule";
  79. // <channel id, RPCChannelInfo>
  80. private Dictionary<UUID, RPCChannelInfo> m_openChannels;
  81. private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses;
  82. private int m_remoteDataPort = 0;
  83. private Dictionary<UUID, RPCRequestInfo> m_rpcPending;
  84. private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses;
  85. private List<Scene> m_scenes = new List<Scene>();
  86. private int RemoteReplyScriptTimeout = 9000;
  87. private int RemoteReplyScriptWait = 300;
  88. private object XMLRPCListLock = new object();
  89. #region IRegionModule Members
  90. public void Initialise(Scene scene, IConfigSource config)
  91. {
  92. // We need to create these early because the scripts might be calling
  93. // But since this gets called for every region, we need to make sure they
  94. // get called only one time (or we lose any open channels)
  95. if (null == m_openChannels)
  96. {
  97. m_openChannels = new Dictionary<UUID, RPCChannelInfo>();
  98. m_rpcPending = new Dictionary<UUID, RPCRequestInfo>();
  99. m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>();
  100. m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>();
  101. try
  102. {
  103. m_remoteDataPort = config.Configs["Network"].GetInt("remoteDataPort", m_remoteDataPort);
  104. }
  105. catch (Exception)
  106. {
  107. }
  108. }
  109. if (!m_scenes.Contains(scene))
  110. {
  111. m_scenes.Add(scene);
  112. scene.RegisterModuleInterface<IXMLRPC>(this);
  113. }
  114. }
  115. public void PostInitialise()
  116. {
  117. if (IsEnabled())
  118. {
  119. // Start http server
  120. // Attach xmlrpc handlers
  121. m_log.Info("[REMOTE_DATA]: " +
  122. "Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands.");
  123. BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort);
  124. httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData);
  125. httpServer.Start();
  126. }
  127. }
  128. public void Close()
  129. {
  130. }
  131. public string Name
  132. {
  133. get { return m_name; }
  134. }
  135. public bool IsSharedModule
  136. {
  137. get { return true; }
  138. }
  139. #endregion
  140. #region IXMLRPC Members
  141. public bool IsEnabled()
  142. {
  143. return (m_remoteDataPort > 0);
  144. }
  145. /**********************************************
  146. * OpenXMLRPCChannel
  147. *
  148. * Generate a UUID channel key and add it and
  149. * the prim id to dictionary <channelUUID, primUUID>
  150. *
  151. * A custom channel key can be proposed.
  152. * Otherwise, passing UUID.Zero will generate
  153. * and return a random channel
  154. *
  155. * First check if there is a channel assigned for
  156. * this itemID. If there is, then someone called
  157. * llOpenRemoteDataChannel twice. Just return the
  158. * original channel. Other option is to delete the
  159. * current channel and assign a new one.
  160. *
  161. * ********************************************/
  162. public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID)
  163. {
  164. UUID newChannel = UUID.Zero;
  165. // This should no longer happen, but the check is reasonable anyway
  166. if (null == m_openChannels)
  167. {
  168. m_log.Warn("[RemoteDataReply] Attempt to open channel before initialization is complete");
  169. return newChannel;
  170. }
  171. //Is a dupe?
  172. foreach (RPCChannelInfo ci in m_openChannels.Values)
  173. {
  174. if (ci.GetItemID().Equals(itemID))
  175. {
  176. // return the original channel ID for this item
  177. newChannel = ci.GetChannelID();
  178. break;
  179. }
  180. }
  181. if (newChannel == UUID.Zero)
  182. {
  183. newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID;
  184. RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel);
  185. lock (XMLRPCListLock)
  186. {
  187. m_openChannels.Add(newChannel, rpcChanInfo);
  188. }
  189. }
  190. return newChannel;
  191. }
  192. // Delete channels based on itemID
  193. // for when a script is deleted
  194. public void DeleteChannels(UUID itemID)
  195. {
  196. if (m_openChannels != null)
  197. {
  198. ArrayList tmp = new ArrayList();
  199. lock (XMLRPCListLock)
  200. {
  201. foreach (RPCChannelInfo li in m_openChannels.Values)
  202. {
  203. if (li.GetItemID().Equals(itemID))
  204. {
  205. tmp.Add(itemID);
  206. }
  207. }
  208. IEnumerator tmpEnumerator = tmp.GetEnumerator();
  209. while (tmpEnumerator.MoveNext())
  210. m_openChannels.Remove((UUID) tmpEnumerator.Current);
  211. }
  212. }
  213. }
  214. /**********************************************
  215. * Remote Data Reply
  216. *
  217. * Response to RPC message
  218. *
  219. *********************************************/
  220. public void RemoteDataReply(string channel, string message_id, string sdata, int idata)
  221. {
  222. UUID message_key = new UUID(message_id);
  223. UUID channel_key = new UUID(channel);
  224. RPCRequestInfo rpcInfo = null;
  225. if (message_key == UUID.Zero)
  226. {
  227. foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values)
  228. if (oneRpcInfo.GetChannelKey() == channel_key)
  229. rpcInfo = oneRpcInfo;
  230. }
  231. else
  232. {
  233. m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo);
  234. }
  235. if (rpcInfo != null)
  236. {
  237. rpcInfo.SetStrRetval(sdata);
  238. rpcInfo.SetIntRetval(idata);
  239. rpcInfo.SetProcessed(true);
  240. m_rpcPendingResponses.Remove(message_key);
  241. }
  242. else
  243. {
  244. m_log.Warn("[RemoteDataReply]: Channel or message_id not found");
  245. }
  246. }
  247. /**********************************************
  248. * CloseXMLRPCChannel
  249. *
  250. * Remove channel from dictionary
  251. *
  252. *********************************************/
  253. public void CloseXMLRPCChannel(UUID channelKey)
  254. {
  255. if (m_openChannels.ContainsKey(channelKey))
  256. m_openChannels.Remove(channelKey);
  257. }
  258. public bool hasRequests()
  259. {
  260. lock (XMLRPCListLock)
  261. {
  262. if (m_rpcPending != null)
  263. return (m_rpcPending.Count > 0);
  264. else
  265. return false;
  266. }
  267. }
  268. public RPCRequestInfo GetNextCompletedRequest()
  269. {
  270. if (m_rpcPending != null)
  271. {
  272. lock (XMLRPCListLock)
  273. {
  274. foreach (UUID luid in m_rpcPending.Keys)
  275. {
  276. RPCRequestInfo tmpReq;
  277. if (m_rpcPending.TryGetValue(luid, out tmpReq))
  278. {
  279. if (!tmpReq.IsProcessed()) return tmpReq;
  280. }
  281. }
  282. }
  283. }
  284. return null;
  285. }
  286. public void RemoveCompletedRequest(UUID id)
  287. {
  288. lock (XMLRPCListLock)
  289. {
  290. RPCRequestInfo tmp;
  291. if (m_rpcPending.TryGetValue(id, out tmp))
  292. {
  293. m_rpcPending.Remove(id);
  294. m_rpcPendingResponses.Add(id, tmp);
  295. }
  296. else
  297. {
  298. Console.WriteLine("UNABLE TO REMOVE COMPLETED REQUEST");
  299. }
  300. }
  301. }
  302. public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
  303. {
  304. SendRemoteDataRequest req = new SendRemoteDataRequest(
  305. localID, itemID, channel, dest, idata, sdata
  306. );
  307. m_pendingSRDResponses.Add(req.GetReqID(), req);
  308. return req.process();
  309. }
  310. public SendRemoteDataRequest GetNextCompletedSRDRequest()
  311. {
  312. if (m_pendingSRDResponses != null)
  313. {
  314. lock (XMLRPCListLock)
  315. {
  316. foreach (UUID luid in m_pendingSRDResponses.Keys)
  317. {
  318. SendRemoteDataRequest tmpReq;
  319. if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq))
  320. {
  321. if (tmpReq.finished)
  322. return tmpReq;
  323. }
  324. }
  325. }
  326. }
  327. return null;
  328. }
  329. public void RemoveCompletedSRDRequest(UUID id)
  330. {
  331. lock (XMLRPCListLock)
  332. {
  333. SendRemoteDataRequest tmpReq;
  334. if (m_pendingSRDResponses.TryGetValue(id, out tmpReq))
  335. {
  336. m_pendingSRDResponses.Remove(id);
  337. }
  338. }
  339. }
  340. public void CancelSRDRequests(UUID itemID)
  341. {
  342. if (m_pendingSRDResponses != null)
  343. {
  344. lock (XMLRPCListLock)
  345. {
  346. foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values)
  347. {
  348. if (li.m_itemID.Equals(itemID))
  349. m_pendingSRDResponses.Remove(li.GetReqID());
  350. }
  351. }
  352. }
  353. }
  354. #endregion
  355. public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request)
  356. {
  357. XmlRpcResponse response = new XmlRpcResponse();
  358. Hashtable requestData = (Hashtable) request.Params[0];
  359. bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") &&
  360. requestData.Contains("StringValue"));
  361. if (GoodXML)
  362. {
  363. UUID channel = new UUID((string) requestData["Channel"]);
  364. RPCChannelInfo rpcChanInfo;
  365. if (m_openChannels.TryGetValue(channel, out rpcChanInfo))
  366. {
  367. string intVal = Convert.ToInt32(requestData["IntValue"]).ToString();
  368. string strVal = (string) requestData["StringValue"];
  369. RPCRequestInfo rpcInfo;
  370. lock (XMLRPCListLock)
  371. {
  372. rpcInfo =
  373. new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal,
  374. intVal);
  375. m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo);
  376. }
  377. int timeoutCtr = 0;
  378. while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout))
  379. {
  380. Thread.Sleep(RemoteReplyScriptWait);
  381. timeoutCtr += RemoteReplyScriptWait;
  382. }
  383. if (rpcInfo.IsProcessed())
  384. {
  385. Hashtable param = new Hashtable();
  386. param["StringValue"] = rpcInfo.GetStrRetval();
  387. param["IntValue"] = rpcInfo.GetIntRetval();
  388. ArrayList parameters = new ArrayList();
  389. parameters.Add(param);
  390. response.Value = parameters;
  391. rpcInfo = null;
  392. }
  393. else
  394. {
  395. response.SetFault(-1, "Script timeout");
  396. rpcInfo = null;
  397. }
  398. }
  399. else
  400. {
  401. response.SetFault(-1, "Invalid channel");
  402. }
  403. }
  404. return response;
  405. }
  406. }
  407. public class RPCRequestInfo
  408. {
  409. private UUID m_ChannelKey;
  410. private string m_IntVal;
  411. private UUID m_ItemID;
  412. private uint m_localID;
  413. private UUID m_MessageID;
  414. private bool m_processed;
  415. private int m_respInt;
  416. private string m_respStr;
  417. private string m_StrVal;
  418. public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal)
  419. {
  420. m_localID = localID;
  421. m_StrVal = strVal;
  422. m_IntVal = intVal;
  423. m_ItemID = itemID;
  424. m_ChannelKey = channelKey;
  425. m_MessageID = UUID.Random();
  426. m_processed = false;
  427. m_respStr = String.Empty;
  428. m_respInt = 0;
  429. }
  430. public bool IsProcessed()
  431. {
  432. return m_processed;
  433. }
  434. public UUID GetChannelKey()
  435. {
  436. return m_ChannelKey;
  437. }
  438. public void SetProcessed(bool processed)
  439. {
  440. m_processed = processed;
  441. }
  442. public void SetStrRetval(string resp)
  443. {
  444. m_respStr = resp;
  445. }
  446. public string GetStrRetval()
  447. {
  448. return m_respStr;
  449. }
  450. public void SetIntRetval(int resp)
  451. {
  452. m_respInt = resp;
  453. }
  454. public int GetIntRetval()
  455. {
  456. return m_respInt;
  457. }
  458. public uint GetLocalID()
  459. {
  460. return m_localID;
  461. }
  462. public UUID GetItemID()
  463. {
  464. return m_ItemID;
  465. }
  466. public string GetStrVal()
  467. {
  468. return m_StrVal;
  469. }
  470. public int GetIntValue()
  471. {
  472. return int.Parse(m_IntVal);
  473. }
  474. public UUID GetMessageID()
  475. {
  476. return m_MessageID;
  477. }
  478. }
  479. public class RPCChannelInfo
  480. {
  481. private UUID m_ChannelKey;
  482. private UUID m_itemID;
  483. private uint m_localID;
  484. public RPCChannelInfo(uint localID, UUID itemID, UUID channelID)
  485. {
  486. m_ChannelKey = channelID;
  487. m_localID = localID;
  488. m_itemID = itemID;
  489. }
  490. public UUID GetItemID()
  491. {
  492. return m_itemID;
  493. }
  494. public UUID GetChannelID()
  495. {
  496. return m_ChannelKey;
  497. }
  498. public uint GetLocalID()
  499. {
  500. return m_localID;
  501. }
  502. }
  503. public class SendRemoteDataRequest
  504. {
  505. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  506. public string channel;
  507. public string destURL;
  508. public bool finished;
  509. private Thread httpThread;
  510. public int idata;
  511. public UUID m_itemID;
  512. public uint m_localID;
  513. public UUID reqID;
  514. public XmlRpcRequest request;
  515. public int response_idata;
  516. public string response_sdata;
  517. public string sdata;
  518. public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
  519. {
  520. this.channel = channel;
  521. destURL = dest;
  522. this.idata = idata;
  523. this.sdata = sdata;
  524. m_itemID = itemID;
  525. m_localID = localID;
  526. reqID = UUID.Random();
  527. }
  528. public UUID process()
  529. {
  530. httpThread = new Thread(SendRequest);
  531. httpThread.Name = "HttpRequestThread";
  532. httpThread.Priority = ThreadPriority.BelowNormal;
  533. httpThread.IsBackground = true;
  534. finished = false;
  535. httpThread.Start();
  536. ThreadTracker.Add(httpThread);
  537. return reqID;
  538. }
  539. /*
  540. * TODO: More work on the response codes. Right now
  541. * returning 200 for success or 499 for exception
  542. */
  543. public void SendRequest()
  544. {
  545. Hashtable param = new Hashtable();
  546. // Check if channel is an UUID
  547. // if not, use as method name
  548. UUID parseUID;
  549. string mName = "llRemoteData";
  550. if ((channel != null) && (channel != ""))
  551. if (!UUID.TryParse(channel, out parseUID))
  552. mName = channel;
  553. else
  554. param["Channel"] = channel;
  555. param["StringValue"] = sdata;
  556. param["IntValue"] = Convert.ToString(idata);
  557. ArrayList parameters = new ArrayList();
  558. parameters.Add(param);
  559. XmlRpcRequest req = new XmlRpcRequest(mName, parameters);
  560. try
  561. {
  562. XmlRpcResponse resp = req.Send(destURL, 30000);
  563. if (resp != null)
  564. {
  565. Hashtable respParms;
  566. if (resp.Value.GetType().Equals(typeof(System.Collections.Hashtable)))
  567. {
  568. respParms = (Hashtable) resp.Value;
  569. }
  570. else
  571. {
  572. ArrayList respData = (ArrayList) resp.Value;
  573. respParms = (Hashtable) respData[0];
  574. }
  575. if (respParms != null)
  576. {
  577. if (respParms.Contains("StringValue"))
  578. {
  579. sdata = (string) respParms["StringValue"];
  580. }
  581. if (respParms.Contains("IntValue"))
  582. {
  583. idata = Convert.ToInt32((string) respParms["IntValue"]);
  584. }
  585. if (respParms.Contains("faultString"))
  586. {
  587. sdata = (string) respParms["faultString"];
  588. }
  589. if (respParms.Contains("faultCode"))
  590. {
  591. idata = Convert.ToInt32(respParms["faultCode"]);
  592. }
  593. }
  594. }
  595. }
  596. catch (Exception we)
  597. {
  598. sdata = we.Message;
  599. m_log.Warn("[SendRemoteDataRequest]: Request failed");
  600. m_log.Warn(we.StackTrace);
  601. }
  602. finished = true;
  603. }
  604. public void Stop()
  605. {
  606. try
  607. {
  608. httpThread.Abort();
  609. }
  610. catch (Exception)
  611. {
  612. }
  613. }
  614. public UUID GetReqID()
  615. {
  616. return reqID;
  617. }
  618. }
  619. }