XMLRPCModule.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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.Reflection;
  31. using System.Threading;
  32. using log4net;
  33. using Nini.Config;
  34. using Nwc.XmlRpc;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Servers;
  38. using OpenSim.Region.Framework.Interfaces;
  39. using OpenSim.Region.Framework.Scenes;
  40. /*****************************************************
  41. *
  42. * XMLRPCModule
  43. *
  44. * Module for accepting incoming communications from
  45. * external XMLRPC client and calling a remote data
  46. * procedure for a registered data channel/prim.
  47. *
  48. *
  49. * 1. On module load, open a listener port
  50. * 2. Attach an XMLRPC handler
  51. * 3. When a request is received:
  52. * 3.1 Parse into components: channel key, int, string
  53. * 3.2 Look up registered channel listeners
  54. * 3.3 Call the channel (prim) remote data method
  55. * 3.4 Capture the response (llRemoteDataReply)
  56. * 3.5 Return response to client caller
  57. * 3.6 If no response from llRemoteDataReply within
  58. * RemoteReplyScriptTimeout, generate script timeout fault
  59. *
  60. * Prims in script must:
  61. * 1. Open a remote data channel
  62. * 1.1 Generate a channel ID
  63. * 1.2 Register primid,channelid pair with module
  64. * 2. Implement the remote data procedure handler
  65. *
  66. * llOpenRemoteDataChannel
  67. * llRemoteDataReply
  68. * remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval)
  69. * llCloseRemoteDataChannel
  70. *
  71. * **************************************************/
  72. namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
  73. {
  74. public class XMLRPCModule : IRegionModule, IXMLRPC
  75. {
  76. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  77. private string m_name = "XMLRPCModule";
  78. // <channel id, RPCChannelInfo>
  79. private Dictionary<UUID, RPCChannelInfo> m_openChannels;
  80. private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses;
  81. private int m_remoteDataPort = 0;
  82. private Dictionary<UUID, RPCRequestInfo> m_rpcPending;
  83. private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses;
  84. private List<Scene> m_scenes = new List<Scene>();
  85. private int RemoteReplyScriptTimeout = 9000;
  86. private int RemoteReplyScriptWait = 300;
  87. private object XMLRPCListLock = new object();
  88. #region IRegionModule Members
  89. public void Initialise(Scene scene, IConfigSource config)
  90. {
  91. // We need to create these early because the scripts might be calling
  92. // But since this gets called for every region, we need to make sure they
  93. // get called only one time (or we lose any open channels)
  94. if (null == m_openChannels)
  95. {
  96. m_openChannels = new Dictionary<UUID, RPCChannelInfo>();
  97. m_rpcPending = new Dictionary<UUID, RPCRequestInfo>();
  98. m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>();
  99. m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>();
  100. try
  101. {
  102. m_remoteDataPort = config.Configs["Network"].GetInt("remoteDataPort", m_remoteDataPort);
  103. }
  104. catch (Exception)
  105. {
  106. }
  107. }
  108. if (!m_scenes.Contains(scene))
  109. {
  110. m_scenes.Add(scene);
  111. scene.RegisterModuleInterface<IXMLRPC>(this);
  112. }
  113. }
  114. public void PostInitialise()
  115. {
  116. if (IsEnabled())
  117. {
  118. // Start http server
  119. // Attach xmlrpc handlers
  120. m_log.Info("[REMOTE_DATA]: " +
  121. "Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands.");
  122. BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort);
  123. httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData);
  124. httpServer.Start();
  125. }
  126. }
  127. public void Close()
  128. {
  129. }
  130. public string Name
  131. {
  132. get { return m_name; }
  133. }
  134. public bool IsSharedModule
  135. {
  136. get { return true; }
  137. }
  138. #endregion
  139. #region IXMLRPC Members
  140. public bool IsEnabled()
  141. {
  142. return (m_remoteDataPort > 0);
  143. }
  144. /**********************************************
  145. * OpenXMLRPCChannel
  146. *
  147. * Generate a UUID channel key and add it and
  148. * the prim id to dictionary <channelUUID, primUUID>
  149. *
  150. * A custom channel key can be proposed.
  151. * Otherwise, passing UUID.Zero will generate
  152. * and return a random channel
  153. *
  154. * First check if there is a channel assigned for
  155. * this itemID. If there is, then someone called
  156. * llOpenRemoteDataChannel twice. Just return the
  157. * original channel. Other option is to delete the
  158. * current channel and assign a new one.
  159. *
  160. * ********************************************/
  161. public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID)
  162. {
  163. UUID newChannel = UUID.Zero;
  164. // This should no longer happen, but the check is reasonable anyway
  165. if (null == m_openChannels)
  166. {
  167. m_log.Warn("[RemoteDataReply] Attempt to open channel before initialization is complete");
  168. return newChannel;
  169. }
  170. //Is a dupe?
  171. foreach (RPCChannelInfo ci in m_openChannels.Values)
  172. {
  173. if (ci.GetItemID().Equals(itemID))
  174. {
  175. // return the original channel ID for this item
  176. newChannel = ci.GetChannelID();
  177. break;
  178. }
  179. }
  180. if (newChannel == UUID.Zero)
  181. {
  182. newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID;
  183. RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel);
  184. lock (XMLRPCListLock)
  185. {
  186. m_openChannels.Add(newChannel, rpcChanInfo);
  187. }
  188. }
  189. return newChannel;
  190. }
  191. // Delete channels based on itemID
  192. // for when a script is deleted
  193. public void DeleteChannels(UUID itemID)
  194. {
  195. if (m_openChannels != null)
  196. {
  197. ArrayList tmp = new ArrayList();
  198. lock (XMLRPCListLock)
  199. {
  200. foreach (RPCChannelInfo li in m_openChannels.Values)
  201. {
  202. if (li.GetItemID().Equals(itemID))
  203. {
  204. tmp.Add(itemID);
  205. }
  206. }
  207. IEnumerator tmpEnumerator = tmp.GetEnumerator();
  208. while (tmpEnumerator.MoveNext())
  209. m_openChannels.Remove((UUID) tmpEnumerator.Current);
  210. }
  211. }
  212. }
  213. /**********************************************
  214. * Remote Data Reply
  215. *
  216. * Response to RPC message
  217. *
  218. *********************************************/
  219. public void RemoteDataReply(string channel, string message_id, string sdata, int idata)
  220. {
  221. UUID message_key = new UUID(message_id);
  222. UUID channel_key = new UUID(channel);
  223. RPCRequestInfo rpcInfo = null;
  224. if (message_key == UUID.Zero)
  225. {
  226. foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values)
  227. if (oneRpcInfo.GetChannelKey() == channel_key)
  228. rpcInfo = oneRpcInfo;
  229. }
  230. else
  231. {
  232. m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo);
  233. }
  234. if (rpcInfo != null)
  235. {
  236. rpcInfo.SetStrRetval(sdata);
  237. rpcInfo.SetIntRetval(idata);
  238. rpcInfo.SetProcessed(true);
  239. m_rpcPendingResponses.Remove(message_key);
  240. }
  241. else
  242. {
  243. m_log.Warn("[RemoteDataReply]: Channel or message_id not found");
  244. }
  245. }
  246. /**********************************************
  247. * CloseXMLRPCChannel
  248. *
  249. * Remove channel from dictionary
  250. *
  251. *********************************************/
  252. public void CloseXMLRPCChannel(UUID channelKey)
  253. {
  254. if (m_openChannels.ContainsKey(channelKey))
  255. m_openChannels.Remove(channelKey);
  256. }
  257. public bool hasRequests()
  258. {
  259. lock (XMLRPCListLock)
  260. {
  261. if (m_rpcPending != null)
  262. return (m_rpcPending.Count > 0);
  263. else
  264. return false;
  265. }
  266. }
  267. public IXmlRpcRequestInfo GetNextCompletedRequest()
  268. {
  269. if (m_rpcPending != null)
  270. {
  271. lock (XMLRPCListLock)
  272. {
  273. foreach (UUID luid in m_rpcPending.Keys)
  274. {
  275. RPCRequestInfo tmpReq;
  276. if (m_rpcPending.TryGetValue(luid, out tmpReq))
  277. {
  278. if (!tmpReq.IsProcessed()) return tmpReq;
  279. }
  280. }
  281. }
  282. }
  283. return null;
  284. }
  285. public void RemoveCompletedRequest(UUID id)
  286. {
  287. lock (XMLRPCListLock)
  288. {
  289. RPCRequestInfo tmp;
  290. if (m_rpcPending.TryGetValue(id, out tmp))
  291. {
  292. m_rpcPending.Remove(id);
  293. m_rpcPendingResponses.Add(id, tmp);
  294. }
  295. else
  296. {
  297. m_log.Error("UNABLE TO REMOVE COMPLETED REQUEST");
  298. }
  299. }
  300. }
  301. public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
  302. {
  303. SendRemoteDataRequest req = new SendRemoteDataRequest(
  304. localID, itemID, channel, dest, idata, sdata
  305. );
  306. m_pendingSRDResponses.Add(req.GetReqID(), req);
  307. req.Process();
  308. return req.ReqID;
  309. }
  310. public IServiceRequest 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.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: IXmlRpcRequestInfo
  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: IServiceRequest
  504. {
  505. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  506. public string Channel;
  507. public string DestURL;
  508. private bool _finished;
  509. public bool Finished
  510. {
  511. get { return _finished; }
  512. set { _finished = value; }
  513. }
  514. private Thread httpThread;
  515. public int Idata;
  516. private UUID _itemID;
  517. public UUID ItemID
  518. {
  519. get { return _itemID; }
  520. set { _itemID = value; }
  521. }
  522. private uint _localID;
  523. public uint LocalID
  524. {
  525. get { return _localID; }
  526. set { _localID = value; }
  527. }
  528. private UUID _reqID;
  529. public UUID ReqID
  530. {
  531. get { return _reqID; }
  532. set { _reqID = value; }
  533. }
  534. public XmlRpcRequest Request;
  535. public int ResponseIdata;
  536. public string ResponseSdata;
  537. public string Sdata;
  538. public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
  539. {
  540. this.Channel = channel;
  541. DestURL = dest;
  542. this.Idata = idata;
  543. this.Sdata = sdata;
  544. ItemID = itemID;
  545. LocalID = localID;
  546. ReqID = UUID.Random();
  547. }
  548. public void Process()
  549. {
  550. httpThread = new Thread(SendRequest);
  551. httpThread.Name = "HttpRequestThread";
  552. httpThread.Priority = ThreadPriority.BelowNormal;
  553. httpThread.IsBackground = true;
  554. _finished = false;
  555. httpThread.Start();
  556. ThreadTracker.Add(httpThread);
  557. }
  558. /*
  559. * TODO: More work on the response codes. Right now
  560. * returning 200 for success or 499 for exception
  561. */
  562. public void SendRequest()
  563. {
  564. Hashtable param = new Hashtable();
  565. // Check if channel is an UUID
  566. // if not, use as method name
  567. UUID parseUID;
  568. string mName = "llRemoteData";
  569. if ((Channel != null) && (Channel != ""))
  570. if (!UUID.TryParse(Channel, out parseUID))
  571. mName = Channel;
  572. else
  573. param["Channel"] = Channel;
  574. param["StringValue"] = Sdata;
  575. param["IntValue"] = Convert.ToString(Idata);
  576. ArrayList parameters = new ArrayList();
  577. parameters.Add(param);
  578. XmlRpcRequest req = new XmlRpcRequest(mName, parameters);
  579. try
  580. {
  581. XmlRpcResponse resp = req.Send(DestURL, 30000);
  582. if (resp != null)
  583. {
  584. Hashtable respParms;
  585. if (resp.Value.GetType().Equals(typeof(Hashtable)))
  586. {
  587. respParms = (Hashtable) resp.Value;
  588. }
  589. else
  590. {
  591. ArrayList respData = (ArrayList) resp.Value;
  592. respParms = (Hashtable) respData[0];
  593. }
  594. if (respParms != null)
  595. {
  596. if (respParms.Contains("StringValue"))
  597. {
  598. Sdata = (string) respParms["StringValue"];
  599. }
  600. if (respParms.Contains("IntValue"))
  601. {
  602. Idata = Convert.ToInt32((string) respParms["IntValue"]);
  603. }
  604. if (respParms.Contains("faultString"))
  605. {
  606. Sdata = (string) respParms["faultString"];
  607. }
  608. if (respParms.Contains("faultCode"))
  609. {
  610. Idata = Convert.ToInt32(respParms["faultCode"]);
  611. }
  612. }
  613. }
  614. }
  615. catch (Exception we)
  616. {
  617. Sdata = we.Message;
  618. m_log.Warn("[SendRemoteDataRequest]: Request failed");
  619. m_log.Warn(we.StackTrace);
  620. }
  621. _finished = true;
  622. }
  623. public void Stop()
  624. {
  625. try
  626. {
  627. httpThread.Abort();
  628. }
  629. catch (Exception)
  630. {
  631. }
  632. }
  633. public UUID GetReqID()
  634. {
  635. return ReqID;
  636. }
  637. }
  638. }