/couchapp/autopush/watchdog/observers/winapi.py

https://github.com/andrewjw/couchapp · Python · 246 lines · 173 code · 27 blank · 46 comment · 13 complexity · e563ef1f2c6dfc254a04c1123f05c5d0 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. # winapi.py: Windows API-Python interface (removes dependency on pywin32)
  3. #
  4. # Copyright (C) 2007 Thomas Heller <theller@ctypes.org>
  5. # Copyright (C) 2010 Will McGugan <will@willmcgugan.com>
  6. # Copyright (C) 2010 Ryan Kelly <ryan@rfk.id.au>
  7. # Copyright (C) 2010 Yesudeep Mangalapilly <yesudeep@gmail.com>
  8. # All rights reserved.
  9. #
  10. # Redistribution and use in source and binary forms, with or without
  11. # modification, are permitted provided that the following conditions are met:
  12. #
  13. # * Redistributions of source code must retain the above copyright notice, this
  14. # list of conditions and the following disclaimer.
  15. # * Redistributions in binary form must reproduce the above copyright notice,
  16. # this list of conditions and the following disclaimer in the documentation
  17. # and / or other materials provided with the distribution.
  18. # * Neither the name of the organization nor the names of its contributors may
  19. # be used to endorse or promote products derived from this software without
  20. # specific prior written permission.
  21. #
  22. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  23. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  24. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  25. # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  26. # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  27. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  28. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  29. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  30. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  31. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  32. # POSSIBILITY OF SUCH DAMAGE.
  33. #
  34. # Portions of this code were taken from pyfilesystem, which uses the above
  35. # new BSD license.
  36. from __future__ import with_statement
  37. from ..utils import platform
  38. if platform.is_windows():
  39. import ctypes.wintypes
  40. import struct
  41. try:
  42. LPVOID = ctypes.wintypes.LPVOID
  43. except AttributeError:
  44. # LPVOID wasn't defined in Py2.5, guess it was introduced in Py2.6
  45. LPVOID = ctypes.c_void_p
  46. # Invalid handle value.
  47. INVALID_HANDLE_VALUE = 0xFFFFFFFF # -1
  48. # File notification contants.
  49. FILE_NOTIFY_CHANGE_FILE_NAME = 0x01
  50. FILE_NOTIFY_CHANGE_DIR_NAME = 0x02
  51. FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x04
  52. FILE_NOTIFY_CHANGE_SIZE = 0x08
  53. FILE_NOTIFY_CHANGE_LAST_WRITE = 0x010
  54. FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x020
  55. FILE_NOTIFY_CHANGE_CREATION = 0x040
  56. FILE_NOTIFY_CHANGE_SECURITY = 0x0100
  57. FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
  58. FILE_FLAG_OVERLAPPED = 0x40000000
  59. FILE_LIST_DIRECTORY = 0x01
  60. FILE_SHARE_READ = 0x01
  61. FILE_SHARE_WRITE = 0x02
  62. FILE_SHARE_DELETE = 0x04
  63. OPEN_EXISTING = 3
  64. # File action constants.
  65. FILE_ACTION_CREATED = 1
  66. FILE_ACTION_DELETED = 2
  67. FILE_ACTION_MODIFIED = 3
  68. FILE_ACTION_RENAMED_OLD_NAME = 4
  69. FILE_ACTION_RENAMED_NEW_NAME = 5
  70. FILE_ACTION_OVERFLOW = 0xFFFF
  71. # Aliases
  72. FILE_ACTION_ADDED = FILE_ACTION_CREATED
  73. FILE_ACTION_REMOVED = FILE_ACTION_DELETED
  74. THREAD_TERMINATE = 0x0001
  75. # IO waiting constants.
  76. WAIT_ABANDONED = 0x00000080
  77. WAIT_IO_COMPLETION = 0x000000C0
  78. WAIT_OBJECT_0 = 0x00000000
  79. WAIT_TIMEOUT = 0x00000102
  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. try:
  103. ReadDirectoryChangesW = ctypes.windll.kernel32.ReadDirectoryChangesW
  104. except AttributeError:
  105. raise ImportError("ReadDirectoryChangesW is not available")
  106. ReadDirectoryChangesW.restype = ctypes.wintypes.BOOL
  107. ReadDirectoryChangesW.errcheck = _errcheck_bool
  108. ReadDirectoryChangesW.argtypes = (
  109. ctypes.wintypes.HANDLE, # hDirectory
  110. LPVOID, # lpBuffer
  111. ctypes.wintypes.DWORD, # nBufferLength
  112. ctypes.wintypes.BOOL, # bWatchSubtree
  113. ctypes.wintypes.DWORD, # dwNotifyFilter
  114. ctypes.POINTER(ctypes.wintypes.DWORD), # lpBytesReturned
  115. ctypes.POINTER(OVERLAPPED), # lpOverlapped
  116. LPVOID #FileIOCompletionRoutine # lpCompletionRoutine
  117. )
  118. CreateFileW = ctypes.windll.kernel32.CreateFileW
  119. CreateFileW.restype = ctypes.wintypes.HANDLE
  120. CreateFileW.errcheck = _errcheck_handle
  121. CreateFileW.argtypes = (
  122. ctypes.wintypes.LPCWSTR, # lpFileName
  123. ctypes.wintypes.DWORD, # dwDesiredAccess
  124. ctypes.wintypes.DWORD, # dwShareMode
  125. LPVOID, # lpSecurityAttributes
  126. ctypes.wintypes.DWORD, # dwCreationDisposition
  127. ctypes.wintypes.DWORD, # dwFlagsAndAttributes
  128. ctypes.wintypes.HANDLE # hTemplateFile
  129. )
  130. CloseHandle = ctypes.windll.kernel32.CloseHandle
  131. CloseHandle.restype = ctypes.wintypes.BOOL
  132. CloseHandle.argtypes = (
  133. ctypes.wintypes.HANDLE, # hObject
  134. )
  135. CreateEvent = ctypes.windll.kernel32.CreateEventW
  136. CreateEvent.restype = ctypes.wintypes.HANDLE
  137. CreateEvent.errcheck = _errcheck_handle
  138. CreateEvent.argtypes = (
  139. LPVOID, # lpEventAttributes
  140. ctypes.wintypes.BOOL, # bManualReset
  141. ctypes.wintypes.BOOL, # bInitialState
  142. ctypes.wintypes.LPCWSTR, #lpName
  143. )
  144. SetEvent = ctypes.windll.kernel32.SetEvent
  145. SetEvent.restype = ctypes.wintypes.BOOL
  146. SetEvent.errcheck = _errcheck_bool
  147. SetEvent.argtypes = (
  148. ctypes.wintypes.HANDLE, # hEvent
  149. )
  150. WaitForSingleObjectEx = ctypes.windll.kernel32.WaitForSingleObjectEx
  151. WaitForSingleObjectEx.restype = ctypes.wintypes.DWORD
  152. WaitForSingleObjectEx.errcheck = _errcheck_dword
  153. WaitForSingleObjectEx.argtypes = (
  154. ctypes.wintypes.HANDLE, # hObject
  155. ctypes.wintypes.DWORD, # dwMilliseconds
  156. ctypes.wintypes.BOOL, # bAlertable
  157. )
  158. CreateIoCompletionPort = ctypes.windll.kernel32.CreateIoCompletionPort
  159. CreateIoCompletionPort.restype = ctypes.wintypes.HANDLE
  160. CreateIoCompletionPort.errcheck = _errcheck_handle
  161. CreateIoCompletionPort.argtypes = (
  162. ctypes.wintypes.HANDLE, # FileHandle
  163. ctypes.wintypes.HANDLE, # ExistingCompletionPort
  164. LPVOID, # CompletionKey
  165. ctypes.wintypes.DWORD, # NumberOfConcurrentThreads
  166. )
  167. GetQueuedCompletionStatus = ctypes.windll.kernel32.GetQueuedCompletionStatus
  168. GetQueuedCompletionStatus.restype = ctypes.wintypes.BOOL
  169. GetQueuedCompletionStatus.errcheck = _errcheck_bool
  170. GetQueuedCompletionStatus.argtypes = (
  171. ctypes.wintypes.HANDLE, # CompletionPort
  172. LPVOID, # lpNumberOfBytesTransferred
  173. LPVOID, # lpCompletionKey
  174. ctypes.POINTER(OVERLAPPED), # lpOverlapped
  175. ctypes.wintypes.DWORD, # dwMilliseconds
  176. )
  177. PostQueuedCompletionStatus = ctypes.windll.kernel32.PostQueuedCompletionStatus
  178. PostQueuedCompletionStatus.restype = ctypes.wintypes.BOOL
  179. PostQueuedCompletionStatus.errcheck = _errcheck_bool
  180. PostQueuedCompletionStatus.argtypes = (
  181. ctypes.wintypes.HANDLE, # CompletionPort
  182. ctypes.wintypes.DWORD, # lpNumberOfBytesTransferred
  183. ctypes.wintypes.DWORD, # lpCompletionKey
  184. ctypes.POINTER(OVERLAPPED), # lpOverlapped
  185. )
  186. class FILE_NOTIFY_INFORMATION(ctypes.Structure):
  187. _fields_ = [("NextEntryOffset", ctypes.wintypes.DWORD),
  188. ("Action", ctypes.wintypes.DWORD),
  189. ("FileNameLength", ctypes.wintypes.DWORD),
  190. #("FileName", (ctypes.wintypes.WCHAR * 1))]
  191. ("FileName", (ctypes.c_char * 1))]
  192. LPFNI = ctypes.POINTER(FILE_NOTIFY_INFORMATION)
  193. def get_FILE_NOTIFY_INFORMATION(readBuffer, nBytes):
  194. results = []
  195. while nBytes > 0:
  196. fni = ctypes.cast(readBuffer, LPFNI)[0]
  197. ptr = ctypes.addressof(fni) + FILE_NOTIFY_INFORMATION.FileName.offset
  198. #filename = ctypes.wstring_at(ptr, fni.FileNameLength)
  199. filename = ctypes.string_at(ptr, fni.FileNameLength)
  200. results.append((fni.Action, filename.decode('utf-16')))
  201. numToSkip = fni.NextEntryOffset
  202. if numToSkip <= 0:
  203. break
  204. readBuffer = readBuffer[numToSkip:]
  205. nBytes -= numToSkip # numToSkip is long. nBytes should be long too.
  206. return results
  207. def get_FILE_NOTIFY_INFORMATION_alt(event_buffer, nBytes):
  208. """Extract the information out of a FILE_NOTIFY_INFORMATION structure."""
  209. pos = 0
  210. event_buffer = event_buffer[:nBytes]
  211. while pos < len(event_buffer):
  212. jump, action, namelen = struct.unpack("iii", event_buffer[pos:pos + 12])
  213. # TODO: this may return a shortname or a longname, with no way
  214. # to tell which. Normalise them somehow?
  215. name = event_buffer[pos + 12:pos + 12 + namelen].decode("utf-16")
  216. yield (name, action)
  217. if not jump:
  218. break
  219. pos += jump