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