XEngine.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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. lock (m_Scripts)
  595. {
  596. ScriptInstance instance = null;
  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. lock (m_PrimObjects)
  667. {
  668. if (!m_PrimObjects.ContainsKey(localID))
  669. m_PrimObjects[localID] = new List<UUID>();
  670. if (!m_PrimObjects[localID].Contains(itemID))
  671. m_PrimObjects[localID].Add(itemID);
  672. }
  673. if (!m_Assemblies.ContainsKey(assetID))
  674. m_Assemblies[assetID] = assembly;
  675. lock (m_AddingAssemblies)
  676. {
  677. m_AddingAssemblies[assembly]--;
  678. }
  679. if (instance!=null)
  680. instance.Init();
  681. }
  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. lock (m_Scripts)
  693. {
  694. // Do we even have it?
  695. if (!m_Scripts.ContainsKey(itemID))
  696. return;
  697. IScriptInstance instance=m_Scripts[itemID];
  698. m_Scripts.Remove(itemID);
  699. instance.ClearQueue();
  700. instance.Stop(0);
  701. // bool objectRemoved = false;
  702. lock (m_PrimObjects)
  703. {
  704. // Remove the script from it's prim
  705. if (m_PrimObjects.ContainsKey(localID))
  706. {
  707. // Remove inventory item record
  708. if (m_PrimObjects[localID].Contains(itemID))
  709. m_PrimObjects[localID].Remove(itemID);
  710. // If there are no more scripts, remove prim
  711. if (m_PrimObjects[localID].Count == 0)
  712. {
  713. m_PrimObjects.Remove(localID);
  714. // objectRemoved = true;
  715. }
  716. }
  717. }
  718. instance.RemoveState();
  719. instance.DestroyScriptInstance();
  720. m_DomainScripts[instance.AppDomain].Remove(instance.ItemID);
  721. if (m_DomainScripts[instance.AppDomain].Count == 0)
  722. {
  723. m_DomainScripts.Remove(instance.AppDomain);
  724. UnloadAppDomain(instance.AppDomain);
  725. }
  726. instance = null;
  727. ObjectRemoved handlerObjectRemoved = OnObjectRemoved;
  728. if (handlerObjectRemoved != null)
  729. {
  730. SceneObjectPart part = m_Scene.GetSceneObjectPart(localID);
  731. handlerObjectRemoved(part.UUID);
  732. }
  733. CleanAssemblies();
  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. lock (m_PrimObjects)
  849. {
  850. if (!m_PrimObjects.ContainsKey(localID))
  851. return false;
  852. foreach (UUID itemID in m_PrimObjects[localID])
  853. {
  854. if (m_Scripts.ContainsKey(itemID))
  855. {
  856. IScriptInstance instance = m_Scripts[itemID];
  857. if (instance != null)
  858. {
  859. instance.PostEvent(p);
  860. result = true;
  861. }
  862. }
  863. }
  864. }
  865. return result;
  866. }
  867. /// <summary>
  868. /// Post an event to a single script
  869. /// </summary>
  870. /// <param name="itemID"></param>
  871. /// <param name="p"></param>
  872. /// <returns></returns>
  873. public bool PostScriptEvent(UUID itemID, EventParams p)
  874. {
  875. if (m_Scripts.ContainsKey(itemID))
  876. {
  877. IScriptInstance instance = m_Scripts[itemID];
  878. if (instance != null)
  879. instance.PostEvent(p);
  880. return true;
  881. }
  882. return false;
  883. }
  884. public bool PostScriptEvent(UUID itemID, string name, Object[] p)
  885. {
  886. Object[] lsl_p = new Object[p.Length];
  887. for (int i = 0; i < p.Length ; i++)
  888. {
  889. if (p[i] is int)
  890. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  891. else if (p[i] is string)
  892. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  893. else if (p[i] is Vector3)
  894. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  895. else if (p[i] is Quaternion)
  896. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  897. else if (p[i] is float)
  898. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  899. else
  900. lsl_p[i] = p[i];
  901. }
  902. return PostScriptEvent(itemID, new EventParams(name, lsl_p, new DetectParams[0]));
  903. }
  904. public bool PostObjectEvent(UUID itemID, string name, Object[] p)
  905. {
  906. SceneObjectPart part = m_Scene.GetSceneObjectPart(itemID);
  907. if (part == null)
  908. return false;
  909. Object[] lsl_p = new Object[p.Length];
  910. for (int i = 0; i < p.Length ; i++)
  911. {
  912. if (p[i] is int)
  913. lsl_p[i] = new LSL_Types.LSLInteger((int)p[i]);
  914. else if (p[i] is string)
  915. lsl_p[i] = new LSL_Types.LSLString((string)p[i]);
  916. else if (p[i] is Vector3)
  917. lsl_p[i] = new LSL_Types.Vector3(((Vector3)p[i]).X, ((Vector3)p[i]).Y, ((Vector3)p[i]).Z);
  918. else if (p[i] is Quaternion)
  919. lsl_p[i] = new LSL_Types.Quaternion(((Quaternion)p[i]).X, ((Quaternion)p[i]).Y, ((Quaternion)p[i]).Z, ((Quaternion)p[i]).W);
  920. else if (p[i] is float)
  921. lsl_p[i] = new LSL_Types.LSLFloat((float)p[i]);
  922. else
  923. lsl_p[i] = p[i];
  924. }
  925. return PostObjectEvent(part.LocalId, new EventParams(name, lsl_p, new DetectParams[0]));
  926. }
  927. public Assembly OnAssemblyResolve(object sender,
  928. ResolveEventArgs args)
  929. {
  930. if (!(sender is System.AppDomain))
  931. return null;
  932. string[] pathList = new string[] {"bin", "ScriptEngines",
  933. Path.Combine("ScriptEngines",
  934. m_Scene.RegionInfo.RegionID.ToString())};
  935. string assemblyName = args.Name;
  936. if (assemblyName.IndexOf(",") != -1)
  937. assemblyName = args.Name.Substring(0, args.Name.IndexOf(","));
  938. foreach (string s in pathList)
  939. {
  940. string path = Path.Combine(Directory.GetCurrentDirectory(),
  941. Path.Combine(s, assemblyName))+".dll";
  942. if (File.Exists(path))
  943. return Assembly.LoadFrom(path);
  944. }
  945. return null;
  946. }
  947. private IScriptInstance GetInstance(UUID itemID)
  948. {
  949. IScriptInstance instance;
  950. lock (m_Scripts)
  951. {
  952. if (!m_Scripts.ContainsKey(itemID))
  953. return null;
  954. instance = m_Scripts[itemID];
  955. }
  956. return instance;
  957. }
  958. public void SetScriptState(UUID itemID, bool running)
  959. {
  960. IScriptInstance instance = GetInstance(itemID);
  961. if (instance != null)
  962. {
  963. if (running)
  964. instance.Start();
  965. else
  966. instance.Stop(100);
  967. }
  968. }
  969. public bool GetScriptState(UUID itemID)
  970. {
  971. IScriptInstance instance = GetInstance(itemID);
  972. if (instance != null)
  973. return instance.Running;
  974. return false;
  975. }
  976. public void ApiResetScript(UUID itemID)
  977. {
  978. IScriptInstance instance = GetInstance(itemID);
  979. if (instance != null)
  980. instance.ApiResetScript();
  981. }
  982. public void ResetScript(UUID itemID)
  983. {
  984. IScriptInstance instance = GetInstance(itemID);
  985. if (instance != null)
  986. instance.ResetScript();
  987. }
  988. public void StartScript(UUID itemID)
  989. {
  990. IScriptInstance instance = GetInstance(itemID);
  991. if (instance != null)
  992. instance.Start();
  993. }
  994. public void StopScript(UUID itemID)
  995. {
  996. IScriptInstance instance = GetInstance(itemID);
  997. if (instance != null)
  998. instance.Stop(0);
  999. }
  1000. public DetectParams GetDetectParams(UUID itemID, int idx)
  1001. {
  1002. IScriptInstance instance = GetInstance(itemID);
  1003. if (instance != null)
  1004. return instance.GetDetectParams(idx);
  1005. return null;
  1006. }
  1007. public void SetMinEventDelay(UUID itemID, double delay)
  1008. {
  1009. IScriptInstance instance = GetInstance(itemID);
  1010. if (instance != null)
  1011. instance.MinEventDelay = delay;
  1012. }
  1013. public UUID GetDetectID(UUID itemID, int idx)
  1014. {
  1015. IScriptInstance instance = GetInstance(itemID);
  1016. if (instance != null)
  1017. return instance.GetDetectID(idx);
  1018. return UUID.Zero;
  1019. }
  1020. public void SetState(UUID itemID, string newState)
  1021. {
  1022. IScriptInstance instance = GetInstance(itemID);
  1023. if (instance == null)
  1024. return;
  1025. instance.SetState(newState);
  1026. }
  1027. public int GetStartParameter(UUID itemID)
  1028. {
  1029. IScriptInstance instance = GetInstance(itemID);
  1030. if (instance == null)
  1031. return 0;
  1032. return instance.StartParam;
  1033. }
  1034. public void OnShutdown()
  1035. {
  1036. List<IScriptInstance> instances = new List<IScriptInstance>();
  1037. lock (m_Scripts)
  1038. {
  1039. foreach (IScriptInstance instance in m_Scripts.Values)
  1040. instances.Add(instance);
  1041. }
  1042. foreach (IScriptInstance i in instances)
  1043. {
  1044. // Stop the script, even forcibly if needed. Then flag
  1045. // it as shutting down and restore the previous run state
  1046. // for serialization, so the scripts don't come back
  1047. // dead after region restart
  1048. //
  1049. bool prevRunning = i.Running;
  1050. i.Stop(50);
  1051. i.ShuttingDown = true;
  1052. i.Running = prevRunning;
  1053. }
  1054. DoBackup(new Object[] {0});
  1055. }
  1056. public IScriptApi GetApi(UUID itemID, string name)
  1057. {
  1058. IScriptInstance instance = GetInstance(itemID);
  1059. if (instance == null)
  1060. return null;
  1061. return instance.GetApi(name);
  1062. }
  1063. public void OnGetScriptRunning(IClientAPI controllingClient, UUID objectID, UUID itemID)
  1064. {
  1065. IScriptInstance instance = GetInstance(itemID);
  1066. if (instance == null)
  1067. return;
  1068. IEventQueue eq = World.RequestModuleInterface<IEventQueue>();
  1069. if (eq == null)
  1070. {
  1071. controllingClient.SendScriptRunningReply(objectID, itemID,
  1072. GetScriptState(itemID));
  1073. }
  1074. else
  1075. {
  1076. eq.Enqueue(EventQueueHelper.ScriptRunningReplyEvent(objectID, itemID, GetScriptState(itemID), true),
  1077. controllingClient.AgentId);
  1078. }
  1079. }
  1080. public string GetXMLState(UUID itemID)
  1081. {
  1082. IScriptInstance instance = GetInstance(itemID);
  1083. if (instance == null)
  1084. return "";
  1085. string xml = instance.GetXMLState();
  1086. XmlDocument sdoc = new XmlDocument();
  1087. bool loadedState = true;
  1088. try
  1089. {
  1090. sdoc.LoadXml(xml);
  1091. }
  1092. catch (System.Xml.XmlException e)
  1093. {
  1094. loadedState = false;
  1095. }
  1096. XmlNodeList rootL = null;
  1097. XmlNode rootNode = null;
  1098. if (loadedState)
  1099. {
  1100. rootL = sdoc.GetElementsByTagName("ScriptState");
  1101. rootNode = rootL[0];
  1102. }
  1103. // Create <State UUID="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx">
  1104. XmlDocument doc = new XmlDocument();
  1105. XmlElement stateData = doc.CreateElement("", "State", "");
  1106. XmlAttribute stateID = doc.CreateAttribute("", "UUID", "");
  1107. stateID.Value = itemID.ToString();
  1108. stateData.Attributes.Append(stateID);
  1109. XmlAttribute assetID = doc.CreateAttribute("", "Asset", "");
  1110. assetID.Value = instance.AssetID.ToString();
  1111. stateData.Attributes.Append(assetID);
  1112. XmlAttribute engineName = doc.CreateAttribute("", "Engine", "");
  1113. engineName.Value = ScriptEngineName;
  1114. stateData.Attributes.Append(engineName);
  1115. doc.AppendChild(stateData);
  1116. XmlNode xmlstate = null;
  1117. // Add <ScriptState>...</ScriptState>
  1118. if (loadedState)
  1119. {
  1120. xmlstate = doc.ImportNode(rootNode, true);
  1121. }
  1122. else
  1123. {
  1124. xmlstate = doc.CreateElement("", "ScriptState", "");
  1125. }
  1126. stateData.AppendChild(xmlstate);
  1127. string assemName = instance.GetAssemblyName();
  1128. string fn = Path.GetFileName(assemName);
  1129. string assem = String.Empty;
  1130. if (File.Exists(assemName + ".text"))
  1131. {
  1132. FileInfo tfi = new FileInfo(assemName + ".text");
  1133. if (tfi != null)
  1134. {
  1135. Byte[] tdata = new Byte[tfi.Length];
  1136. try
  1137. {
  1138. using (FileStream tfs = File.Open(assemName + ".text",
  1139. FileMode.Open, FileAccess.Read))
  1140. {
  1141. tfs.Read(tdata, 0, tdata.Length);
  1142. tfs.Close();
  1143. }
  1144. assem = new System.Text.ASCIIEncoding().GetString(tdata);
  1145. }
  1146. catch (Exception e)
  1147. {
  1148. m_log.DebugFormat("[XEngine]: Unable to open script textfile {0}, reason: {1}", assemName+".text", e.Message);
  1149. }
  1150. }
  1151. }
  1152. else
  1153. {
  1154. FileInfo fi = new FileInfo(assemName);
  1155. if (fi != null)
  1156. {
  1157. Byte[] data = new Byte[fi.Length];
  1158. try
  1159. {
  1160. using (FileStream fs = File.Open(assemName, FileMode.Open, FileAccess.Read))
  1161. {
  1162. fs.Read(data, 0, data.Length);
  1163. fs.Close();
  1164. }
  1165. assem = System.Convert.ToBase64String(data);
  1166. }
  1167. catch (Exception e)
  1168. {
  1169. m_log.DebugFormat("[XEngine]: Unable to open script assembly {0}, reason: {1}", assemName, e.Message);
  1170. }
  1171. }
  1172. }
  1173. string map = String.Empty;
  1174. if (File.Exists(fn + ".map"))
  1175. {
  1176. using (FileStream mfs = File.Open(fn + ".map", FileMode.Open, FileAccess.Read))
  1177. {
  1178. using (StreamReader msr = new StreamReader(mfs))
  1179. {
  1180. map = msr.ReadToEnd();
  1181. msr.Close();
  1182. }
  1183. mfs.Close();
  1184. }
  1185. }
  1186. XmlElement assemblyData = doc.CreateElement("", "Assembly", "");
  1187. XmlAttribute assemblyName = doc.CreateAttribute("", "Filename", "");
  1188. assemblyName.Value = fn;
  1189. assemblyData.Attributes.Append(assemblyName);
  1190. assemblyData.InnerText = assem;
  1191. stateData.AppendChild(assemblyData);
  1192. XmlElement mapData = doc.CreateElement("", "LineMap", "");
  1193. XmlAttribute mapName = doc.CreateAttribute("", "Filename", "");
  1194. mapName.Value = fn + ".map";
  1195. mapData.Attributes.Append(mapName);
  1196. mapData.InnerText = map;
  1197. stateData.AppendChild(mapData);
  1198. return doc.InnerXml;
  1199. }
  1200. private bool ShowScriptSaveResponse(UUID ownerID, UUID assetID, string text, bool compiled)
  1201. {
  1202. return false;
  1203. }
  1204. public bool SetXMLState(UUID itemID, string xml)
  1205. {
  1206. if (xml == String.Empty)
  1207. return false;
  1208. XmlDocument doc = new XmlDocument();
  1209. try
  1210. {
  1211. doc.LoadXml(xml);
  1212. }
  1213. catch (Exception)
  1214. {
  1215. m_log.Error("[XEngine]: Exception decoding XML data from region transfer");
  1216. return false;
  1217. }
  1218. XmlNodeList rootL = doc.GetElementsByTagName("State");
  1219. if (rootL.Count < 1)
  1220. return false;
  1221. XmlElement rootE = (XmlElement)rootL[0];
  1222. if (rootE.GetAttribute("Engine") != ScriptEngineName)
  1223. return false;
  1224. // On rez from inventory, that ID will have changed. It was only
  1225. // advisory anyway. So we don't check it anymore.
  1226. //
  1227. // if (rootE.GetAttribute("UUID") != itemID.ToString())
  1228. // return;
  1229. XmlNodeList stateL = rootE.GetElementsByTagName("ScriptState");
  1230. if (stateL.Count != 1)
  1231. return false;
  1232. XmlElement stateE = (XmlElement)stateL[0];
  1233. if (World.m_trustBinaries)
  1234. {
  1235. XmlNodeList assemL = rootE.GetElementsByTagName("Assembly");
  1236. if (assemL.Count != 1)
  1237. return false;
  1238. XmlElement assemE = (XmlElement)assemL[0];
  1239. string fn = assemE.GetAttribute("Filename");
  1240. string base64 = assemE.InnerText;
  1241. string path = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
  1242. path = Path.Combine(path, fn);
  1243. if (!File.Exists(path))
  1244. {
  1245. Byte[] filedata = Convert.FromBase64String(base64);
  1246. try
  1247. {
  1248. using (FileStream fs = File.Create(path))
  1249. {
  1250. fs.Write(filedata, 0, filedata.Length);
  1251. fs.Close();
  1252. }
  1253. }
  1254. catch (IOException ex)
  1255. {
  1256. // if there already exists a file at that location, it may be locked.
  1257. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", path, ex.Message);
  1258. }
  1259. try
  1260. {
  1261. using (FileStream fs = File.Create(path + ".text"))
  1262. {
  1263. using (StreamWriter sw = new StreamWriter(fs))
  1264. {
  1265. sw.Write(base64);
  1266. sw.Close();
  1267. }
  1268. fs.Close();
  1269. }
  1270. }
  1271. catch (IOException ex)
  1272. {
  1273. // if there already exists a file at that location, it may be locked.
  1274. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", path, ex.Message);
  1275. }
  1276. }
  1277. }
  1278. string statepath = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
  1279. statepath = Path.Combine(statepath, itemID.ToString() + ".state");
  1280. try
  1281. {
  1282. using (FileStream sfs = File.Create(statepath))
  1283. {
  1284. using (StreamWriter ssw = new StreamWriter(sfs))
  1285. {
  1286. ssw.Write(stateE.OuterXml);
  1287. ssw.Close();
  1288. }
  1289. sfs.Close();
  1290. }
  1291. }
  1292. catch (IOException ex)
  1293. {
  1294. // if there already exists a file at that location, it may be locked.
  1295. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", statepath, ex.Message);
  1296. }
  1297. XmlNodeList mapL = rootE.GetElementsByTagName("LineMap");
  1298. if (mapL.Count > 0)
  1299. {
  1300. XmlElement mapE = (XmlElement)mapL[0];
  1301. string mappath = Path.Combine("ScriptEngines", World.RegionInfo.RegionID.ToString());
  1302. mappath = Path.Combine(mappath, mapE.GetAttribute("Filename"));
  1303. try
  1304. {
  1305. using (FileStream mfs = File.Create(mappath))
  1306. {
  1307. using (StreamWriter msw = new StreamWriter(mfs))
  1308. {
  1309. msw.Write(mapE.InnerText);
  1310. msw.Close();
  1311. }
  1312. mfs.Close();
  1313. }
  1314. }
  1315. catch (IOException ex)
  1316. {
  1317. // if there already exists a file at that location, it may be locked.
  1318. m_log.ErrorFormat("[XEngine]: File {0} already exists! {1}", statepath, ex.Message);
  1319. }
  1320. }
  1321. return true;
  1322. }
  1323. public ArrayList GetScriptErrors(UUID itemID)
  1324. {
  1325. System.Threading.Thread.Sleep(1000);
  1326. lock (m_ScriptErrors)
  1327. {
  1328. if (m_ScriptErrors.ContainsKey(itemID))
  1329. {
  1330. ArrayList ret = m_ScriptErrors[itemID];
  1331. m_ScriptErrors.Remove(itemID);
  1332. return ret;
  1333. }
  1334. return new ArrayList();
  1335. }
  1336. }
  1337. public void SuspendScript(UUID itemID)
  1338. {
  1339. IScriptInstance instance = GetInstance(itemID);
  1340. if (instance == null)
  1341. return;
  1342. instance.Suspend();
  1343. }
  1344. public void ResumeScript(UUID itemID)
  1345. {
  1346. IScriptInstance instance = GetInstance(itemID);
  1347. if (instance == null)
  1348. return;
  1349. instance.Resume();
  1350. }
  1351. }
  1352. }