XMLRPCModule.cs 23 KB

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