MRMModule.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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.CodeDom.Compiler;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Diagnostics;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Security;
  35. using System.Security.Permissions;
  36. using System.Security.Policy;
  37. using System.Text;
  38. using log4net;
  39. using Microsoft.CSharp;
  40. using Nini.Config;
  41. using OpenMetaverse;
  42. using OpenSim.Framework;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. using Mono.Addins;
  46. namespace OpenSim.Region.OptionalModules.Scripting.Minimodule
  47. {
  48. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MRMModule")]
  49. public class MRMModule : INonSharedRegionModule, IMRMModule
  50. {
  51. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  52. private Scene m_scene;
  53. private bool m_Enabled;
  54. private bool m_Hidden;
  55. private readonly Dictionary<UUID,MRMBase> m_scripts = new Dictionary<UUID, MRMBase>();
  56. private readonly Dictionary<Type,object> m_extensions = new Dictionary<Type, object>();
  57. private static readonly CSharpCodeProvider CScodeProvider = new CSharpCodeProvider();
  58. private readonly MicroScheduler m_microthreads = new MicroScheduler();
  59. private IConfig m_config;
  60. public void RegisterExtension<T>(T instance)
  61. {
  62. m_extensions[typeof (T)] = instance;
  63. }
  64. #region INonSharedRegionModule
  65. public void Initialise(IConfigSource source)
  66. {
  67. if (source.Configs["MRM"] != null)
  68. {
  69. m_config = source.Configs["MRM"];
  70. if (source.Configs["MRM"].GetBoolean("Enabled", false))
  71. {
  72. m_log.Info("[MRM]: Enabling MRM Module");
  73. m_Enabled = true;
  74. m_Hidden = source.Configs["MRM"].GetBoolean("Hidden", false);
  75. }
  76. }
  77. }
  78. public void AddRegion(Scene scene)
  79. {
  80. if (!m_Enabled)
  81. return;
  82. m_scene = scene;
  83. // when hidden, we don't listen for client initiated script events
  84. // only making the MRM engine available for region modules
  85. if (!m_Hidden)
  86. {
  87. scene.EventManager.OnRezScript += EventManager_OnRezScript;
  88. scene.EventManager.OnStopScript += EventManager_OnStopScript;
  89. }
  90. scene.EventManager.OnFrame += EventManager_OnFrame;
  91. scene.RegisterModuleInterface<IMRMModule>(this);
  92. }
  93. public void RegionLoaded(Scene scene)
  94. {
  95. }
  96. public void RemoveRegion(Scene scene)
  97. {
  98. }
  99. public void Close()
  100. {
  101. foreach (KeyValuePair<UUID, MRMBase> pair in m_scripts)
  102. {
  103. pair.Value.Stop();
  104. }
  105. }
  106. public string Name
  107. {
  108. get { return "MiniRegionModule"; }
  109. }
  110. public Type ReplaceableInterface
  111. {
  112. get { return null; }
  113. }
  114. #endregion
  115. void EventManager_OnStopScript(uint localID, UUID itemID)
  116. {
  117. if (m_scripts.ContainsKey(itemID))
  118. {
  119. m_scripts[itemID].Stop();
  120. }
  121. }
  122. void EventManager_OnFrame()
  123. {
  124. m_microthreads.Tick(1000);
  125. }
  126. static string ConvertMRMKeywords(string script)
  127. {
  128. script = script.Replace("microthreaded void", "IEnumerable");
  129. script = script.Replace("relax;", "yield return null;");
  130. return script;
  131. }
  132. /// <summary>
  133. /// Create an AppDomain that contains policy restricting code to execute
  134. /// with only the permissions granted by a named permission set
  135. /// </summary>
  136. /// <param name="permissionSetName">name of the permission set to restrict to</param>
  137. /// <param name="appDomainName">'friendly' name of the appdomain to be created</param>
  138. /// <exception cref="ArgumentNullException">
  139. /// if <paramref name="permissionSetName"/> is null
  140. /// </exception>
  141. /// <exception cref="ArgumentOutOfRangeException">
  142. /// if <paramref name="permissionSetName"/> is empty
  143. /// </exception>
  144. /// <returns>AppDomain with a restricted security policy</returns>
  145. /// <remarks>Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
  146. /// Valid permissionSetName values are:
  147. /// * FullTrust
  148. /// * SkipVerification
  149. /// * Execution
  150. /// * Nothing
  151. /// * LocalIntranet
  152. /// * Internet
  153. /// * Everything
  154. /// </remarks>
  155. #pragma warning disable 0618
  156. public static AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName)
  157. {
  158. if (permissionSetName == null)
  159. throw new ArgumentNullException("permissionSetName");
  160. if (permissionSetName.Length == 0)
  161. throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
  162. "Cannot have an empty permission set name");
  163. // Default to all code getting nothing
  164. PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
  165. UnionCodeGroup policyRoot = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);
  166. bool foundName = false;
  167. PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);
  168. // iterate over each policy level
  169. IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
  170. while (levelEnumerator.MoveNext())
  171. {
  172. PolicyLevel level = levelEnumerator.Current as PolicyLevel;
  173. // if this level has defined a named permission set with the
  174. // given name, then intersect it with what we've retrieved
  175. // from all the previous levels
  176. if (level != null)
  177. {
  178. PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
  179. if (levelSet != null)
  180. {
  181. foundName = true;
  182. if (setIntersection != null)
  183. setIntersection = setIntersection.Intersect(levelSet);
  184. }
  185. }
  186. }
  187. // Intersect() can return null for an empty set, so convert that
  188. // to an empty set object. Also return an empty set if we didn't find
  189. // the named permission set we were looking for
  190. if (setIntersection == null || !foundName)
  191. setIntersection = new PermissionSet(PermissionState.None);
  192. else
  193. setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
  194. // if no named permission sets were found, return an empty set,
  195. // otherwise return the set that was found
  196. PolicyStatement permissions = new PolicyStatement(setIntersection);
  197. policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));
  198. // create an AppDomain policy level for the policy tree
  199. PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
  200. appDomainLevel.RootCodeGroup = policyRoot;
  201. // create an AppDomain where this policy will be in effect
  202. string domainName = appDomainName;
  203. AppDomain restrictedDomain = AppDomain.CreateDomain(domainName);
  204. restrictedDomain.SetAppDomainPolicy(appDomainLevel);
  205. return restrictedDomain;
  206. }
  207. #pragma warning restore 0618
  208. void EventManager_OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  209. {
  210. if (script.StartsWith("//MRM:C#"))
  211. {
  212. if (m_config.GetBoolean("OwnerOnly", true))
  213. if (m_scene.GetSceneObjectPart(localID).OwnerID != m_scene.RegionInfo.EstateSettings.EstateOwner
  214. || m_scene.GetSceneObjectPart(localID).CreatorID != m_scene.RegionInfo.EstateSettings.EstateOwner)
  215. return;
  216. script = ConvertMRMKeywords(script);
  217. try
  218. {
  219. AppDomain target;
  220. if (m_config.GetBoolean("Sandboxed", true))
  221. {
  222. m_log.Info("[MRM] Found C# MRM - Starting in AppDomain with " +
  223. m_config.GetString("SandboxLevel", "Internet") + "-level security.");
  224. string domainName = UUID.Random().ToString();
  225. target = CreateRestrictedDomain(m_config.GetString("SandboxLevel", "Internet"),
  226. domainName);
  227. }
  228. else
  229. {
  230. m_log.Info("[MRM] Found C# MRM - Starting in current AppDomain");
  231. m_log.Warn(
  232. "[MRM] Security Risk: AppDomain is run in current context. Use only in trusted environments.");
  233. target = AppDomain.CurrentDomain;
  234. }
  235. m_log.Info("[MRM] Unwrapping into target AppDomain");
  236. MRMBase mmb = (MRMBase) target.CreateInstanceFromAndUnwrap(
  237. CompileFromDotNetText(script, itemID.ToString()),
  238. "OpenSim.MiniModule");
  239. m_log.Info("[MRM] Initialising MRM Globals");
  240. InitializeMRM(mmb, localID, itemID);
  241. m_scripts[itemID] = mmb;
  242. m_log.Info("[MRM] Starting MRM");
  243. mmb.Start();
  244. }
  245. catch (UnauthorizedAccessException e)
  246. {
  247. m_log.Error("[MRM] UAE " + e.Message);
  248. m_log.Error("[MRM] " + e.StackTrace);
  249. if (e.InnerException != null)
  250. m_log.Error("[MRM] " + e.InnerException);
  251. m_scene.ForEachClient(delegate(IClientAPI user)
  252. {
  253. user.SendAlertMessage(
  254. "MRM UnAuthorizedAccess: " + e);
  255. });
  256. }
  257. catch (Exception e)
  258. {
  259. m_log.Info("[MRM] Error: " + e);
  260. m_scene.ForEachClient(delegate(IClientAPI user)
  261. {
  262. user.SendAlertMessage(
  263. "Compile error while building MRM script, check OpenSim console for more information.");
  264. });
  265. }
  266. }
  267. }
  268. public void GetGlobalEnvironment(uint localID, out IWorld world, out IHost host)
  269. {
  270. // UUID should be changed to object owner.
  271. UUID owner = m_scene.RegionInfo.EstateSettings.EstateOwner;
  272. SEUser securityUser = new SEUser(owner, "Name Unassigned");
  273. SecurityCredential creds = new SecurityCredential(securityUser, m_scene);
  274. world = new World(m_scene, creds);
  275. host = new Host(new SOPObject(m_scene, localID, creds), m_scene, new ExtensionHandler(m_extensions),
  276. m_microthreads);
  277. }
  278. public void InitializeMRM(MRMBase mmb, uint localID, UUID itemID)
  279. {
  280. m_log.Info("[MRM] Created MRM Instance");
  281. IWorld world;
  282. IHost host;
  283. GetGlobalEnvironment(localID, out world, out host);
  284. mmb.InitMiniModule(world, host, itemID);
  285. }
  286. /// <summary>
  287. /// Stolen from ScriptEngine Common
  288. /// </summary>
  289. /// <param name="Script"></param>
  290. /// <param name="uuid">Unique ID for this module</param>
  291. /// <returns></returns>
  292. internal string CompileFromDotNetText(string Script, string uuid)
  293. {
  294. m_log.Info("MRM 1");
  295. const string ext = ".cs";
  296. const string FilePrefix = "MiniModule";
  297. // Output assembly name
  298. string OutFile = Path.Combine("MiniModules", Path.Combine(
  299. m_scene.RegionInfo.RegionID.ToString(),
  300. FilePrefix + "_compiled_" + uuid + "_" +
  301. Util.RandomClass.Next(9000) + ".dll"));
  302. // Create Directories for Assemblies
  303. if (!Directory.Exists("MiniModules"))
  304. Directory.CreateDirectory("MiniModules");
  305. string tmp = Path.Combine("MiniModules", m_scene.RegionInfo.RegionID.ToString());
  306. if (!Directory.Exists(tmp))
  307. Directory.CreateDirectory(tmp);
  308. m_log.Info("MRM 2");
  309. try
  310. {
  311. File.Delete(OutFile);
  312. }
  313. catch (UnauthorizedAccessException e)
  314. {
  315. throw new Exception("Unable to delete old existing " +
  316. "script-file before writing new. Compile aborted: " +
  317. e);
  318. }
  319. catch (IOException e)
  320. {
  321. throw new Exception("Unable to delete old existing " +
  322. "script-file before writing new. Compile aborted: " +
  323. e);
  324. }
  325. m_log.Info("MRM 3");
  326. // DEBUG - write source to disk
  327. string srcFileName = FilePrefix + "_source_" +
  328. Path.GetFileNameWithoutExtension(OutFile) + ext;
  329. try
  330. {
  331. File.WriteAllText(Path.Combine(Path.Combine(
  332. "MiniModules",
  333. m_scene.RegionInfo.RegionID.ToString()),
  334. srcFileName), Script);
  335. }
  336. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  337. {
  338. m_log.Error("[Compiler]: Exception while " +
  339. "trying to write script source to file \"" +
  340. srcFileName + "\": " + ex);
  341. }
  342. m_log.Info("MRM 4");
  343. // Do actual compile
  344. CompilerParameters parameters = new CompilerParameters();
  345. parameters.IncludeDebugInformation = true;
  346. string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  347. List<string> libraries = new List<string>();
  348. string[] lines = Script.Split(new string[] {"\n"}, StringSplitOptions.RemoveEmptyEntries);
  349. foreach (string s in lines)
  350. {
  351. if (s.StartsWith("//@DEPENDS:"))
  352. {
  353. libraries.Add(s.Replace("//@DEPENDS:", ""));
  354. }
  355. }
  356. libraries.Add("OpenSim.Region.OptionalModules.dll");
  357. libraries.Add("OpenMetaverseTypes.dll");
  358. libraries.Add("log4net.dll");
  359. foreach (string library in libraries)
  360. {
  361. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, library));
  362. }
  363. parameters.GenerateExecutable = false;
  364. parameters.OutputAssembly = OutFile;
  365. parameters.IncludeDebugInformation = true;
  366. parameters.TreatWarningsAsErrors = false;
  367. m_log.Info("MRM 5");
  368. CompilerResults results = CScodeProvider.CompileAssemblyFromSource(
  369. parameters, Script);
  370. m_log.Info("MRM 6");
  371. int display = 5;
  372. if (results.Errors.Count > 0)
  373. {
  374. string errtext = String.Empty;
  375. foreach (CompilerError CompErr in results.Errors)
  376. {
  377. // Show 5 errors max
  378. //
  379. if (display <= 0)
  380. break;
  381. display--;
  382. string severity = "Error";
  383. if (CompErr.IsWarning)
  384. {
  385. severity = "Warning";
  386. }
  387. string text = CompErr.ErrorText;
  388. // The Second Life viewer's script editor begins
  389. // countingn lines and columns at 0, so we subtract 1.
  390. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
  391. CompErr.Line - 1, CompErr.Column - 1,
  392. CompErr.ErrorNumber, text, severity);
  393. }
  394. if (!File.Exists(OutFile))
  395. {
  396. throw new Exception(errtext);
  397. }
  398. }
  399. m_log.Info("MRM 7");
  400. if (!File.Exists(OutFile))
  401. {
  402. string errtext = String.Empty;
  403. errtext += "No compile error. But not able to locate compiled file.";
  404. throw new Exception(errtext);
  405. }
  406. FileInfo fi = new FileInfo(OutFile);
  407. Byte[] data = new Byte[fi.Length];
  408. try
  409. {
  410. FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
  411. fs.Read(data, 0, data.Length);
  412. fs.Close();
  413. }
  414. catch (IOException)
  415. {
  416. string errtext = String.Empty;
  417. errtext += "No compile error. But not able to open file.";
  418. throw new Exception(errtext);
  419. }
  420. m_log.Info("MRM 8");
  421. // Convert to base64
  422. //
  423. string filetext = Convert.ToBase64String(data);
  424. Byte[] buf = Encoding.ASCII.GetBytes(filetext);
  425. m_log.Info("MRM 9");
  426. FileStream sfs = File.Create(OutFile + ".cil.b64");
  427. sfs.Write(buf, 0, buf.Length);
  428. sfs.Close();
  429. m_log.Info("MRM 10");
  430. return OutFile;
  431. }
  432. }
  433. }