MRMModule.cs 20 KB

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