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