ScriptManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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.Environment.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. }
  187. catch (Exception e) // LEGIT: User Scripting
  188. {
  189. if (presence != null && (!postOnRez))
  190. presence.ControllingClient.SendAgentAlertMessage(
  191. "Script saved with errors, check debug window!",
  192. false);
  193. try
  194. {
  195. // DISPLAY ERROR INWORLD
  196. string text = "Error compiling script:\n" +
  197. e.Message.ToString();
  198. if (text.Length > 1100)
  199. text = text.Substring(0, 1099);
  200. World.SimChat(Utils.StringToBytes(text),
  201. ChatTypeEnum.DebugChannel, 2147483647,
  202. m_host.AbsolutePosition, m_host.Name, m_host.UUID,
  203. false);
  204. }
  205. catch (Exception e2) // LEGIT: User Scripting
  206. {
  207. m_scriptEngine.Log.Error("[" +
  208. m_scriptEngine.ScriptEngineName +
  209. "]: Error displaying error in-world: " +
  210. e2.ToString());
  211. m_scriptEngine.Log.Error("[" +
  212. m_scriptEngine.ScriptEngineName + "]: " +
  213. "Errormessage: Error compiling script:\r\n" +
  214. e2.Message.ToString());
  215. }
  216. }
  217. }
  218. public void _StopScript(uint localID, UUID itemID)
  219. {
  220. InstanceData id = GetScript(localID, itemID);
  221. if (id == null)
  222. return;
  223. m_scriptEngine.Log.DebugFormat("[{0}]: Unloading script",
  224. m_scriptEngine.ScriptEngineName);
  225. // Stop long command on script
  226. AsyncCommandManager.RemoveScript(m_scriptEngine, localID, itemID);
  227. try
  228. {
  229. // Get AppDomain
  230. // Tell script not to accept new requests
  231. id.Running = false;
  232. id.Disabled = true;
  233. AppDomain ad = id.AppDomain;
  234. // Remove from internal structure
  235. RemoveScript(localID, itemID);
  236. // Tell AppDomain that we have stopped script
  237. m_scriptEngine.m_AppDomainManager.StopScript(ad);
  238. }
  239. catch (Exception e) // LEGIT: User Scripting
  240. {
  241. m_scriptEngine.Log.Error("[" +
  242. m_scriptEngine.ScriptEngineName +
  243. "]: Exception stopping script localID: " +
  244. localID + " LLUID: " + itemID.ToString() +
  245. ": " + e.ToString());
  246. }
  247. }
  248. public void ReadConfig()
  249. {
  250. // TODO: Requires sharing of all ScriptManagers to single thread
  251. PrivateThread = true;
  252. LoadUnloadMaxQueueSize = m_scriptEngine.ScriptConfigSource.GetInt(
  253. "LoadUnloadMaxQueueSize", 100);
  254. }
  255. #region Object init/shutdown
  256. public ScriptEngine m_scriptEngine;
  257. public ScriptManager(ScriptEngine scriptEngine)
  258. {
  259. m_scriptEngine = scriptEngine;
  260. }
  261. public void Setup()
  262. {
  263. ReadConfig();
  264. Initialize();
  265. }
  266. public void Start()
  267. {
  268. m_started = true;
  269. AppDomain.CurrentDomain.AssemblyResolve +=
  270. new ResolveEventHandler(CurrentDomain_AssemblyResolve);
  271. //
  272. // CREATE THREAD
  273. // Private or shared
  274. //
  275. if (PrivateThread)
  276. {
  277. // Assign one thread per region
  278. //scriptLoadUnloadThread = StartScriptLoadUnloadThread();
  279. }
  280. else
  281. {
  282. // Shared thread - make sure one exist, then assign it to the private
  283. if (staticScriptLoadUnloadThread == null)
  284. {
  285. //staticScriptLoadUnloadThread =
  286. // StartScriptLoadUnloadThread();
  287. }
  288. scriptLoadUnloadThread = staticScriptLoadUnloadThread;
  289. }
  290. }
  291. ~ScriptManager()
  292. {
  293. // Abort load/unload thread
  294. try
  295. {
  296. if (scriptLoadUnloadThread != null &&
  297. scriptLoadUnloadThread.IsAlive == true)
  298. {
  299. scriptLoadUnloadThread.Abort();
  300. //scriptLoadUnloadThread.Join();
  301. }
  302. }
  303. catch
  304. {
  305. }
  306. }
  307. #endregion
  308. #region Load / Unload scripts (Thread loop)
  309. public void DoScriptLoadUnload()
  310. {
  311. if (!m_started)
  312. return;
  313. lock (LUQueue)
  314. {
  315. if (LUQueue.Count > 0)
  316. {
  317. LUStruct item = LUQueue.Dequeue();
  318. if (item.Action == LUType.Unload)
  319. {
  320. _StopScript(item.localID, item.itemID);
  321. RemoveScript(item.localID, item.itemID);
  322. }
  323. else if (item.Action == LUType.Load)
  324. {
  325. m_scriptEngine.Log.DebugFormat("[{0}]: Loading script",
  326. m_scriptEngine.ScriptEngineName);
  327. _StartScript(item.localID, item.itemID, item.script,
  328. item.startParam, item.postOnRez);
  329. }
  330. }
  331. }
  332. }
  333. #endregion
  334. #region Helper functions
  335. private static Assembly CurrentDomain_AssemblyResolve(
  336. object sender, ResolveEventArgs args)
  337. {
  338. return Assembly.GetExecutingAssembly().FullName == args.Name ?
  339. Assembly.GetExecutingAssembly() : null;
  340. }
  341. #endregion
  342. #region Start/Stop/Reset script
  343. /// <summary>
  344. /// Fetches, loads and hooks up a script to an objects events
  345. /// </summary>
  346. /// <param name="itemID"></param>
  347. /// <param name="localID"></param>
  348. public void StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez)
  349. {
  350. lock (LUQueue)
  351. {
  352. if ((LUQueue.Count >= LoadUnloadMaxQueueSize) && m_started)
  353. {
  354. m_scriptEngine.Log.Error("[" +
  355. m_scriptEngine.ScriptEngineName +
  356. "]: ERROR: Load/unload queue item count is at " +
  357. LUQueue.Count +
  358. ". Config variable \"LoadUnloadMaxQueueSize\" "+
  359. "is set to " + LoadUnloadMaxQueueSize +
  360. ", so ignoring new script.");
  361. return;
  362. }
  363. LUStruct ls = new LUStruct();
  364. ls.localID = localID;
  365. ls.itemID = itemID;
  366. ls.script = Script;
  367. ls.Action = LUType.Load;
  368. ls.startParam = startParam;
  369. ls.postOnRez = postOnRez;
  370. LUQueue.Enqueue(ls);
  371. }
  372. }
  373. /// <summary>
  374. /// Disables and unloads a script
  375. /// </summary>
  376. /// <param name="localID"></param>
  377. /// <param name="itemID"></param>
  378. public void StopScript(uint localID, UUID itemID)
  379. {
  380. LUStruct ls = new LUStruct();
  381. ls.localID = localID;
  382. ls.itemID = itemID;
  383. ls.Action = LUType.Unload;
  384. ls.startParam = 0;
  385. ls.postOnRez = false;
  386. lock (LUQueue)
  387. {
  388. LUQueue.Enqueue(ls);
  389. }
  390. }
  391. #endregion
  392. #region Perform event execution in script
  393. // Execute a LL-event-function in Script
  394. internal void ExecuteEvent(uint localID, UUID itemID,
  395. string FunctionName, DetectParams[] qParams, object[] args)
  396. {
  397. InstanceData id = GetScript(localID, itemID);
  398. if (id == null)
  399. return;
  400. detparms[id] = qParams;
  401. if (id.Running)
  402. id.Script.ExecuteEvent(id.State, FunctionName, args);
  403. detparms.Remove(id);
  404. }
  405. public uint GetLocalID(UUID itemID)
  406. {
  407. foreach (KeyValuePair<uint, Dictionary<UUID, InstanceData> > k
  408. in Scripts)
  409. {
  410. if (k.Value.ContainsKey(itemID))
  411. return k.Key;
  412. }
  413. return 0;
  414. }
  415. public int GetStateEventFlags(uint localID, UUID itemID)
  416. {
  417. try
  418. {
  419. InstanceData id = GetScript(localID, itemID);
  420. if (id == null)
  421. {
  422. return 0;
  423. }
  424. int evflags = id.Script.GetStateEventFlags(id.State);
  425. return (int)evflags;
  426. }
  427. catch (Exception)
  428. {
  429. }
  430. return 0;
  431. }
  432. #endregion
  433. #region Internal functions to keep track of script
  434. public List<UUID> GetScriptKeys(uint localID)
  435. {
  436. if (Scripts.ContainsKey(localID) == false)
  437. return new List<UUID>();
  438. Dictionary<UUID, InstanceData> Obj;
  439. Scripts.TryGetValue(localID, out Obj);
  440. return new List<UUID>(Obj.Keys);
  441. }
  442. public InstanceData GetScript(uint localID, UUID itemID)
  443. {
  444. lock (scriptLock)
  445. {
  446. InstanceData id = null;
  447. if (Scripts.ContainsKey(localID) == false)
  448. return null;
  449. Dictionary<UUID, InstanceData> Obj;
  450. Scripts.TryGetValue(localID, out Obj);
  451. if (Obj.ContainsKey(itemID) == false)
  452. return null;
  453. // Get script
  454. Obj.TryGetValue(itemID, out id);
  455. return id;
  456. }
  457. }
  458. public void SetScript(uint localID, UUID itemID, InstanceData id)
  459. {
  460. lock (scriptLock)
  461. {
  462. // Create object if it doesn't exist
  463. if (Scripts.ContainsKey(localID) == false)
  464. {
  465. Scripts.Add(localID, new Dictionary<UUID, InstanceData>());
  466. }
  467. // Delete script if it exists
  468. Dictionary<UUID, InstanceData> Obj;
  469. Scripts.TryGetValue(localID, out Obj);
  470. if (Obj.ContainsKey(itemID) == true)
  471. Obj.Remove(itemID);
  472. // Add to object
  473. Obj.Add(itemID, id);
  474. }
  475. }
  476. public void RemoveScript(uint localID, UUID itemID)
  477. {
  478. if (localID == 0)
  479. localID = GetLocalID(itemID);
  480. // Don't have that object?
  481. if (Scripts.ContainsKey(localID) == false)
  482. return;
  483. // Delete script if it exists
  484. Dictionary<UUID, InstanceData> Obj;
  485. Scripts.TryGetValue(localID, out Obj);
  486. if (Obj.ContainsKey(itemID) == true)
  487. Obj.Remove(itemID);
  488. }
  489. #endregion
  490. public void ResetScript(uint localID, UUID itemID)
  491. {
  492. InstanceData id = GetScript(localID, itemID);
  493. string script = id.Source;
  494. StopScript(localID, itemID);
  495. SceneObjectPart part = World.GetSceneObjectPart(localID);
  496. part.Inventory.GetInventoryItem(itemID).PermsMask = 0;
  497. part.Inventory.GetInventoryItem(itemID).PermsGranter = UUID.Zero;
  498. StartScript(localID, itemID, script, id.StartParam, false);
  499. }
  500. #region Script serialization/deserialization
  501. public void GetSerializedScript(uint localID, UUID itemID)
  502. {
  503. // Serialize the script and return it
  504. // Should not be a problem
  505. FileStream fs = File.Create("SERIALIZED_SCRIPT_" + itemID);
  506. BinaryFormatter b = new BinaryFormatter();
  507. b.Serialize(fs, GetScript(localID, itemID));
  508. fs.Close();
  509. }
  510. public void PutSerializedScript(uint localID, UUID itemID)
  511. {
  512. // Deserialize the script and inject it into an AppDomain
  513. // How to inject into an AppDomain?
  514. }
  515. #endregion
  516. public DetectParams[] GetDetectParams(InstanceData id)
  517. {
  518. if (detparms.ContainsKey(id))
  519. return detparms[id];
  520. return null;
  521. }
  522. public int GetStartParameter(UUID itemID)
  523. {
  524. uint localID = GetLocalID(itemID);
  525. InstanceData id = GetScript(localID, itemID);
  526. if (id == null)
  527. return 0;
  528. return id.StartParam;
  529. }
  530. public IScriptApi GetApi(UUID itemID, string name)
  531. {
  532. uint localID = GetLocalID(itemID);
  533. InstanceData id = GetScript(localID, itemID);
  534. if (id == null)
  535. return null;
  536. if (id.Apis.ContainsKey(name))
  537. return id.Apis[name];
  538. return null;
  539. }
  540. }
  541. }