2004-04-13 Sebastien Pouliot <sebastien@ximian.com>
[mono.git] / mcs / class / corlib / System.Security.Principal / WindowsImpersonationContext.cs
1 //
2 // System.Security.Principal.WindowsImpersonationContext
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //      Sebastien Pouliot  (sebastien@ximian.com)
7 //
8 // (C) 2002 Ximian, Inc (http://www.ximian.com)
9 // (C) 2004 Novell (http://www.novell.com)
10 //
11
12 using System;
13 using System.Runtime.CompilerServices;
14 using System.Security;
15
16 namespace System.Security.Principal {
17
18         public class WindowsImpersonationContext {
19
20                 private IntPtr _token;
21                 private bool undo;
22
23                 internal WindowsImpersonationContext (IntPtr token)
24                 {
25                         // we get a copy to control it's lifetime
26                         _token = DuplicateToken (token);
27                         if (!SetCurrentToken (token)) {
28                                 throw new SecurityException ("Couldn't impersonate token.");
29                         }
30                         undo = false;
31                 }
32
33                 ~WindowsImpersonationContext ()
34                 {
35                         if (!undo) {
36                                 Undo ();
37                         }
38                 }
39
40                 public void Undo ()
41                 {
42                         if (!RevertToSelf ()) {
43                                 CloseToken (_token);
44                                 throw new SecurityException ("Couldn't switch back to original token.");
45                         }
46                         CloseToken (_token);
47                         undo = true;
48                         GC.SuppressFinalize (this);
49                 }
50
51                 // see mono/mono/metadata/security.c for implementation
52
53                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
54                 private extern static bool CloseToken (IntPtr token);
55
56                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
57                 private extern static IntPtr DuplicateToken (IntPtr token);
58
59                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
60                 private extern static bool SetCurrentToken (IntPtr token);
61
62                 [MethodImplAttribute (MethodImplOptions.InternalCall)]
63                 private extern static bool RevertToSelf ();
64         }
65 }