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