2009-06-30 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mcs / class / corlib / System.Security / PermissionSet.cs
index cc567ebf4120c85ff0cd15eaa125169dc99bab26..1ac01aefc570a1b0c17db5df6ffc48336567945d 100644 (file)
@@ -7,7 +7,7 @@
 //
 // (C) Nick Drochak
 // Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
-// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
+// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the
@@ -33,25 +33,35 @@ using System.Collections;
 using System.Diagnostics;
 using System.IO;
 using System.Reflection;
+using System.Runtime.InteropServices;
 using System.Runtime.Serialization;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.Security.Permissions;
 using System.Security.Policy;
 using System.Text;
+using System.Threading;
 
 namespace System.Security {
 
        [Serializable]
+       // Microsoft public key - i.e. only MS signed assembly can inherit from PermissionSet (1.x) or (2.0) FullTrust assemblies
+       [StrongNameIdentityPermission (SecurityAction.InheritanceDemand, PublicKey="002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
+#if NET_2_0
+       [ComVisible (true)]
+#endif
+       [MonoTODO ("CAS support is experimental (and unsupported).")]
        public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
 
-               private static string tagName = "PermissionSet";
+               private const string tagName = "PermissionSet";
                private const int version = 1;
-               private static object[] psNone = new object [1] { PermissionState.None };
+               private static object[] psUnrestricted = new object [1] { PermissionState.Unrestricted };
 
                private PermissionState state;
                private ArrayList list;
-               private int _hashcode;
                private PolicyLevel _policyLevel;
+               private bool _declsec;
+               private bool _readOnly;
+               private bool[] _ignored; // for asserts and non-CAS permissions
 
                // constructors
 
@@ -63,9 +73,7 @@ namespace System.Security {
 
                public PermissionSet (PermissionState state) : this ()
                {
-                       if (!Enum.IsDefined (typeof (PermissionState), state))
-                               throw new System.ArgumentException ("state");
-                       this.state = state;
+                       this.state = CodeAccessPermission.CheckPermissionState (state, true);
                }
 
                public PermissionSet (PermissionSet permSet) : this ()
@@ -73,13 +81,16 @@ namespace System.Security {
                        // LAMESPEC: This would be handled by the compiler.  No way permSet is not a PermissionSet.
                        //if (!(permSet is PermissionSet))
                        //      throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
-                       if (permSet == null)
-                               state = PermissionState.Unrestricted;
-                       else {
+                       if (permSet != null) {
                                state = permSet.state;
                                foreach (IPermission p in permSet.list)
                                        list.Add (p);
                        }
+#if !NET_2_0
+                       else {
+                               state = PermissionState.Unrestricted;
+                       }
+#endif
                }
 
                internal PermissionSet (string xml)
@@ -92,22 +103,41 @@ namespace System.Security {
                        }
                }
 
+               // Light version for creating a (non unrestricted) PermissionSet with
+               // a single permission. This allows to relax most validations.
+               internal PermissionSet (IPermission perm)
+                       : this ()
+               {
+                       if (perm != null) {
+                               // note: we do not copy IPermission like AddPermission
+                               list.Add (perm);
+                       }
+               }
+
                // methods
 
+#if NET_2_0
+               public IPermission AddPermission (IPermission perm)
+#else
                public virtual IPermission AddPermission (IPermission perm)
+#endif
                {
-                       if (perm == null)
-                               return null;
+                       if ((perm == null) || _readOnly)
+                               return perm;
 
                        // we don't add to an unrestricted permission set unless...
                        if (state == PermissionState.Unrestricted) {
+#if NET_2_0
+                               // identity permissions can be unrestricted under 2.x
+                               {
+#else
                                // we're adding identity permission as they don't support unrestricted
                                if (perm is IUnrestrictedPermission) {
+#endif
                                        // we return the union of the permission with unrestricted
                                        // which results in a permission of the same type initialized 
                                        // with PermissionState.Unrestricted
-                                       object[] args = new object [1] { PermissionState.Unrestricted };
-                                       return (IPermission) Activator.CreateInstance (perm.GetType (), args);
+                                       return (IPermission) Activator.CreateInstance (perm.GetType (), psUnrestricted);
                                }
                        }
 
@@ -118,14 +148,20 @@ namespace System.Security {
                                perm = perm.Union (existing);
                        }
 
+                       // note: Add doesn't copy
                        list.Add (perm);
                        return perm;
                }
 
-               [MonoTODO ("unmanaged side is incomplete")]
+               [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
+               [SecurityPermission (SecurityAction.Demand, Assertion = true)]
+#if NET_2_0
+               public void Assert ()
+#else
                public virtual void Assert ()
+#endif
                {
-                       new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
+                       int count = this.Count;
 
                        // we (current frame) must have the permission to assert it to others
                        // otherwise we don't assert (but we don't throw an exception)
@@ -135,10 +171,13 @@ namespace System.Security {
                                        if (!SecurityManager.IsGranted (p)) {
                                                return;
                                        }
-                               }
+                               } else
+                                       count--;
                        }
 
-                       CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.Assert, this.Copy ());
+                       // note: we must ignore the stack modifiers for the non-CAS permissions
+                       if (SecurityManager.SecurityEnabled && (count > 0))
+                               throw new NotSupportedException ("Currently only declarative Assert are supported.");
                }
 
                internal void Clear () 
@@ -169,48 +208,104 @@ namespace System.Security {
                        }
                }
 
-               [MonoTODO ("Assert, Deny and PermitOnly aren't yet supported")]
+#if NET_2_0
+               public void Demand ()
+#else
                public virtual void Demand ()
+#endif
                {
+                       // Note: SecurityEnabled only applies to CAS permissions
+                       // so we're not checking for it (yet)
                        if (IsEmpty ())
                                return;
 
-                       PermissionSet cas = this;
-                       // avoid copy (if possible)
-                       if (ContainsNonCodeAccessPermissions ()) {
-                               // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
-                               cas = this.Copy ();
-                               foreach (IPermission p in list) {
-                                       Type t = p.GetType ();
-                                       if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
-                                               p.Demand ();
-                                               // we wont have to process this one in the stack walk
-                                               cas.RemovePermission (t);
-                                       }
+                       int n = list.Count;
+                       if ((_ignored == null) || (_ignored.Length != n)) {
+                               _ignored = new bool [n];
+                       }
+
+                       bool call_cas_only = this.IsUnrestricted ();
+                       // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
+                       for (int i = 0; i < n; i++) {
+                               IPermission p = (IPermission) list [i];
+                               Type t = p.GetType ();
+                               if (t.IsSubclassOf (typeof (CodeAccessPermission))) {
+                                       _ignored [i] = false;
+                                       call_cas_only = true;
+                               } else {
+                                       _ignored [i] = true;
+                                       p.Demand ();
                                }
+                       }
+
+                       // don't start the stack walk if
+                       // - the permission set only contains non CAS permissions; or
+                       // - security isn't enabled (applis only to CAS!)
+                       if (call_cas_only && SecurityManager.SecurityEnabled)
+                               CasOnlyDemand (_declsec ? 5 : 3);
+               }
 
-                               // don't start the walk if the permission set only contains non CAS permissions
-                               if (cas.Count == 0)
-                                       return;
+               // The number of frames to skip depends on who's calling
+               // - CodeAccessPermission.Demand (imperative)
+               // - PermissionSet.Demand (imperative)
+               // - SecurityManager.InternalDemand (declarative)
+               internal void CasOnlyDemand (int skip)
+               {
+                       Assembly current = null;
+                       AppDomain domain = null;
+
+                       if (_ignored == null) {
+                               // special case when directly called from CodeAccessPermission.Demand
+                               _ignored = new bool [list.Count];
                        }
 
-                       // Note: SecurityEnabled only applies to CAS permissions
-                       if (!SecurityManager.SecurityEnabled)
-                               return;
+                       ArrayList frames = SecurityFrame.GetStack (skip);
+                       if ((frames != null) && (frames.Count > 0)) {
+                               SecurityFrame first = ((SecurityFrame) frames [0]);
+                               current = first.Assembly;
+                               domain = first.Domain;
+                               // skip ourself, Demand and other security runtime methods
+                               foreach (SecurityFrame sf in frames) {
+                                       if (ProcessFrame (sf, ref current, ref domain)) {
+                                               if (AllIgnored ())
+                                                       return; // reached Assert
+                                       }
+                               }
+                               SecurityFrame last = ((SecurityFrame) frames [frames.Count - 1]);
+                               CheckAssembly (current, last);
+                               CheckAppDomain (domain, last);
+                       }
 
-                       // FIXME: optimize
-                       foreach (IPermission p in cas.list) {
-                               p.Demand ();
+                       // Is there a CompressedStack to handle ?
+                       CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
+                       if ((stack != null) && !stack.IsEmpty ()) {
+                               foreach (SecurityFrame frame in stack.List) {
+                                       if (ProcessFrame (frame, ref current, ref domain)) {
+                                               if (AllIgnored ())
+                                                       return; // reached Assert
+                                       }
+                               }
                        }
                }
 
-               [MonoTODO ("unmanaged side is incomplete")]
+               [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
+#if NET_2_0
+               public void Deny ()
+#else
                public virtual void Deny ()
+#endif
                {
-                       CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.Deny, this.Copy ());
+                       if (!SecurityManager.SecurityEnabled)
+                               return;
+
+                       foreach (IPermission p in list) {
+                               // note: we ignore non-CAS permissions
+                               if (p is IStackWalk) {
+                                       throw new NotSupportedException ("Currently only declarative Deny are supported.");
+                               }
+                       }
                }
 
-               [MonoTODO ("adjust class version with current runtime - unification")]
                public virtual void FromXml (SecurityElement et)
                {
                        if (et == null)
@@ -220,12 +315,19 @@ namespace System.Security {
                                throw new ArgumentException (msg, "et");
                        }
 
-                       if (CodeAccessPermission.IsUnrestricted (et))
+                       list.Clear ();
+
+                       if (CodeAccessPermission.IsUnrestricted (et)) {
                                state = PermissionState.Unrestricted;
-                       else
+#if NET_2_0
+                               // no need to continue for an unrestricted permission
+                               // because identity permissions now "supports" unrestricted
+                               return;
+#endif
+                       } else {
                                state = PermissionState.None;
+                       }
 
-                       list.Clear ();
                        if (et.Children != null) {
                                foreach (SecurityElement se in et.Children) {
                                        string className = se.Attribute ("class");
@@ -237,73 +339,95 @@ namespace System.Security {
                                                // policy class names do not have to be fully qualified
                                                className = Resolver.ResolveClassName (className);
                                        }
-                                       // TODO: adjust class version with current runtime (unification)
-                                       // http://blogs.msdn.com/shawnfa/archive/2004/08/05/209320.aspx
-                                       Type classType = Type.GetType (className);
-                                       if (classType != null) {
-                                               IPermission p = (IPermission) Activator.CreateInstance (classType, psNone);
-                                               p.FromXml (se);
-                                               list.Add (p);
-                                       }
-#if !NET_2_0
-                                       else {
-                                               string msg = Locale.GetText ("Can't create an instance of permission class {0}.");
-                                               throw new ArgumentException (String.Format (msg, se.Attribute ("class")));
-                                       }
-#endif
+
+                                       list.Add (PermissionBuilder.Create (className, se));
                                }
                        }
                }
 
+#if NET_2_0
+               public IEnumerator GetEnumerator ()
+#else
                public virtual IEnumerator GetEnumerator ()
+#endif
                {
                        return list.GetEnumerator ();
                }
 
-               public virtual bool IsSubsetOf (PermissionSet target)
+#if NET_2_0
+               public bool IsSubsetOf (PermissionSet target)
                {
                        // if target is empty we must be empty too
                        if ((target == null) || (target.IsEmpty ()))
                                return this.IsEmpty ();
 
-                       // TODO - non CAS permissions must be evaluated for unrestricted
-
-                       // if target is unrestricted then we are a subset
-                       if (!this.IsUnrestricted () && target.IsUnrestricted ())
+                       // all permissions support unrestricted in 2.0
+                       if (target.IsUnrestricted ())
                                return true;
-                       // else target isn't unrestricted.
-                       // so if we are unrestricted, the we can't be a subset
-                       if (this.IsUnrestricted () && !target.IsUnrestricted ())
+                       if (this.IsUnrestricted ())
+                               return false;
+#else
+               public virtual bool IsSubsetOf (PermissionSet target)
+               {
+#endif
+                       if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
                                return false;
 
                        // if each of our permission is (a) present and (b) a subset of target
                        foreach (IPermission p in list) {
-                               // for every type in both list
-                               IPermission i = target.GetPermission (p.GetType ());
-                               if (i == null)
-                                       return false; // not present (condition a)
-                               if (!p.IsSubsetOf (i))
-                                       return false; // not a subset (condition b)
+#if !NET_2_0
+                               if (target == null) {
+                                       if (!p.IsSubsetOf (null))
+                                               return false;
+                               } else
+#endif
+                               {
+                                       // non CAS permissions must be evaluated for unrestricted
+                                       Type t = p.GetType ();
+                                       IPermission i = null;
+                                       if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
+                                               i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
+                                       } else {
+                                               i = target.GetPermission (t);
+                                       }
+
+                                       if (!p.IsSubsetOf (i))
+                                               return false; // not a subset (condition b)
+                               }
                        }
                        return true;
                }
 
-               [MonoTODO ("unmanaged side is incomplete")]
+               [MonoTODO ("CAS support is experimental (and unsupported). Imperative mode is not implemented.")]
+#if NET_2_0
+               public void PermitOnly ()
+#else
                public virtual void PermitOnly ()
+#endif
                {
-                       CodeAccessPermission.SetCurrentFrame (CodeAccessPermission.StackModifier.PermitOnly, this.Copy ());
+                       if (!SecurityManager.SecurityEnabled)
+                               return;
+
+                       foreach (IPermission p in list) {
+                               // note: we ignore non-CAS permissions
+                               if (p is IStackWalk) {
+                                       throw new NotSupportedException ("Currently only declarative Deny are supported.");
+                               }
+                       }
                }
 
                public bool ContainsNonCodeAccessPermissions () 
                {
-                       foreach (IPermission p in list) {
-                               if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
-                                       return true;
+                       if (list.Count > 0) {
+                               foreach (IPermission p in list) {
+                                       if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
+                                               return true;
+                               }
                        }
                        return false;
                }
 
-               [MonoTODO ("little documentation in Fx 2.0 beta 1")]
+               // FIXME little documentation in Fx 2.0 beta 1
                public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat) 
                {
                        if (inFormat == null)
@@ -375,17 +499,28 @@ namespace System.Security {
                        throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
                }
 
-               public virtual IPermission GetPermission (Type permClass) 
+#if NET_2_0
+               public IPermission GetPermission (Type permClass)
+#else
+               public virtual IPermission GetPermission (Type permClass)
+#endif
                {
+                       if ((permClass == null) || (list.Count == 0))
+                               return null;
+
                        foreach (object o in list) {
-                               if (o.GetType ().Equals (permClass))
+                               if ((o != null) && o.GetType ().Equals (permClass))
                                        return (IPermission) o;
                        }
                        // it's normal to return null for unrestricted sets
                        return null;
                }
 
-               public virtual PermissionSet Intersect (PermissionSet other) 
+#if NET_2_0
+               public PermissionSet Intersect (PermissionSet other)
+#else
+               public virtual PermissionSet Intersect (PermissionSet other)
+#endif
                {
                        // no intersection possible
                        if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
@@ -395,20 +530,32 @@ namespace System.Security {
                        if (this.IsUnrestricted () && other.IsUnrestricted ())
                                state = PermissionState.Unrestricted;
 
-                       PermissionSet interSet = new PermissionSet (state);
+                       PermissionSet interSet = null;
+#if NET_2_0
+                       // much simpler with 2.0
+                       if (state == PermissionState.Unrestricted) {
+                               interSet = new PermissionSet (state);
+                       } else if (this.IsUnrestricted ()) {
+                               interSet = other.Copy ();
+                       } else if (other.IsUnrestricted ()) {
+                               interSet = this.Copy ();
+                       } else {
+                               interSet = new PermissionSet (state);
+                               InternalIntersect (interSet, this, other, false);
+                       }
+#else
+                       interSet = new PermissionSet (state);
                        if (state == PermissionState.Unrestricted) {
                                InternalIntersect (interSet, this, other, true);
                                InternalIntersect (interSet, other, this, true);
-                       }
-                       else if (this.IsUnrestricted ()) {
+                       } else if (this.IsUnrestricted ()) {
                                InternalIntersect (interSet, this, other, true);
-                       }
-                       else if (other.IsUnrestricted ()) {
+                       } else if (other.IsUnrestricted ()) {
                                InternalIntersect (interSet, other, this, true);
-                       }
-                       else {
+                       } else {
                                InternalIntersect (interSet, this, other, false);
                        }
+#endif
                        return interSet;
                }
 
@@ -421,14 +568,23 @@ namespace System.Security {
                                        // add intersection for this type
                                        intersect.AddPermission (p.Intersect (i));
                                }
+#if NET_2_0
+                               // unrestricted is possible for indentity permissions
+                               else if (unrestricted) {
+#else
                                else if (unrestricted && (p is IUnrestrictedPermission)) {
+#endif
                                        intersect.AddPermission (p);
                                }
                                // or reject!
                        }
                }
 
-               public virtual bool IsEmpty () 
+#if NET_2_0
+               public bool IsEmpty ()
+#else
+               public virtual bool IsEmpty ()
+#endif
                {
                        // note: Unrestricted isn't empty
                        if (state == PermissionState.Unrestricted)
@@ -437,21 +593,29 @@ namespace System.Security {
                                return true;
                        // the set may include some empty permissions
                        foreach (IPermission p in list) {
-                               // empty == fully restricted == IsSubsetOg(null) == true
+                               // empty == fully restricted == IsSubsetOf(null) == true
                                if (!p.IsSubsetOf (null))
                                        return false;
                        }
                        return true;
                }
 
-               public virtual bool IsUnrestricted () 
+#if NET_2_0
+               public bool IsUnrestricted ()
+#else
+               public virtual bool IsUnrestricted ()
+#endif
                {
                        return (state == PermissionState.Unrestricted);
                }
 
-               public virtual IPermission RemovePermission (Type permClass) 
+#if NET_2_0
+               public IPermission RemovePermission (Type permClass)
+#else
+               public virtual IPermission RemovePermission (Type permClass)
+#endif
                {
-                       if (permClass == null)
+                       if ((permClass == null) || _readOnly)
                                return null;
 
                        foreach (object o in list) {
@@ -463,12 +627,25 @@ namespace System.Security {
                        return null;
                }
 
-               public virtual IPermission SetPermission (IPermission perm) 
+#if NET_2_0
+               public IPermission SetPermission (IPermission perm)
+#else
+               public virtual IPermission SetPermission (IPermission perm)
+#endif
                {
-                       if (perm == null)
-                               return null;
+                       if ((perm == null) || _readOnly)
+                               return perm;
+#if NET_2_0
+                       IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
+                       if (u == null) {
+                               state = PermissionState.None;
+                       } else {
+                               state = u.IsUnrestricted () ? state : PermissionState.None;
+                       }
+#else
                        if (perm is IUnrestrictedPermission)
                                state = PermissionState.None;
+#endif
                        RemovePermission (perm.GetType ());
                        list.Add (perm);
                        return perm;
@@ -494,14 +671,23 @@ namespace System.Security {
                        return se;
                }
 
+#if NET_2_0
+               public PermissionSet Union (PermissionSet other)
+#else
                public virtual PermissionSet Union (PermissionSet other)
+#endif
                {
                        if (other == null)
                                return this.Copy ();
 
-                       PermissionSet copy = this.Copy ();
+                       PermissionSet copy = null;
                        if (this.IsUnrestricted () || other.IsUnrestricted ()) {
-                               // so we keep the "right" type
+#if NET_2_0
+                               // there are no child elements in unrestricted permission sets
+                               return new PermissionSet (PermissionState.Unrestricted);
+#else
+                               copy = this.Copy ();
+                               // so we keep the "right" type (e.g. NamedPermissionSet)
                                copy.Clear ();
                                copy.state = PermissionState.Unrestricted;
                                // copy all permissions that do not implement IUnrestrictedPermission
@@ -513,8 +699,9 @@ namespace System.Security {
                                        if (!(p is IUnrestrictedPermission))
                                                copy.AddPermission (p);
                                }
-                       }
-                       else {
+#endif
+                       } else {
+                               copy = this.Copy ();
                                // PermissionState.None -> copy all permissions
                                foreach (IPermission p in other.list) {
                                        copy.AddPermission (p);
@@ -532,19 +719,27 @@ namespace System.Security {
                }
 
                public virtual bool IsReadOnly {
-                       get { return false; } // always false
+                       // always false (as documented) but the PermissionSet can be read-only
+                       // e.g. in a PolicyStatement
+                       get { return false; } 
                }
 
                public virtual object SyncRoot {
                        get { return this; }
                }
 
-               [MonoTODO()]
+               internal bool DeclarativeSecurity {
+                       get { return _declsec; }
+                       set { _declsec = value; }
+               }
+
+               [MonoTODO ("may not be required")]
                void IDeserializationCallback.OnDeserialization (object sender) 
                {
                }
 
 #if NET_2_0
+               [ComVisible (false)]
                public override bool Equals (object obj)
                {
                        if (obj == null)
@@ -552,6 +747,8 @@ namespace System.Security {
                        PermissionSet ps = (obj as PermissionSet);
                        if (ps == null)
                                return false;
+                       if (state != ps.state)
+                               return false;
                        if (list.Count != ps.Count)
                                return false;
 
@@ -569,23 +766,16 @@ namespace System.Security {
                        return true;
                }
 
+               [ComVisible (false)]
                public override int GetHashCode ()
                {
-                       if (list.Count == 0)
-                               return (int) state;
-
-                       if (_hashcode == 0) {
-                               _hashcode = state.GetHashCode ();
-                               foreach (IPermission p in list) {
-                                       _hashcode ^= p.GetHashCode ();
-                               }
-                       }
-                       return _hashcode;
+                       return (list.Count == 0) ? (int) state : base.GetHashCode ();
                }
 
-               [MonoTODO ("what's it doing here?")]
+               // FIXME what's it doing here? There's probably a reason this was added here.
                static public void RevertAssert ()
                {
+                       CodeAccessPermission.RevertAssert ();
                }
 #endif
 
@@ -596,35 +786,253 @@ namespace System.Security {
                        set { _policyLevel = value; }
                }
 
+               internal void SetReadOnly (bool value)
+               {
+                       _readOnly = value;
+               }
 
-               internal void ImmediateCallerDemand ()
+               private bool AllIgnored ()
                {
-                       if (!SecurityManager.SecurityEnabled)
-                               return;
-                       if (IsEmpty ())
-                               return;
+                       if (_ignored == null)
+                               throw new NotSupportedException ("bad bad bad");
 
-                       StackTrace st = new StackTrace (1); // skip ourself
-                       StackFrame sf = st.GetFrame (0);
-                       MethodBase mb = sf.GetMethod ();
-                       Assembly af = mb.ReflectedType.Assembly;
-                       if (!af.Demand (this)) {
-                               Type t = this.GetType ();
-                               // TODO add more details
-                               throw new SecurityException ("LinkDemand failed", t);
+                       for (int i=0; i < _ignored.Length; i++) {
+                               if (!_ignored [i])
+                                       return false;
                        }
+                       // everything is ignored (i.e. non-CAS permission or asserted permission).
+                       return true;
                }
 
-               // Note: Non-CAS demands aren't affected by SecurityManager.SecurityEnabled
-               internal void ImmediateCallerNonCasDemand ()
+               internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
                {
-                       if (IsEmpty ())
-                               return;
+                       if (IsUnrestricted ()) {
+                               // we request unrestricted
+                               if (frame.Deny != null) {
+                                       // but have restrictions (some denied permissions)
+                                       CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
+                               } else if ((frame.PermitOnly != null) && !frame.PermitOnly.IsUnrestricted ()) {
+                                       // but have restrictions (only some permitted permissions)
+                                       CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
+                               }
+                       }
 
-                       // non CAS permissions (e.g. PrincipalPermission) requires direct call to Demand
-                       foreach (IPermission p in list) {
-                               p.Demand ();
+                       // skip next steps if no Assert, Deny or PermitOnly are present
+                       if (frame.HasStackModifiers) {
+                               for (int i = 0; i < list.Count; i++) {
+                                       CodeAccessPermission cap = (CodeAccessPermission) list [i];
+                                       if (cap.ProcessFrame (frame)) {
+                                               _ignored [i] = true; // asserted
+                                               if (AllIgnored ())
+                                                       return true; // no more, abort stack walk!
+                                       }
+                               }
+                       }
+
+                       // however the "final" grant set is resolved by assembly, so
+                       // there's no need to check it every time (just when we're 
+                       // changing assemblies between frames).
+                       if (frame.Assembly != current) {
+                               CheckAssembly (current, frame);
+                               current = frame.Assembly;
+                       }
+
+                       if (frame.Domain != domain) {
+                               CheckAppDomain (domain, frame);
+                               domain = frame.Domain;
+                       }
+
+                       return false;
+               }
+
+               internal void CheckAssembly (Assembly a, SecurityFrame frame)
+               {
+                       IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
+                       if (p != null) {
+                               CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
+                                       frame, SecurityAction.Demand, p);
+                       }
+               }
+
+               internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
+               {
+                       IPermission p = SecurityManager.CheckPermissionSet (domain, this);
+                       if (p != null) {
+                               CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
+                                       frame, SecurityAction.Demand, p);
+                       }
+               }
+
+               // 2.0 metadata format
+
+               internal static PermissionSet CreateFromBinaryFormat (byte[] data)
+               {
+                       if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
+                               string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
+                               throw new SecurityException (msg);
+                       }
+
+                       int pos = 1;
+                       int numattr = ReadEncodedInt (data, ref pos);
+                       PermissionSet ps = new PermissionSet (PermissionState.None);
+                       for (int i = 0; i < numattr; i++) {
+                               IPermission p = ProcessAttribute (data, ref pos);
+                               if (p == null) {
+                                       string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
+                                       throw new SecurityException (msg);
+                               }
+                               ps.AddPermission (p);
+                       }
+                       return ps;
+               }
+
+               internal static int ReadEncodedInt (byte[] data, ref int position)
+               {
+                       int len = 0;
+                       if ((data [position] & 0x80) == 0) {
+                               len = data [position];
+                               position ++;
+                       } else if ((data [position] & 0x40) == 0) {
+                               len = ((data [position] & 0x3f) << 8 | data [position + 1]);
+                               position += 2;
+                       } else {
+                               len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
+                                       (data [position + 2] << 8) | (data [position + 3]));
+                               position += 4;
+                       }
+                       return len;
+               }
+
+               static object[] action = new object [1] { (SecurityAction) 0 };
+
+               // TODO: add support for arrays and enums (2.0)
+               internal static IPermission ProcessAttribute (byte[] data, ref int position)
+               {
+                       int clen = ReadEncodedInt (data, ref position);
+                       string cnam = Encoding.UTF8.GetString (data, position, clen);
+                       position += clen;
+
+                       Type secattr = Type.GetType (cnam);
+                       SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
+                       if (sa == null)
+                               return null;
+
+                       /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
+                       int numberOfParameters = ReadEncodedInt (data, ref position);
+                       for (int j=0; j < numberOfParameters; j++) {
+                               bool property = false;
+                               switch (data [position++]) {
+                               case 0x53: // field (technically possible and working)
+                                       property = false;
+                                       break;
+                               case 0x54: // property (common case)
+                                       property = true;
+                                       break;
+                               default:
+                                       return null;
+                               }
+
+                               bool array = false;
+                               byte type = data [position++];
+                               if (type == 0x1D) {
+                                       array = true;
+                                       type = data [position++];
+                               }
+
+                               int plen = ReadEncodedInt (data, ref position);
+                               string pnam = Encoding.UTF8.GetString (data, position, plen);
+                               position += plen;
+
+                               int arrayLength = 1;
+                               if (array) {
+                                       arrayLength = BitConverter.ToInt32 (data, position);
+                                       position += 4;
+                               }
+
+                               object obj = null;
+                               object[] arrayIndex = null;
+                               for (int i = 0; i < arrayLength; i++) {
+                                       if (array) {
+                                               // TODO - setup index (2.0)
+                                       }
+
+                                       // sadly type values doesn't match ther TypeCode enum :(
+                                       switch (type) {
+                                       case 0x02: // MONO_TYPE_BOOLEAN
+                                               obj = (object) Convert.ToBoolean (data [position++]);
+                                               break;
+                                       case 0x03: // MONO_TYPE_CHAR
+                                               obj = (object) Convert.ToChar (data [position]);
+                                               position += 2;
+                                               break;
+                                       case 0x04: // MONO_TYPE_I1
+                                               obj = (object) Convert.ToSByte (data [position++]);
+                                               break;
+                                       case 0x05: // MONO_TYPE_U1
+                                               obj = (object) Convert.ToByte (data [position++]);
+                                               break;
+                                       case 0x06: // MONO_TYPE_I2
+                                               obj = (object) Convert.ToInt16 (data [position]);
+                                               position += 2;
+                                               break;
+                                       case 0x07: // MONO_TYPE_U2
+                                               obj = (object) Convert.ToUInt16 (data [position]);
+                                               position += 2;
+                                               break;
+                                       case 0x08: // MONO_TYPE_I4
+                                               obj = (object) Convert.ToInt32 (data [position]);
+                                               position += 4;
+                                               break;
+                                       case 0x09: // MONO_TYPE_U4
+                                               obj = (object) Convert.ToUInt32 (data [position]);
+                                               position += 4;
+                                               break;
+                                       case 0x0A: // MONO_TYPE_I8
+                                               obj = (object) Convert.ToInt64 (data [position]);
+                                               position += 8;
+                                               break;
+                                       case 0x0B: // MONO_TYPE_U8
+                                               obj = (object) Convert.ToUInt64 (data [position]);
+                                               position += 8;
+                                               break;
+                                       case 0x0C: // MONO_TYPE_R4
+                                               obj = (object) Convert.ToSingle (data [position]);
+                                               position += 4;
+                                               break;
+                                       case 0x0D: // MONO_TYPE_R8
+                                               obj = (object) Convert.ToDouble (data [position]);
+                                               position += 8;
+                                               break;
+                                       case 0x0E: // MONO_TYPE_STRING
+                                               string s = null;
+                                               if (data [position] != 0xFF) {
+                                                       int slen = ReadEncodedInt (data, ref position);
+                                                       s = Encoding.UTF8.GetString (data, position, slen);
+                                                       position += slen;
+                                               } else {
+                                                       position++;
+                                               }
+                                               obj = (object) s;
+                                               break;
+                                       case 0x50: // special for TYPE
+                                               int tlen = ReadEncodedInt (data, ref position);
+                                               obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
+                                               position += tlen;
+                                               break;
+                                       default:
+                                               return null; // unsupported
+                                       }
+
+                                       if (property) {
+                                               PropertyInfo pi = secattr.GetProperty (pnam);
+                                               pi.SetValue (sa, obj, arrayIndex);
+                                       } else {
+                                               FieldInfo fi = secattr.GetField (pnam);
+                                               fi.SetValue (sa, obj);
+                                       }
+                               }
                        }
+                       return sa.CreatePermission ();
                }
        }
 }