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