| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
local ffi = require "ffi" |
| 21 |
local bitlib = assert(bit32 or bit, "Neither bit32 (Lua 5.2) nor bit (LuaJIT) found") |
| 22 |
|
| 23 |
ffi.cdef[[ |
| 24 |
typedef int BOOL; |
| 25 |
typedef unsigned int UINT; |
| 26 |
typedef uint32_t DWORD; |
| 27 |
typedef void *HANDLE; |
| 28 |
typedef uintptr_t ULONG_PTR; |
| 29 |
typedef uint16_t WCHAR; |
| 30 |
typedef struct _OVERLAPPED { |
| 31 |
ULONG_PTR Internal; |
| 32 |
ULONG_PTR InternalHigh; |
| 33 |
union { |
| 34 |
struct { |
| 35 |
DWORD Offset; |
| 36 |
DWORD OffsetHigh; |
| 37 |
}; |
| 38 |
void *Pointer; |
| 39 |
}; |
| 40 |
HANDLE hEvent; |
| 41 |
} OVERLAPPED; |
| 42 |
typedef struct _FILE_NOTIFY_INFORMATION { |
| 43 |
DWORD NextEntryOffset; |
| 44 |
DWORD Action; |
| 45 |
DWORD FileNameLength; |
| 46 |
WCHAR FileName[?]; |
| 47 |
} FILE_NOTIFY_INFORMATION; |
| 48 |
typedef void (__stdcall *LPOVERLAPPED_COMPLETION_ROUTINE)(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, OVERLAPPED *lpOverlapped); |
| 49 |
DWORD GetLastError(); |
| 50 |
BOOL CloseHandle(HANDLE hObject); |
| 51 |
HANDLE CreateFileA(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, void *lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile); |
| 52 |
HANDLE CreateIoCompletionPort(HANDLE fileHandle, HANDLE existingCompletionPort, ULONG_PTR completionKey, DWORD numberOfConcurrentThreads); |
| 53 |
BOOL ReadDirectoryChangesW(HANDLE hDirectory, void *lpBuffer, DWORD nBufferLength, BOOL bWatchSubtree, DWORD dwNotifyFilter, DWORD *lpBytesReturned, OVERLAPPED *lpOverlapped, LPOVERLAPPED_COMPLETION_ROUTINE lpOverlappedCompletionRoutine); |
| 54 |
BOOL GetQueuedCompletionStatus(HANDLE CompletionPort, DWORD *lpNumberOfBytes, ULONG_PTR *lpCompletionKey, OVERLAPPED **lpOverlapped, DWORD dwMilliseconds); |
| 55 |
int MultiByteToWideChar(UINT CodePage, DWORD dwFlags, const char *lpMultiByteStr, int cbMultiByte, WCHAR *lpWideCharStr, int cchWideChar); |
| 56 |
int WideCharToMultiByte(UINT CodePage, DWORD dwFlags, const WCHAR *lpWideCharStr, int cchWideChar, char *lpMultiByteStr, int cbMultiByte, const char *lpDefaultChar, BOOL *lpUsedDefaultChar); |
| 57 |
DWORD GetFullPathNameA(const char *lpFileName, DWORD nBufferLength, char *lpBuffer, char **lpFilePart); |
| 58 |
uint64_t GetTickCount64(); |
| 59 |
]] |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
local NULL = ffi.NULL |
| 64 |
|
| 65 |
|
| 66 |
local ERROR_FILE_NOT_FOUND = 0x0002 |
| 67 |
local ERROR_PATH_NOT_FOUND = 0x0003 |
| 68 |
local ERROR_ACCESS_DENIED = 0x0005 |
| 69 |
local ERROR_INVALID_PARAMETER = 0x0057 |
| 70 |
local ERROR_INSUFFICIENT_BUFFER = 0x007A |
| 71 |
local WAIT_TIMEOUT = 0x0102 |
| 72 |
local ERROR_ABANDONED_WAIT_0 = 0x02DF |
| 73 |
local ERROR_NOACCESS = 0x03E6 |
| 74 |
local ERROR_INVALID_FLAGS = 0x03EC |
| 75 |
local ERROR_NOTIFY_ENUM_DIR = 0x03FE |
| 76 |
local ERROR_NO_UNICODE_TRANSLATION = 0x0459 |
| 77 |
local KnownErrors = { |
| 78 |
[ERROR_FILE_NOT_FOUND] = "ERROR_FILE_NOT_FOUND", |
| 79 |
[ERROR_PATH_NOT_FOUND] = "ERROR_PATH_NOT_FOUND", |
| 80 |
[ERROR_ACCESS_DENIED] = "ERROR_ACCESS_DENIED", |
| 81 |
[ERROR_INVALID_PARAMETER] = "ERROR_INVALID_PARAMETER", |
| 82 |
[ERROR_INSUFFICIENT_BUFFER] = "ERROR_INSUFFICIENT_BUFFER", |
| 83 |
[ERROR_ABANDONED_WAIT_0] = "ERROR_ABANDONED_WAIT_0", |
| 84 |
[ERROR_NOACCESS] = "ERROR_NOACCESS", |
| 85 |
[ERROR_INVALID_FLAGS] = "ERROR_INVALID_FLAGS", |
| 86 |
[ERROR_NOTIFY_ENUM_DIR] = "ERROR_NOTIFY_ENUM_DIR", |
| 87 |
[ERROR_NO_UNICODE_TRANSLATION] = "ERROR_NO_UNICODE_TRANSLATION", |
| 88 |
} |
| 89 |
|
| 90 |
|
| 91 |
local FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 |
| 92 |
local FILE_FLAG_OVERLAPPED = 0x40000000 |
| 93 |
local OPEN_EXISTING = 3 |
| 94 |
local FILE_SHARE_READ = 0x00000001 |
| 95 |
local FILE_SHARE_WRITE = 0x00000002 |
| 96 |
local FILE_SHARE_DELETE = 0x00000004 |
| 97 |
local FILE_LIST_DIRECTORY = 0x1 |
| 98 |
local INVALID_HANDLE_VALUE = ffi.cast("void *", -1) |
| 99 |
|
| 100 |
|
| 101 |
local FILE_NOTIFY_CHANGE_FILE_NAME = 0x00000001 |
| 102 |
local FILE_NOTIFY_CHANGE_DIR_NAME = 0x00000002 |
| 103 |
local FILE_NOTIFY_CHANGE_ATTRIBUTES = 0x00000004 |
| 104 |
local FILE_NOTIFY_CHANGE_SIZE = 0x00000008 |
| 105 |
local FILE_NOTIFY_CHANGE_LAST_WRITE = 0x00000010 |
| 106 |
local FILE_NOTIFY_CHANGE_LAST_ACCESS = 0x00000020 |
| 107 |
local FILE_NOTIFY_CHANGE_CREATION = 0x00000040 |
| 108 |
local FILE_NOTIFY_CHANGE_SECURITY = 0x00000100 |
| 109 |
local FILE_ACTION_ADDED = 0x00000001 |
| 110 |
local FILE_ACTION_REMOVED = 0x00000002 |
| 111 |
local FILE_ACTION_MODIFIED = 0x00000003 |
| 112 |
local FILE_ACTION_RENAMED_OLD_NAME = 0x00000004 |
| 113 |
local FILE_ACTION_RENAMED_NEW_NAME = 0x00000005 |
| 114 |
|
| 115 |
|
| 116 |
local CP_ACP = 0 |
| 117 |
local CP_UTF8 = 65001 |
| 118 |
|
| 119 |
local C = ffi.C |
| 120 |
|
| 121 |
local function format_error(name, lasterror, extra) |
| 122 |
local errorname = KnownErrors[lasterror] or string.format("error code %d", lasterror) |
| 123 |
if extra then |
| 124 |
return string.format("%s failed with %s (0x%04x) [%s]", name, errorname, lasterror, extra) |
| 125 |
else |
| 126 |
return string.format("%s failed with %s (0x%04x)", name, errorname, lasterror) |
| 127 |
end |
| 128 |
end |
| 129 |
local function wcs_to_mbs(wstr, wstrlen, codepage) |
| 130 |
|
| 131 |
|
| 132 |
if wstrlen == 0 then |
| 133 |
return "" |
| 134 |
end |
| 135 |
codepage = codepage or CP_ACP |
| 136 |
local dwFlags = 0 |
| 137 |
local result = C.WideCharToMultiByte(codepage, dwFlags, wstr, wstrlen, nil, 0, nil, nil) |
| 138 |
if result <= 0 then |
| 139 |
|
| 140 |
local lasterror = C.GetLastError() |
| 141 |
|
| 142 |
return nil, format_error("WideCharToMultiByte", lasterror) |
| 143 |
end |
| 144 |
local mbsbuf = ffi.new("char[?]", result) |
| 145 |
result = C.WideCharToMultiByte(codepage, dwFlags, wstr, wstrlen, mbsbuf, result, nil, nil) |
| 146 |
if result <= 0 then |
| 147 |
|
| 148 |
local lasterror = C.GetLastError() |
| 149 |
|
| 150 |
return nil, format_error("WideCharToMultiByte", lasterror) |
| 151 |
end |
| 152 |
return ffi.string(mbsbuf, result) |
| 153 |
end |
| 154 |
local function mbs_to_wcs(str, codepage) |
| 155 |
|
| 156 |
if str == "" then |
| 157 |
return ffi.new("WCHAR[0]") |
| 158 |
end |
| 159 |
codepage = codepage or CP_ACP |
| 160 |
local dwFlags = 0 |
| 161 |
local result = C.MultiByteToWideChar(codepage, dwFlags, str, #str, nil, 0) |
| 162 |
if result <= 0 then |
| 163 |
local lasterror = C.GetLastError() |
| 164 |
|
| 165 |
return nil, format_error("MultiByteToWideChar", lasterror) |
| 166 |
end |
| 167 |
local wcsbuf = ffi.new("WCHAR[?]", result) |
| 168 |
result = C.MultiByteToWideChar(codepage, dwFlags, str, #str, wcsbuf, result) |
| 169 |
if result <= 0 then |
| 170 |
local lasterror = C.GetLastError() |
| 171 |
return nil, format_error("MultiByteToWideChar", lasterror) |
| 172 |
end |
| 173 |
return wcsbuf, result |
| 174 |
end |
| 175 |
|
| 176 |
|
| 177 |
do |
| 178 |
local ws = {0x3042} |
| 179 |
local resultstr = wcs_to_mbs(ffi.new("WCHAR[1]", ws), 1, CP_UTF8) |
| 180 |
assert(#resultstr == 3) |
| 181 |
assert(resultstr == "\xE3\x81\x82") |
| 182 |
end |
| 183 |
|
| 184 |
|
| 185 |
local function get_full_path_name(filename) |
| 186 |
local bufsize = 1024 |
| 187 |
local buffer |
| 188 |
local filePartPtr = ffi.new("char*[1]") |
| 189 |
local result |
| 190 |
repeat |
| 191 |
buffer = ffi.new("char[?]", bufsize) |
| 192 |
result = C.GetFullPathNameA(filename, bufsize, buffer, filePartPtr) |
| 193 |
if result == 0 then |
| 194 |
local lasterror = C.GetLastError() |
| 195 |
return nil, format_error("GetFullPathNameA", lasterror, filename) |
| 196 |
elseif bufsize < result then |
| 197 |
|
| 198 |
bufsize = result |
| 199 |
end |
| 200 |
until result < bufsize |
| 201 |
local fullpath = ffi.string(buffer, result) |
| 202 |
local filePart = ffi.string(filePartPtr[0]) |
| 203 |
local dirPart = ffi.string(buffer, ffi.cast("intptr_t", filePartPtr[0]) - ffi.cast("intptr_t", buffer)) |
| 204 |
return fullpath, filePart, dirPart |
| 205 |
end |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
local dirwatcher_meta = {} |
| 214 |
dirwatcher_meta.__index = dirwatcher_meta |
| 215 |
function dirwatcher_meta:close() |
| 216 |
if self._rawhandle ~= nil then |
| 217 |
C.CloseHandle(ffi.gc(self._rawhandle, nil)) |
| 218 |
self._rawhandle = nil |
| 219 |
end |
| 220 |
end |
| 221 |
local function open_directory(dirname) |
| 222 |
local dwShareMode = bitlib.bor(FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_SHARE_DELETE) |
| 223 |
local dwFlagsAndAttributes = bitlib.bor(FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED) |
| 224 |
local handle = C.CreateFileA(dirname, FILE_LIST_DIRECTORY, dwShareMode, nil, OPEN_EXISTING, dwFlagsAndAttributes, nil) |
| 225 |
if handle == INVALID_HANDLE_VALUE then |
| 226 |
local lasterror = C.GetLastError() |
| 227 |
print("Failed to open "..dirname) |
| 228 |
return nil, format_error("CreateFileA", lasterror, dirname) |
| 229 |
end |
| 230 |
return setmetatable({ |
| 231 |
dirname = dirname, |
| 232 |
_rawhandle = ffi.gc(handle, C.CloseHandle), |
| 233 |
_overlapped = ffi.new("OVERLAPPED"), |
| 234 |
_buffer = ffi.new("char[?]", 1024), |
| 235 |
}, dirwatcher_meta) |
| 236 |
end |
| 237 |
function dirwatcher_meta:start_watch(watchSubtree) |
| 238 |
local dwNotifyFilter = bitlib.bor(FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_LAST_ACCESS, FILE_NOTIFY_CHANGE_CREATION, FILE_NOTIFY_CHANGE_SECURITY) |
| 239 |
local buffer = self._buffer |
| 240 |
local bufferSize = ffi.sizeof(buffer) |
| 241 |
local result = C.ReadDirectoryChangesW(self._rawhandle, buffer, bufferSize, watchSubtree, dwNotifyFilter, nil, self._overlapped, nil) |
| 242 |
if result == 0 then |
| 243 |
local lasterror = C.GetLastError() |
| 244 |
return nil, format_error("ReadDirectoryChangesW", lasterror, self.dirname) |
| 245 |
end |
| 246 |
return true |
| 247 |
end |
| 248 |
local ActionTable = { |
| 249 |
[FILE_ACTION_ADDED] = "added", |
| 250 |
[FILE_ACTION_REMOVED] = "removed", |
| 251 |
[FILE_ACTION_MODIFIED] = "modified", |
| 252 |
[FILE_ACTION_RENAMED_OLD_NAME] = "rename_from", |
| 253 |
[FILE_ACTION_RENAMED_NEW_NAME] = "rename_to", |
| 254 |
} |
| 255 |
function dirwatcher_meta:process(numberOfBytes) |
| 256 |
|
| 257 |
local buffer = self._buffer |
| 258 |
numberOfBytes = math.min(numberOfBytes, ffi.sizeof(buffer)) |
| 259 |
local ptr = ffi.cast("char *", buffer) |
| 260 |
local structSize = ffi.sizeof("FILE_NOTIFY_INFORMATION", 1) |
| 261 |
local t = {} |
| 262 |
while numberOfBytes >= structSize do |
| 263 |
local notifyInfo = ffi.cast("FILE_NOTIFY_INFORMATION*", ptr) |
| 264 |
local nextEntryOffset = notifyInfo.NextEntryOffset |
| 265 |
local action = notifyInfo.Action |
| 266 |
local fileNameLength = notifyInfo.FileNameLength |
| 267 |
local fileName = notifyInfo.FileName |
| 268 |
local u = { action = ActionTable[action], filename = wcs_to_mbs(fileName, fileNameLength / 2) } |
| 269 |
table.insert(t, u) |
| 270 |
if nextEntryOffset == 0 or numberOfBytes <= nextEntryOffset then |
| 271 |
break |
| 272 |
end |
| 273 |
numberOfBytes = numberOfBytes - nextEntryOffset |
| 274 |
ptr = ptr + nextEntryOffset |
| 275 |
end |
| 276 |
return t |
| 277 |
end |
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 292 |
local fswatcher_meta = {} |
| 293 |
fswatcher_meta.__index = fswatcher_meta |
| 294 |
local function new_watcher() |
| 295 |
local port = C.CreateIoCompletionPort(INVALID_HANDLE_VALUE, nil, 0, 0) |
| 296 |
if port == NULL then |
| 297 |
local lasterror = C.GetLastError() |
| 298 |
return nil, format_error("CreateIoCompletionPort", lasterror) |
| 299 |
end |
| 300 |
return setmetatable({ |
| 301 |
_rawport = ffi.gc(port, C.CloseHandle), |
| 302 |
_pending = {}, |
| 303 |
_directories = {}, |
| 304 |
}, fswatcher_meta) |
| 305 |
end |
| 306 |
local function add_directory(self, dirname) |
| 307 |
local t = self._directories[dirname] |
| 308 |
if not t then |
| 309 |
local dirwatcher, err = open_directory(dirname) |
| 310 |
if not dirwatcher then |
| 311 |
return dirwatcher, err |
| 312 |
end |
| 313 |
t = { dirwatcher = dirwatcher, dirname = dirname, files = {} } |
| 314 |
table.insert(self, t) |
| 315 |
local i = #self |
| 316 |
local result = C.CreateIoCompletionPort(dirwatcher._rawhandle, self._rawport, i, 0) |
| 317 |
if result == NULL then |
| 318 |
local lasterror = C.GetLastError() |
| 319 |
return nil, format_error("CreateIoCompletionPort", lasterror, dirname) |
| 320 |
end |
| 321 |
self._directories[dirname] = t |
| 322 |
local result, err = dirwatcher:start_watch(false) |
| 323 |
if not result then |
| 324 |
return result, err |
| 325 |
end |
| 326 |
end |
| 327 |
return t |
| 328 |
end |
| 329 |
function fswatcher_meta:add_file(path, ...) |
| 330 |
local fullpath, filename, dirname = get_full_path_name(path) |
| 331 |
local t, err = add_directory(self, dirname) |
| 332 |
if not t then |
| 333 |
return t, err |
| 334 |
end |
| 335 |
t.files[filename] = path |
| 336 |
return true |
| 337 |
end |
| 338 |
local INFINITE = 0xFFFFFFFF |
| 339 |
local function get_queued(self, timeout) |
| 340 |
local startTime = C.GetTickCount64() |
| 341 |
local timeout_ms |
| 342 |
if timeout == nil then |
| 343 |
timeout_ms = INFINITE |
| 344 |
else |
| 345 |
timeout_ms = timeout * 1000 |
| 346 |
end |
| 347 |
local numberOfBytesPtr = ffi.new("DWORD[1]") |
| 348 |
local completionKeyPtr = ffi.new("ULONG_PTR[1]") |
| 349 |
local lpOverlapped = ffi.new("OVERLAPPED*[1]") |
| 350 |
repeat |
| 351 |
local result = C.GetQueuedCompletionStatus(self._rawport, numberOfBytesPtr, completionKeyPtr, lpOverlapped, timeout_ms) |
| 352 |
if result == 0 then |
| 353 |
local lasterror = C.GetLastError() |
| 354 |
if lasterror == WAIT_TIMEOUT then |
| 355 |
return nil, "timeout" |
| 356 |
else |
| 357 |
return nil, format_error("GetQueuedCompletionStatus", lasterror) |
| 358 |
end |
| 359 |
end |
| 360 |
local numberOfBytes = numberOfBytesPtr[0] |
| 361 |
local completionKey = tonumber(completionKeyPtr[0]) |
| 362 |
local dir_t = assert(self[completionKey], "invalid completion key: " .. tostring(completionKey)) |
| 363 |
local t = dir_t.dirwatcher:process(numberOfBytes) |
| 364 |
dir_t.dirwatcher:start_watch(false) |
| 365 |
local found = false |
| 366 |
for i,v in ipairs(t) do |
| 367 |
local path = dir_t.files[v.filename] |
| 368 |
if path then |
| 369 |
found = true |
| 370 |
table.insert(self._pending, {path = path, action = v.action}) |
| 371 |
end |
| 372 |
end |
| 373 |
if found then |
| 374 |
return true |
| 375 |
end |
| 376 |
if timeout_ms ~= INFINITE then |
| 377 |
local tt = C.GetTickCount64() |
| 378 |
timeout_ms = timeout_ms - (tt - startTime) |
| 379 |
startTime = tt |
| 380 |
end |
| 381 |
until timeout_ms < 0 |
| 382 |
return nil, "timeout" |
| 383 |
end |
| 384 |
function fswatcher_meta:next(timeout) |
| 385 |
if #self._pending > 0 then |
| 386 |
local result = table.remove(self._pending, 1) |
| 387 |
get_queued(self, 0) |
| 388 |
return result |
| 389 |
else |
| 390 |
local result, err = get_queued(self, timeout) |
| 391 |
if result == nil then |
| 392 |
return nil, err |
| 393 |
end |
| 394 |
return table.remove(self._pending, 1) |
| 395 |
end |
| 396 |
end |
| 397 |
function fswatcher_meta:close() |
| 398 |
if self._rawport ~= nil then |
| 399 |
for i,v in ipairs(self) do |
| 400 |
v.dirwatcher:close() |
| 401 |
end |
| 402 |
C.CloseHandle(ffi.gc(self._rawport, nil)) |
| 403 |
self._rawport = nil |
| 404 |
end |
| 405 |
end |
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
|
| 420 |
|
| 421 |
return { |
| 422 |
new = new_watcher, |
| 423 |
} |