* PermissionSet.cs: Added support for non-CAS permissions in the
[mono.git] / mcs / class / corlib / System.Security / PermissionSet.cs
1 //
2 // System.Security.PermissionSet.cs
3 //
4 // Authors:
5 //      Nick Drochak(ndrochak@gol.com)
6 //      Sebastien Pouliot  <sebastien@ximian.com>
7 //
8 // (C) Nick Drochak
9 // Portions (C) 2003, 2004 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.Collections;
33 using System.Diagnostics;
34 using System.IO;
35 using System.Reflection;
36 using System.Runtime.InteropServices;
37 using System.Runtime.Serialization;
38 using System.Runtime.Serialization.Formatters.Binary;
39 using System.Security.Permissions;
40 using System.Security.Policy;
41 using System.Text;
42 using System.Threading;
43
44 namespace System.Security {
45
46         [Serializable]
47         // Microsoft public key - i.e. only MS signed assembly can inherit from PermissionSet (1.x) or (2.0) FullTrust assemblies
48         [StrongNameIdentityPermission (SecurityAction.InheritanceDemand, PublicKey="002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293")]
49 #if NET_2_0
50         [ComVisible (true)]
51 #endif
52         public class PermissionSet: ISecurityEncodable, ICollection, IEnumerable, IStackWalk, IDeserializationCallback {
53
54                 private const string tagName = "PermissionSet";
55                 private const int version = 1;
56                 private static object[] psUnrestricted = new object [1] { PermissionState.Unrestricted };
57
58                 private PermissionState state;
59                 private ArrayList list;
60                 private int _hashcode;
61                 private PolicyLevel _policyLevel;
62                 private bool _declsec;
63                 private bool _readOnly;
64
65                 // constructors
66
67                 // for PolicyLevel (to avoid validation duplication)
68                 internal PermissionSet () 
69                 {
70                         list = new ArrayList ();
71                 }
72
73                 public PermissionSet (PermissionState state) : this ()
74                 {
75                         if (!Enum.IsDefined (typeof (PermissionState), state))
76                                 throw new System.ArgumentException ("state");
77                         this.state = state;
78                 }
79
80                 public PermissionSet (PermissionSet permSet) : this ()
81                 {
82                         // LAMESPEC: This would be handled by the compiler.  No way permSet is not a PermissionSet.
83                         //if (!(permSet is PermissionSet))
84                         //      throw new System.ArgumentException(); // permSet is not an instance of System.Security.PermissionSet.
85                         if (permSet != null) {
86                                 state = permSet.state;
87                                 foreach (IPermission p in permSet.list)
88                                         list.Add (p);
89                         }
90 #if !NET_2_0
91                         else {
92                                 state = PermissionState.Unrestricted;
93                         }
94 #endif
95                 }
96
97                 internal PermissionSet (string xml)
98                         : this ()
99                 {
100                         state = PermissionState.None;
101                         if (xml != null) {
102                                 SecurityElement se = SecurityElement.FromString (xml);
103                                 FromXml (se);
104                         }
105                 }
106
107                 // Light version for creating a (non unrestricted) PermissionSet with
108                 // a single permission. This allows to relax most validations.
109                 internal PermissionSet (IPermission perm)
110                         : this ()
111                 {
112                         if (perm != null) {
113                                 // note: we do not copy IPermission like AddPermission
114                                 list.Add (perm);
115                         }
116                 }
117
118                 // methods
119
120                 public virtual IPermission AddPermission (IPermission perm)
121                 {
122                         if ((perm == null) || _readOnly)
123                                 return perm;
124
125                         // we don't add to an unrestricted permission set unless...
126                         if (state == PermissionState.Unrestricted) {
127 #if NET_2_0
128                                 // identity permissions can be unrestricted under 2.x
129                                 {
130 #else
131                                 // we're adding identity permission as they don't support unrestricted
132                                 if (perm is IUnrestrictedPermission) {
133 #endif
134                                         // we return the union of the permission with unrestricted
135                                         // which results in a permission of the same type initialized 
136                                         // with PermissionState.Unrestricted
137                                         return (IPermission) Activator.CreateInstance (perm.GetType (), psUnrestricted);
138                                 }
139                         }
140
141                         // we can't add two permissions of the same type in a set
142                         // so we remove an existing one, union with it and add it back
143                         IPermission existing = RemovePermission (perm.GetType ());
144                         if (existing != null) {
145                                 perm = perm.Union (existing);
146                         }
147
148                         // note: Add doesn't copy
149                         list.Add (perm);
150                         return perm;
151                 }
152
153                 [MonoTODO ("Imperative mode isn't supported")]
154                 public virtual void Assert ()
155                 {
156                         new SecurityPermission (SecurityPermissionFlag.Assertion).Demand ();
157
158                         int count = this.Count;
159
160                         // we (current frame) must have the permission to assert it to others
161                         // otherwise we don't assert (but we don't throw an exception)
162                         foreach (IPermission p in list) {
163                                 // note: we ignore non-CAS permissions
164                                 if (p is IStackWalk) {
165                                         if (!SecurityManager.IsGranted (p)) {
166                                                 return;
167                                         }
168                                 } else
169                                         count--;
170                         }
171
172                         // note: we must ignore the stack modifiers for the non-CAS permissions
173                         if (SecurityManager.SecurityEnabled && (count > 0))
174                                 throw new NotSupportedException ("Currently only declarative Assert are supported.");
175                 }
176
177                 internal void Clear () 
178                 {
179                         list.Clear ();
180                 }
181
182                 public virtual PermissionSet Copy ()
183                 {
184                         return new PermissionSet (this);
185                 }
186
187                 public virtual void CopyTo (Array array, int index)
188                 {
189                         if (null == array)
190                                 throw new ArgumentNullException ("array");
191
192                         if (list.Count > 0) {
193                                 if (array.Rank > 1) {
194                                         throw new ArgumentException (Locale.GetText (
195                                                 "Array has more than one dimension"));
196                                 }
197                                 if (index < 0 || index >= array.Length) {
198                                         throw new IndexOutOfRangeException ("index");
199                                 }
200
201                                 list.CopyTo (array, index);
202                         }
203                 }
204
205                 [MonoTODO ("Imperative Assert, Deny and PermitOnly aren't yet supported")]
206                 public virtual void Demand ()
207                 {
208                         // Note: SecurityEnabled only applies to CAS permissions
209                         // so we're not checking for it (yet)
210                         if (IsEmpty ())
211                                 return;
212
213                         PermissionSet cas = this;
214                         // avoid copy (if possible)
215                         if (ContainsNonCodeAccessPermissions ()) {
216                                 // non CAS permissions (e.g. PrincipalPermission) do not requires a stack walk
217                                 cas = this.Copy ();
218                                 foreach (IPermission p in list) {
219                                         Type t = p.GetType ();
220                                         if (!t.IsSubclassOf (typeof (CodeAccessPermission))) {
221                                                 p.Demand ();
222                                                 // we wont have to process this one in the stack walk
223                                                 cas.RemovePermission (t);
224                                         }
225                                 }
226                         }
227
228                         // don't start the stack walk if
229                         // - the permission set only contains non CAS permissions; or
230                         // - security isn't enabled (applis only to CAS!)
231                         if (!cas.IsEmpty () && SecurityManager.SecurityEnabled)
232                                 CasOnlyDemand (_declsec ? 5 : 3);
233                 }
234
235                 // The number of frames to skip depends on who's calling
236                 // - CodeAccessPermission.Demand (imperative)
237                 // - PermissionSet.Demand (imperative)
238                 // - SecurityManager.InternalDemand (declarative)
239                 internal void CasOnlyDemand (int skip)
240                 {
241                         Assembly current = null;
242                         AppDomain domain = null;
243
244                         ArrayList frames = SecurityFrame.GetStack (skip);
245                         if ((frames != null) && (frames.Count > 0)) {
246                                 SecurityFrame first = ((SecurityFrame) frames [0]);
247                                 current = first.Assembly;
248                                 domain = first.Domain;
249                                 // skip ourself, Demand and other security runtime methods
250                                 foreach (SecurityFrame sf in frames) {
251                                         if (ProcessFrame (sf, ref current, ref domain))
252                                                 return; // reached Assert
253                                 }
254                                 SecurityFrame last = ((SecurityFrame) frames [frames.Count - 1]);
255                                 CheckAssembly (current, last);
256                                 CheckAppDomain (domain, last);
257                         }
258
259                         // Is there a CompressedStack to handle ?
260                         CompressedStack stack = Thread.CurrentThread.GetCompressedStack ();
261                         if ((stack != null) && !stack.IsEmpty ()) {
262                                 foreach (SecurityFrame frame in stack.List) {
263                                         if (ProcessFrame (frame, ref current, ref domain))
264                                                 return; // reached Assert
265                                 }
266                         }
267                 }
268
269                 [MonoTODO ("Imperative mode isn't supported")]
270                 public virtual void Deny ()
271                 {
272                         if (!SecurityManager.SecurityEnabled)
273                                 return;
274
275                         foreach (IPermission p in list) {
276                                 // note: we ignore non-CAS permissions
277                                 if (p is IStackWalk) {
278                                         throw new NotSupportedException ("Currently only declarative Deny are supported.");
279                                 }
280                         }
281                 }
282
283                 public virtual void FromXml (SecurityElement et)
284                 {
285                         if (et == null)
286                                 throw new ArgumentNullException ("et");
287                         if (et.Tag != tagName) {
288                                 string msg = String.Format ("Invalid tag {0} expected {1}", et.Tag, tagName);
289                                 throw new ArgumentException (msg, "et");
290                         }
291
292                         list.Clear ();
293
294                         if (CodeAccessPermission.IsUnrestricted (et)) {
295                                 state = PermissionState.Unrestricted;
296 #if NET_2_0
297                                 // no need to continue for an unrestricted permission
298                                 // because identity permissions now "supports" unrestricted
299                                 return;
300 #endif
301                         } else {
302                                 state = PermissionState.None;
303                         }
304
305                         if (et.Children != null) {
306                                 foreach (SecurityElement se in et.Children) {
307                                         string className = se.Attribute ("class");
308                                         if (className == null) {
309                                                 throw new ArgumentException (Locale.GetText (
310                                                         "No permission class is specified."));
311                                         }
312                                         if (Resolver != null) {
313                                                 // policy class names do not have to be fully qualified
314                                                 className = Resolver.ResolveClassName (className);
315                                         }
316
317                                         list.Add (PermissionBuilder.Create (className, se));
318                                 }
319                         }
320                 }
321
322                 public virtual IEnumerator GetEnumerator ()
323                 {
324                         return list.GetEnumerator ();
325                 }
326
327                 public virtual bool IsSubsetOf (PermissionSet target)
328                 {
329 #if NET_2_0
330                         // if target is empty we must be empty too
331                         if ((target == null) || (target.IsEmpty ()))
332                                 return this.IsEmpty ();
333
334                         // all permissions support unrestricted in 2.0
335                         if (target.IsUnrestricted ())
336                                 return true;
337                         if (this.IsUnrestricted ())
338                                 return false;
339 #endif
340                         if (this.IsUnrestricted () && ((target == null) || !target.IsUnrestricted ()))
341                                 return false;
342
343                         // if each of our permission is (a) present and (b) a subset of target
344                         foreach (IPermission p in list) {
345 #if !NET_2_0
346                                 if (target == null) {
347                                         if (!p.IsSubsetOf (null))
348                                                 return false;
349                                 } else
350 #endif
351                                 {
352                                         // non CAS permissions must be evaluated for unrestricted
353                                         Type t = p.GetType ();
354                                         IPermission i = null;
355                                         if (target.IsUnrestricted () && (p is CodeAccessPermission) && (p is IUnrestrictedPermission)) {
356                                                 i = (IPermission) Activator.CreateInstance (t, psUnrestricted);
357                                         } else {
358                                                 i = target.GetPermission (t);
359                                         }
360
361                                         if (!p.IsSubsetOf (i))
362                                                 return false; // not a subset (condition b)
363                                 }
364                         }
365                         return true;
366                 }
367
368                 [MonoTODO ("Imperative mode isn't supported")]
369                 public virtual void PermitOnly ()
370                 {
371                         if (!SecurityManager.SecurityEnabled)
372                                 return;
373
374                         foreach (IPermission p in list) {
375                                 // note: we ignore non-CAS permissions
376                                 if (p is IStackWalk) {
377                                         throw new NotSupportedException ("Currently only declarative Deny are supported.");
378                                 }
379                         }
380                 }
381
382                 public bool ContainsNonCodeAccessPermissions () 
383                 {
384                         foreach (IPermission p in list) {
385                                 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
386                                         return true;
387                         }
388                         return false;
389                 }
390
391                 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
392                 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat) 
393                 {
394                         if (inFormat == null)
395                                 throw new ArgumentNullException ("inFormat");
396                         if (outFormat == null)
397                                 throw new ArgumentNullException ("outFormat");
398                         if (inData == null)
399                                 return null;
400
401                         if (inFormat == outFormat)
402                                 return inData;
403
404                         PermissionSet ps = null;
405
406                         if (inFormat == "BINARY") {
407                                 if (outFormat.StartsWith ("XML")) {
408                                         using (MemoryStream ms = new MemoryStream (inData)) {
409                                                 BinaryFormatter formatter = new BinaryFormatter ();
410                                                 ps = (PermissionSet) formatter.Deserialize (ms);
411                                                 ms.Close ();
412                                         }
413                                         string xml = ps.ToString ();
414                                         switch (outFormat) {
415                                                 case "XML":
416                                                 case "XMLASCII":
417                                                         return Encoding.ASCII.GetBytes (xml);
418                                                 case "XMLUNICODE":
419                                                         return Encoding.Unicode.GetBytes (xml);
420                                         }
421                                 }
422                         }
423                         else if (inFormat.StartsWith ("XML")) {
424                                 if (outFormat == "BINARY") {
425                                         string xml = null;
426                                         switch (inFormat) {
427                                                 case "XML":
428                                                 case "XMLASCII":
429                                                         xml = Encoding.ASCII.GetString (inData);
430                                                         break;
431                                                 case "XMLUNICODE":
432                                                         xml = Encoding.Unicode.GetString (inData);
433                                                         break;
434                                         }
435                                         if (xml != null) {
436                                                 ps = new PermissionSet (PermissionState.None);
437                                                 ps.FromXml (SecurityElement.FromString (xml));
438
439                                                 MemoryStream ms = new MemoryStream ();
440                                                 BinaryFormatter formatter = new BinaryFormatter ();
441                                                 formatter.Serialize (ms, ps);
442                                                 ms.Close ();
443                                                 return ms.ToArray ();
444                                         }
445                                 }
446                                 else if (outFormat.StartsWith ("XML")) {
447                                         string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
448 #if NET_2_0
449                                         throw new XmlSyntaxException (msg);
450 #else
451                                         throw new ArgumentException (msg);
452 #endif
453                                 }
454                         }
455                         else {
456                                 // unknown inFormat, returns null
457                                 return null;
458                         }
459                         // unknown outFormat, throw
460                         throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
461                 }
462
463                 public virtual IPermission GetPermission (Type permClass) 
464                 {
465                         if ((permClass == null) || (list.Count == 0))
466                                 return null;
467
468                         foreach (object o in list) {
469                                 if ((o != null) && o.GetType ().Equals (permClass))
470                                         return (IPermission) o;
471                         }
472                         // it's normal to return null for unrestricted sets
473                         return null;
474                 }
475
476                 public virtual PermissionSet Intersect (PermissionSet other) 
477                 {
478                         // no intersection possible
479                         if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
480                                 return null;
481
482                         PermissionState state = PermissionState.None;
483                         if (this.IsUnrestricted () && other.IsUnrestricted ())
484                                 state = PermissionState.Unrestricted;
485
486                         PermissionSet interSet = new PermissionSet (state);
487                         if (state == PermissionState.Unrestricted) {
488                                 InternalIntersect (interSet, this, other, true);
489                                 InternalIntersect (interSet, other, this, true);
490                         }
491                         else if (this.IsUnrestricted ()) {
492                                 InternalIntersect (interSet, this, other, true);
493                         }
494                         else if (other.IsUnrestricted ()) {
495                                 InternalIntersect (interSet, other, this, true);
496                         }
497                         else {
498                                 InternalIntersect (interSet, this, other, false);
499                         }
500                         return interSet;
501                 }
502
503                 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
504                 {
505                         foreach (IPermission p in b.list) {
506                                 // for every type in both list
507                                 IPermission i = a.GetPermission (p.GetType ());
508                                 if (i != null) {
509                                         // add intersection for this type
510                                         intersect.AddPermission (p.Intersect (i));
511                                 }
512 #if NET_2_0
513                                 // unrestricted is possible for indentity permissions
514                                 else if (unrestricted) {
515 #else
516                                 else if (unrestricted && (p is IUnrestrictedPermission)) {
517 #endif
518                                         intersect.AddPermission (p);
519                                 }
520                                 // or reject!
521                         }
522                 }
523
524                 public virtual bool IsEmpty () 
525                 {
526                         // note: Unrestricted isn't empty
527                         if (state == PermissionState.Unrestricted)
528                                 return false;
529                         if ((list == null) || (list.Count == 0))
530                                 return true;
531                         // the set may include some empty permissions
532                         foreach (IPermission p in list) {
533                                 // empty == fully restricted == IsSubsetOf(null) == true
534                                 if (!p.IsSubsetOf (null))
535                                         return false;
536                         }
537                         return true;
538                 }
539
540                 public virtual bool IsUnrestricted () 
541                 {
542                         return (state == PermissionState.Unrestricted);
543                 }
544
545                 public virtual IPermission RemovePermission (Type permClass) 
546                 {
547                         if ((permClass == null) || _readOnly)
548                                 return null;
549
550                         foreach (object o in list) {
551                                 if (o.GetType ().Equals (permClass)) {
552                                         list.Remove (o);
553                                         return (IPermission) o;
554                                 }
555                         }
556                         return null;
557                 }
558
559                 public virtual IPermission SetPermission (IPermission perm) 
560                 {
561                         if ((perm == null) || _readOnly)
562                                 return perm;
563 #if NET_2_0
564                         IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
565                         if (u == null) {
566                                 state = PermissionState.None;
567                         } else {
568                                 state = u.IsUnrestricted () ? state : PermissionState.None;
569                         }
570 #else
571                         if (perm is IUnrestrictedPermission)
572                                 state = PermissionState.None;
573 #endif
574                         RemovePermission (perm.GetType ());
575                         list.Add (perm);
576                         return perm;
577                 }
578
579                 public override string ToString ()
580                 {
581                         return ToXml ().ToString ();
582                 }
583
584                 public virtual SecurityElement ToXml ()
585                 {
586                         SecurityElement se = new SecurityElement (tagName);
587                         se.AddAttribute ("class", GetType ().FullName);
588                         se.AddAttribute ("version", version.ToString ());
589                         if (state == PermissionState.Unrestricted)
590                                 se.AddAttribute ("Unrestricted", "true");
591
592                         // required for permissions that do not implement IUnrestrictedPermission
593                         foreach (IPermission p in list) {
594                                 se.AddChild (p.ToXml ());
595                         }
596                         return se;
597                 }
598
599                 public virtual PermissionSet Union (PermissionSet other)
600                 {
601                         if (other == null)
602                                 return this.Copy ();
603
604                         PermissionSet copy = this.Copy ();
605                         if (this.IsUnrestricted () || other.IsUnrestricted ()) {
606                                 // so we keep the "right" type
607                                 copy.Clear ();
608                                 copy.state = PermissionState.Unrestricted;
609                                 // copy all permissions that do not implement IUnrestrictedPermission
610                                 foreach (IPermission p in this.list) {
611                                         if (!(p is IUnrestrictedPermission))
612                                                 copy.AddPermission (p);
613                                 }
614                                 foreach (IPermission p in other.list) {
615                                         if (!(p is IUnrestrictedPermission))
616                                                 copy.AddPermission (p);
617                                 }
618                         }
619                         else {
620                                 // PermissionState.None -> copy all permissions
621                                 foreach (IPermission p in other.list) {
622                                         copy.AddPermission (p);
623                                 }
624                         }
625                         return copy;
626                 }
627
628                 public virtual int Count {
629                         get { return list.Count; }
630                 }
631
632                 public virtual bool IsSynchronized {
633                         get { return list.IsSynchronized; }
634                 }
635
636                 public virtual bool IsReadOnly {
637                         // always false (as documented) but the PermissionSet can be read-only
638                         // e.g. in a PolicyStatement
639                         get { return false; } 
640                 }
641
642                 public virtual object SyncRoot {
643                         get { return this; }
644                 }
645
646                 internal bool DeclarativeSecurity {
647                         get { return _declsec; }
648                         set { _declsec = value; }
649                 }
650
651                 [MonoTODO()]
652                 void IDeserializationCallback.OnDeserialization (object sender) 
653                 {
654                 }
655
656 #if NET_2_0
657                 [ComVisible (false)]
658                 public override bool Equals (object obj)
659                 {
660                         if (obj == null)
661                                 return false;
662                         PermissionSet ps = (obj as PermissionSet);
663                         if (ps == null)
664                                 return false;
665                         if (state != ps.state)
666                                 return false;
667                         if (list.Count != ps.Count)
668                                 return false;
669
670                         for (int i=0; i < list.Count; i++) {
671                                 bool found = false;
672                                 for (int j=0; i < ps.list.Count; j++) {
673                                         if (list [i].Equals (ps.list [j])) {
674                                                 found = true;
675                                                 break;
676                                         }
677                                 }
678                                 if (!found)
679                                         return false;
680                         }
681                         return true;
682                 }
683
684                 [ComVisible (false)]
685                 public override int GetHashCode ()
686                 {
687                         return (list.Count == 0) ? (int) state : base.GetHashCode ();
688                 }
689
690                 [MonoTODO ("what's it doing here?")]
691                 static public void RevertAssert ()
692                 {
693                         // FIXME: There's probably a reason this was added here ?
694                         CodeAccessPermission.RevertAssert ();
695                 }
696 #endif
697
698                 // internal
699
700                 internal PolicyLevel Resolver {
701                         get { return _policyLevel; }
702                         set { _policyLevel = value; }
703                 }
704
705                 internal void SetReadOnly (bool value)
706                 {
707                         _readOnly = value;
708                 }
709
710                 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
711                 {
712                         if (IsUnrestricted ()) {
713                                 // we request unrestricted
714                                 if (frame.Deny != null) {
715                                         // but have restrictions (some denied permissions)
716                                         CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
717                                 } else if (frame.PermitOnly != null) {
718                                         // but have restrictions (only some permitted permissions)
719                                         CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
720                                 }
721                         }
722
723                         // skip next steps if no Assert, Deny or PermitOnly are present
724                         if (frame.HasStackModifiers) {
725                                 foreach (CodeAccessPermission cap in list) {
726                                         if (cap.ProcessFrame (frame))
727                                                 return true; // Assert reached - abort stack walk!
728                                 }
729                         }
730
731                         // however the "final" grant set is resolved by assembly, so
732                         // there's no need to check it every time (just when we're 
733                         // changing assemblies between frames).
734                         if (frame.Assembly != current) {
735                                 CheckAssembly (current, frame);
736                                 current = frame.Assembly;
737                         }
738
739                         if (frame.Domain != domain) {
740                                 CheckAppDomain (domain, frame);
741                                 domain = frame.Domain;
742                         }
743
744                         return false;
745                 }
746
747                 internal void CheckAssembly (Assembly a, SecurityFrame frame)
748                 {
749                         IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
750                         if (p != null) {
751                                 CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
752                                         frame, SecurityAction.Demand, p);
753                         }
754                 }
755
756                 internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
757                 {
758                         IPermission p = SecurityManager.CheckPermissionSet (domain, this);
759                         if (p != null) {
760                                 CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
761                                         frame, SecurityAction.Demand, p);
762                         }
763                 }
764
765                 // 2.0 metadata format
766
767                 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
768                 {
769                         if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
770                                 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
771                                 throw new SecurityException (msg);
772                         }
773
774                         int pos = 1;
775                         int numattr = ReadEncodedInt (data, ref pos);
776                         PermissionSet ps = new PermissionSet (PermissionState.None);
777                         for (int i = 0; i < numattr; i++) {
778                                 IPermission p = ProcessAttribute (data, ref pos);
779                                 if (p == null) {
780                                         string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
781                                         throw new SecurityException (msg);
782                                 }
783                                 ps.AddPermission (p);
784                         }
785                         return ps;
786                 }
787
788                 internal static int ReadEncodedInt (byte[] data, ref int position)
789                 {
790                         int len = 0;
791                         if ((data [position] & 0x80) == 0) {
792                                 len = data [position];
793                                 position ++;
794                         } else if ((data [position] & 0x40) == 0) {
795                                 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
796                                 position += 2;
797                         } else {
798                                 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
799                                         (data [position + 2] << 8) | (data [position + 3]));
800                                 position += 4;
801                         }
802                         return len;
803                 }
804
805                 static object[] action = new object [1] { (SecurityAction) 0 };
806
807                 // TODO: add support for arrays and enums
808                 internal static IPermission ProcessAttribute (byte[] data, ref int position)
809                 {
810                         int clen = ReadEncodedInt (data, ref position);
811                         string cnam = Encoding.UTF8.GetString (data, position, clen);
812                         position += clen;
813
814                         // TODO: Unification
815                         Type secattr = Type.GetType (cnam);
816                         SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
817                         if (sa == null)
818                                 return null;
819
820                         /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
821                         int numberOfParameters = ReadEncodedInt (data, ref position);
822                         for (int j=0; j < numberOfParameters; j++) {
823                                 bool property = false;
824                                 switch (data [position++]) {
825                                 case 0x53: // field (technically possible and working)
826                                         property = false;
827                                         break;
828                                 case 0x54: // property (common case)
829                                         property = true;
830                                         break;
831                                 default:
832                                         return null;
833                                 }
834
835                                 bool array = false;
836                                 byte type = data [position++];
837                                 if (type == 0x1D) {
838                                         array = true;
839                                         type = data [position++];
840                                 }
841
842                                 int plen = ReadEncodedInt (data, ref position);
843                                 string pnam = Encoding.UTF8.GetString (data, position, plen);
844                                 position += plen;
845
846                                 int arrayLength = 1;
847                                 if (array) {
848                                         arrayLength = BitConverter.ToInt32 (data, position);
849                                         position += 4;
850                                 }
851
852                                 object obj = null;
853                                 object[] arrayIndex = null;
854                                 for (int i = 0; i < arrayLength; i++) {
855                                         if (array) {
856                                                 // TODO - setup index
857                                         }
858
859                                         // sadly type values doesn't match ther TypeCode enum :(
860                                         switch (type) {
861                                         case 0x02: // MONO_TYPE_BOOLEAN
862                                                 obj = (object) Convert.ToBoolean (data [position++]);
863                                                 break;
864                                         case 0x03: // MONO_TYPE_CHAR
865                                                 obj = (object) Convert.ToChar (data [position]);
866                                                 position += 2;
867                                                 break;
868                                         case 0x04: // MONO_TYPE_I1
869                                                 obj = (object) Convert.ToSByte (data [position++]);
870                                                 break;
871                                         case 0x05: // MONO_TYPE_U1
872                                                 obj = (object) Convert.ToByte (data [position++]);
873                                                 break;
874                                         case 0x06: // MONO_TYPE_I2
875                                                 obj = (object) Convert.ToInt16 (data [position]);
876                                                 position += 2;
877                                                 break;
878                                         case 0x07: // MONO_TYPE_U2
879                                                 obj = (object) Convert.ToUInt16 (data [position]);
880                                                 position += 2;
881                                                 break;
882                                         case 0x08: // MONO_TYPE_I4
883                                                 obj = (object) Convert.ToInt32 (data [position]);
884                                                 position += 4;
885                                                 break;
886                                         case 0x09: // MONO_TYPE_U4
887                                                 obj = (object) Convert.ToUInt32 (data [position]);
888                                                 position += 4;
889                                                 break;
890                                         case 0x0A: // MONO_TYPE_I8
891                                                 obj = (object) Convert.ToInt64 (data [position]);
892                                                 position += 8;
893                                                 break;
894                                         case 0x0B: // MONO_TYPE_U8
895                                                 obj = (object) Convert.ToUInt64 (data [position]);
896                                                 position += 8;
897                                                 break;
898                                         case 0x0C: // MONO_TYPE_R4
899                                                 obj = (object) Convert.ToSingle (data [position]);
900                                                 position += 4;
901                                                 break;
902                                         case 0x0D: // MONO_TYPE_R8
903                                                 obj = (object) Convert.ToDouble (data [position]);
904                                                 position += 8;
905                                                 break;
906                                         case 0x0E: // MONO_TYPE_STRING
907                                                 string s = null;
908                                                 if (data [position] != 0xFF) {
909                                                         int slen = ReadEncodedInt (data, ref position);
910                                                         s = Encoding.UTF8.GetString (data, position, slen);
911                                                         position += slen;
912                                                 } else {
913                                                         position++;
914                                                 }
915                                                 obj = (object) s;
916                                                 break;
917                                         case 0x50: // special for TYPE
918                                                 int tlen = ReadEncodedInt (data, ref position);
919                                                 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
920                                                 position += tlen;
921                                                 break;
922                                         default:
923                                                 return null; // unsupported
924                                         }
925
926                                         if (property) {
927                                                 PropertyInfo pi = secattr.GetProperty (pnam);
928                                                 pi.SetValue (sa, obj, arrayIndex);
929                                         } else {
930                                                 FieldInfo fi = secattr.GetField (pnam);
931                                                 fi.SetValue (sa, obj);
932                                         }
933                                 }
934                         }
935                         return sa.CreatePermission ();
936                 }
937         }
938 }