XEngine.cs 54 KB

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