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