source: trunk/libtransmission/watchdir-win32.c

Last change on this file was 14653, checked in by mikedld, 5 years ago

Fix line endings on last commit

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