Package paramiko :: Module _winapi
[frames] | no frames]

Source Code for Module paramiko._winapi

  1  """ 
  2  Windows API functions implemented as ctypes functions and classes as found 
  3  in jaraco.windows (2.10). 
  4   
  5  If you encounter issues with this module, please consider reporting the issues 
  6  in jaraco.windows and asking the author to port the fixes back here. 
  7  """ 
  8   
  9  import ctypes 
 10  import ctypes.wintypes 
 11  import __builtin__ 
 12   
 13  try: 
 14          USHORT = ctypes.wintypes.USHORT 
 15  except AttributeError: 
 16          USHORT = ctypes.c_ushort 
17 18 ###################### 19 # jaraco.windows.error 20 21 -def format_system_message(errno):
22 """ 23 Call FormatMessage with a system error number to retrieve 24 the descriptive error message. 25 """ 26 # first some flags used by FormatMessageW 27 ALLOCATE_BUFFER = 0x100 28 ARGUMENT_ARRAY = 0x2000 29 FROM_HMODULE = 0x800 30 FROM_STRING = 0x400 31 FROM_SYSTEM = 0x1000 32 IGNORE_INSERTS = 0x200 33 34 # Let FormatMessageW allocate the buffer (we'll free it below) 35 # Also, let it know we want a system error message. 36 flags = ALLOCATE_BUFFER | FROM_SYSTEM 37 source = None 38 message_id = errno 39 language_id = 0 40 result_buffer = ctypes.wintypes.LPWSTR() 41 buffer_size = 0 42 arguments = None 43 bytes = ctypes.windll.kernel32.FormatMessageW( 44 flags, 45 source, 46 message_id, 47 language_id, 48 ctypes.byref(result_buffer), 49 buffer_size, 50 arguments, 51 ) 52 # note the following will cause an infinite loop if GetLastError 53 # repeatedly returns an error that cannot be formatted, although 54 # this should not happen. 55 handle_nonzero_success(bytes) 56 message = result_buffer.value 57 ctypes.windll.kernel32.LocalFree(result_buffer) 58 return message
59
60 61 -class WindowsError(__builtin__.WindowsError):
62 "more info about errors at http://msdn.microsoft.com/en-us/library/ms681381(VS.85).aspx" 63
64 - def __init__(self, value=None):
65 if value is None: 66 value = ctypes.windll.kernel32.GetLastError() 67 strerror = format_system_message(value) 68 super(WindowsError, self).__init__(value, strerror)
69 70 @property
71 - def message(self):
72 return self.strerror
73 74 @property
75 - def code(self):
76 return self.winerror
77
78 - def __str__(self):
79 return self.message
80
81 - def __repr__(self):
82 return '{self.__class__.__name__}({self.winerror})'.format(**vars())
83
84 -def handle_nonzero_success(result):
85 if result == 0: 86 raise WindowsError()
87 88 89 CreateFileMapping = ctypes.windll.kernel32.CreateFileMappingW 90 CreateFileMapping.argtypes = [ 91 ctypes.wintypes.HANDLE, 92 ctypes.c_void_p, 93 ctypes.wintypes.DWORD, 94 ctypes.wintypes.DWORD, 95 ctypes.wintypes.DWORD, 96 ctypes.wintypes.LPWSTR, 97 ] 98 CreateFileMapping.restype = ctypes.wintypes.HANDLE 99 100 MapViewOfFile = ctypes.windll.kernel32.MapViewOfFile 101 MapViewOfFile.restype = ctypes.wintypes.HANDLE
102 103 -class MemoryMap(object):
104 """ 105 A memory map object which can have security attributes overrideden. 106 """
107 - def __init__(self, name, length, security_attributes=None):
108 self.name = name 109 self.length = length 110 self.security_attributes = security_attributes 111 self.pos = 0
112
113 - def __enter__(self):
114 p_SA = ( 115 ctypes.byref(self.security_attributes) 116 if self.security_attributes else None 117 ) 118 INVALID_HANDLE_VALUE = -1 119 PAGE_READWRITE = 0x4 120 FILE_MAP_WRITE = 0x2 121 filemap = ctypes.windll.kernel32.CreateFileMappingW( 122 INVALID_HANDLE_VALUE, p_SA, PAGE_READWRITE, 0, self.length, 123 unicode(self.name)) 124 handle_nonzero_success(filemap) 125 if filemap == INVALID_HANDLE_VALUE: 126 raise Exception("Failed to create file mapping") 127 self.filemap = filemap 128 self.view = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0) 129 return self
130
131 - def seek(self, pos):
132 self.pos = pos
133
134 - def write(self, msg):
135 n = len(msg) 136 if self.pos + n >= self.length: # A little safety. 137 raise ValueError("Refusing to write %d bytes" % n) 138 ctypes.windll.kernel32.RtlMoveMemory(self.view + self.pos, msg, n) 139 self.pos += n
140
141 - def read(self, n):
142 """ 143 Read n bytes from mapped view. 144 """ 145 out = ctypes.create_string_buffer(n) 146 ctypes.windll.kernel32.RtlMoveMemory(out, self.view + self.pos, n) 147 self.pos += n 148 return out.raw
149
150 - def __exit__(self, exc_type, exc_val, tb):
151 ctypes.windll.kernel32.UnmapViewOfFile(self.view) 152 ctypes.windll.kernel32.CloseHandle(self.filemap)
153
154 ######################### 155 # jaraco.windows.security 156 157 -class TokenInformationClass:
158 TokenUser = 1
159
160 -class TOKEN_USER(ctypes.Structure):
161 num = 1 162 _fields_ = [ 163 ('SID', ctypes.c_void_p), 164 ('ATTRIBUTES', ctypes.wintypes.DWORD), 165 ]
166
167 168 -class SECURITY_DESCRIPTOR(ctypes.Structure):
169 """ 170 typedef struct _SECURITY_DESCRIPTOR 171 { 172 UCHAR Revision; 173 UCHAR Sbz1; 174 SECURITY_DESCRIPTOR_CONTROL Control; 175 PSID Owner; 176 PSID Group; 177 PACL Sacl; 178 PACL Dacl; 179 } SECURITY_DESCRIPTOR; 180 """ 181 SECURITY_DESCRIPTOR_CONTROL = USHORT 182 REVISION = 1 183 184 _fields_ = [ 185 ('Revision', ctypes.c_ubyte), 186 ('Sbz1', ctypes.c_ubyte), 187 ('Control', SECURITY_DESCRIPTOR_CONTROL), 188 ('Owner', ctypes.c_void_p), 189 ('Group', ctypes.c_void_p), 190 ('Sacl', ctypes.c_void_p), 191 ('Dacl', ctypes.c_void_p), 192 ]
193
194 -class SECURITY_ATTRIBUTES(ctypes.Structure):
195 """ 196 typedef struct _SECURITY_ATTRIBUTES { 197 DWORD nLength; 198 LPVOID lpSecurityDescriptor; 199 BOOL bInheritHandle; 200 } SECURITY_ATTRIBUTES; 201 """ 202 _fields_ = [ 203 ('nLength', ctypes.wintypes.DWORD), 204 ('lpSecurityDescriptor', ctypes.c_void_p), 205 ('bInheritHandle', ctypes.wintypes.BOOL), 206 ] 207
208 - def __init__(self, *args, **kwargs):
209 super(SECURITY_ATTRIBUTES, self).__init__(*args, **kwargs) 210 self.nLength = ctypes.sizeof(SECURITY_ATTRIBUTES)
211
212 - def _get_descriptor(self):
213 return self._descriptor
214 - def _set_descriptor(self, descriptor):
215 self._descriptor = descriptor 216 self.lpSecurityDescriptor = ctypes.addressof(descriptor)
217 descriptor = property(_get_descriptor, _set_descriptor)
218
219 -def GetTokenInformation(token, information_class):
220 """ 221 Given a token, get the token information for it. 222 """ 223 data_size = ctypes.wintypes.DWORD() 224 ctypes.windll.advapi32.GetTokenInformation(token, information_class.num, 225 0, 0, ctypes.byref(data_size)) 226 data = ctypes.create_string_buffer(data_size.value) 227 handle_nonzero_success(ctypes.windll.advapi32.GetTokenInformation(token, 228 information_class.num, 229 ctypes.byref(data), ctypes.sizeof(data), 230 ctypes.byref(data_size))) 231 return ctypes.cast(data, ctypes.POINTER(TOKEN_USER)).contents
232
233 -class TokenAccess:
234 TOKEN_QUERY = 0x8
235
236 -def OpenProcessToken(proc_handle, access):
237 result = ctypes.wintypes.HANDLE() 238 proc_handle = ctypes.wintypes.HANDLE(proc_handle) 239 handle_nonzero_success(ctypes.windll.advapi32.OpenProcessToken( 240 proc_handle, access, ctypes.byref(result))) 241 return result
242
243 -def get_current_user():
244 """ 245 Return a TOKEN_USER for the owner of this process. 246 """ 247 process = OpenProcessToken( 248 ctypes.windll.kernel32.GetCurrentProcess(), 249 TokenAccess.TOKEN_QUERY, 250 ) 251 return GetTokenInformation(process, TOKEN_USER)
252
253 -def get_security_attributes_for_user(user=None):
254 """ 255 Return a SECURITY_ATTRIBUTES structure with the SID set to the 256 specified user (uses current user if none is specified). 257 """ 258 if user is None: 259 user = get_current_user() 260 261 assert isinstance(user, TOKEN_USER), "user must be TOKEN_USER instance" 262 263 SD = SECURITY_DESCRIPTOR() 264 SA = SECURITY_ATTRIBUTES() 265 # by attaching the actual security descriptor, it will be garbage- 266 # collected with the security attributes 267 SA.descriptor = SD 268 SA.bInheritHandle = 1 269 270 ctypes.windll.advapi32.InitializeSecurityDescriptor(ctypes.byref(SD), 271 SECURITY_DESCRIPTOR.REVISION) 272 ctypes.windll.advapi32.SetSecurityDescriptorOwner(ctypes.byref(SD), 273 user.SID, 0) 274 return SA
275