XEngine.cs 58 KB

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