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