XEngine.cs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  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.Framework.Scenes;
  44. using OpenSim.Region.Framework.Interfaces;
  45. using OpenSim.Region.ScriptEngine.Shared;
  46. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  47. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  48. using OpenSim.Region.ScriptEngine.Shared.Instance;
  49. using OpenSim.Region.ScriptEngine.Interfaces;
  50. using ScriptCompileQueue = OpenSim.Framework.LocklessQueue<object[]>;
  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. private Dictionary<string, string> m_uniqueScripts = new Dictionary<string, string>();
  74. private bool m_AppDomainLoading;
  75. private Dictionary<UUID,ArrayList> m_ScriptErrors =
  76. new Dictionary<UUID,ArrayList>();
  77. // disable warning: need to keep a reference to XEngine.EventManager
  78. // alive to avoid it being garbage collected
  79. #pragma warning disable 414
  80. private EventManager m_EventManager;
  81. #pragma warning restore 414
  82. private IXmlRpcRouter m_XmlRpcRouter;
  83. private int m_EventLimit;
  84. private bool m_KillTimedOutScripts;
  85. private string m_ScriptEnginesPath = null;
  86. private static List<XEngine> m_ScriptEngines =
  87. new List<XEngine>();
  88. // Maps the local id to the script inventory items in it
  89. private Dictionary<uint, List<UUID> > m_PrimObjects =
  90. new Dictionary<uint, List<UUID> >();
  91. // Maps the UUID above to the script instance
  92. private Dictionary<UUID, IScriptInstance> m_Scripts =
  93. new Dictionary<UUID, IScriptInstance>();
  94. // Maps the asset ID to the assembly
  95. private Dictionary<UUID, string> m_Assemblies =
  96. new Dictionary<UUID, string>();
  97. private Dictionary<string, int> m_AddingAssemblies =
  98. new Dictionary<string, int>();
  99. // This will list AppDomains by script asset
  100. private Dictionary<UUID, AppDomain> m_AppDomains =
  101. new Dictionary<UUID, AppDomain>();
  102. // List the scripts running in each appdomain
  103. private Dictionary<UUID, List<UUID> > m_DomainScripts =
  104. new Dictionary<UUID, List<UUID> >();
  105. private ScriptCompileQueue m_CompileQueue = new ScriptCompileQueue();
  106. IWorkItemResult m_CurrentCompile = null;
  107. private Dictionary<UUID, int> m_CompileDict = new Dictionary<UUID, int>();
  108. public string ScriptEngineName
  109. {
  110. get { return "XEngine"; }
  111. }
  112. public Scene World
  113. {
  114. get { return m_Scene; }
  115. }
  116. public static List<XEngine> ScriptEngines
  117. {
  118. get { return m_ScriptEngines; }
  119. }
  120. public IScriptModule ScriptModule
  121. {
  122. get { return this; }
  123. }
  124. // private struct RezScriptParms
  125. // {
  126. // uint LocalID;
  127. // UUID ItemID;
  128. // string Script;
  129. // }
  130. public IConfig Config
  131. {
  132. get { return m_ScriptConfig; }
  133. }
  134. public string ScriptEnginePath
  135. {
  136. get { return m_ScriptEnginesPath; }
  137. }
  138. public IConfigSource ConfigSource
  139. {
  140. get { return m_ConfigSource; }
  141. }
  142. public event ScriptRemoved OnScriptRemoved;
  143. public event ObjectRemoved OnObjectRemoved;
  144. //
  145. // IRegionModule functions
  146. //
  147. public void Initialise(IConfigSource configSource)
  148. {
  149. if (configSource.Configs["XEngine"] == null)
  150. return;
  151. m_ScriptConfig = configSource.Configs["XEngine"];
  152. m_ConfigSource = configSource;
  153. }
  154. public void AddRegion(Scene scene)
  155. {
  156. if (m_ScriptConfig == null)
  157. return;
  158. m_ScriptFailCount = 0;
  159. m_ScriptErrorMessage = String.Empty;
  160. if (m_ScriptConfig == null)
  161. {
  162. // m_log.ErrorFormat("[XEngine] No script configuration found. Scripts disabled");
  163. return;
  164. }
  165. m_Enabled = m_ScriptConfig.GetBoolean("Enabled", true);
  166. if (!m_Enabled)
  167. return;
  168. AppDomain.CurrentDomain.AssemblyResolve +=
  169. OnAssemblyResolve;
  170. m_log.InfoFormat("[XEngine] Initializing scripts in region {0}",
  171. scene.RegionInfo.RegionName);
  172. m_Scene = scene;
  173. m_MinThreads = m_ScriptConfig.GetInt("MinThreads", 2);
  174. m_MaxThreads = m_ScriptConfig.GetInt("MaxThreads", 100);
  175. m_IdleTimeout = m_ScriptConfig.GetInt("IdleTimeout", 60);
  176. string priority = m_ScriptConfig.GetString("Priority", "BelowNormal");
  177. m_MaxScriptQueue = m_ScriptConfig.GetInt("MaxScriptEventQueue",300);
  178. m_StackSize = m_ScriptConfig.GetInt("ThreadStackSize", 262144);
  179. m_SleepTime = m_ScriptConfig.GetInt("MaintenanceInterval", 10) * 1000;
  180. m_AppDomainLoading = m_ScriptConfig.GetBoolean("AppDomainLoading", true);
  181. m_EventLimit = m_ScriptConfig.GetInt("EventLimit", 30);
  182. m_KillTimedOutScripts = m_ScriptConfig.GetBoolean("KillTimedOutScripts", false);
  183. m_SaveTime = m_ScriptConfig.GetInt("SaveInterval", 120) * 1000;
  184. m_ScriptEnginesPath = m_ScriptConfig.GetString("ScriptEnginesPath", "ScriptEngines");
  185. m_Prio = ThreadPriority.BelowNormal;
  186. switch (priority)
  187. {
  188. case "Lowest":
  189. m_Prio = ThreadPriority.Lowest;
  190. break;
  191. case "BelowNormal":
  192. m_Prio = ThreadPriority.BelowNormal;
  193. break;
  194. case "Normal":
  195. m_Prio = ThreadPriority.Normal;
  196. break;
  197. case "AboveNormal":
  198. m_Prio = ThreadPriority.AboveNormal;
  199. break;
  200. case "Highest":
  201. m_Prio = ThreadPriority.Highest;
  202. break;
  203. default:
  204. m_log.ErrorFormat("[XEngine] Invalid thread priority: '{0}'. Assuming BelowNormal", priority);
  205. break;
  206. }
  207. lock (m_ScriptEngines)
  208. {
  209. m_ScriptEngines.Add(this);
  210. }
  211. // Needs to be here so we can queue the scripts that need starting
  212. //
  213. m_Scene.EventManager.OnRezScript += OnRezScript;
  214. // Complete basic setup of the thread pool
  215. //
  216. SetupEngine(m_MinThreads, m_MaxThreads, m_IdleTimeout, m_Prio,
  217. m_MaxScriptQueue, m_StackSize);
  218. m_Scene.StackModuleInterface<IScriptModule>(this);
  219. m_XmlRpcRouter = m_Scene.RequestModuleInterface<IXmlRpcRouter>();
  220. if (m_XmlRpcRouter != null)
  221. {
  222. OnScriptRemoved += m_XmlRpcRouter.ScriptRemoved;
  223. OnObjectRemoved += m_XmlRpcRouter.ObjectRemoved;
  224. }
  225. }
  226. public void RemoveRegion(Scene scene)
  227. {
  228. lock (m_Scripts)
  229. {
  230. foreach (IScriptInstance instance in m_Scripts.Values)
  231. {
  232. // Force a final state save
  233. //
  234. if (m_Assemblies.ContainsKey(instance.AssetID))
  235. {
  236. string assembly = m_Assemblies[instance.AssetID];
  237. instance.SaveState(assembly);
  238. }
  239. // Clear the event queue and abort the instance thread
  240. //
  241. instance.ClearQueue();
  242. instance.Stop(0);
  243. // Release events, timer, etc
  244. //
  245. instance.DestroyScriptInstance();
  246. // Unload scripts and app domains
  247. // Must be done explicitly because they have infinite
  248. // lifetime
  249. //
  250. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  251. if (m_DomainScripts[instance.AppDomain].Count == 0)
  252. {
  253. m_DomainScripts.Remove(instance.AppDomain);
  254. UnloadAppDomain(instance.AppDomain);
  255. }
  256. }
  257. m_Scripts.Clear();
  258. m_PrimObjects.Clear();
  259. m_Assemblies.Clear();
  260. m_DomainScripts.Clear();
  261. }
  262. lock (m_ScriptEngines)
  263. {
  264. m_ScriptEngines.Remove(this);
  265. }
  266. }
  267. public void RegionLoaded(Scene scene)
  268. {
  269. if (!m_Enabled)
  270. return;
  271. m_EventManager = new EventManager(this);
  272. m_Compiler = new Compiler(this);
  273. m_Scene.EventManager.OnRemoveScript += OnRemoveScript;
  274. m_Scene.EventManager.OnScriptReset += OnScriptReset;
  275. m_Scene.EventManager.OnStartScript += OnStartScript;
  276. m_Scene.EventManager.OnStopScript += OnStopScript;
  277. m_Scene.EventManager.OnGetScriptRunning += OnGetScriptRunning;
  278. m_Scene.EventManager.OnShutdown += OnShutdown;
  279. if (m_SleepTime > 0)
  280. {
  281. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  282. new Object[]{ m_SleepTime });
  283. }
  284. if (m_SaveTime > 0)
  285. {
  286. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  287. new Object[] { m_SaveTime });
  288. }
  289. }
  290. public void StartProcessing()
  291. {
  292. m_ThreadPool.Start();
  293. }
  294. public void Close()
  295. {
  296. lock (m_ScriptEngines)
  297. {
  298. if (m_ScriptEngines.Contains(this))
  299. m_ScriptEngines.Remove(this);
  300. }
  301. }
  302. public object DoBackup(object o)
  303. {
  304. Object[] p = (Object[])o;
  305. int saveTime = (int)p[0];
  306. if (saveTime > 0)
  307. System.Threading.Thread.Sleep(saveTime);
  308. // m_log.Debug("[XEngine] Backing up script states");
  309. List<IScriptInstance> instances = new List<IScriptInstance>();
  310. lock (m_Scripts)
  311. {
  312. foreach (IScriptInstance instance in m_Scripts.Values)
  313. instances.Add(instance);
  314. }
  315. foreach (IScriptInstance i in instances)
  316. {
  317. string assembly = String.Empty;
  318. lock (m_Scripts)
  319. {
  320. if (!m_Assemblies.ContainsKey(i.AssetID))
  321. continue;
  322. assembly = m_Assemblies[i.AssetID];
  323. }
  324. i.SaveState(assembly);
  325. }
  326. instances.Clear();
  327. if (saveTime > 0)
  328. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoBackup),
  329. new Object[] { saveTime });
  330. return 0;
  331. }
  332. public void SaveAllState()
  333. {
  334. foreach (IScriptInstance inst in m_Scripts.Values)
  335. {
  336. if (inst.EventTime() > m_EventLimit)
  337. {
  338. inst.Stop(100);
  339. if (!m_KillTimedOutScripts)
  340. inst.Start();
  341. }
  342. }
  343. }
  344. public object DoMaintenance(object p)
  345. {
  346. object[] parms = (object[])p;
  347. int sleepTime = (int)parms[0];
  348. SaveAllState();
  349. System.Threading.Thread.Sleep(sleepTime);
  350. m_ThreadPool.QueueWorkItem(new WorkItemCallback(this.DoMaintenance),
  351. new Object[]{ sleepTime });
  352. return 0;
  353. }
  354. public Type ReplaceableInterface
  355. {
  356. get { return null; }
  357. }
  358. public string Name
  359. {
  360. get { return "XEngine"; }
  361. }
  362. public void OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  363. {
  364. if (script.StartsWith("//MRM:"))
  365. return;
  366. List<IScriptModule> engines = new List<IScriptModule>(m_Scene.RequestModuleInterfaces<IScriptModule>());
  367. List<string> names = new List<string>();
  368. foreach (IScriptModule m in engines)
  369. names.Add(m.ScriptEngineName);
  370. int lineEnd = script.IndexOf('\n');
  371. if (lineEnd > 1)
  372. {
  373. string firstline = script.Substring(0, lineEnd).Trim();
  374. int colon = firstline.IndexOf(':');
  375. if (firstline.Length > 2 && firstline.Substring(0, 2) == "//" && colon != -1)
  376. {
  377. string engineName = firstline.Substring(2, colon-2);
  378. if (names.Contains(engineName))
  379. {
  380. engine = engineName;
  381. script = "//" + script.Substring(script.IndexOf(':')+1);
  382. }
  383. else
  384. {
  385. if (engine == ScriptEngineName)
  386. {
  387. SceneObjectPart part =
  388. m_Scene.GetSceneObjectPart(
  389. localID);
  390. TaskInventoryItem item =
  391. part.Inventory.GetInventoryItem(itemID);
  392. ScenePresence presence =
  393. m_Scene.GetScenePresence(
  394. item.OwnerID);
  395. if (presence != null)
  396. {
  397. presence.ControllingClient.SendAgentAlertMessage(
  398. "Selected engine unavailable. "+
  399. "Running script on "+
  400. ScriptEngineName,
  401. false);
  402. }
  403. }
  404. }
  405. }
  406. }
  407. if (engine != ScriptEngineName)
  408. return;
  409. // If we've seen this exact script text before, use that reference instead
  410. if (m_uniqueScripts.ContainsKey(script))
  411. script = m_uniqueScripts[script];
  412. else
  413. m_uniqueScripts[script] = script;
  414. Object[] parms = new Object[]{localID, itemID, script, startParam, postOnRez, (StateSource)stateSource};
  415. if (stateSource == (int)StateSource.ScriptedRez)
  416. {
  417. lock (m_CompileDict)
  418. {
  419. m_CompileDict[itemID] = 0;
  420. }
  421. DoOnRezScript(parms);
  422. }
  423. else
  424. {
  425. m_CompileQueue.Enqueue(parms);
  426. lock (m_CompileDict)
  427. {
  428. m_CompileDict[itemID] = 0;
  429. }
  430. if (m_CurrentCompile == null)
  431. {
  432. // NOTE: Although we use a lockless queue, the lock here
  433. // is required. It ensures that there are never two
  434. // compile threads running, which, due to a race
  435. // conndition, might otherwise happen
  436. //
  437. lock (m_CompileQueue)
  438. {
  439. if (m_CurrentCompile == null)
  440. m_CurrentCompile = m_ThreadPool.QueueWorkItem(DoOnRezScriptQueue, null);
  441. }
  442. }
  443. }
  444. }
  445. public Object DoOnRezScriptQueue(Object dummy)
  446. {
  447. if (m_InitialStartup)
  448. {
  449. m_InitialStartup = false;
  450. System.Threading.Thread.Sleep(15000);
  451. if (m_CompileQueue.Count == 0)
  452. {
  453. // No scripts on region, so won't get triggered later
  454. // by the queue becoming empty so we trigger it here
  455. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(0, String.Empty);
  456. }
  457. }
  458. object[] o;
  459. while (m_CompileQueue.Dequeue(out o))
  460. DoOnRezScript(o);
  461. // NOTE: Despite having a lockless queue, this lock is required
  462. // to make sure there is never no compile thread while there
  463. // are still scripts to compile. This could otherwise happen
  464. // due to a race condition
  465. //
  466. lock (m_CompileQueue)
  467. {
  468. m_CurrentCompile = null;
  469. }
  470. m_Scene.EventManager.TriggerEmptyScriptCompileQueue(m_ScriptFailCount,
  471. m_ScriptErrorMessage);
  472. m_ScriptFailCount = 0;
  473. return null;
  474. }
  475. private bool DoOnRezScript(object[] parms)
  476. {
  477. Object[] p = parms;
  478. uint localID = (uint)p[0];
  479. UUID itemID = (UUID)p[1];
  480. string script =(string)p[2];
  481. int startParam = (int)p[3];
  482. bool postOnRez = (bool)p[4];
  483. StateSource stateSource = (StateSource)p[5];
  484. lock (m_CompileDict)
  485. {
  486. if (!m_CompileDict.ContainsKey(itemID))
  487. return false;
  488. m_CompileDict.Remove(itemID);
  489. }
  490. // Get the asset ID of the script, so we can check if we
  491. // already have it.
  492. // We must look for the part outside the m_Scripts lock because GetSceneObjectPart later triggers the
  493. // m_parts lock on SOG. At the same time, a scene object that is being deleted will take the m_parts lock
  494. // and then later on try to take the m_scripts lock in this class when it calls OnRemoveScript()
  495. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  496. if (part == null)
  497. {
  498. m_log.ErrorFormat("[Script]: SceneObjectPart with localID {0} unavailable. Script NOT started.", localID);
  499. m_ScriptErrorMessage += "SceneObjectPart unavailable. Script NOT started.\n";
  500. m_ScriptFailCount++;
  501. return false;
  502. }
  503. TaskInventoryItem item = part.Inventory.GetInventoryItem(itemID);
  504. if (item == null)
  505. {
  506. m_ScriptErrorMessage += "Can't find script inventory item.\n";
  507. m_ScriptFailCount++;
  508. return false;
  509. }
  510. UUID assetID = item.AssetID;
  511. //m_log.DebugFormat("[XEngine] Compiling script {0} ({1} on object {2})",
  512. // item.Name, itemID.ToString(), part.ParentGroup.RootPart.Name);
  513. ScenePresence presence = m_Scene.GetScenePresence(item.OwnerID);
  514. string assembly = "";
  515. CultureInfo USCulture = new CultureInfo("en-US");
  516. Thread.CurrentThread.CurrentCulture = USCulture;
  517. Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> linemap;
  518. lock (m_ScriptErrors)
  519. {
  520. try
  521. {
  522. lock (m_AddingAssemblies)
  523. {
  524. m_Compiler.PerformScriptCompile(script, assetID.ToString(), item.OwnerID, out assembly, out linemap);
  525. if (!m_AddingAssemblies.ContainsKey(assembly)) {
  526. m_AddingAssemblies[assembly] = 1;
  527. } else {
  528. m_AddingAssemblies[assembly]++;
  529. }
  530. }
  531. string[] warnings = m_Compiler.GetWarnings();
  532. if (warnings != null && warnings.Length != 0)
  533. {
  534. foreach (string warning in warnings)
  535. {
  536. if (!m_ScriptErrors.ContainsKey(itemID))
  537. m_ScriptErrors[itemID] = new ArrayList();
  538. m_ScriptErrors[itemID].Add(warning);
  539. // try
  540. // {
  541. // // DISPLAY WARNING INWORLD
  542. // string text = "Warning:\n" + warning;
  543. // if (text.Length > 1000)
  544. // text = text.Substring(0, 1000);
  545. // if (!ShowScriptSaveResponse(item.OwnerID,
  546. // assetID, text, true))
  547. // {
  548. // if (presence != null && (!postOnRez))
  549. // presence.ControllingClient.SendAgentAlertMessage("Script saved with warnings, check debug window!", false);
  550. //
  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 warning in-world: " +
  561. // e2.ToString());
  562. // m_log.Error("[XEngine]: " +
  563. // "Warning:\r\n" +
  564. // warning);
  565. // }
  566. }
  567. }
  568. }
  569. catch (Exception e)
  570. {
  571. // try
  572. // {
  573. if (!m_ScriptErrors.ContainsKey(itemID))
  574. m_ScriptErrors[itemID] = new ArrayList();
  575. // DISPLAY ERROR INWORLD
  576. // m_ScriptErrorMessage += "Failed to compile script in object: '" + part.ParentGroup.RootPart.Name + "' Script name: '" + item.Name + "' Error message: " + e.Message.ToString();
  577. //
  578. m_ScriptFailCount++;
  579. m_ScriptErrors[itemID].Add(e.Message.ToString());
  580. // string text = "Error compiling script '" + item.Name + "':\n" + e.Message.ToString();
  581. // if (text.Length > 1000)
  582. // text = text.Substring(0, 1000);
  583. // if (!ShowScriptSaveResponse(item.OwnerID,
  584. // assetID, text, false))
  585. // {
  586. // if (presence != null && (!postOnRez))
  587. // presence.ControllingClient.SendAgentAlertMessage("Script saved with errors, check debug window!", false);
  588. // World.SimChat(Utils.StringToBytes(text),
  589. // ChatTypeEnum.DebugChannel, 2147483647,
  590. // part.AbsolutePosition,
  591. // part.Name, part.UUID, false);
  592. // }
  593. // }
  594. // catch (Exception e2) // LEGIT: User Scripting
  595. // {
  596. // m_log.Error("[XEngine]: "+
  597. // "Error displaying error in-world: " +
  598. // e2.ToString());
  599. // m_log.Error("[XEngine]: " +
  600. // "Errormessage: Error compiling script:\r\n" +
  601. // e.Message.ToString());
  602. // }
  603. return false;
  604. }
  605. }
  606. ScriptInstance instance = null;
  607. lock (m_Scripts)
  608. {
  609. // Create the object record
  610. if ((!m_Scripts.ContainsKey(itemID)) ||
  611. (m_Scripts[itemID].AssetID != assetID))
  612. {
  613. UUID appDomain = assetID;
  614. if (part.ParentGroup.IsAttachment)
  615. appDomain = part.ParentGroup.RootPart.UUID;
  616. if (!m_AppDomains.ContainsKey(appDomain))
  617. {
  618. try
  619. {
  620. AppDomainSetup appSetup = new AppDomainSetup();
  621. appSetup.PrivateBinPath = Path.Combine(
  622. m_ScriptEnginesPath,
  623. m_Scene.RegionInfo.RegionID.ToString());
  624. Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
  625. Evidence evidence = new Evidence(baseEvidence);
  626. AppDomain sandbox;
  627. if (m_AppDomainLoading)
  628. sandbox = AppDomain.CreateDomain(
  629. m_Scene.RegionInfo.RegionID.ToString(),
  630. evidence, appSetup);
  631. else
  632. sandbox = AppDomain.CurrentDomain;
  633. //PolicyLevel sandboxPolicy = PolicyLevel.CreateAppDomainLevel();
  634. //AllMembershipCondition sandboxMembershipCondition = new AllMembershipCondition();
  635. //PermissionSet sandboxPermissionSet = sandboxPolicy.GetNamedPermissionSet("Internet");
  636. //PolicyStatement sandboxPolicyStatement = new PolicyStatement(sandboxPermissionSet);
  637. //CodeGroup sandboxCodeGroup = new UnionCodeGroup(sandboxMembershipCondition, sandboxPolicyStatement);
  638. //sandboxPolicy.RootCodeGroup = sandboxCodeGroup;
  639. //sandbox.SetAppDomainPolicy(sandboxPolicy);
  640. m_AppDomains[appDomain] = sandbox;
  641. m_AppDomains[appDomain].AssemblyResolve +=
  642. new ResolveEventHandler(
  643. AssemblyResolver.OnAssemblyResolve);
  644. m_DomainScripts[appDomain] = new List<UUID>();
  645. }
  646. catch (Exception e)
  647. {
  648. m_log.ErrorFormat("[XEngine] Exception creating app domain:\n {0}", e.ToString());
  649. m_ScriptErrorMessage += "Exception creating app domain:\n";
  650. m_ScriptFailCount++;
  651. lock (m_AddingAssemblies)
  652. {
  653. m_AddingAssemblies[assembly]--;
  654. }
  655. return false;
  656. }
  657. }
  658. m_DomainScripts[appDomain].Add(itemID);
  659. instance = new ScriptInstance(this, part,
  660. itemID, assetID, assembly,
  661. m_AppDomains[appDomain],
  662. part.ParentGroup.RootPart.Name,
  663. item.Name, startParam, postOnRez,
  664. stateSource, m_MaxScriptQueue);
  665. m_log.DebugFormat(
  666. "[XEngine] Loaded script {0}.{1}, script UUID {2}, prim UUID {3} @ {4}.{5}",
  667. part.ParentGroup.RootPart.Name, item.Name, assetID, part.UUID,
  668. part.ParentGroup.RootPart.AbsolutePosition, part.ParentGroup.Scene.RegionInfo.RegionName);
  669. if (presence != null)
  670. {
  671. ShowScriptSaveResponse(item.OwnerID,
  672. assetID, "Compile successful", true);
  673. }
  674. instance.AppDomain = appDomain;
  675. instance.LineMap = linemap;
  676. m_Scripts[itemID] = instance;
  677. }
  678. }
  679. lock (m_PrimObjects)
  680. {
  681. if (!m_PrimObjects.ContainsKey(localID))
  682. m_PrimObjects[localID] = new List<UUID>();
  683. if (!m_PrimObjects[localID].Contains(itemID))
  684. m_PrimObjects[localID].Add(itemID);
  685. }
  686. if (!m_Assemblies.ContainsKey(assetID))
  687. m_Assemblies[assetID] = assembly;
  688. lock (m_AddingAssemblies)
  689. {
  690. m_AddingAssemblies[assembly]--;
  691. }
  692. if (instance != null)
  693. instance.Init();
  694. return true;
  695. }
  696. public void OnRemoveScript(uint localID, UUID itemID)
  697. {
  698. // If it's not yet been compiled, make sure we don't try
  699. lock (m_CompileDict)
  700. {
  701. if (m_CompileDict.ContainsKey(itemID))
  702. m_CompileDict.Remove(itemID);
  703. }
  704. IScriptInstance instance = null;
  705. lock (m_Scripts)
  706. {
  707. // Do we even have it?
  708. if (!m_Scripts.ContainsKey(itemID))
  709. return;
  710. instance=m_Scripts[itemID];
  711. m_Scripts.Remove(itemID);
  712. }
  713. instance.ClearQueue();
  714. instance.Stop(0);
  715. // bool objectRemoved = false;
  716. lock (m_PrimObjects)
  717. {
  718. // Remove the script from it's prim
  719. if (m_PrimObjects.ContainsKey(localID))
  720. {
  721. // Remove inventory item record
  722. if (m_PrimObjects[localID].Contains(itemID))
  723. m_PrimObjects[localID].Remove(itemID);
  724. // If there are no more scripts, remove prim
  725. if (m_PrimObjects[localID].Count == 0)
  726. {
  727. m_PrimObjects.Remove(localID);
  728. // objectRemoved = true;
  729. }
  730. }
  731. }
  732. instance.RemoveState();
  733. instance.DestroyScriptInstance();
  734. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  735. if (m_DomainScripts[instance.AppDomain].Count == 0)
  736. {
  737. m_DomainScripts.Remove(instance.AppDomain);
  738. UnloadAppDomain(instance.AppDomain);
  739. }
  740. instance = null;
  741. ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
  742. if (handlerObjectRemoved != null)
  743. {
  744. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  745. handlerObjectRemoved(part.UUID);
  746. }
  747. ScriptRemoved handlerScriptRemoved = OnScriptRemoved;
  748. if (handlerScriptRemoved != null)
  749. handlerScriptRemoved(itemID);
  750. }
  751. public void OnScriptReset(uint localID, UUID itemID)
  752. {
  753. ResetScript(itemID);
  754. }
  755. public void OnStartScript(uint localID, UUID itemID)
  756. {
  757. StartScript(itemID);
  758. }
  759. public void OnStopScript(uint localID, UUID itemID)
  760. {
  761. StopScript(itemID);
  762. }
  763. private void CleanAssemblies()
  764. {
  765. List<UUID> assetIDList = new List<UUID>(m_Assemblies.Keys);
  766. foreach (IScriptInstance i in m_Scripts.Values)
  767. {
  768. if (assetIDList.Contains(i.AssetID))
  769. assetIDList.Remove(i.AssetID);
  770. }
  771. lock (m_AddingAssemblies)
  772. {
  773. foreach (UUID assetID in assetIDList)
  774. {
  775. // Do not remove assembly files if another instance of the script
  776. // is currently initialising
  777. if (!m_AddingAssemblies.ContainsKey(m_Assemblies[assetID])
  778. || m_AddingAssemblies[m_Assemblies[assetID]] == 0)
  779. {
  780. // m_log.DebugFormat("[XEngine] Removing unreferenced assembly {0}", m_Assemblies[assetID]);
  781. try
  782. {
  783. if (File.Exists(m_Assemblies[assetID]))
  784. File.Delete(m_Assemblies[assetID]);
  785. if (File.Exists(m_Assemblies[assetID]+".text"))
  786. File.Delete(m_Assemblies[assetID]+".text");
  787. if (File.Exists(m_Assemblies[assetID]+".mdb"))
  788. File.Delete(m_Assemblies[assetID]+".mdb");
  789. if (File.Exists(m_Assemblies[assetID]+".map"))
  790. File.Delete(m_Assemblies[assetID]+".map");
  791. }
  792. catch (Exception)
  793. {
  794. }
  795. m_Assemblies.Remove(assetID);
  796. }
  797. }
  798. }
  799. }
  800. private void UnloadAppDomain(UUID id)
  801. {
  802. if (m_AppDomains.ContainsKey(id))
  803. {
  804. AppDomain domain = m_AppDomains[id];
  805. m_AppDomains.Remove(id);
  806. if (domain != AppDomain.CurrentDomain)
  807. AppDomain.Unload(domain);
  808. domain = null;
  809. // m_log.DebugFormat("[XEngine] Unloaded app domain {0}", id.ToString());
  810. }
  811. }
  812. //
  813. // Start processing
  814. //
  815. private void SetupEngine(int minThreads, int maxThreads,
  816. int idleTimeout, ThreadPriority threadPriority,
  817. int maxScriptQueue, int stackSize)
  818. {
  819. m_MaxScriptQueue = maxScriptQueue;
  820. STPStartInfo startInfo = new STPStartInfo();
  821. startInfo.IdleTimeout = idleTimeout*1000; // convert to seconds as stated in .ini
  822. startInfo.MaxWorkerThreads = maxThreads;
  823. startInfo.MinWorkerThreads = minThreads;
  824. startInfo.ThreadPriority = threadPriority;;
  825. startInfo.StackSize = stackSize;
  826. startInfo.StartSuspended = true;
  827. m_ThreadPool = new SmartThreadPool(startInfo);
  828. }
  829. //
  830. // Used by script instances to queue event handler jobs
  831. //
  832. public IScriptWorkItem QueueEventHandler(object parms)
  833. {
  834. return new XWorkItem(m_ThreadPool.QueueWorkItem(
  835. new WorkItemCallback(this.ProcessEventHandler),
  836. parms));
  837. }
  838. /// <summary>
  839. /// Process a previously posted script event.
  840. /// </summary>
  841. /// <param name="parms"></param>
  842. /// <returns></returns>
  843. private object ProcessEventHandler(object parms)
  844. {
  845. CultureInfo USCulture = new CultureInfo("en-US");
  846. Thread.CurrentThread.CurrentCulture = USCulture;
  847. IScriptInstance instance = (ScriptInstance) parms;
  848. //m_log.DebugFormat("[XENGINE]: Processing event for {0}", instance);
  849. return instance.EventProcessor();
  850. }
  851. /// <summary>
  852. /// Post event to an entire prim
  853. /// </summary>
  854. /// <param name="localID"></param>
  855. /// <param name="p"></param>
  856. /// <returns></returns>
  857. public bool PostObjectEvent(uint localID, EventParams p)
  858. {
  859. bool result = false;
  860. List<UUID> uuids = null;
  861. lock (m_PrimObjects)
  862. {
  863. if (!m_PrimObjects.ContainsKey(localID))
  864. return false;
  865. uuids = m_PrimObjects[localID];
  866. }
  867. foreach (UUID itemID in uuids)
  868. {
  869. IScriptInstance instance = null;
  870. try
  871. {
  872. if (m_Scripts.ContainsKey(itemID))
  873. instance = m_Scripts[itemID];
  874. }
  875. catch { /* ignore race conditions */ }
  876. if (instance != null)
  877. {
  878. instance.PostEvent(p);
  879. result = true;
  880. }
  881. }
  882. return result;
  883. }
  884. /// <summary>
  885. /// Post an event to a single script
  886. /// </summary>
  887. /// <param name="itemID"></param>
  888. /// <param name="p"></param>
  889. /// <returns></returns>
  890. public bool PostScriptEvent(UUID itemID, EventParams p)
  891. {
  892. if (m_Scripts.ContainsKey(itemID))
  893. {
  894. IScriptInstance instance = m_Scripts[itemID];
  895. if (instance != null)
  896. instance.PostEvent(p);
  897. return true;
  898. }
  899. return false;
  900. }
  901. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  902. {
  903. Object[] lsl_p = new Object[p.Length];
  904. for (int i = 0; i < p.Length ; i++)
  905. {
  906. if (p[i] is int)
  907. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  908. else if (p[i] is string)
  909. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  910. else if (p[i] is Vector3)
  911. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  912. else if (p[i] is Quaternion)
  913. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  914. else if (p[i] is float)
  915. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  916. else
  917. lsl_p[i] = p[i];
  918. }
  919. return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
  920. }
  921. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  922. {
  923. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  924. if (part == null)
  925. return false;
  926. Object[] lsl_p = new Object[p.Length];
  927. for (int i = 0; i < p.Length ; i++)
  928. {
  929. if (p[i] is int)
  930. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  931. else if (p[i] is string)
  932. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  933. else if (p[i] is Vector3)
  934. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  935. else if (p[i] is Quaternion)
  936. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  937. else if (p[i] is float)
  938. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  939. else
  940. lsl_p[i] = p[i];
  941. }
  942. return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
  943. }
  944. public Assembly OnAssemblyResolve(object sender,
  945. ResolveEventArgs args)
  946. {
  947. if (!(sender is System.AppDomain))
  948. return null;
  949. string[] pathList = new string[] {"bin", m_ScriptEnginesPath,
  950. Path.Combine(m_ScriptEnginesPath,
  951. m_Scene.RegionInfo.RegionID.ToString())};
  952. string assemblyName = args.Name;
  953. if (assemblyName.IndexOf(",") != -1)
  954. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  955. foreach (string s in pathList)
  956. {
  957. string path = Path.Combine(Directory.GetCurrentDirectory(),
  958. Path.Combine(s, assemblyName))+".dll";
  959. if (File.Exists(path))
  960. return Assembly.LoadFrom(path);
  961. }
  962. return null;
  963. }
  964. private IScriptInstance GetInstance(UUID itemID)
  965. {
  966. IScriptInstance instance;
  967. lock (m_Scripts)
  968. {
  969. if (!m_Scripts.ContainsKey(itemID))
  970. return null;
  971. instance = m_Scripts[itemID];
  972. }
  973. return instance;
  974. }
  975. public void SetScriptState(UUID itemID, bool running)
  976. {
  977. IScriptInstance instance = GetInstance(itemID);
  978. if (instance != null)
  979. {
  980. if (running)
  981. instance.Start();
  982. else
  983. instance.Stop(100);
  984. }
  985. }
  986. public bool GetScriptState(UUID itemID)
  987. {
  988. IScriptInstance instance = GetInstance(itemID);
  989. if (instance != null)
  990. return instance.Running;
  991. return false;
  992. }
  993. public void ApiResetScript(UUID itemID)
  994. {
  995. IScriptInstance instance = GetInstance(itemID);
  996. if (instance != null)
  997. instance.ApiResetScript();
  998. }
  999. public void ResetScript(UUID itemID)
  1000. {
  1001. IScriptInstance instance = GetInstance(itemID);
  1002. if (instance != null)
  1003. instance.ResetScript();
  1004. }
  1005. public void StartScript(UUID itemID)
  1006. {
  1007. IScriptInstance instance = GetInstance(itemID);
  1008. if (instance != null)
  1009. instance.Start();
  1010. }
  1011. public void StopScript(UUID itemID)
  1012. {
  1013. IScriptInstance instance = GetInstance(itemID);
  1014. if (instance != null)
  1015. instance.Stop(0);
  1016. }
  1017. public DetectParams GetDetectParams(UUID itemID, int idx)
  1018. {
  1019. IScriptInstance instance = GetInstance(itemID);
  1020. if (instance != null)
  1021. return instance.GetDetectParams(idx);
  1022. return null;
  1023. }
  1024. public void SetMinEventDelay(UUID itemID, double delay)
  1025. {
  1026. IScriptInstance instance = GetInstance(itemID);
  1027. if (instance != null)
  1028. instance.MinEventDelay = delay;
  1029. }
  1030. public UUID GetDetectID(UUID itemID, int idx)
  1031. {
  1032. IScriptInstance instance = GetInstance(itemID);
  1033. if (instance != null)
  1034. return instance.GetDetectID(idx);
  1035. return UUID.Zero;
  1036. }
  1037. public void SetState(UUID itemID, string newState)
  1038. {
  1039. IScriptInstance instance = GetInstance(itemID);
  1040. if (instance == null)
  1041. return;
  1042. instance.SetState(newState);
  1043. }
  1044. public int GetStartParameter(UUID itemID)
  1045. {
  1046. IScriptInstance instance = GetInstance(itemID);
  1047. if (instance == null)
  1048. return 0;
  1049. return instance.StartParam;
  1050. }
  1051. public void OnShutdown()
  1052. {
  1053. List<IScriptInstance> instances = new List<IScriptInstance>();
  1054. lock (m_Scripts)
  1055. {
  1056. foreach (IScriptInstance instance in m_Scripts.Values)
  1057. instances.Add(instance);
  1058. }
  1059. foreach (IScriptInstance i in instances)
  1060. {
  1061. // Stop the script, even forcibly if needed. Then flag
  1062. // it as shutting down and restore the previous run state
  1063. // for serialization, so the scripts don't come back
  1064. // dead after region restart
  1065. //
  1066. bool prevRunning = i.Running;
  1067. i.Stop(50);
  1068. i.ShuttingDown = true;
  1069. i.Running = prevRunning;
  1070. }
  1071. DoBackup(new Object[] {0});
  1072. }
  1073. public IScriptApi GetApi(UUID itemID, string name)
  1074. {
  1075. IScriptInstance instance = GetInstance(itemID);
  1076. if (instance == null)
  1077. return null;
  1078. return instance.GetApi(name);
  1079. }
  1080. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  1081. {
  1082. IScriptInstance instance = GetInstance(itemID);
  1083. if (instance == null)
  1084. return;
  1085. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1086. if (eq == null)
  1087. {
  1088. controllingClient.SendScriptRunningReply(objectID, itemID,
  1089. GetScriptState(itemID));
  1090. }
  1091. else
  1092. {
  1093. eq.Enqueue(eq.ScriptRunningEvent(objectID, itemID, GetScriptState(itemID), true),
  1094. controllingClient.AgentId);
  1095. }
  1096. }
  1097. public string GetXMLState(UUID itemID)
  1098. {
  1099. // m_log.DebugFormat("[XEngine]: Getting XML state for {0}", itemID);
  1100. IScriptInstance instance = GetInstance(itemID);
  1101. if (instance == null)
  1102. {
  1103. // m_log.DebugFormat("[XEngine]: Found no script for {0}, returning empty string", itemID);
  1104. return "";
  1105. }
  1106. string xml = instance.GetXMLState();
  1107. XmlDocument sdoc = new XmlDocument();
  1108. bool loadedState = true;
  1109. try
  1110. {
  1111. sdoc.LoadXml(xml);
  1112. }
  1113. catch (System.Xml.XmlException)
  1114. {
  1115. loadedState = false;
  1116. }
  1117. XmlNodeList rootL = null;
  1118. XmlNode rootNode = null;
  1119. if (loadedState)
  1120. {
  1121. rootL = sdoc.GetElementsByTagName("ScriptState");
  1122. rootNode = rootL[0];
  1123. }
  1124. // Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
  1125. XmlDocument doc = new XmlDocument();
  1126. XmlElement stateData = doc.CreateElement("", "State", "");
  1127. XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
  1128. stateID.Value = itemID.ToString();
  1129. stateData.Attributes.Append(stateID);
  1130. XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
  1131. assetID.Value = instance.AssetID.ToString();
  1132. stateData.Attributes.Append(assetID);
  1133. XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
  1134. engineName.Value = ScriptEngineName;
  1135. stateData.Attributes.Append(engineName);
  1136. doc.AppendChild(stateData);
  1137. XmlNode xmlstate = null;
  1138. // Add <ScriptState>...</ScriptState>
  1139. if (loadedState)
  1140. {
  1141. xmlstate = doc.ImportNode(rootNode, true);
  1142. }
  1143. else
  1144. {
  1145. xmlstate = doc.CreateElement("", "ScriptState", "");
  1146. }
  1147. stateData.AppendChild(xmlstate);
  1148. string assemName = instance.GetAssemblyName();
  1149. string fn = Path.GetFileName(assemName);
  1150. string assem = String.Empty;
  1151. if (File.Exists(assemName + ".text"))
  1152. {
  1153. FileInfo tfi = new FileInfo(assemName + ".text");
  1154. if (tfi != null)
  1155. {
  1156. Byte[] tdata = new Byte[tfi.Length];
  1157. try
  1158. {
  1159. using (FileStream tfs = File.Open(assemName + ".text",
  1160. FileMode.Open, FileAccess.Read))
  1161. {
  1162. tfs.Read(tdata, 0, tdata.Length);
  1163. tfs.Close();
  1164. }
  1165. assem = new System.Text.ASCIIEncoding().GetString(tdata);
  1166. }
  1167. catch (Exception e)
  1168. {
  1169. m_log.DebugFormat("[XEngine]: Unable to open script textfile {0}, reason: {1}", assemName+".text", e.Message);
  1170. }
  1171. }
  1172. }
  1173. else
  1174. {
  1175. FileInfo fi = new FileInfo(assemName);
  1176. if (fi != null)
  1177. {
  1178. Byte[] data = new Byte[fi.Length];
  1179. try
  1180. {
  1181. using (FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read))
  1182. {
  1183. fs.Read(data, 0, data.Length);
  1184. fs.Close();
  1185. }
  1186. assem = System.Convert.ToBase64String(data);
  1187. }
  1188. catch (Exception e)
  1189. {
  1190. m_log.DebugFormat("[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
  1191. }
  1192. }
  1193. }
  1194. string map = String.Empty;
  1195. if (File.Exists(fn + ".map"))
  1196. {
  1197. using (FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read))
  1198. {
  1199. using (StreamReader msr = new StreamReader(mfs))
  1200. {
  1201. map = msr.ReadToEnd();
  1202. msr.Close();
  1203. }
  1204. mfs.Close();
  1205. }
  1206. }
  1207. XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
  1208. XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");
  1209. assemblyName.Value = fn;
  1210. assemblyData.Attributes.Append(assemblyName);
  1211. assemblyData.InnerText = assem;
  1212. stateData.AppendChild(assemblyData);
  1213. XmlElement mapData = doc.CreateElement("", "LineMap", "");
  1214. XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");
  1215. mapName.Value = fn + ".map";
  1216. mapData.Attributes.Append(mapName);
  1217. mapData.InnerText = map;
  1218. stateData.AppendChild(mapData);
  1219. // m_log.DebugFormat("[XEngine]: Got XML state for {0}", itemID);
  1220. return doc.InnerXml;
  1221. }
  1222. private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
  1223. {
  1224. return false;
  1225. }
  1226. public bool SetXMLState(UUID itemID, string xml)
  1227. {
  1228. if (xml == String.Empty)
  1229. return false;
  1230. XmlDocument doc = new XmlDocument();
  1231. try
  1232. {
  1233. doc.LoadXml(xml);
  1234. }
  1235. catch (Exception)
  1236. {
  1237. m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
  1238. return false;
  1239. }
  1240. XmlNodeList rootL = doc.GetElementsByTagName("State");
  1241. if (rootL.Count < 1)
  1242. return false;
  1243. XmlElement rootE = (XmlElement)rootL[0];
  1244. if (rootE.GetAttribute("Engine") != ScriptEngineName)
  1245. return false;
  1246. // On rez from inventory, that ID will have changed. It was only
  1247. // advisory anyway. So we don't check it anymore.
  1248. //
  1249. // if (rootE.GetAttribute("UUID") != itemID.ToString())
  1250. // return;
  1251. XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");
  1252. if (stateL.Count != 1)
  1253. return false;
  1254. XmlElement stateE = (XmlElement)stateL[0];
  1255. if (World.m_trustBinaries)
  1256. {
  1257. XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");
  1258. if (assemL.Count != 1)
  1259. return false;
  1260. XmlElement assemE = (XmlElement)assemL[0];
  1261. string fn = assemE.GetAttribute("Filename");
  1262. string base64 = assemE.InnerText;
  1263. string path = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1264. path = Path.Combine(path, fn);
  1265. if (!File.Exists(path))
  1266. {
  1267. Byte[] filedata = Convert.FromBase64String(base64);
  1268. try
  1269. {
  1270. using (FileStream fs = File.Create(path))
  1271. {
  1272. fs.Write(filedata, 0, filedata.Length);
  1273. fs.Close();
  1274. }
  1275. }
  1276. catch (IOException ex)
  1277. {
  1278. // if there already exists a file at that location, it may be locked.
  1279. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", path, ex.Message);
  1280. }
  1281. try
  1282. {
  1283. using (FileStream fs = File.Create(path + ".text"))
  1284. {
  1285. using (StreamWriter sw = new StreamWriter(fs))
  1286. {
  1287. sw.Write(base64);
  1288. sw.Close();
  1289. }
  1290. fs.Close();
  1291. }
  1292. }
  1293. catch (IOException ex)
  1294. {
  1295. // if there already exists a file at that location, it may be locked.
  1296. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", path, ex.Message);
  1297. }
  1298. }
  1299. }
  1300. string statepath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1301. statepath = Path.Combine(statepath, itemID.ToString() + ".state");
  1302. try
  1303. {
  1304. using (FileStream sfs = File.Create(statepath))
  1305. {
  1306. using (StreamWriter ssw = new StreamWriter(sfs))
  1307. {
  1308. ssw.Write(stateE.OuterXml);
  1309. ssw.Close();
  1310. }
  1311. sfs.Close();
  1312. }
  1313. }
  1314. catch (IOException ex)
  1315. {
  1316. // if there already exists a file at that location, it may be locked.
  1317. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", statepath, ex.Message);
  1318. }
  1319. XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
  1320. if (mapL.Count > 0)
  1321. {
  1322. XmlElement mapE = (XmlElement)mapL[0];
  1323. string mappath = Path.Combine(m_ScriptEnginesPath, World.RegionInfo.RegionID.ToString());
  1324. mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));
  1325. try
  1326. {
  1327. using (FileStream mfs = File.Create(mappath))
  1328. {
  1329. using (StreamWriter msw = new StreamWriter(mfs))
  1330. {
  1331. msw.Write(mapE.InnerText);
  1332. msw.Close();
  1333. }
  1334. mfs.Close();
  1335. }
  1336. }
  1337. catch (IOException ex)
  1338. {
  1339. // if there already exists a file at that location, it may be locked.
  1340. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", statepath, ex.Message);
  1341. }
  1342. }
  1343. return true;
  1344. }
  1345. public ArrayList GetScriptErrors(UUID itemID)
  1346. {
  1347. System.Threading.Thread.Sleep(1000);
  1348. lock (m_ScriptErrors)
  1349. {
  1350. if (m_ScriptErrors.ContainsKey(itemID))
  1351. {
  1352. ArrayList ret = m_ScriptErrors[itemID];
  1353. m_ScriptErrors.Remove(itemID);
  1354. return ret;
  1355. }
  1356. return new ArrayList();
  1357. }
  1358. }
  1359. public void SuspendScript(UUID itemID)
  1360. {
  1361. IScriptInstance instance = GetInstance(itemID);
  1362. if (instance == null)
  1363. return;
  1364. instance.Suspend();
  1365. }
  1366. public void ResumeScript(UUID itemID)
  1367. {
  1368. IScriptInstance instance = GetInstance(itemID);
  1369. if (instance == null)
  1370. return;
  1371. instance.Resume();
  1372. }
  1373. }
  1374. }