XEngine.cs 58 KB

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