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