1
0

XEngine.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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.IO;
  29. using System.Threading;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Security;
  33. using System.Security.Policy;
  34. using System.Reflection;
  35. using System.Globalization;
  36. using System.Xml;
  37. using OpenMetaverse;
  38. using OpenMetaverse.StructuredData;
  39. using log4net;
  40. using Nini.Config;
  41. using Amib.Threading;
  42. using OpenSim.Framework;
  43. using OpenSim.Region.CoreModules.Framework.EventQueue;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.ScriptEngine.Shared;
  47. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  48. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  49. using OpenSim.Region.ScriptEngine.Shared.Instance;
  50. using OpenSim.Region.ScriptEngine.Interfaces;
  51. namespace OpenSim.Region.ScriptEngine.XEngine
  52. {
  53. public class XEngine : INonSharedRegionModule, IScriptModule, IScriptEngine
  54. {
  55. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  56. private SmartThreadPool m_ThreadPool;
  57. private int m_MaxScriptQueue;
  58. private Scene m_Scene;
  59. private IConfig m_ScriptConfig = null;
  60. private IConfigSource m_ConfigSource = null;
  61. private ICompiler m_Compiler;
  62. private int m_MinThreads;
  63. private int m_MaxThreads ;
  64. private int m_IdleTimeout;
  65. private int m_StackSize;
  66. private int m_SleepTime;
  67. private int m_SaveTime;
  68. private ThreadPriority m_Prio;
  69. private bool m_Enabled = false;
  70. private bool m_InitialStartup = true;
  71. private int m_ScriptFailCount; // Number of script fails since compile queue was last empty
  72. private string m_ScriptErrorMessage;
  73. // disable warning: need to keep a reference to XEngine.EventManager
  74. // alive to avoid it being garbage collected
  75. #pragma warning disable 414
  76. private EventManager m_EventManager;
  77. #pragma warning restore 414
  78. private IXmlRpcRouter m_XmlRpcRouter;
  79. private int m_EventLimit;
  80. private bool m_KillTimedOutScripts;
  81. private static List<XEngine> m_ScriptEngines =
  82. new List<XEngine>();
  83. // Maps the local id to the script inventory items in it
  84. private Dictionary<uint, List<UUID> > m_PrimObjects =
  85. new Dictionary<uint, List<UUID> >();
  86. // Maps the UUID above to the script instance
  87. private Dictionary<UUID, IScriptInstance> m_Scripts =
  88. new Dictionary<UUID, IScriptInstance>();
  89. // Maps the asset ID to the assembly
  90. private Dictionary<UUID, string> m_Assemblies =
  91. new Dictionary<UUID, string>();
  92. private Dictionary<string, int> m_AddingAssemblies =
  93. new Dictionary<string, int>();
  94. // This will list AppDomains by script asset
  95. private Dictionary<UUID, AppDomain> m_AppDomains =
  96. new Dictionary<UUID, AppDomain>();
  97. // List the scripts running in each appdomain
  98. private Dictionary<UUID, List<UUID> > m_DomainScripts =
  99. new Dictionary<UUID, List<UUID> >();
  100. private Queue m_CompileQueue = new Queue(100);
  101. IWorkItemResult m_CurrentCompile = null;
  102. public string ScriptEngineName
  103. {
  104. get { return "XEngine"; }
  105. }
  106. public Scene World
  107. {
  108. get { return m_Scene; }
  109. }
  110. public static List<XEngine> ScriptEngines
  111. {
  112. get { return m_ScriptEngines; }
  113. }
  114. public IScriptModule ScriptModule
  115. {
  116. get { return this; }
  117. }
  118. // private struct RezScriptParms
  119. // {
  120. // uint LocalID;
  121. // UUID ItemID;
  122. // string Script;
  123. // }
  124. public IConfig Config
  125. {
  126. get { return m_ScriptConfig; }
  127. }
  128. public IConfigSource ConfigSource
  129. {
  130. get { return m_ConfigSource; }
  131. }
  132. public event ScriptRemoved OnScriptRemoved;
  133. public event ObjectRemoved OnObjectRemoved;
  134. //
  135. // IRegionModule functions
  136. //
  137. public void Initialise(IConfigSource configSource)
  138. {
  139. if (configSource.Configs["XEngine"] == null)
  140. return;
  141. m_ScriptConfig = configSource.Configs["XEngine"];
  142. m_ConfigSource = configSource;
  143. }
  144. public void AddRegion(Scene scene)
  145. {
  146. if (m_ScriptConfig == null)
  147. return;
  148. m_ScriptFailCount = 0;
  149. m_ScriptErrorMessage = String.Empty;
  150. if (m_ScriptConfig == null)
  151. {
  152. // m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
  153. return;
  154. }
  155. m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
  156. if (!m_Enabled)
  157. return;
  158. AppDomain.CurrentDomain.AssemblyResolve +=
  159. OnAssemblyResolve;
  160. m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
  161. scene.RegionInfo.RegionName);
  162. m_Scene = scene;
  163. m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
  164. m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
  165. m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
  166. string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
  167. m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
  168. m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
  169. m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
  170. m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
  171. m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
  172. m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
  173. m_Prio = ThreadPriority.BelowNormal;
  174. switch (priority)
  175. {
  176. case "Lowest":
  177. m_Prio = ThreadPriority.Lowest;
  178. break;
  179. case "BelowNormal":
  180. m_Prio = ThreadPriority.BelowNormal;
  181. break;
  182. case "Normal":
  183. m_Prio = ThreadPriority.Normal;
  184. break;
  185. case "AboveNormal":
  186. m_Prio = ThreadPriority.AboveNormal;
  187. break;
  188. case "Highest":
  189. m_Prio = ThreadPriority.Highest;
  190. break;
  191. default:
  192. m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
  193. break;
  194. }
  195. lock (m_ScriptEngines)
  196. {
  197. m_ScriptEngines.Add(this);
  198. }
  199. // Needs to be here so we can queue the scripts that need starting
  200. //
  201. m_Scene.EventManager.OnRezScript += OnRezScript;
  202. // Complete basic setup of the thread pool
  203. //
  204. SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
  205. m_MaxScriptQueue, m_StackSize);
  206. m_Scene.StackModuleInterface<IScriptModule>(this);
  207. m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
  208. if (m_XmlRpcRouter != null)
  209. {
  210. OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
  211. OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
  212. }
  213. }
  214. public void RemoveRegion(Scene scene)
  215. {
  216. lock (m_Scripts)
  217. {
  218. foreach (IScriptInstance instance in m_Scripts.Values)
  219. {
  220. // Force a final state save
  221. //
  222. if (m_Assemblies.ContainsKey(instance.AssetID))
  223. {
  224. string assembly = m_Assemblies[instance.AssetID];
  225. instance.SaveState(assembly);
  226. }
  227. // Clear the event queue and abort the instance thread
  228. //
  229. instance.ClearQueue();
  230. instance.Stop(0);
  231. // Release events, timer, etc
  232. //
  233. instance.DestroyScriptInstance();
  234. // Unload scripts and app domains
  235. // Must be done explicitly because they have infinite
  236. // lifetime
  237. //
  238. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  239. if (m_DomainScripts[instance.AppDomain].Count == 0)
  240. {
  241. m_DomainScripts.Remove(instance.AppDomain);
  242. UnloadAppDomain(instance.AppDomain);
  243. }
  244. }
  245. m_Scripts.Clear();
  246. m_PrimObjects.Clear();
  247. m_Assemblies.Clear();
  248. m_DomainScripts.Clear();
  249. }
  250. lock (m_ScriptEngines)
  251. {
  252. m_ScriptEngines.Remove(this);
  253. }
  254. }
  255. public void RegionLoaded(Scene scene)
  256. {
  257. if (!m_Enabled)
  258. return;
  259. m_EventManager = new EventManager(this);
  260. m_Compiler = new Compiler(this);
  261. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  262. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  263. m_Scene.EventManager.OnStartScript += OnStartScript;
  264. m_Scene.EventManager.OnStopScript += OnStopScript;
  265. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  266. m_Scene.EventManager.OnShutdown += OnShutdown;
  267. if (m_SleepTime > 0)
  268. {
  269. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  270. new Object[]{ m_SleepTime });
  271. }
  272. if (m_SaveTime > 0)
  273. {
  274. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  275. new Object[] { m_SaveTime });
  276. }
  277. m_ThreadPool.Start();
  278. }
  279. public void Close()
  280. {
  281. lock (m_ScriptEngines)
  282. {
  283. if (m_ScriptEngines.Contains(this))
  284. m_ScriptEngines.Remove(this);
  285. }
  286. }
  287. public object DoBackup(object o)
  288. {
  289. Object[] p = (Object[])o;
  290. int saveTime = (int)p[0];
  291. if (saveTime > 0)
  292. System.Threading.Thread.Sleep(saveTime);
  293. // m_log.Debug("[XEngine] Backing up script states");
  294. List<IScriptInstance> instances = new List<IScriptInstance>();
  295. lock (m_Scripts)
  296. {
  297. foreach (IScriptInstance instance in m_Scripts.Values)
  298. instances.Add(instance);
  299. }
  300. foreach (IScriptInstance i in instances)
  301. {
  302. string assembly = String.Empty;
  303. lock (m_Scripts)
  304. {
  305. if (!m_Assemblies.ContainsKey(i.AssetID))
  306. continue;
  307. assembly = m_Assemblies[i.AssetID];
  308. }
  309. i.SaveState(assembly);
  310. }
  311. instances.Clear();
  312. if (saveTime > 0)
  313. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  314. new Object[] { saveTime });
  315. return 0;
  316. }
  317. public object DoMaintenance(object p)
  318. {
  319. object[] parms = (object[])p;
  320. int sleepTime = (int)parms[0];
  321. foreach (IScriptInstance inst in m_Scripts.Values)
  322. {
  323. if (inst.EventTime() > m_EventLimit)
  324. {
  325. inst.Stop(100);
  326. if (!m_KillTimedOutScripts)
  327. inst.Start();
  328. }
  329. }
  330. System.Threading.Thread.Sleep(sleepTime);
  331. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  332. new Object[]{ sleepTime });
  333. return 0;
  334. }
  335. public Type ReplaceableInterface
  336. {
  337. get { return null; }
  338. }
  339. public string Name
  340. {
  341. get { return "XEngine"; }
  342. }
  343. public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  344. {
  345. if (script.StartsWith("//MRM:"))
  346. return;
  347. List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
  348. List<string> names = new List<string>();
  349. foreach (IScriptModule m in engines)
  350. names.Add(m.ScriptEngineName);
  351. int lineEnd = script.IndexOf('\n');
  352. if (lineEnd > 1)
  353. {
  354. string firstline = script.Substring(0, lineEnd).Trim();
  355. int colon = firstline.IndexOf(':');
  356. if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
  357. {
  358. string engineName = firstline.Substring(2, colon-2);
  359. if (names.Contains(engineName))
  360. {
  361. engine = engineName;
  362. script = "//" + script.Substring(script.IndexOf(':')+1);
  363. }
  364. else
  365. {
  366. if (engine == ScriptEngineName)
  367. {
  368. SceneObjectPart part =
  369. m_Scene.GetSceneObjectPart(
  370. localID);
  371. TaskInventoryItem item =
  372. part.Inventory.GetInventoryItem(itemID);
  373. ScenePresence presence =
  374. m_Scene.GetScenePresence(
  375. item.OwnerID);
  376. if (presence != null)
  377. {
  378. presence.ControllingClient.SendAgentAlertMessage(
  379. "Selected engine unavailable. "+
  380. "Running script on "+
  381. ScriptEngineName,
  382. false);
  383. }
  384. }
  385. }
  386. }
  387. }
  388. if (engine != ScriptEngineName)
  389. return;
  390. Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
  391. if (stateSource == (int)StateSource.ScriptedRez)
  392. {
  393. DoOnRezScript(parms);
  394. }
  395. else
  396. {
  397. lock (m_CompileQueue)
  398. {
  399. m_CompileQueue.Enqueue(parms);
  400. if (m_CurrentCompile == null)
  401. {
  402. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  403. new WorkItemCallback(this.DoOnRezScriptQueue),
  404. new Object[0]);
  405. }
  406. }
  407. }
  408. }
  409. public Object DoOnRezScriptQueue(Object dummy)
  410. {
  411. if (m_InitialStartup)
  412. {
  413. m_InitialStartup = false;
  414. System.Threading.Thread.Sleep(15000);
  415. lock (m_CompileQueue)
  416. {
  417. if (m_CompileQueue.Count==0)
  418. // No scripts on region, so won't get triggered later
  419. // by the queue becoming empty so we trigger it here
  420. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
  421. }
  422. }
  423. Object o;
  424. lock (m_CompileQueue)
  425. {
  426. o = m_CompileQueue.Dequeue();
  427. if (o == null)
  428. {
  429. m_CurrentCompile = null;
  430. return null;
  431. }
  432. }
  433. DoOnRezScript(o);
  434. lock (m_CompileQueue)
  435. {
  436. if (m_CompileQueue.Count > 0)
  437. {
  438. m_CurrentCompile = m_ThreadPool.QueueWorkItem(
  439. new WorkItemCallback(this.DoOnRezScriptQueue),
  440. new Object[0]);
  441. }
  442. else
  443. {
  444. m_CurrentCompile = null;
  445. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
  446. m_ScriptErrorMessage);
  447. m_ScriptFailCount = 0;
  448. }
  449. }
  450. return null;
  451. }
  452. private bool DoOnRezScript(object parm)
  453. {
  454. Object[] p = (Object[])parm;
  455. uint localID = (uint)p[0];
  456. UUID itemID = (UUID)p[1];
  457. string script =(string)p[2];
  458. int startParam = (int)p[3];
  459. bool postOnRez = (bool)p[4];
  460. StateSource stateSource = (StateSource)p[5];
  461. // Get the asset ID of the script, so we can check if we
  462. // already have it.
  463. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
  464. // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
  465. // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
  466. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  467. if (part == null)
  468. {
  469. m_log.Error("[Script] SceneObjectPart unavailable. Script NOT started.");
  470. m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
  471. m_ScriptFailCount++;
  472. return false;
  473. }
  474. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  475. if (item == null)
  476. {
  477. m_ScriptErrorMessage += "Can't find script inventory item.\n";
  478. m_ScriptFailCount++;
  479. return false;
  480. }
  481. UUID assetID = item.AssetID;
  482. //m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})",
  483. // item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name);
  484. ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
  485. string assembly = "";
  486. CultureInfo USCulture = new CultureInfo("en-US");
  487. Thread.CurrentThread.CurrentCulture = USCulture;
  488. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  489. try
  490. {
  491. lock (m_AddingAssemblies)
  492. {
  493. assembly = (string)m_Compiler.PerformScriptCompile(script,
  494. assetID.ToString(), item.OwnerID);
  495. if (!m_AddingAssemblies.ContainsKey(assembly)) {
  496. m_AddingAssemblies[assembly] = 1;
  497. } else {
  498. m_AddingAssemblies[assembly]++;
  499. }
  500. linemap = m_Compiler.LineMap();
  501. }
  502. string[] warnings = m_Compiler.GetWarnings();
  503. if (warnings != null && warnings.Length != 0)
  504. {
  505. foreach (string warning in warnings)
  506. {
  507. try
  508. {
  509. // DISPLAY WARNING INWORLD
  510. string text = "Warning:\n" + warning;
  511. if (text.Length > 1000)
  512. text = text.Substring(0, 1000);
  513. if (!ShowScriptSaveResponse(item.OwnerID,
  514. assetID, text, true))
  515. {
  516. if (presence != null && (!postOnRez))
  517. presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
  518. World.SimChat(Utils.StringToBytes(text),
  519. ChatTypeEnum.DebugChannel, 2147483647,
  520. part.AbsolutePosition,
  521. part.Name, part.UUID, false);
  522. }
  523. }
  524. catch (Exception e2) // LEGIT: User Scripting
  525. {
  526. m_log.Error("[XEngine]: " +
  527. "Error displaying warning in-world: " +
  528. e2.ToString());
  529. m_log.Error("[XEngine]: " +
  530. "Warning:\r\n" +
  531. warning);
  532. }
  533. }
  534. }
  535. }
  536. catch (Exception e)
  537. {
  538. try
  539. {
  540. // DISPLAY ERROR INWORLD
  541. m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
  542. m_ScriptFailCount++;
  543. string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
  544. if (text.Length > 1000)
  545. text = text.Substring(0, 1000);
  546. if (!ShowScriptSaveResponse(item.OwnerID,
  547. assetID, text, false))
  548. {
  549. if (presence != null && (!postOnRez))
  550. presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
  551. World.SimChat(Utils.StringToBytes(text),
  552. ChatTypeEnum.DebugChannel, 2147483647,
  553. part.AbsolutePosition,
  554. part.Name, part.UUID, false);
  555. }
  556. }
  557. catch (Exception e2) // LEGIT: User Scripting
  558. {
  559. m_log.Error("[XEngine]: "+
  560. "Error displaying error in-world: " +
  561. e2.ToString());
  562. m_log.Error("[XEngine]: " +
  563. "Errormessage: Error compiling script:\r\n" +
  564. e.Message.ToString());
  565. }
  566. return false;
  567. }
  568. lock (m_Scripts)
  569. {
  570. ScriptInstance instance = null;
  571. // Create the object record
  572. if ((!m_Scripts.ContainsKey(itemID)) ||
  573. (m_Scripts[itemID].AssetID != assetID))
  574. {
  575. UUID appDomain = assetID;
  576. if (part.ParentGroup.IsAttachment)
  577. appDomain = part.ParentGroup.RootPart.UUID;
  578. if (!m_AppDomains.ContainsKey(appDomain))
  579. {
  580. try
  581. {
  582. AppDomainSetup appSetup = new AppDomainSetup();
  583. // appSetup.ApplicationBase = Path.Combine(
  584. // "ScriptEngines",
  585. // m_Scene.RegionInfo.RegionID.ToString());
  586. Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
  587. Evidence evidence = new Evidence(baseEvidence);
  588. AppDomain sandbox =
  589. AppDomain.CreateDomain(
  590. m_Scene.RegionInfo.RegionID.ToString(),
  591. evidence, appSetup);
  592. /*
  593. PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
  594. AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
  595. PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
  596. PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
  597. CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
  598. sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
  599. sandbox.SetAppDomainPolicy(sandboxPolicy);
  600. */
  601. m_AppDomains[appDomain] = sandbox;
  602. m_AppDomains[appDomain].AssemblyResolve +=
  603. new ResolveEventHandler(
  604. AssemblyResolver.OnAssemblyResolve);
  605. m_DomainScripts[appDomain] = new List<UUID>();
  606. }
  607. catch (Exception e)
  608. {
  609. m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
  610. m_ScriptErrorMessage += "Exception creating app domain:\n";
  611. m_ScriptFailCount++;
  612. lock (m_AddingAssemblies)
  613. {
  614. m_AddingAssemblies[assembly]--;
  615. }
  616. return false;
  617. }
  618. }
  619. m_DomainScripts[appDomain].Add(itemID);
  620. instance = new ScriptInstance(this, part,
  621. itemID, assetID, assembly,
  622. m_AppDomains[appDomain],
  623. part.ParentGroup.RootPart.Name,
  624. item.Name, startParam, postOnRez,
  625. stateSource, m_MaxScriptQueue);
  626. m_log.DebugFormat("[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}",
  627. part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID, part.ParentGroup.RootPart.AbsolutePosition.ToString());
  628. if (presence != null)
  629. {
  630. ShowScriptSaveResponse(item.OwnerID,
  631. assetID, "Compile successful", true);
  632. }
  633. instance.AppDomain = appDomain;
  634. instance.LineMap = linemap;
  635. m_Scripts[itemID] = instance;
  636. }
  637. lock (m_PrimObjects)
  638. {
  639. if (!m_PrimObjects.ContainsKey(localID))
  640. m_PrimObjects[localID] = new List<UUID>();
  641. if (!m_PrimObjects[localID].Contains(itemID))
  642. m_PrimObjects[localID].Add(itemID);
  643. }
  644. if (!m_Assemblies.ContainsKey(assetID))
  645. m_Assemblies[assetID] = assembly;
  646. lock (m_AddingAssemblies)
  647. {
  648. m_AddingAssemblies[assembly]--;
  649. }
  650. if (instance!=null)
  651. instance.Init();
  652. }
  653. return true;
  654. }
  655. public void OnRemoveScript(uint localID, UUID itemID)
  656. {
  657. lock (m_Scripts)
  658. {
  659. // Do we even have it?
  660. if (!m_Scripts.ContainsKey(itemID))
  661. return;
  662. IScriptInstance instance=m_Scripts[itemID];
  663. m_Scripts.Remove(itemID);
  664. instance.ClearQueue();
  665. instance.Stop(0);
  666. SceneObjectPart part =
  667. m_Scene.GetSceneObjectPart(localID);
  668. if (part != null)
  669. part.RemoveScriptEvents(itemID);
  670. // bool objectRemoved = false;
  671. lock (m_PrimObjects)
  672. {
  673. // Remove the script from it's prim
  674. if (m_PrimObjects.ContainsKey(localID))
  675. {
  676. // Remove inventory item record
  677. if (m_PrimObjects[localID].Contains(itemID))
  678. m_PrimObjects[localID].Remove(itemID);
  679. // If there are no more scripts, remove prim
  680. if (m_PrimObjects[localID].Count == 0)
  681. {
  682. m_PrimObjects.Remove(localID);
  683. // objectRemoved = true;
  684. }
  685. }
  686. }
  687. instance.RemoveState();
  688. instance.DestroyScriptInstance();
  689. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  690. if (m_DomainScripts[instance.AppDomain].Count == 0)
  691. {
  692. m_DomainScripts.Remove(instance.AppDomain);
  693. UnloadAppDomain(instance.AppDomain);
  694. }
  695. instance = null;
  696. ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
  697. if (handlerObjectRemoved != null)
  698. handlerObjectRemoved(part.UUID);
  699. CleanAssemblies();
  700. }
  701. ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
  702. if (handlerScriptRemoved != null)
  703. handlerScriptRemoved(itemID);
  704. }
  705. public void OnScriptReset(uint localID, UUID itemID)
  706. {
  707. ResetScript(itemID);
  708. }
  709. public void OnStartScript(uint localID, UUID itemID)
  710. {
  711. StartScript(itemID);
  712. }
  713. public void OnStopScript(uint localID, UUID itemID)
  714. {
  715. StopScript(itemID);
  716. }
  717. private void CleanAssemblies()
  718. {
  719. List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
  720. foreach (IScriptInstance i in m_Scripts.Values)
  721. {
  722. if (assetIDList.Contains(i.AssetID))
  723. assetIDList.Remove(i.AssetID);
  724. }
  725. lock (m_AddingAssemblies)
  726. {
  727. foreach (UUID assetID in assetIDList)
  728. {
  729. // Do not remove assembly files if another instance of the script
  730. // is currently initialising
  731. if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
  732. || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
  733. {
  734. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  735. try
  736. {
  737. if (File.Exists(m_Assemblies[assetID]))
  738. File.Delete(m_Assemblies[assetID]);
  739. if (File.Exists(m_Assemblies[assetID]+".text"))
  740. File.Delete(m_Assemblies[assetID]+".text");
  741. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  742. File.Delete(m_Assemblies[assetID]+".mdb");
  743. if (File.Exists(m_Assemblies[assetID]+".map"))
  744. File.Delete(m_Assemblies[assetID]+".map");
  745. }
  746. catch (Exception)
  747. {
  748. }
  749. m_Assemblies.Remove(assetID);
  750. }
  751. }
  752. }
  753. }
  754. private void UnloadAppDomain(UUID id)
  755. {
  756. if (m_AppDomains.ContainsKey(id))
  757. {
  758. AppDomain domain = m_AppDomains[id];
  759. m_AppDomains.Remove(id);
  760. AppDomain.Unload(domain);
  761. domain = null;
  762. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  763. }
  764. }
  765. //
  766. // Start processing
  767. //
  768. private void SetupEngine(int minThreads, int maxThreads,
  769. int idleTimeout, ThreadPriority threadPriority,
  770. int maxScriptQueue, int stackSize)
  771. {
  772. m_MaxScriptQueue = maxScriptQueue;
  773. STPStartInfo startInfo = new STPStartInfo();
  774. startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
  775. startInfo.MaxWorkerThreads = maxThreads;
  776. startInfo.MinWorkerThreads = minThreads;
  777. startInfo.ThreadPriority = threadPriority;
  778. startInfo.StackSize = stackSize;
  779. startInfo.StartSuspended = true;
  780. m_ThreadPool = new SmartThreadPool(startInfo);
  781. }
  782. //
  783. // Used by script instances to queue event handler jobs
  784. //
  785. public IScriptWorkItem QueueEventHandler(object parms)
  786. {
  787. return new XWorkItem(m_ThreadPool.QueueWorkItem(
  788. new WorkItemCallback(this.ProcessEventHandler),
  789. parms));
  790. }
  791. /// <summary>
  792. /// Process a previously posted script event.
  793. /// </summary>
  794. /// <param name="parms"></param>
  795. /// <returns></returns>
  796. private object ProcessEventHandler(object parms)
  797. {
  798. CultureInfo USCulture = new CultureInfo("en-US");
  799. Thread.CurrentThread.CurrentCulture = USCulture;
  800. IScriptInstance instance = (ScriptInstance) parms;
  801. //m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);
  802. return instance.EventProcessor();
  803. }
  804. /// <summary>
  805. /// Post event to an entire prim
  806. /// </summary>
  807. /// <param name="localID"></param>
  808. /// <param name="p"></param>
  809. /// <returns></returns>
  810. public bool PostObjectEvent(uint localID, EventParams p)
  811. {
  812. bool result = false;
  813. lock (m_PrimObjects)
  814. {
  815. if (!m_PrimObjects.ContainsKey(localID))
  816. return false;
  817. foreach (UUID itemID in m_PrimObjects[localID])
  818. {
  819. if (m_Scripts.ContainsKey(itemID))
  820. {
  821. IScriptInstance instance = m_Scripts[itemID];
  822. if (instance != null)
  823. {
  824. instance.PostEvent(p);
  825. result = true;
  826. }
  827. }
  828. }
  829. }
  830. return result;
  831. }
  832. /// <summary>
  833. /// Post an event to a single script
  834. /// </summary>
  835. /// <param name="itemID"></param>
  836. /// <param name="p"></param>
  837. /// <returns></returns>
  838. public bool PostScriptEvent(UUID itemID, EventParams p)
  839. {
  840. if (m_Scripts.ContainsKey(itemID))
  841. {
  842. IScriptInstance instance = m_Scripts[itemID];
  843. if (instance != null)
  844. instance.PostEvent(p);
  845. return true;
  846. }
  847. return false;
  848. }
  849. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  850. {
  851. Object[] lsl_p = new Object[p.Length];
  852. for (int i = 0; i < p.Length ; i++)
  853. {
  854. if (p[i] is int)
  855. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  856. else if (p[i] is string)
  857. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  858. else if (p[i] is Vector3)
  859. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  860. else if (p[i] is Quaternion)
  861. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  862. else if (p[i] is float)
  863. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  864. else
  865. lsl_p[i] = p[i];
  866. }
  867. return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
  868. }
  869. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  870. {
  871. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  872. if (part == null)
  873. return false;
  874. Object[] lsl_p = new Object[p.Length];
  875. for (int i = 0; i < p.Length ; i++)
  876. {
  877. if (p[i] is int)
  878. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  879. else if (p[i] is string)
  880. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  881. else if (p[i] is Vector3)
  882. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  883. else if (p[i] is Quaternion)
  884. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  885. else if (p[i] is float)
  886. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  887. else
  888. lsl_p[i] = p[i];
  889. }
  890. return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
  891. }
  892. public Assembly OnAssemblyResolve(object sender,
  893. ResolveEventArgs args)
  894. {
  895. if (!(sender is System.AppDomain))
  896. return null;
  897. string[] pathList = new string[] {"bin", "ScriptEngines",
  898. Path.Combine("ScriptEngines",
  899. m_Scene.RegionInfo.RegionID.ToString())};
  900. string assemblyName = args.Name;
  901. if (assemblyName.IndexOf(",") != -1)
  902. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  903. foreach (string s in pathList)
  904. {
  905. string path = Path.Combine(Directory.GetCurrentDirectory(),
  906. Path.Combine(s, assemblyName))+".dll";
  907. if (File.Exists(path))
  908. return Assembly.LoadFrom(path);
  909. }
  910. return null;
  911. }
  912. private IScriptInstance GetInstance(UUID itemID)
  913. {
  914. IScriptInstance instance;
  915. lock (m_Scripts)
  916. {
  917. if (!m_Scripts.ContainsKey(itemID))
  918. return null;
  919. instance = m_Scripts[itemID];
  920. }
  921. return instance;
  922. }
  923. public void SetScriptState(UUID itemID, bool running)
  924. {
  925. IScriptInstance instance = GetInstance(itemID);
  926. if (instance != null)
  927. {
  928. if (running)
  929. instance.Start();
  930. else
  931. instance.Stop(100);
  932. }
  933. }
  934. public bool GetScriptState(UUID itemID)
  935. {
  936. IScriptInstance instance = GetInstance(itemID);
  937. if (instance != null)
  938. return instance.Running;
  939. return false;
  940. }
  941. public void ApiResetScript(UUID itemID)
  942. {
  943. IScriptInstance instance = GetInstance(itemID);
  944. if (instance != null)
  945. instance.ApiResetScript();
  946. }
  947. public void ResetScript(UUID itemID)
  948. {
  949. IScriptInstance instance = GetInstance(itemID);
  950. if (instance != null)
  951. instance.ResetScript();
  952. }
  953. public void StartScript(UUID itemID)
  954. {
  955. IScriptInstance instance = GetInstance(itemID);
  956. if (instance != null)
  957. instance.Start();
  958. }
  959. public void StopScript(UUID itemID)
  960. {
  961. IScriptInstance instance = GetInstance(itemID);
  962. if (instance != null)
  963. instance.Stop(0);
  964. }
  965. public DetectParams GetDetectParams(UUID itemID, int idx)
  966. {
  967. IScriptInstance instance = GetInstance(itemID);
  968. if (instance != null)
  969. return instance.GetDetectParams(idx);
  970. return null;
  971. }
  972. public void SetMinEventDelay(UUID itemID, double delay)
  973. {
  974. IScriptInstance instance = GetInstance(itemID);
  975. if (instance != null)
  976. instance.MinEventDelay = delay;
  977. }
  978. public UUID GetDetectID(UUID itemID, int idx)
  979. {
  980. IScriptInstance instance = GetInstance(itemID);
  981. if (instance != null)
  982. return instance.GetDetectID(idx);
  983. return UUID.Zero;
  984. }
  985. public void SetState(UUID itemID, string newState)
  986. {
  987. IScriptInstance instance = GetInstance(itemID);
  988. if (instance == null)
  989. return;
  990. instance.SetState(newState);
  991. }
  992. public string GetState(UUID itemID)
  993. {
  994. IScriptInstance instance = GetInstance(itemID);
  995. if (instance == null)
  996. return "default";
  997. return instance.State;
  998. }
  999. public int GetStartParameter(UUID itemID)
  1000. {
  1001. IScriptInstance instance = GetInstance(itemID);
  1002. if (instance == null)
  1003. return 0;
  1004. return instance.StartParam;
  1005. }
  1006. public void OnShutdown()
  1007. {
  1008. List<IScriptInstance> instances = new List<IScriptInstance>();
  1009. lock (m_Scripts)
  1010. {
  1011. foreach (IScriptInstance instance in m_Scripts.Values)
  1012. instances.Add(instance);
  1013. }
  1014. foreach (IScriptInstance i in instances)
  1015. {
  1016. // Stop the script, even forcibly if needed. Then flag
  1017. // it as shutting down and restore the previous run state
  1018. // for serialization, so the scripts don't come back
  1019. // dead after region restart
  1020. //
  1021. bool prevRunning = i.Running;
  1022. i.Stop(50);
  1023. i.ShuttingDown = true;
  1024. i.Running = prevRunning;
  1025. }
  1026. DoBackup(new Object[] {0});
  1027. }
  1028. public IScriptApi GetApi(UUID itemID, string name)
  1029. {
  1030. IScriptInstance instance = GetInstance(itemID);
  1031. if (instance == null)
  1032. return null;
  1033. return instance.GetApi(name);
  1034. }
  1035. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  1036. {
  1037. IScriptInstance instance = GetInstance(itemID);
  1038. if (instance == null)
  1039. return;
  1040. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1041. if (eq == null)
  1042. {
  1043. controllingClient.SendScriptRunningReply(objectID, itemID,
  1044. GetScriptState(itemID));
  1045. }
  1046. else
  1047. {
  1048. eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
  1049. controllingClient.AgentId);
  1050. }
  1051. }
  1052. public string GetAssemblyName(UUID itemID)
  1053. {
  1054. IScriptInstance instance = GetInstance(itemID);
  1055. if (instance == null)
  1056. return "";
  1057. return instance.GetAssemblyName();
  1058. }
  1059. public string GetXMLState(UUID itemID)
  1060. {
  1061. IScriptInstance instance = GetInstance(itemID);
  1062. if (instance == null)
  1063. return "";
  1064. return instance.GetXMLState();
  1065. }
  1066. public bool CanBeDeleted(UUID itemID)
  1067. {
  1068. IScriptInstance instance = GetInstance(itemID);
  1069. if (instance == null)
  1070. return true;
  1071. return instance.CanBeDeleted();
  1072. }
  1073. private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
  1074. {
  1075. return false;
  1076. }
  1077. }
  1078. }