ScriptManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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.Reflection;
  29. using System.Globalization;
  30. using System.Runtime.Remoting;
  31. using System.Runtime.Remoting.Lifetime;
  32. using log4net;
  33. using OpenMetaverse;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.Framework.Scenes;
  36. using OpenSim.Region.ScriptEngine.Interfaces;
  37. using OpenSim.Region.ScriptEngine.Shared;
  38. using OpenSim.Region.ScriptEngine.Shared.Api;
  39. using System.Collections.Generic;
  40. using System.IO;
  41. using System.Runtime.Serialization.Formatters.Binary;
  42. using System.Threading;
  43. using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
  44. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  45. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  46. namespace OpenSim.Region.ScriptEngine.DotNetEngine
  47. {
  48. public class InstanceData
  49. {
  50. public IScript Script;
  51. public string State;
  52. public bool Running;
  53. public bool Disabled;
  54. public string Source;
  55. public int StartParam;
  56. public AppDomain AppDomain;
  57. public Dictionary<string, IScriptApi> Apis;
  58. public Dictionary<KeyValuePair<int,int>, KeyValuePair<int,int>>
  59. LineMap;
  60. // public ISponsor ScriptSponsor;
  61. }
  62. public class ScriptManager
  63. {
  64. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  65. #region Declares
  66. private Thread scriptLoadUnloadThread;
  67. private static Thread staticScriptLoadUnloadThread;
  68. private Queue<LUStruct> LUQueue = new Queue<LUStruct>();
  69. private static bool PrivateThread;
  70. private int LoadUnloadMaxQueueSize;
  71. private Object scriptLock = new Object();
  72. private bool m_started = false;
  73. private Dictionary<InstanceData, DetectParams[]> detparms =
  74. new Dictionary<InstanceData, DetectParams[]>();
  75. // Load/Unload structure
  76. private struct LUStruct
  77. {
  78. public uint localID;
  79. public UUID itemID;
  80. public string script;
  81. public LUType Action;
  82. public int startParam;
  83. public bool postOnRez;
  84. }
  85. private enum LUType
  86. {
  87. Unknown = 0,
  88. Load = 1,
  89. Unload = 2
  90. }
  91. public Dictionary<uint, Dictionary<UUID, InstanceData>> Scripts =
  92. new Dictionary<uint, Dictionary<UUID, InstanceData>>();
  93. private Compiler LSLCompiler;
  94. public Scene World
  95. {
  96. get { return m_scriptEngine.World; }
  97. }
  98. #endregion
  99. public void Initialize()
  100. {
  101. // Create our compiler
  102. LSLCompiler = new Compiler(m_scriptEngine);
  103. }
  104. public void _StartScript(uint localID, UUID itemID, string Script,
  105. int startParam, bool postOnRez)
  106. {
  107. m_log.DebugFormat(
  108. "[{0}]: ScriptManager StartScript: localID: {1}, itemID: {2}",
  109. m_scriptEngine.ScriptEngineName, localID, itemID);
  110. // We will initialize and start the script.
  111. // It will be up to the script itself to hook up the correct events.
  112. string CompiledScriptFile = String.Empty;
  113. SceneObjectPart m_host = World.GetSceneObjectPart(localID);
  114. if (null == m_host)
  115. {
  116. m_log.ErrorFormat(
  117. "[{0}]: Could not find scene object part corresponding "+
  118. "to localID {1} to start script",
  119. m_scriptEngine.ScriptEngineName, localID);
  120. return;
  121. }
  122. UUID assetID = UUID.Zero;
  123. TaskInventoryItem taskInventoryItem = new TaskInventoryItem();
  124. if (m_host.TaskInventory.TryGetValue(itemID, out taskInventoryItem))
  125. assetID = taskInventoryItem.AssetID;
  126. ScenePresence presence =
  127. World.GetScenePresence(taskInventoryItem.OwnerID);
  128. CultureInfo USCulture = new CultureInfo("en-US");
  129. Thread.CurrentThread.CurrentCulture = USCulture;
  130. try
  131. {
  132. // Compile (We assume LSL)
  133. CompiledScriptFile =
  134. LSLCompiler.PerformScriptCompile(Script,
  135. assetID.ToString());
  136. if (presence != null && (!postOnRez))
  137. presence.ControllingClient.SendAgentAlertMessage(
  138. "Compile successful", false);
  139. m_log.InfoFormat("[SCRIPT]: Compiled assetID {0}: {1}",
  140. assetID, CompiledScriptFile);
  141. InstanceData id = new InstanceData();
  142. IScript CompiledScript;
  143. CompiledScript =
  144. m_scriptEngine.m_AppDomainManager.LoadScript(
  145. CompiledScriptFile, out id.AppDomain);
  146. //Register the sponsor
  147. // ISponsor scriptSponsor = new ScriptSponsor();
  148. // ILease lease = (ILease)RemotingServices.GetLifetimeService(CompiledScript as MarshalByRefObject);
  149. // lease.Register(scriptSponsor);
  150. // id.ScriptSponsor = scriptSponsor;
  151. id.LineMap = LSLCompiler.LineMap();
  152. id.Script = CompiledScript;
  153. id.Source = Script;
  154. id.StartParam = startParam;
  155. id.State = "default";
  156. id.Running = true;
  157. id.Disabled = false;
  158. // Add it to our script memstruct
  159. m_scriptEngine.m_ScriptManager.SetScript(localID, itemID, id);
  160. id.Apis = new Dictionary<string, IScriptApi>();
  161. ApiManager am = new ApiManager();
  162. foreach (string api in am.GetApis())
  163. {
  164. id.Apis[api] = am.CreateApi(api);
  165. id.Apis[api].Initialize(m_scriptEngine, m_host,
  166. localID, itemID);
  167. }
  168. foreach (KeyValuePair<string,IScriptApi> kv in id.Apis)
  169. {
  170. CompiledScript.InitApi(kv.Key, kv.Value);
  171. }
  172. // Fire the first start-event
  173. int eventFlags =
  174. m_scriptEngine.m_ScriptManager.GetStateEventFlags(
  175. localID, itemID);
  176. m_host.SetScriptEvents(itemID, eventFlags);
  177. m_scriptEngine.m_EventQueueManager.AddToScriptQueue(
  178. localID, itemID, "state_entry", new DetectParams[0],
  179. new object[] { });
  180. if (postOnRez)
  181. {
  182. m_scriptEngine.m_EventQueueManager.AddToScriptQueue(
  183. localID, itemID, "on_rez", new DetectParams[0],
  184. new object[] { new LSL_Types.LSLInteger(startParam) });
  185. }
  186. string[] warnings = LSLCompiler.GetWarnings();
  187. if (warnings != null && warnings.Length != 0)
  188. {
  189. if (presence != null && (!postOnRez))
  190. presence.ControllingClient.SendAgentAlertMessage(
  191. "Script saved with warnings, check debug window!",
  192. false);
  193. foreach (string warning in warnings)
  194. {
  195. try
  196. {
  197. // DISPLAY WARNING INWORLD
  198. string text = "Warning:\n" + warning;
  199. if (text.Length > 1100)
  200. text = text.Substring(0, 1099);
  201. World.SimChat(Utils.StringToBytes(text),
  202. ChatTypeEnum.DebugChannel, 2147483647,
  203. m_host.AbsolutePosition, m_host.Name, m_host.UUID,
  204. false);
  205. }
  206. catch (Exception e2) // LEGIT: User Scripting
  207. {
  208. m_log.Error("[" +
  209. m_scriptEngine.ScriptEngineName +
  210. "]: Error displaying warning in-world: " +
  211. e2.ToString());
  212. m_log.Error("[" +
  213. m_scriptEngine.ScriptEngineName + "]: " +
  214. "Warning:\r\n" +
  215. warning);
  216. }
  217. }
  218. }
  219. }
  220. catch (Exception e) // LEGIT: User Scripting
  221. {
  222. if (presence != null && (!postOnRez))
  223. presence.ControllingClient.SendAgentAlertMessage(
  224. "Script saved with errors, check debug window!",
  225. false);
  226. try
  227. {
  228. // DISPLAY ERROR INWORLD
  229. string text = "Error compiling script:\n" +
  230. e.Message.ToString();
  231. if (text.Length > 1100)
  232. text = text.Substring(0, 1099);
  233. World.SimChat(Utils.StringToBytes(text),
  234. ChatTypeEnum.DebugChannel, 2147483647,
  235. m_host.AbsolutePosition, m_host.Name, m_host.UUID,
  236. false);
  237. }
  238. catch (Exception e2) // LEGIT: User Scripting
  239. {
  240. m_log.Error("[" +
  241. m_scriptEngine.ScriptEngineName +
  242. "]: Error displaying error in-world: " +
  243. e2.ToString());
  244. m_log.Error("[" +
  245. m_scriptEngine.ScriptEngineName + "]: " +
  246. "Errormessage: Error compiling script:\r\n" +
  247. e2.Message.ToString());
  248. }
  249. }
  250. }
  251. public void _StopScript(uint localID, UUID itemID)
  252. {
  253. InstanceData id = GetScript(localID, itemID);
  254. if (id == null)
  255. return;
  256. m_log.DebugFormat("[{0}]: Unloading script",
  257. m_scriptEngine.ScriptEngineName);
  258. // Stop long command on script
  259. AsyncCommandManager.RemoveScript(m_scriptEngine, localID, itemID);
  260. try
  261. {
  262. // Get AppDomain
  263. // Tell script not to accept new requests
  264. id.Running = false;
  265. id.Disabled = true;
  266. AppDomain ad = id.AppDomain;
  267. // Remove from internal structure
  268. RemoveScript(localID, itemID);
  269. // Tell AppDomain that we have stopped script
  270. m_scriptEngine.m_AppDomainManager.StopScript(ad);
  271. }
  272. catch (Exception e) // LEGIT: User Scripting
  273. {
  274. m_log.Error("[" +
  275. m_scriptEngine.ScriptEngineName +
  276. "]: Exception stopping script localID: " +
  277. localID + " LLUID: " + itemID.ToString() +
  278. ": " + e.ToString());
  279. }
  280. }
  281. public void ReadConfig()
  282. {
  283. // TODO: Requires sharing of all ScriptManagers to single thread
  284. PrivateThread = true;
  285. LoadUnloadMaxQueueSize = m_scriptEngine.ScriptConfigSource.GetInt(
  286. "LoadUnloadMaxQueueSize", 100);
  287. }
  288. #region Object init/shutdown
  289. public ScriptEngine m_scriptEngine;
  290. public ScriptManager(ScriptEngine scriptEngine)
  291. {
  292. m_scriptEngine = scriptEngine;
  293. }
  294. public void Setup()
  295. {
  296. ReadConfig();
  297. Initialize();
  298. }
  299. public void Start()
  300. {
  301. m_started = true;
  302. AppDomain.CurrentDomain.AssemblyResolve +=
  303. new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  304. //
  305. // CREATE THREAD
  306. // Private or shared
  307. //
  308. if (PrivateThread)
  309. {
  310. // Assign one thread per region
  311. //scriptLoadUnloadThread = StartScriptLoadUnloadThread();
  312. }
  313. else
  314. {
  315. // Shared thread - make sure one exist, then assign it to the private
  316. if (staticScriptLoadUnloadThread == null)
  317. {
  318. //staticScriptLoadUnloadThread =
  319. // StartScriptLoadUnloadThread();
  320. }
  321. scriptLoadUnloadThread = staticScriptLoadUnloadThread;
  322. }
  323. }
  324. ~ScriptManager()
  325. {
  326. // Abort load/unload thread
  327. try
  328. {
  329. if (scriptLoadUnloadThread != null &&
  330. scriptLoadUnloadThread.IsAlive == true)
  331. {
  332. scriptLoadUnloadThread.Abort();
  333. //scriptLoadUnloadThread.Join();
  334. }
  335. }
  336. catch
  337. {
  338. }
  339. }
  340. #endregion
  341. #region Load / Unload scripts (Thread loop)
  342. public void DoScriptLoadUnload()
  343. {
  344. if (!m_started)
  345. return;
  346. lock (LUQueue)
  347. {
  348. if (LUQueue.Count > 0)
  349. {
  350. LUStruct item = LUQueue.Dequeue();
  351. if (item.Action == LUType.Unload)
  352. {
  353. _StopScript(item.localID, item.itemID);
  354. RemoveScript(item.localID, item.itemID);
  355. }
  356. else if (item.Action == LUType.Load)
  357. {
  358. m_log.DebugFormat("[{0}]: Loading script",
  359. m_scriptEngine.ScriptEngineName);
  360. _StartScript(item.localID, item.itemID, item.script,
  361. item.startParam, item.postOnRez);
  362. }
  363. }
  364. }
  365. }
  366. #endregion
  367. #region Helper functions
  368. private static Assembly CurrentDomain_AssemblyResolve(
  369. object sender, ResolveEventArgs args)
  370. {
  371. return Assembly.GetExecutingAssembly().FullName == args.Name ?
  372. Assembly.GetExecutingAssembly() : null;
  373. }
  374. #endregion
  375. #region Start/Stop/Reset script
  376. /// <summary>
  377. /// Fetches, loads and hooks up a script to an objects events
  378. /// </summary>
  379. /// <param name="itemID"></param>
  380. /// <param name="localID"></param>
  381. public void StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez)
  382. {
  383. lock (LUQueue)
  384. {
  385. if ((LUQueue.Count >= LoadUnloadMaxQueueSize) && m_started)
  386. {
  387. m_log.Error("[" +
  388. m_scriptEngine.ScriptEngineName +
  389. "]: ERROR: Load/unload queue item count is at " +
  390. LUQueue.Count +
  391. ". Config variable \"LoadUnloadMaxQueueSize\" "+
  392. "is set to " + LoadUnloadMaxQueueSize +
  393. ", so ignoring new script.");
  394. return;
  395. }
  396. LUStruct ls = new LUStruct();
  397. ls.localID = localID;
  398. ls.itemID = itemID;
  399. ls.script = Script;
  400. ls.Action = LUType.Load;
  401. ls.startParam = startParam;
  402. ls.postOnRez = postOnRez;
  403. LUQueue.Enqueue(ls);
  404. }
  405. }
  406. /// <summary>
  407. /// Disables and unloads a script
  408. /// </summary>
  409. /// <param name="localID"></param>
  410. /// <param name="itemID"></param>
  411. public void StopScript(uint localID, UUID itemID)
  412. {
  413. LUStruct ls = new LUStruct();
  414. ls.localID = localID;
  415. ls.itemID = itemID;
  416. ls.Action = LUType.Unload;
  417. ls.startParam = 0;
  418. ls.postOnRez = false;
  419. lock (LUQueue)
  420. {
  421. LUQueue.Enqueue(ls);
  422. }
  423. }
  424. #endregion
  425. #region Perform event execution in script
  426. // Execute a LL-event-function in Script
  427. internal void ExecuteEvent(uint localID, UUID itemID,
  428. string FunctionName, DetectParams[] qParams, object[] args)
  429. {
  430. InstanceData id = GetScript(localID, itemID);
  431. if (id == null)
  432. return;
  433. detparms[id] = qParams;
  434. if (id.Running)
  435. id.Script.ExecuteEvent(id.State, FunctionName, args);
  436. detparms.Remove(id);
  437. }
  438. public uint GetLocalID(UUID itemID)
  439. {
  440. foreach (KeyValuePair<uint, Dictionary<UUID, InstanceData> > k
  441. in Scripts)
  442. {
  443. if (k.Value.ContainsKey(itemID))
  444. return k.Key;
  445. }
  446. return 0;
  447. }
  448. public int GetStateEventFlags(uint localID, UUID itemID)
  449. {
  450. try
  451. {
  452. InstanceData id = GetScript(localID, itemID);
  453. if (id == null)
  454. {
  455. return 0;
  456. }
  457. int evflags = id.Script.GetStateEventFlags(id.State);
  458. return (int)evflags;
  459. }
  460. catch (Exception)
  461. {
  462. }
  463. return 0;
  464. }
  465. #endregion
  466. #region Internal functions to keep track of script
  467. public List<UUID> GetScriptKeys(uint localID)
  468. {
  469. if (Scripts.ContainsKey(localID) == false)
  470. return new List<UUID>();
  471. Dictionary<UUID, InstanceData> Obj;
  472. Scripts.TryGetValue(localID, out Obj);
  473. return new List<UUID>(Obj.Keys);
  474. }
  475. public InstanceData GetScript(uint localID, UUID itemID)
  476. {
  477. lock (scriptLock)
  478. {
  479. InstanceData id = null;
  480. if (Scripts.ContainsKey(localID) == false)
  481. return null;
  482. Dictionary<UUID, InstanceData> Obj;
  483. Scripts.TryGetValue(localID, out Obj);
  484. if (Obj.ContainsKey(itemID) == false)
  485. return null;
  486. // Get script
  487. Obj.TryGetValue(itemID, out id);
  488. return id;
  489. }
  490. }
  491. public void SetScript(uint localID, UUID itemID, InstanceData id)
  492. {
  493. lock (scriptLock)
  494. {
  495. // Create object if it doesn't exist
  496. if (Scripts.ContainsKey(localID) == false)
  497. {
  498. Scripts.Add(localID, new Dictionary<UUID, InstanceData>());
  499. }
  500. // Delete script if it exists
  501. Dictionary<UUID, InstanceData> Obj;
  502. Scripts.TryGetValue(localID, out Obj);
  503. if (Obj.ContainsKey(itemID) == true)
  504. Obj.Remove(itemID);
  505. // Add to object
  506. Obj.Add(itemID, id);
  507. }
  508. }
  509. public void RemoveScript(uint localID, UUID itemID)
  510. {
  511. if (localID == 0)
  512. localID = GetLocalID(itemID);
  513. // Don't have that object?
  514. if (Scripts.ContainsKey(localID) == false)
  515. return;
  516. // Delete script if it exists
  517. Dictionary<UUID, InstanceData> Obj;
  518. Scripts.TryGetValue(localID, out Obj);
  519. if (Obj.ContainsKey(itemID) == true)
  520. Obj.Remove(itemID);
  521. }
  522. #endregion
  523. public void ResetScript(uint localID, UUID itemID)
  524. {
  525. InstanceData id = GetScript(localID, itemID);
  526. string script = id.Source;
  527. StopScript(localID, itemID);
  528. SceneObjectPart part = World.GetSceneObjectPart(localID);
  529. part.Inventory.GetInventoryItem(itemID).PermsMask = 0;
  530. part.Inventory.GetInventoryItem(itemID).PermsGranter = UUID.Zero;
  531. StartScript(localID, itemID, script, id.StartParam, false);
  532. }
  533. #region Script serialization/deserialization
  534. public void GetSerializedScript(uint localID, UUID itemID)
  535. {
  536. // Serialize the script and return it
  537. // Should not be a problem
  538. FileStream fs = File.Create("SERIALIZED_SCRIPT_" + itemID);
  539. BinaryFormatter b = new BinaryFormatter();
  540. b.Serialize(fs, GetScript(localID, itemID));
  541. fs.Close();
  542. }
  543. public void PutSerializedScript(uint localID, UUID itemID)
  544. {
  545. // Deserialize the script and inject it into an AppDomain
  546. // How to inject into an AppDomain?
  547. }
  548. #endregion
  549. public DetectParams[] GetDetectParams(InstanceData id)
  550. {
  551. if (detparms.ContainsKey(id))
  552. return detparms[id];
  553. return null;
  554. }
  555. public int GetStartParameter(UUID itemID)
  556. {
  557. uint localID = GetLocalID(itemID);
  558. InstanceData id = GetScript(localID, itemID);
  559. if (id == null)
  560. return 0;
  561. return id.StartParam;
  562. }
  563. public IScriptApi GetApi(UUID itemID, string name)
  564. {
  565. uint localID = GetLocalID(itemID);
  566. InstanceData id = GetScript(localID, itemID);
  567. if (id == null)
  568. return null;
  569. if (id.Apis.ContainsKey(name))
  570. return id.Apis[name];
  571. return null;
  572. }
  573. }
  574. }