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