2005-06-14 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 #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 target is empty we must be empty too
330                         if ((target == null) || (target.IsEmpty ()))
331                                 return this.IsEmpty ();
332
333                         // TODO - non CAS permissions must be evaluated for unrestricted
334
335                         // if target is unrestricted then we are a subset
336                         if (!this.IsUnrestricted () && target.IsUnrestricted ())
337                                 return true;
338                         // else target isn't unrestricted.
339                         // so if we are unrestricted, the we can't be a subset
340                         if (this.IsUnrestricted () && !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                                 // for every type in both list
346                                 IPermission i = target.GetPermission (p.GetType ());
347                                 if (i == null)
348                                         return false; // not present (condition a)
349                                 if (!p.IsSubsetOf (i))
350                                         return false; // not a subset (condition b)
351                         }
352                         return true;
353                 }
354
355                 [MonoTODO ("Imperative mode isn't supported")]
356                 public virtual void PermitOnly ()
357                 {
358                         if (!SecurityManager.SecurityEnabled)
359                                 return;
360
361                         foreach (IPermission p in list) {
362                                 // note: we ignore non-CAS permissions
363                                 if (p is IStackWalk) {
364                                         throw new NotSupportedException ("Currently only declarative Deny are supported.");
365                                 }
366                         }
367                 }
368
369                 public bool ContainsNonCodeAccessPermissions () 
370                 {
371                         foreach (IPermission p in list) {
372                                 if (! p.GetType ().IsSubclassOf (typeof (CodeAccessPermission)))
373                                         return true;
374                         }
375                         return false;
376                 }
377
378                 [MonoTODO ("little documentation in Fx 2.0 beta 1")]
379                 public static byte[] ConvertPermissionSet (string inFormat, byte[] inData, string outFormat) 
380                 {
381                         if (inFormat == null)
382                                 throw new ArgumentNullException ("inFormat");
383                         if (outFormat == null)
384                                 throw new ArgumentNullException ("outFormat");
385                         if (inData == null)
386                                 return null;
387
388                         if (inFormat == outFormat)
389                                 return inData;
390
391                         PermissionSet ps = null;
392
393                         if (inFormat == "BINARY") {
394                                 if (outFormat.StartsWith ("XML")) {
395                                         using (MemoryStream ms = new MemoryStream (inData)) {
396                                                 BinaryFormatter formatter = new BinaryFormatter ();
397                                                 ps = (PermissionSet) formatter.Deserialize (ms);
398                                                 ms.Close ();
399                                         }
400                                         string xml = ps.ToString ();
401                                         switch (outFormat) {
402                                                 case "XML":
403                                                 case "XMLASCII":
404                                                         return Encoding.ASCII.GetBytes (xml);
405                                                 case "XMLUNICODE":
406                                                         return Encoding.Unicode.GetBytes (xml);
407                                         }
408                                 }
409                         }
410                         else if (inFormat.StartsWith ("XML")) {
411                                 if (outFormat == "BINARY") {
412                                         string xml = null;
413                                         switch (inFormat) {
414                                                 case "XML":
415                                                 case "XMLASCII":
416                                                         xml = Encoding.ASCII.GetString (inData);
417                                                         break;
418                                                 case "XMLUNICODE":
419                                                         xml = Encoding.Unicode.GetString (inData);
420                                                         break;
421                                         }
422                                         if (xml != null) {
423                                                 ps = new PermissionSet (PermissionState.None);
424                                                 ps.FromXml (SecurityElement.FromString (xml));
425
426                                                 MemoryStream ms = new MemoryStream ();
427                                                 BinaryFormatter formatter = new BinaryFormatter ();
428                                                 formatter.Serialize (ms, ps);
429                                                 ms.Close ();
430                                                 return ms.ToArray ();
431                                         }
432                                 }
433                                 else if (outFormat.StartsWith ("XML")) {
434                                         string msg = String.Format (Locale.GetText ("Can't convert from {0} to {1}"), inFormat, outFormat);
435 #if NET_2_0
436                                         throw new XmlSyntaxException (msg);
437 #else
438                                         throw new ArgumentException (msg);
439 #endif
440                                 }
441                         }
442                         else {
443                                 // unknown inFormat, returns null
444                                 return null;
445                         }
446                         // unknown outFormat, throw
447                         throw new SerializationException (String.Format (Locale.GetText ("Unknown output format {0}."), outFormat));
448                 }
449
450                 public virtual IPermission GetPermission (Type permClass) 
451                 {
452                         if ((permClass == null) || (list.Count == 0))
453                                 return null;
454
455                         foreach (object o in list) {
456                                 if ((o != null) && o.GetType ().Equals (permClass))
457                                         return (IPermission) o;
458                         }
459                         // it's normal to return null for unrestricted sets
460                         return null;
461                 }
462
463                 public virtual PermissionSet Intersect (PermissionSet other) 
464                 {
465                         // no intersection possible
466                         if ((other == null) || (other.IsEmpty ()) || (this.IsEmpty ()))
467                                 return null;
468
469                         PermissionState state = PermissionState.None;
470                         if (this.IsUnrestricted () && other.IsUnrestricted ())
471                                 state = PermissionState.Unrestricted;
472
473                         PermissionSet interSet = new PermissionSet (state);
474                         if (state == PermissionState.Unrestricted) {
475                                 InternalIntersect (interSet, this, other, true);
476                                 InternalIntersect (interSet, other, this, true);
477                         }
478                         else if (this.IsUnrestricted ()) {
479                                 InternalIntersect (interSet, this, other, true);
480                         }
481                         else if (other.IsUnrestricted ()) {
482                                 InternalIntersect (interSet, other, this, true);
483                         }
484                         else {
485                                 InternalIntersect (interSet, this, other, false);
486                         }
487                         return interSet;
488                 }
489
490                 internal void InternalIntersect (PermissionSet intersect, PermissionSet a, PermissionSet b, bool unrestricted)
491                 {
492                         foreach (IPermission p in b.list) {
493                                 // for every type in both list
494                                 IPermission i = a.GetPermission (p.GetType ());
495                                 if (i != null) {
496                                         // add intersection for this type
497                                         intersect.AddPermission (p.Intersect (i));
498                                 }
499 #if NET_2_0
500                                 // unrestricted is possible for indentity permissions
501                                 else if (unrestricted) {
502 #else
503                                 else if (unrestricted && (p is IUnrestrictedPermission)) {
504 #endif
505                                         intersect.AddPermission (p);
506                                 }
507                                 // or reject!
508                         }
509                 }
510
511                 public virtual bool IsEmpty () 
512                 {
513                         // note: Unrestricted isn't empty
514                         if (state == PermissionState.Unrestricted)
515                                 return false;
516                         if ((list == null) || (list.Count == 0))
517                                 return true;
518                         // the set may include some empty permissions
519                         foreach (IPermission p in list) {
520                                 // empty == fully restricted == IsSubsetOf(null) == true
521                                 if (!p.IsSubsetOf (null))
522                                         return false;
523                         }
524                         return true;
525                 }
526
527                 public virtual bool IsUnrestricted () 
528                 {
529                         return (state == PermissionState.Unrestricted);
530                 }
531
532                 public virtual IPermission RemovePermission (Type permClass) 
533                 {
534                         if ((permClass == null) || _readOnly)
535                                 return null;
536
537                         foreach (object o in list) {
538                                 if (o.GetType ().Equals (permClass)) {
539                                         list.Remove (o);
540                                         return (IPermission) o;
541                                 }
542                         }
543                         return null;
544                 }
545
546                 public virtual IPermission SetPermission (IPermission perm) 
547                 {
548                         if ((perm == null) || _readOnly)
549                                 return perm;
550 #if NET_2_0
551                         IUnrestrictedPermission u = (perm as IUnrestrictedPermission);
552                         if (u == null) {
553                                 state = PermissionState.None;
554                         } else {
555                                 state = u.IsUnrestricted () ? state : PermissionState.None;
556                         }
557 #else
558                         if (perm is IUnrestrictedPermission)
559                                 state = PermissionState.None;
560 #endif
561                         RemovePermission (perm.GetType ());
562                         list.Add (perm);
563                         return perm;
564                 }
565
566                 public override string ToString ()
567                 {
568                         return ToXml ().ToString ();
569                 }
570
571                 public virtual SecurityElement ToXml ()
572                 {
573                         SecurityElement se = new SecurityElement (tagName);
574                         se.AddAttribute ("class", GetType ().FullName);
575                         se.AddAttribute ("version", version.ToString ());
576                         if (state == PermissionState.Unrestricted)
577                                 se.AddAttribute ("Unrestricted", "true");
578
579                         // required for permissions that do not implement IUnrestrictedPermission
580                         foreach (IPermission p in list) {
581                                 se.AddChild (p.ToXml ());
582                         }
583                         return se;
584                 }
585
586                 public virtual PermissionSet Union (PermissionSet other)
587                 {
588                         if (other == null)
589                                 return this.Copy ();
590
591                         PermissionSet copy = this.Copy ();
592                         if (this.IsUnrestricted () || other.IsUnrestricted ()) {
593                                 // so we keep the "right" type
594                                 copy.Clear ();
595                                 copy.state = PermissionState.Unrestricted;
596                                 // copy all permissions that do not implement IUnrestrictedPermission
597                                 foreach (IPermission p in this.list) {
598                                         if (!(p is IUnrestrictedPermission))
599                                                 copy.AddPermission (p);
600                                 }
601                                 foreach (IPermission p in other.list) {
602                                         if (!(p is IUnrestrictedPermission))
603                                                 copy.AddPermission (p);
604                                 }
605                         }
606                         else {
607                                 // PermissionState.None -> copy all permissions
608                                 foreach (IPermission p in other.list) {
609                                         copy.AddPermission (p);
610                                 }
611                         }
612                         return copy;
613                 }
614
615                 public virtual int Count {
616                         get { return list.Count; }
617                 }
618
619                 public virtual bool IsSynchronized {
620                         get { return list.IsSynchronized; }
621                 }
622
623                 public virtual bool IsReadOnly {
624                         // always false (as documented) but the PermissionSet can be read-only
625                         // e.g. in a PolicyStatement
626                         get { return false; } 
627                 }
628
629                 public virtual object SyncRoot {
630                         get { return this; }
631                 }
632
633                 internal bool DeclarativeSecurity {
634                         get { return _declsec; }
635                         set { _declsec = value; }
636                 }
637
638                 [MonoTODO()]
639                 void IDeserializationCallback.OnDeserialization (object sender) 
640                 {
641                 }
642
643 #if NET_2_0
644                 [ComVisible (false)]
645                 public override bool Equals (object obj)
646                 {
647                         if (obj == null)
648                                 return false;
649                         PermissionSet ps = (obj as PermissionSet);
650                         if (ps == null)
651                                 return false;
652                         if (state != ps.state)
653                                 return false;
654                         if (list.Count != ps.Count)
655                                 return false;
656
657                         for (int i=0; i < list.Count; i++) {
658                                 bool found = false;
659                                 for (int j=0; i < ps.list.Count; j++) {
660                                         if (list [i].Equals (ps.list [j])) {
661                                                 found = true;
662                                                 break;
663                                         }
664                                 }
665                                 if (!found)
666                                         return false;
667                         }
668                         return true;
669                 }
670
671                 [ComVisible (false)]
672                 public override int GetHashCode ()
673                 {
674                         return (list.Count == 0) ? (int) state : base.GetHashCode ();
675                 }
676
677                 [MonoTODO ("what's it doing here?")]
678                 static public void RevertAssert ()
679                 {
680                         // FIXME: There's probably a reason this was added here ?
681                         CodeAccessPermission.RevertAssert ();
682                 }
683 #endif
684
685                 // internal
686
687                 internal PolicyLevel Resolver {
688                         get { return _policyLevel; }
689                         set { _policyLevel = value; }
690                 }
691
692                 internal void SetReadOnly (bool value)
693                 {
694                         _readOnly = value;
695                 }
696
697                 internal bool ProcessFrame (SecurityFrame frame, ref Assembly current, ref AppDomain domain)
698                 {
699                         if (IsUnrestricted ()) {
700                                 // we request unrestricted
701                                 if (frame.Deny != null) {
702                                         // but have restrictions (some denied permissions)
703                                         CodeAccessPermission.ThrowSecurityException (this, "Deny", frame, SecurityAction.Demand, null);
704                                 } else if (frame.PermitOnly != null) {
705                                         // but have restrictions (only some permitted permissions)
706                                         CodeAccessPermission.ThrowSecurityException (this, "PermitOnly", frame, SecurityAction.Demand, null);
707                                 }
708                         }
709
710                         // skip next steps if no Assert, Deny or PermitOnly are present
711                         if (frame.HasStackModifiers) {
712                                 foreach (CodeAccessPermission cap in list) {
713                                         if (cap.ProcessFrame (frame))
714                                                 return true; // Assert reached - abort stack walk!
715                                 }
716                         }
717
718                         // however the "final" grant set is resolved by assembly, so
719                         // there's no need to check it every time (just when we're 
720                         // changing assemblies between frames).
721                         if (frame.Assembly != current) {
722                                 CheckAssembly (current, frame);
723                                 current = frame.Assembly;
724                         }
725
726                         if (frame.Domain != domain) {
727                                 CheckAppDomain (domain, frame);
728                                 domain = frame.Domain;
729                         }
730
731                         return false;
732                 }
733
734                 internal void CheckAssembly (Assembly a, SecurityFrame frame)
735                 {
736                         IPermission p = SecurityManager.CheckPermissionSet (a, this, false);
737                         if (p != null) {
738                                 CodeAccessPermission.ThrowSecurityException (this, "Demand failed assembly permissions checks.",
739                                         frame, SecurityAction.Demand, p);
740                         }
741                 }
742
743                 internal void CheckAppDomain (AppDomain domain, SecurityFrame frame)
744                 {
745                         IPermission p = SecurityManager.CheckPermissionSet (domain, this);
746                         if (p != null) {
747                                 CodeAccessPermission.ThrowSecurityException (this, "Demand failed appdomain permissions checks.",
748                                         frame, SecurityAction.Demand, p);
749                         }
750                 }
751
752                 // 2.0 metadata format
753
754                 internal static PermissionSet CreateFromBinaryFormat (byte[] data)
755                 {
756                         if ((data == null) || (data [0] != 0x2E) || (data.Length < 2)) {
757                                 string msg = Locale.GetText ("Invalid data in 2.0 metadata format.");
758                                 throw new SecurityException (msg);
759                         }
760
761                         int pos = 1;
762                         int numattr = ReadEncodedInt (data, ref pos);
763                         PermissionSet ps = new PermissionSet (PermissionState.None);
764                         for (int i = 0; i < numattr; i++) {
765                                 IPermission p = ProcessAttribute (data, ref pos);
766                                 if (p == null) {
767                                         string msg = Locale.GetText ("Unsupported data found in 2.0 metadata format.");
768                                         throw new SecurityException (msg);
769                                 }
770                                 ps.AddPermission (p);
771                         }
772                         return ps;
773                 }
774
775                 internal static int ReadEncodedInt (byte[] data, ref int position)
776                 {
777                         int len = 0;
778                         if ((data [position] & 0x80) == 0) {
779                                 len = data [position];
780                                 position ++;
781                         } else if ((data [position] & 0x40) == 0) {
782                                 len = ((data [position] & 0x3f) << 8 | data [position + 1]);
783                                 position += 2;
784                         } else {
785                                 len = (((data [position] & 0x1f) << 24) | (data [position + 1] << 16) |
786                                         (data [position + 2] << 8) | (data [position + 3]));
787                                 position += 4;
788                         }
789                         return len;
790                 }
791
792                 static object[] action = new object [1] { (SecurityAction) 0 };
793
794                 // TODO: add support for arrays and enums
795                 internal static IPermission ProcessAttribute (byte[] data, ref int position)
796                 {
797                         int clen = ReadEncodedInt (data, ref position);
798                         string cnam = Encoding.UTF8.GetString (data, position, clen);
799                         position += clen;
800
801                         // TODO: Unification
802                         Type secattr = Type.GetType (cnam);
803                         SecurityAttribute sa = (Activator.CreateInstance (secattr, action) as SecurityAttribute);
804                         if (sa == null)
805                                 return null;
806
807                         /*int optionalParametersLength =*/ ReadEncodedInt (data, ref position);
808                         int numberOfParameters = ReadEncodedInt (data, ref position);
809                         for (int j=0; j < numberOfParameters; j++) {
810                                 bool property = false;
811                                 switch (data [position++]) {
812                                 case 0x53: // field (technically possible and working)
813                                         property = false;
814                                         break;
815                                 case 0x54: // property (common case)
816                                         property = true;
817                                         break;
818                                 default:
819                                         return null;
820                                 }
821
822                                 bool array = false;
823                                 byte type = data [position++];
824                                 if (type == 0x1D) {
825                                         array = true;
826                                         type = data [position++];
827                                 }
828
829                                 int plen = ReadEncodedInt (data, ref position);
830                                 string pnam = Encoding.UTF8.GetString (data, position, plen);
831                                 position += plen;
832
833                                 int arrayLength = 1;
834                                 if (array) {
835                                         arrayLength = BitConverter.ToInt32 (data, position);
836                                         position += 4;
837                                 }
838
839                                 object obj = null;
840                                 object[] arrayIndex = null;
841                                 for (int i = 0; i < arrayLength; i++) {
842                                         if (array) {
843                                                 // TODO - setup index
844                                         }
845
846                                         // sadly type values doesn't match ther TypeCode enum :(
847                                         switch (type) {
848                                         case 0x02: // MONO_TYPE_BOOLEAN
849                                                 obj = (object) Convert.ToBoolean (data [position++]);
850                                                 break;
851                                         case 0x03: // MONO_TYPE_CHAR
852                                                 obj = (object) Convert.ToChar (data [position]);
853                                                 position += 2;
854                                                 break;
855                                         case 0x04: // MONO_TYPE_I1
856                                                 obj = (object) Convert.ToSByte (data [position++]);
857                                                 break;
858                                         case 0x05: // MONO_TYPE_U1
859                                                 obj = (object) Convert.ToByte (data [position++]);
860                                                 break;
861                                         case 0x06: // MONO_TYPE_I2
862                                                 obj = (object) Convert.ToInt16 (data [position]);
863                                                 position += 2;
864                                                 break;
865                                         case 0x07: // MONO_TYPE_U2
866                                                 obj = (object) Convert.ToUInt16 (data [position]);
867                                                 position += 2;
868                                                 break;
869                                         case 0x08: // MONO_TYPE_I4
870                                                 obj = (object) Convert.ToInt32 (data [position]);
871                                                 position += 4;
872                                                 break;
873                                         case 0x09: // MONO_TYPE_U4
874                                                 obj = (object) Convert.ToUInt32 (data [position]);
875                                                 position += 4;
876                                                 break;
877                                         case 0x0A: // MONO_TYPE_I8
878                                                 obj = (object) Convert.ToInt64 (data [position]);
879                                                 position += 8;
880                                                 break;
881                                         case 0x0B: // MONO_TYPE_U8
882                                                 obj = (object) Convert.ToUInt64 (data [position]);
883                                                 position += 8;
884                                                 break;
885                                         case 0x0C: // MONO_TYPE_R4
886                                                 obj = (object) Convert.ToSingle (data [position]);
887                                                 position += 4;
888                                                 break;
889                                         case 0x0D: // MONO_TYPE_R8
890                                                 obj = (object) Convert.ToDouble (data [position]);
891                                                 position += 8;
892                                                 break;
893                                         case 0x0E: // MONO_TYPE_STRING
894                                                 string s = null;
895                                                 if (data [position] != 0xFF) {
896                                                         int slen = ReadEncodedInt (data, ref position);
897                                                         s = Encoding.UTF8.GetString (data, position, slen);
898                                                         position += slen;
899                                                 } else {
900                                                         position++;
901                                                 }
902                                                 obj = (object) s;
903                                                 break;
904                                         case 0x50: // special for TYPE
905                                                 int tlen = ReadEncodedInt (data, ref position);
906                                                 obj = (object) Type.GetType (Encoding.UTF8.GetString (data, position, tlen));
907                                                 position += tlen;
908                                                 break;
909                                         default:
910                                                 return null; // unsupported
911                                         }
912
913                                         if (property) {
914                                                 PropertyInfo pi = secattr.GetProperty (pnam);
915                                                 pi.SetValue (sa, obj, arrayIndex);
916                                         } else {
917                                                 FieldInfo fi = secattr.GetField (pnam);
918                                                 fi.SetValue (sa, obj);
919                                         }
920                                 }
921                         }
922                         return sa.CreatePermission ();
923                 }
924         }
925 }