MRMModule.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. public static AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName)
  156. {
  157. if (permissionSetName == null)
  158. throw new ArgumentNullException("permissionSetName");
  159. if (permissionSetName.Length == 0)
  160. throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
  161. "Cannot have an empty permission set name");
  162. // Default to all code getting nothing
  163. PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
  164. UnionCodeGroup policyRoot = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);
  165. bool foundName = false;
  166. PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);
  167. // iterate over each policy level
  168. IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
  169. while (levelEnumerator.MoveNext())
  170. {
  171. PolicyLevel level = levelEnumerator.Current as PolicyLevel;
  172. // if this level has defined a named permission set with the
  173. // given name, then intersect it with what we've retrieved
  174. // from all the previous levels
  175. if (level != null)
  176. {
  177. PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
  178. if (levelSet != null)
  179. {
  180. foundName = true;
  181. if (setIntersection != null)
  182. setIntersection = setIntersection.Intersect(levelSet);
  183. }
  184. }
  185. }
  186. // Intersect() can return null for an empty set, so convert that
  187. // to an empty set object. Also return an empty set if we didn't find
  188. // the named permission set we were looking for
  189. if (setIntersection == null || !foundName)
  190. setIntersection = new PermissionSet(PermissionState.None);
  191. else
  192. setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);
  193. // if no named permission sets were found, return an empty set,
  194. // otherwise return the set that was found
  195. PolicyStatement permissions = new PolicyStatement(setIntersection);
  196. policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));
  197. // create an AppDomain policy level for the policy tree
  198. PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
  199. appDomainLevel.RootCodeGroup = policyRoot;
  200. // create an AppDomain where this policy will be in effect
  201. string domainName = appDomainName;
  202. AppDomain restrictedDomain = AppDomain.CreateDomain(domainName);
  203. restrictedDomain.SetAppDomainPolicy(appDomainLevel);
  204. return restrictedDomain;
  205. }
  206. void EventManager_OnRezScript(uint localID, UUID itemID, string script, int startParam, bool postOnRez, string engine, int stateSource)
  207. {
  208. if (script.StartsWith("//MRM:C#"))
  209. {
  210. if (m_config.GetBoolean("OwnerOnly", true))
  211. if (m_scene.GetSceneObjectPart(localID).OwnerID != m_scene.RegionInfo.EstateSettings.EstateOwner
  212. || m_scene.GetSceneObjectPart(localID).CreatorID != m_scene.RegionInfo.EstateSettings.EstateOwner)
  213. return;
  214. script = ConvertMRMKeywords(script);
  215. try
  216. {
  217. AppDomain target;
  218. if (m_config.GetBoolean("Sandboxed", true))
  219. {
  220. m_log.Info("[MRM] Found C# MRM - Starting in AppDomain with " +
  221. m_config.GetString("SandboxLevel", "Internet") + "-level security.");
  222. string domainName = UUID.Random().ToString();
  223. target = CreateRestrictedDomain(m_config.GetString("SandboxLevel", "Internet"),
  224. domainName);
  225. }
  226. else
  227. {
  228. m_log.Info("[MRM] Found C# MRM - Starting in current AppDomain");
  229. m_log.Warn(
  230. "[MRM] Security Risk: AppDomain is run in current context. Use only in trusted environments.");
  231. target = AppDomain.CurrentDomain;
  232. }
  233. m_log.Info("[MRM] Unwrapping into target AppDomain");
  234. MRMBase mmb = (MRMBase) target.CreateInstanceFromAndUnwrap(
  235. CompileFromDotNetText(script, itemID.ToString()),
  236. "OpenSim.MiniModule");
  237. m_log.Info("[MRM] Initialising MRM Globals");
  238. InitializeMRM(mmb, localID, itemID);
  239. m_scripts[itemID] = mmb;
  240. m_log.Info("[MRM] Starting MRM");
  241. mmb.Start();
  242. }
  243. catch (UnauthorizedAccessException e)
  244. {
  245. m_log.Error("[MRM] UAE " + e.Message);
  246. m_log.Error("[MRM] " + e.StackTrace);
  247. if (e.InnerException != null)
  248. m_log.Error("[MRM] " + e.InnerException);
  249. m_scene.ForEachClient(delegate(IClientAPI user)
  250. {
  251. user.SendAlertMessage(
  252. "MRM UnAuthorizedAccess: " + e);
  253. });
  254. }
  255. catch (Exception e)
  256. {
  257. m_log.Info("[MRM] Error: " + e);
  258. m_scene.ForEachClient(delegate(IClientAPI user)
  259. {
  260. user.SendAlertMessage(
  261. "Compile error while building MRM script, check OpenSim console for more information.");
  262. });
  263. }
  264. }
  265. }
  266. public void GetGlobalEnvironment(uint localID, out IWorld world, out IHost host)
  267. {
  268. // UUID should be changed to object owner.
  269. UUID owner = m_scene.RegionInfo.EstateSettings.EstateOwner;
  270. SEUser securityUser = new SEUser(owner, "Name Unassigned");
  271. SecurityCredential creds = new SecurityCredential(securityUser, m_scene);
  272. world = new World(m_scene, creds);
  273. host = new Host(new SOPObject(m_scene, localID, creds), m_scene, new ExtensionHandler(m_extensions),
  274. m_microthreads);
  275. }
  276. public void InitializeMRM(MRMBase mmb, uint localID, UUID itemID)
  277. {
  278. m_log.Info("[MRM] Created MRM Instance");
  279. IWorld world;
  280. IHost host;
  281. GetGlobalEnvironment(localID, out world, out host);
  282. mmb.InitMiniModule(world, host, itemID);
  283. }
  284. /// <summary>
  285. /// Stolen from ScriptEngine Common
  286. /// </summary>
  287. /// <param name="Script"></param>
  288. /// <param name="uuid">Unique ID for this module</param>
  289. /// <returns></returns>
  290. internal string CompileFromDotNetText(string Script, string uuid)
  291. {
  292. m_log.Info("MRM 1");
  293. const string ext = ".cs";
  294. const string FilePrefix = "MiniModule";
  295. // Output assembly name
  296. string OutFile = Path.Combine("MiniModules", Path.Combine(
  297. m_scene.RegionInfo.RegionID.ToString(),
  298. FilePrefix + "_compiled_" + uuid + "_" +
  299. Util.RandomClass.Next(9000) + ".dll"));
  300. // Create Directories for Assemblies
  301. if (!Directory.Exists("MiniModules"))
  302. Directory.CreateDirectory("MiniModules");
  303. string tmp = Path.Combine("MiniModules", m_scene.RegionInfo.RegionID.ToString());
  304. if (!Directory.Exists(tmp))
  305. Directory.CreateDirectory(tmp);
  306. m_log.Info("MRM 2");
  307. try
  308. {
  309. File.Delete(OutFile);
  310. }
  311. catch (UnauthorizedAccessException e)
  312. {
  313. throw new Exception("Unable to delete old existing " +
  314. "script-file before writing new. Compile aborted: " +
  315. e);
  316. }
  317. catch (IOException e)
  318. {
  319. throw new Exception("Unable to delete old existing " +
  320. "script-file before writing new. Compile aborted: " +
  321. e);
  322. }
  323. m_log.Info("MRM 3");
  324. // DEBUG - write source to disk
  325. string srcFileName = FilePrefix + "_source_" +
  326. Path.GetFileNameWithoutExtension(OutFile) + ext;
  327. try
  328. {
  329. File.WriteAllText(Path.Combine(Path.Combine(
  330. "MiniModules",
  331. m_scene.RegionInfo.RegionID.ToString()),
  332. srcFileName), Script);
  333. }
  334. catch (Exception ex) //NOTLEGIT - Should be just FileIOException
  335. {
  336. m_log.Error("[Compiler]: Exception while " +
  337. "trying to write script source to file \"" +
  338. srcFileName + "\": " + ex);
  339. }
  340. m_log.Info("MRM 4");
  341. // Do actual compile
  342. CompilerParameters parameters = new CompilerParameters();
  343. parameters.IncludeDebugInformation = true;
  344. string rootPath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
  345. List<string> libraries = new List<string>();
  346. string[] lines = Script.Split(new string[] {"\n"}, StringSplitOptions.RemoveEmptyEntries);
  347. foreach (string s in lines)
  348. {
  349. if (s.StartsWith("//@DEPENDS:"))
  350. {
  351. libraries.Add(s.Replace("//@DEPENDS:", ""));
  352. }
  353. }
  354. libraries.Add("OpenSim.Region.OptionalModules.dll");
  355. libraries.Add("OpenMetaverseTypes.dll");
  356. libraries.Add("log4net.dll");
  357. foreach (string library in libraries)
  358. {
  359. parameters.ReferencedAssemblies.Add(Path.Combine(rootPath, library));
  360. }
  361. parameters.GenerateExecutable = false;
  362. parameters.OutputAssembly = OutFile;
  363. parameters.IncludeDebugInformation = true;
  364. parameters.TreatWarningsAsErrors = false;
  365. m_log.Info("MRM 5");
  366. CompilerResults results = CScodeProvider.CompileAssemblyFromSource(
  367. parameters, Script);
  368. m_log.Info("MRM 6");
  369. int display = 5;
  370. if (results.Errors.Count > 0)
  371. {
  372. string errtext = String.Empty;
  373. foreach (CompilerError CompErr in results.Errors)
  374. {
  375. // Show 5 errors max
  376. //
  377. if (display <= 0)
  378. break;
  379. display--;
  380. string severity = "Error";
  381. if (CompErr.IsWarning)
  382. {
  383. severity = "Warning";
  384. }
  385. string text = CompErr.ErrorText;
  386. // The Second Life viewer's script editor begins
  387. // countingn lines and columns at 0, so we subtract 1.
  388. errtext += String.Format("Line ({0},{1}): {4} {2}: {3}\n",
  389. CompErr.Line - 1, CompErr.Column - 1,
  390. CompErr.ErrorNumber, text, severity);
  391. }
  392. if (!File.Exists(OutFile))
  393. {
  394. throw new Exception(errtext);
  395. }
  396. }
  397. m_log.Info("MRM 7");
  398. if (!File.Exists(OutFile))
  399. {
  400. string errtext = String.Empty;
  401. errtext += "No compile error. But not able to locate compiled file.";
  402. throw new Exception(errtext);
  403. }
  404. FileInfo fi = new FileInfo(OutFile);
  405. Byte[] data = new Byte[fi.Length];
  406. try
  407. {
  408. FileStream fs = File.Open(OutFile, FileMode.Open, FileAccess.Read);
  409. fs.Read(data, 0, data.Length);
  410. fs.Close();
  411. }
  412. catch (IOException)
  413. {
  414. string errtext = String.Empty;
  415. errtext += "No compile error. But not able to open file.";
  416. throw new Exception(errtext);
  417. }
  418. m_log.Info("MRM 8");
  419. // Convert to base64
  420. //
  421. string filetext = Convert.ToBase64String(data);
  422. Byte[] buf = Encoding.ASCII.GetBytes(filetext);
  423. m_log.Info("MRM 9");
  424. FileStream sfs = File.Create(OutFile + ".cil.b64");
  425. sfs.Write(buf, 0, buf.Length);
  426. sfs.Close();
  427. m_log.Info("MRM 10");
  428. return OutFile;
  429. }
  430. }
  431. }