XEngine.cs 58 KB

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