winapi.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # winapi.py: Windows API-Python interface (removes dependency on pywin32)
  4. #
  5. # Copyright (C) 2007 Thomas Heller <theller@ctypes.org>
  6. # Copyright (C) 2010 Will McGugan <will@willmcgugan.com>
  7. # Copyright (C) 2010 Ryan Kelly <ryan@rfk.id.au>
  8. # Copyright (C) 2010 Yesudeep Mangalapilly <yesudeep@gmail.com>
  9. # Copyright (C) 2014 Thomas Amland
  10. # All rights reserved.
  11. #
  12. # Redistribution and use in source and binary forms, with or without
  13. # modification, are permitted provided that the following conditions are met:
  14. #
  15. # * Redistributions of source code must retain the above copyright notice, this
  16. # list of conditions and the following disclaimer.
  17. # * Redistributions in binary form must reproduce the above copyright notice,
  18. # this list of conditions and the following disclaimer in the documentation
  19. # and / or other materials provided with the distribution.
  20. # * Neither the name of the organization nor the names of its contributors may
  21. # be used to endorse or promote products derived from this software without
  22. # specific prior written permission.
  23. #
  24. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  25. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  26. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  27. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  28. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  29. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  30. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  31. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  32. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  33. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  34. # POSSIBILITY OF SUCH DAMAGE.
  35. #
  36. # Portions of this code were taken from pyfilesystem, which uses the above
  37. # new BSD license.
  38. import ctypes.wintypes
  39. from functools import reduce
  40. LPVOID = ctypes.wintypes.LPVOID
  41. # Invalid handle value.
  42. INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
  43. # File notification constants.
  44. FILE_NOTIFY_CHANGE_FILE_NAME = 0x01
  45. FILE_NOTIFY_CHANGE_DIR_NAME = 0x02
  46. FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x04
  47. FILE_NOTIFY_CHANGE_SIZE = 0x08
  48. FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010
  49. FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020
  50. FILE_NOTIFY_CHANGE_CREATION = 0x040
  51. FILE_NOTIFY_CHANGE_SECURITY = 0x0100
  52. FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
  53. FILE_FLAG_OVERLAPPED = 0x40000000
  54. FILE_LIST_DIRECTORY = 1
  55. FILE_SHARE_READ = 0x01
  56. FILE_SHARE_WRITE = 0x02
  57. FILE_SHARE_DELETE = 0x04
  58. OPEN_EXISTING = 3
  59. VOLUME_NAME_NT = 0x02
  60. # File action constants.
  61. FILE_ACTION_CREATED = 1
  62. FILE_ACTION_DELETED = 2
  63. FILE_ACTION_MODIFIED = 3
  64. FILE_ACTION_RENAMED_OLD_NAME = 4
  65. FILE_ACTION_RENAMED_NEW_NAME = 5
  66. FILE_ACTION_DELETED_SELF = 0xFFFE
  67. FILE_ACTION_OVERFLOW = 0xFFFF
  68. # Aliases
  69. FILE_ACTION_ADDED = FILE_ACTION_CREATED
  70. FILE_ACTION_REMOVED = FILE_ACTION_DELETED
  71. FILE_ACTION_REMOVED_SELF = FILE_ACTION_DELETED_SELF
  72. THREAD_TERMINATE = 0x0001
  73. # IO waiting constants.
  74. WAIT_ABANDONED = 0x00000080
  75. WAIT_IO_COMPLETION = 0x000000C0
  76. WAIT_OBJECT_0 = 0x00000000
  77. WAIT_TIMEOUT = 0x00000102
  78. # Error codes
  79. ERROR_OPERATION_ABORTED = 995
  80. class OVERLAPPED(ctypes.Structure):
  81. _fields_ = [('Internal', LPVOID),
  82. ('InternalHigh', LPVOID),
  83. ('Offset', ctypes.wintypes.DWORD),
  84. ('OffsetHigh', ctypes.wintypes.DWORD),
  85. ('Pointer', LPVOID),
  86. ('hEvent', ctypes.wintypes.HANDLE),
  87. ]
  88. def _errcheck_bool(value, func, args):
  89. if not value:
  90. raise ctypes.WinError()
  91. return args
  92. def _errcheck_handle(value, func, args):
  93. if not value:
  94. raise ctypes.WinError()
  95. if value == INVALID_HANDLE_VALUE:
  96. raise ctypes.WinError()
  97. return args
  98. def _errcheck_dword(value, func, args):
  99. if value == 0xFFFFFFFF:
  100. raise ctypes.WinError()
  101. return args
  102. kernel32 = ctypes.WinDLL("kernel32")
  103. ReadDirectoryChangesW = kernel32.ReadDirectoryChangesW
  104. ReadDirectoryChangesW.restype = ctypes.wintypes.BOOL
  105. ReadDirectoryChangesW.errcheck = _errcheck_bool
  106. ReadDirectoryChangesW.argtypes = (
  107. ctypes.wintypes.HANDLE, # hDirectory
  108. LPVOID, # lpBuffer
  109. ctypes.wintypes.DWORD, # nBufferLength
  110. ctypes.wintypes.BOOL, # bWatchSubtree
  111. ctypes.wintypes.DWORD, # dwNotifyFilter
  112. ctypes.POINTER(ctypes.wintypes.DWORD), # lpBytesReturned
  113. ctypes.POINTER(OVERLAPPED), # lpOverlapped
  114. LPVOID # FileIOCompletionRoutine # lpCompletionRoutine
  115. )
  116. CreateFileW = kernel32.CreateFileW
  117. CreateFileW.restype = ctypes.wintypes.HANDLE
  118. CreateFileW.errcheck = _errcheck_handle
  119. CreateFileW.argtypes = (
  120. ctypes.wintypes.LPCWSTR, # lpFileName
  121. ctypes.wintypes.DWORD, # dwDesiredAccess
  122. ctypes.wintypes.DWORD, # dwShareMode
  123. LPVOID, # lpSecurityAttributes
  124. ctypes.wintypes.DWORD, # dwCreationDisposition
  125. ctypes.wintypes.DWORD, # dwFlagsAndAttributes
  126. ctypes.wintypes.HANDLE # hTemplateFile
  127. )
  128. CloseHandle = kernel32.CloseHandle
  129. CloseHandle.restype = ctypes.wintypes.BOOL
  130. CloseHandle.argtypes = (
  131. ctypes.wintypes.HANDLE, # hObject
  132. )
  133. CancelIoEx = kernel32.CancelIoEx
  134. CancelIoEx.restype = ctypes.wintypes.BOOL
  135. CancelIoEx.errcheck = _errcheck_bool
  136. CancelIoEx.argtypes = (
  137. ctypes.wintypes.HANDLE, # hObject
  138. ctypes.POINTER(OVERLAPPED) # lpOverlapped
  139. )
  140. CreateEvent = kernel32.CreateEventW
  141. CreateEvent.restype = ctypes.wintypes.HANDLE
  142. CreateEvent.errcheck = _errcheck_handle
  143. CreateEvent.argtypes = (
  144. LPVOID, # lpEventAttributes
  145. ctypes.wintypes.BOOL, # bManualReset
  146. ctypes.wintypes.BOOL, # bInitialState
  147. ctypes.wintypes.LPCWSTR, # lpName
  148. )
  149. SetEvent = kernel32.SetEvent
  150. SetEvent.restype = ctypes.wintypes.BOOL
  151. SetEvent.errcheck = _errcheck_bool
  152. SetEvent.argtypes = (
  153. ctypes.wintypes.HANDLE, # hEvent
  154. )
  155. WaitForSingleObjectEx = kernel32.WaitForSingleObjectEx
  156. WaitForSingleObjectEx.restype = ctypes.wintypes.DWORD
  157. WaitForSingleObjectEx.errcheck = _errcheck_dword
  158. WaitForSingleObjectEx.argtypes = (
  159. ctypes.wintypes.HANDLE, # hObject
  160. ctypes.wintypes.DWORD, # dwMilliseconds
  161. ctypes.wintypes.BOOL, # bAlertable
  162. )
  163. CreateIoCompletionPort = kernel32.CreateIoCompletionPort
  164. CreateIoCompletionPort.restype = ctypes.wintypes.HANDLE
  165. CreateIoCompletionPort.errcheck = _errcheck_handle
  166. CreateIoCompletionPort.argtypes = (
  167. ctypes.wintypes.HANDLE, # FileHandle
  168. ctypes.wintypes.HANDLE, # ExistingCompletionPort
  169. LPVOID, # CompletionKey
  170. ctypes.wintypes.DWORD, # NumberOfConcurrentThreads
  171. )
  172. GetQueuedCompletionStatus = kernel32.GetQueuedCompletionStatus
  173. GetQueuedCompletionStatus.restype = ctypes.wintypes.BOOL
  174. GetQueuedCompletionStatus.errcheck = _errcheck_bool
  175. GetQueuedCompletionStatus.argtypes = (
  176. ctypes.wintypes.HANDLE, # CompletionPort
  177. LPVOID, # lpNumberOfBytesTransferred
  178. LPVOID, # lpCompletionKey
  179. ctypes.POINTER(OVERLAPPED), # lpOverlapped
  180. ctypes.wintypes.DWORD, # dwMilliseconds
  181. )
  182. PostQueuedCompletionStatus = kernel32.PostQueuedCompletionStatus
  183. PostQueuedCompletionStatus.restype = ctypes.wintypes.BOOL
  184. PostQueuedCompletionStatus.errcheck = _errcheck_bool
  185. PostQueuedCompletionStatus.argtypes = (
  186. ctypes.wintypes.HANDLE, # CompletionPort
  187. ctypes.wintypes.DWORD, # lpNumberOfBytesTransferred
  188. ctypes.wintypes.DWORD, # lpCompletionKey
  189. ctypes.POINTER(OVERLAPPED), # lpOverlapped
  190. )
  191. GetFinalPathNameByHandleW = kernel32.GetFinalPathNameByHandleW
  192. GetFinalPathNameByHandleW.restype = ctypes.wintypes.DWORD
  193. GetFinalPathNameByHandleW.errcheck = _errcheck_dword
  194. GetFinalPathNameByHandleW.argtypes = (
  195. ctypes.wintypes.HANDLE, # hFile
  196. ctypes.wintypes.LPWSTR, # lpszFilePath
  197. ctypes.wintypes.DWORD, # cchFilePath
  198. ctypes.wintypes.DWORD, # DWORD
  199. )
  200. class FILE_NOTIFY_INFORMATION(ctypes.Structure):
  201. _fields_ = [("NextEntryOffset", ctypes.wintypes.DWORD),
  202. ("Action", ctypes.wintypes.DWORD),
  203. ("FileNameLength", ctypes.wintypes.DWORD),
  204. # ("FileName", (ctypes.wintypes.WCHAR * 1))]
  205. ("FileName", (ctypes.c_char * 1))]
  206. LPFNI = ctypes.POINTER(FILE_NOTIFY_INFORMATION)
  207. # We don't need to recalculate these flags every time a call is made to
  208. # the win32 API functions.
  209. WATCHDOG_FILE_FLAGS = FILE_FLAG_BACKUP_SEMANTICS
  210. WATCHDOG_FILE_SHARE_FLAGS = reduce(
  211. lambda x, y: x | y, [
  212. FILE_SHARE_READ,
  213. FILE_SHARE_WRITE,
  214. FILE_SHARE_DELETE,
  215. ])
  216. WATCHDOG_FILE_NOTIFY_FLAGS = reduce(
  217. lambda x, y: x | y, [
  218. FILE_NOTIFY_CHANGE_FILE_NAME,
  219. FILE_NOTIFY_CHANGE_DIR_NAME,
  220. FILE_NOTIFY_CHANGE_ATTRIBUTES,
  221. FILE_NOTIFY_CHANGE_SIZE,
  222. FILE_NOTIFY_CHANGE_LAST_WRITE,
  223. FILE_NOTIFY_CHANGE_SECURITY,
  224. FILE_NOTIFY_CHANGE_LAST_ACCESS,
  225. FILE_NOTIFY_CHANGE_CREATION,
  226. ])
  227. BUFFER_SIZE = 2048
  228. def _parse_event_buffer(readBuffer, nBytes):
  229. results = []
  230. while nBytes > 0:
  231. fni = ctypes.cast(readBuffer, LPFNI)[0]
  232. ptr = ctypes.addressof(fni) + FILE_NOTIFY_INFORMATION.FileName.offset
  233. # filename = ctypes.wstring_at(ptr, fni.FileNameLength)
  234. filename = ctypes.string_at(ptr, fni.FileNameLength)
  235. results.append((fni.Action, filename.decode('utf-16')))
  236. numToSkip = fni.NextEntryOffset
  237. if numToSkip <= 0:
  238. break
  239. readBuffer = readBuffer[numToSkip:]
  240. nBytes -= numToSkip # numToSkip is long. nBytes should be long too.
  241. return results
  242. def _is_observed_path_deleted(handle, path):
  243. # Comparison of observed path and actual path, returned by
  244. # GetFinalPathNameByHandleW. If directory moved to the trash bin, or
  245. # deleted, actual path will not be equal to observed path.
  246. buff = ctypes.create_unicode_buffer(BUFFER_SIZE)
  247. GetFinalPathNameByHandleW(handle, buff, BUFFER_SIZE, VOLUME_NAME_NT)
  248. return buff.value != path
  249. def _generate_observed_path_deleted_event():
  250. # Create synthetic event for notify that observed directory is deleted
  251. path = ctypes.create_unicode_buffer('.')
  252. event = FILE_NOTIFY_INFORMATION(0, FILE_ACTION_DELETED_SELF, len(path), path.value)
  253. event_size = ctypes.sizeof(event)
  254. buff = ctypes.create_string_buffer(BUFFER_SIZE)
  255. ctypes.memmove(buff, ctypes.addressof(event), event_size)
  256. return buff, event_size
  257. def get_directory_handle(path):
  258. """Returns a Windows handle to the specified directory path."""
  259. return CreateFileW(path, FILE_LIST_DIRECTORY, WATCHDOG_FILE_SHARE_FLAGS,
  260. None, OPEN_EXISTING, WATCHDOG_FILE_FLAGS, None)
  261. def close_directory_handle(handle):
  262. try:
  263. CancelIoEx(handle, None) # force ReadDirectoryChangesW to return
  264. CloseHandle(handle) # close directory handle
  265. except WindowsError:
  266. try:
  267. CloseHandle(handle) # close directory handle
  268. except Exception:
  269. return
  270. def read_directory_changes(handle, path, recursive):
  271. """Read changes to the directory using the specified directory handle.
  272. http://timgolden.me.uk/pywin32-docs/win32file__ReadDirectoryChangesW_meth.html
  273. """
  274. event_buffer = ctypes.create_string_buffer(BUFFER_SIZE)
  275. nbytes = ctypes.wintypes.DWORD()
  276. try:
  277. ReadDirectoryChangesW(handle, ctypes.byref(event_buffer),
  278. len(event_buffer), recursive,
  279. WATCHDOG_FILE_NOTIFY_FLAGS,
  280. ctypes.byref(nbytes), None, None)
  281. except WindowsError as e:
  282. if e.winerror == ERROR_OPERATION_ABORTED:
  283. return [], 0
  284. # Handle the case when the root path is deleted
  285. if _is_observed_path_deleted(handle, path):
  286. return _generate_observed_path_deleted_event()
  287. raise e
  288. # Python 2/3 compat
  289. try:
  290. int_class = long
  291. except NameError:
  292. int_class = int
  293. return event_buffer.raw, int_class(nbytes.value)
  294. class WinAPINativeEvent(object):
  295. def __init__(self, action, src_path):
  296. self.action = action
  297. self.src_path = src_path
  298. @property
  299. def is_added(self):
  300. return self.action == FILE_ACTION_CREATED
  301. @property
  302. def is_removed(self):
  303. return self.action == FILE_ACTION_REMOVED
  304. @property
  305. def is_modified(self):
  306. return self.action == FILE_ACTION_MODIFIED
  307. @property
  308. def is_renamed_old(self):
  309. return self.action == FILE_ACTION_RENAMED_OLD_NAME
  310. @property
  311. def is_renamed_new(self):
  312. return self.action == FILE_ACTION_RENAMED_NEW_NAME
  313. @property
  314. def is_removed_self(self):
  315. return self.action == FILE_ACTION_REMOVED_SELF
  316. def __repr__(self):
  317. return ("<%s: action=%d, src_path=%r>" % (
  318. type(self).__name__, self.action, self.src_path))
  319. def read_events(handle, path, recursive):
  320. buf, nbytes = read_directory_changes(handle, path, recursive)
  321. events = _parse_event_buffer(buf, nbytes)
  322. return [WinAPINativeEvent(action, src_path) for action, src_path in events]