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