1 /*
2 * This file Copyright (C) 2015-2016 Mnemosyne LLC
3 *
4 * It may be used under the GNU GPL versions 2 or 3
5 * or any future license endorsed by Mnemosyne LLC.
6 *
7 */
8
9 #include <errno.h>
10 #include <stddef.h> /* offsetof */
11 #include <stdlib.h> /* realloc() */
12
13 #include <process.h> /* _beginthreadex() */
14
15 #include <windows.h>
16
17 #include <event2/bufferevent.h>
18 #include <event2/event.h>
19 #include <event2/util.h>
20
21 #define __LIBTRANSMISSION_WATCHDIR_MODULE__
22
23 #include "transmission.h"
24 #include "log.h"
25 #include "net.h"
26 #include "tr-assert.h"
27 #include "utils.h"
28 #include "watchdir.h"
29 #include "watchdir-common.h"
30
31 /***
32 ****
33 ***/
34
35 #define log_error(...) (!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \
36 tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:win32", __VA_ARGS__))
37
38 /***
39 ****
40 ***/
41
42 typedef struct tr_watchdir_win32
43 {
44 tr_watchdir_backend base;
45
46 HANDLE fd;
47 OVERLAPPED overlapped;
48 DWORD buffer[8 * 1024 / sizeof(DWORD)];
49 evutil_socket_t notify_pipe[2];
50 struct bufferevent* event;
51 HANDLE thread;
52 }
53 tr_watchdir_win32;
54
55 #define BACKEND_UPCAST(b) ((tr_watchdir_win32*)(b))
56
57 #define WIN32_WATCH_MASK (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE)
58
59 /***
60 ****
61 ***/
62
tr_get_overlapped_result_ex(HANDLE handle,LPOVERLAPPED overlapped,LPDWORD bytes_transferred,DWORD timeout,BOOL alertable)63 static BOOL tr_get_overlapped_result_ex(HANDLE handle, LPOVERLAPPED overlapped, LPDWORD bytes_transferred, DWORD timeout,
64 BOOL alertable)
65 {
66 typedef BOOL (WINAPI* impl_t)(HANDLE, LPOVERLAPPED, LPDWORD, DWORD, BOOL);
67
68 static impl_t real_impl = NULL;
69 static bool is_real_impl_valid = false;
70
71 if (!is_real_impl_valid)
72 {
73 real_impl = (impl_t)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "GetOverlappedResultEx");
74 is_real_impl_valid = true;
75 }
76
77 if (real_impl != NULL)
78 {
79 return (*real_impl)(handle, overlapped, bytes_transferred, timeout, alertable);
80 }
81
82 DWORD const wait_result = WaitForSingleObjectEx(handle, timeout, alertable);
83
84 if (wait_result == WAIT_FAILED)
85 {
86 return FALSE;
87 }
88
89 if (wait_result == WAIT_IO_COMPLETION || wait_result == WAIT_TIMEOUT)
90 {
91 SetLastError(wait_result);
92 return FALSE;
93 }
94
95 TR_ASSERT(wait_result == WAIT_OBJECT_0);
96
97 return GetOverlappedResult(handle, overlapped, bytes_transferred, FALSE);
98 }
99
tr_watchdir_win32_thread(void * context)100 static unsigned int __stdcall tr_watchdir_win32_thread(void* context)
101 {
102 tr_watchdir_t const handle = context;
103 tr_watchdir_win32* const backend = BACKEND_UPCAST(tr_watchdir_get_backend(handle));
104 DWORD bytes_transferred;
105
106 while (tr_get_overlapped_result_ex(backend->fd, &backend->overlapped, &bytes_transferred, INFINITE, FALSE))
107 {
108 PFILE_NOTIFY_INFORMATION info = (PFILE_NOTIFY_INFORMATION)backend->buffer;
109
110 while (info->NextEntryOffset != 0)
111 {
112 *((BYTE**)&info) += info->NextEntryOffset;
113 }
114
115 info->NextEntryOffset = bytes_transferred - ((BYTE*)info - (BYTE*)backend->buffer);
116
117 send(backend->notify_pipe[1], (char const*)backend->buffer, bytes_transferred, 0);
118
119 if (!ReadDirectoryChangesW(backend->fd, backend->buffer, sizeof(backend->buffer), FALSE, WIN32_WATCH_MASK, NULL,
120 &backend->overlapped, NULL))
121 {
122 log_error("Failed to read directory changes");
123 return 0;
124 }
125 }
126
127 if (GetLastError() != ERROR_OPERATION_ABORTED)
128 {
129 log_error("Failed to wait for directory changes");
130 }
131
132 return 0;
133 }
134
tr_watchdir_win32_on_first_scan(evutil_socket_t fd UNUSED,short type UNUSED,void * context)135 static void tr_watchdir_win32_on_first_scan(evutil_socket_t fd UNUSED, short type UNUSED, void* context)
136 {
137 tr_watchdir_t const handle = context;
138
139 tr_watchdir_scan(handle, NULL);
140 }
141
tr_watchdir_win32_on_event(struct bufferevent * event,void * context)142 static void tr_watchdir_win32_on_event(struct bufferevent* event, void* context)
143 {
144 tr_watchdir_t const handle = context;
145 size_t nread;
146 size_t name_size = MAX_PATH * sizeof(WCHAR);
147 char* buffer = tr_malloc(sizeof(FILE_NOTIFY_INFORMATION) + name_size);
148 PFILE_NOTIFY_INFORMATION ev = (PFILE_NOTIFY_INFORMATION)buffer;
149 size_t const header_size = offsetof(FILE_NOTIFY_INFORMATION, FileName);
150
151 /* Read the size of the struct excluding name into buf. Guaranteed to have at
152 least sizeof(*ev) available */
153 while ((nread = bufferevent_read(event, ev, header_size)) != 0)
154 {
155 if (nread == (size_t)-1)
156 {
157 log_error("Failed to read event: %s", tr_strerror(errno));
158 break;
159 }
160
161 if (nread != header_size)
162 {
163 log_error("Failed to read event: expected %zu, got %zu bytes.", header_size, nread);
164 break;
165 }
166
167 size_t const nleft = ev->NextEntryOffset - nread;
168
169 TR_ASSERT(ev->FileNameLength % sizeof(WCHAR) == 0);
170 TR_ASSERT(ev->FileNameLength > 0);
171 TR_ASSERT(ev->FileNameLength <= nleft);
172
173 if (nleft > name_size)
174 {
175 name_size = nleft;
176 buffer = tr_realloc(buffer, sizeof(FILE_NOTIFY_INFORMATION) + name_size);
177 ev = (PFILE_NOTIFY_INFORMATION)buffer;
178 }
179
180 /* Consume entire name into buffer */
181 if ((nread = bufferevent_read(event, buffer + header_size, nleft)) == (size_t)-1)
182 {
183 log_error("Failed to read name: %s", tr_strerror(errno));
184 break;
185 }
186
187 if (nread != nleft)
188 {
189 log_error("Failed to read name: expected %zu, got %zu bytes.", nleft, nread);
190 break;
191 }
192
193 if (ev->Action == FILE_ACTION_ADDED || ev->Action == FILE_ACTION_MODIFIED || ev->Action == FILE_ACTION_RENAMED_NEW_NAME)
194 {
195 char* name = tr_win32_native_to_utf8(ev->FileName, ev->FileNameLength / sizeof(WCHAR));
196
197 if (name != NULL)
198 {
199 tr_watchdir_process(handle, name);
200 tr_free(name);
201 }
202 }
203 }
204
205 tr_free(buffer);
206 }
207
tr_watchdir_win32_free(tr_watchdir_backend * backend_base)208 static void tr_watchdir_win32_free(tr_watchdir_backend* backend_base)
209 {
210 tr_watchdir_win32* const backend = BACKEND_UPCAST(backend_base);
211
212 if (backend == NULL)
213 {
214 return;
215 }
216
217 TR_ASSERT(backend->base.free_func == &tr_watchdir_win32_free);
218
219 if (backend->fd != INVALID_HANDLE_VALUE)
220 {
221 CancelIoEx(backend->fd, &backend->overlapped);
222 }
223
224 if (backend->thread != NULL)
225 {
226 WaitForSingleObject(backend->thread, INFINITE);
227 CloseHandle(backend->thread);
228 }
229
230 if (backend->event != NULL)
231 {
232 bufferevent_free(backend->event);
233 }
234
235 if (backend->notify_pipe[0] != TR_BAD_SOCKET)
236 {
237 evutil_closesocket(backend->notify_pipe[0]);
238 }
239
240 if (backend->notify_pipe[1] != TR_BAD_SOCKET)
241 {
242 evutil_closesocket(backend->notify_pipe[1]);
243 }
244
245 if (backend->fd != INVALID_HANDLE_VALUE)
246 {
247 CloseHandle(backend->fd);
248 }
249
250 tr_free(backend);
251 }
252
tr_watchdir_win32_new(tr_watchdir_t handle)253 tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle)
254 {
255 char const* const path = tr_watchdir_get_path(handle);
256 wchar_t* wide_path;
257 tr_watchdir_win32* backend;
258
259 backend = tr_new0(tr_watchdir_win32, 1);
260 backend->base.free_func = &tr_watchdir_win32_free;
261 backend->fd = INVALID_HANDLE_VALUE;
262 backend->notify_pipe[0] = backend->notify_pipe[1] = TR_BAD_SOCKET;
263
264 if ((wide_path = tr_win32_utf8_to_native(path, -1)) == NULL)
265 {
266 log_error("Failed to convert \"%s\" to native path", path);
267 goto fail;
268 }
269
270 if ((backend->fd = CreateFileW(wide_path, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
271 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL)) == INVALID_HANDLE_VALUE)
272 {
273 log_error("Failed to open directory \"%s\"", path);
274 goto fail;
275 }
276
277 tr_free(wide_path);
278 wide_path = NULL;
279
280 backend->overlapped.Pointer = handle;
281
282 if (!ReadDirectoryChangesW(backend->fd, backend->buffer, sizeof(backend->buffer), FALSE, WIN32_WATCH_MASK, NULL,
283 &backend->overlapped, NULL))
284 {
285 log_error("Failed to read directory changes");
286 goto fail;
287 }
288
289 if (evutil_socketpair(AF_INET, SOCK_STREAM, 0, backend->notify_pipe) == -1)
290 {
291 log_error("Failed to create notify pipe: %s", tr_strerror(errno));
292 goto fail;
293 }
294
295 if ((backend->event = bufferevent_socket_new(tr_watchdir_get_event_base(handle), backend->notify_pipe[0], 0)) == NULL)
296 {
297 log_error("Failed to create event buffer: %s", tr_strerror(errno));
298 goto fail;
299 }
300
301 bufferevent_setwatermark(backend->event, EV_READ, sizeof(FILE_NOTIFY_INFORMATION), 0);
302 bufferevent_setcb(backend->event, &tr_watchdir_win32_on_event, NULL, NULL, handle);
303 bufferevent_enable(backend->event, EV_READ);
304
305 if ((backend->thread = (HANDLE)_beginthreadex(NULL, 0, &tr_watchdir_win32_thread, handle, 0, NULL)) == NULL)
306 {
307 log_error("Failed to create thread");
308 goto fail;
309 }
310
311 /* Perform an initial scan on the directory */
312 if (event_base_once(tr_watchdir_get_event_base(handle), -1, EV_TIMEOUT, &tr_watchdir_win32_on_first_scan, handle,
313 NULL) == -1)
314 {
315 log_error("Failed to perform initial scan: %s", tr_strerror(errno));
316 }
317
318 return BACKEND_DOWNCAST(backend);
319
320 fail:
321 tr_watchdir_win32_free(BACKEND_DOWNCAST(backend));
322 tr_free(wide_path);
323 return NULL;
324 }
325