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