Clarify that scripts are called synchronously.
[tinc] / src / event.c
1 /*
2     event.c -- I/O, timeout and signal event handling
3     Copyright (C) 2012-2013 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "dropin.h"
23 #include "event.h"
24 #include "net.h"
25 #include "utils.h"
26 #include "xalloc.h"
27
28 struct timeval now;
29
30 #ifndef HAVE_MINGW
31 static fd_set readfds;
32 static fd_set writefds;
33 #else
34 static const long READ_EVENTS = FD_READ | FD_ACCEPT | FD_CLOSE;
35 static const long WRITE_EVENTS = FD_WRITE | FD_CONNECT;
36 static DWORD event_count = 0;
37 #endif
38 static bool running;
39
40 static int io_compare(const io_t *a, const io_t *b) {
41 #ifndef HAVE_MINGW
42         return a->fd - b->fd;
43 #else
44         return a->event - b->event;
45 #endif
46 }
47
48 static int timeout_compare(const timeout_t *a, const timeout_t *b) {
49         struct timeval diff;
50         timersub(&a->tv, &b->tv, &diff);
51         if(diff.tv_sec < 0)
52                 return -1;
53         if(diff.tv_sec > 0)
54                 return 1;
55         if(diff.tv_usec < 0)
56                 return -1;
57         if(diff.tv_usec > 0)
58                 return 1;
59         if(a < b)
60                 return -1;
61         if(a > b)
62                 return 1;
63         return 0;
64 }
65
66 static splay_tree_t io_tree = {.compare = (splay_compare_t)io_compare};
67 static splay_tree_t timeout_tree = {.compare = (splay_compare_t)timeout_compare};
68
69 void io_add(io_t *io, io_cb_t cb, void *data, int fd, int flags) {
70         if(io->cb)
71                 return;
72
73         io->fd = fd;
74 #ifdef HAVE_MINGW
75         if (io->fd != -1) {
76                 io->event = WSACreateEvent();
77                 if (io->event == WSA_INVALID_EVENT)
78                         abort();
79         }
80         event_count++;
81 #endif
82         io->cb = cb;
83         io->data = data;
84         io->node.data = io;
85
86         io_set(io, flags);
87
88         if(!splay_insert_node(&io_tree, &io->node))
89                 abort();
90 }
91
92 #ifdef HAVE_MINGW
93 void io_add_event(io_t *io, io_cb_t cb, void *data, WSAEVENT event) {
94         io->event = event;
95         io_add(io, cb, data, -1, 0);
96 }
97 #endif
98
99 void io_set(io_t *io, int flags) {
100         if (flags == io->flags)
101                 return;
102         io->flags = flags;
103         if (io->fd == -1)
104                 return;
105
106 #ifndef HAVE_MINGW
107         if(flags & IO_READ)
108                 FD_SET(io->fd, &readfds);
109         else
110                 FD_CLR(io->fd, &readfds);
111
112         if(flags & IO_WRITE)
113                 FD_SET(io->fd, &writefds);
114         else
115                 FD_CLR(io->fd, &writefds);
116 #else
117         long events = 0;
118         if (flags & IO_WRITE)
119                 events |= WRITE_EVENTS;
120         if (flags & IO_READ)
121                 events |= READ_EVENTS;
122         if (WSAEventSelect(io->fd, io->event, events) != 0)
123                 abort();
124 #endif
125 }
126
127 void io_del(io_t *io) {
128         if(!io->cb)
129                 return;
130
131         io_set(io, 0);
132 #ifdef HAVE_MINGW
133         if (io->fd != -1 && WSACloseEvent(io->event) == FALSE)
134                 abort();
135         event_count--;
136 #endif
137
138         splay_unlink_node(&io_tree, &io->node);
139         io->cb = NULL;
140 }
141
142 void timeout_add(timeout_t *timeout, timeout_cb_t cb, void *data, struct timeval *tv) {
143         timeout->cb = cb;
144         timeout->data = data;
145         timeout->node.data = timeout;
146
147         timeout_set(timeout, tv);
148 }
149
150 void timeout_set(timeout_t *timeout, struct timeval *tv) {
151         if(timerisset(&timeout->tv))
152                 splay_unlink_node(&timeout_tree, &timeout->node);
153
154         if(!now.tv_sec)
155                 gettimeofday(&now, NULL);
156
157         timeradd(&now, tv, &timeout->tv);
158
159         if(!splay_insert_node(&timeout_tree, &timeout->node))
160                 abort();
161 }
162
163 void timeout_del(timeout_t *timeout) {
164         if(!timeout->cb)
165                 return;
166
167         splay_unlink_node(&timeout_tree, &timeout->node);
168         timeout->cb = 0;
169         timeout->tv = (struct timeval){0, 0};
170 }
171
172 #ifndef HAVE_MINGW
173 static int signal_compare(const signal_t *a, const signal_t *b) {
174         return a->signum - b->signum;
175 }
176
177 static io_t signalio;
178 static int pipefd[2] = {-1, -1};
179 static splay_tree_t signal_tree = {.compare = (splay_compare_t)signal_compare};
180
181 static void signal_handler(int signum) {
182         unsigned char num = signum;
183         write(pipefd[1], &num, 1);
184 }
185
186 static void signalio_handler(void *data, int flags) {
187         unsigned char signum;
188         if(read(pipefd[0], &signum, 1) != 1)
189                 return;
190
191         signal_t *sig = splay_search(&signal_tree, &((signal_t){.signum = signum}));
192         if(sig)
193                 sig->cb(sig->data);
194 }
195
196 static void pipe_init(void) {
197         if(!pipe(pipefd))
198                 io_add(&signalio, signalio_handler, NULL, pipefd[0], IO_READ);
199 }
200
201 void signal_add(signal_t *sig, signal_cb_t cb, void *data, int signum) {
202         if(sig->cb)
203                 return;
204
205         sig->cb = cb;
206         sig->data = data;
207         sig->signum = signum;
208         sig->node.data = sig;
209
210         if(pipefd[0] == -1)
211                 pipe_init();
212
213         signal(sig->signum, signal_handler);
214
215         if(!splay_insert_node(&signal_tree, &sig->node))
216                 abort();
217 }
218
219 void signal_del(signal_t *sig) {
220         if(!sig->cb)
221                 return;
222
223         signal(sig->signum, SIG_DFL);
224
225         splay_unlink_node(&signal_tree, &sig->node);
226         sig->cb = NULL;
227 }
228 #endif
229
230 static struct timeval * get_time_remaining(struct timeval *diff) {
231         gettimeofday(&now, NULL);
232         struct timeval *tv = NULL;
233
234         while(timeout_tree.head) {
235                 timeout_t *timeout = timeout_tree.head->data;
236                 timersub(&timeout->tv, &now, diff);
237
238                 if(diff->tv_sec < 0) {
239                         timeout->cb(timeout->data);
240                         if(timercmp(&timeout->tv, &now, <))
241                                 timeout_del(timeout);
242                 } else {
243                         tv = diff;
244                         break;
245                 }
246         }
247
248         return tv;
249 }
250
251 bool event_loop(void) {
252         running = true;
253
254 #ifndef HAVE_MINGW
255         fd_set readable;
256         fd_set writable;
257
258         while(running) {
259                 struct timeval diff;
260                 struct timeval *tv = get_time_remaining(&diff);
261                 memcpy(&readable, &readfds, sizeof readable);
262                 memcpy(&writable, &writefds, sizeof writable);
263
264                 int fds = 0;
265
266                 if(io_tree.tail) {
267                         io_t *last = io_tree.tail->data;
268                         fds = last->fd + 1;
269                 }
270
271                 int n = select(fds, &readable, &writable, NULL, tv);
272
273                 if(n < 0) {
274                         if(sockwouldblock(sockerrno))
275                                 continue;
276                         else
277                                 return false;
278                 }
279
280                 if(!n)
281                         continue;
282
283                 for splay_each(io_t, io, &io_tree) {
284                         if(FD_ISSET(io->fd, &writable))
285                                 io->cb(io->data, IO_WRITE);
286                         else if(FD_ISSET(io->fd, &readable))
287                                 io->cb(io->data, IO_READ);
288                         else
289                                 continue;
290
291                         /*
292                            There are scenarios in which the callback will remove another io_t from the tree
293                            (e.g. closing a double connection). Since splay_each does not support that, we
294                            need to exit the loop now. That's okay, since any remaining events will get picked
295                            up by the next select() call.
296                          */
297                         break;
298                 }
299         }
300 #else
301         while (running) {
302                 struct timeval diff;
303                 struct timeval *tv = get_time_remaining(&diff);
304                 DWORD timeout_ms = tv ? (tv->tv_sec * 1000 + tv->tv_usec / 1000 + 1) : WSA_INFINITE;
305
306                 if (!event_count) {
307                         Sleep(timeout_ms);
308                         continue;
309                 }
310
311                 /*
312                    For some reason, Microsoft decided to make the FD_WRITE event edge-triggered instead of level-triggered,
313                    which is the opposite of what select() does. In practice, that means that if a FD_WRITE event triggers,
314                    it will never trigger again until a send() returns EWOULDBLOCK. Since the semantics of this event loop
315                    is that write events are level-triggered (i.e. they continue firing until the socket is full), we need
316                    to emulate these semantics by making sure we fire each IO_WRITE that is still writeable.
317
318                    Note that technically FD_CLOSE has the same problem, but it's okay because user code does not rely on
319                    this event being fired again if ignored.
320                 */
321                 io_t* writeable_io = NULL;
322                 for splay_each(io_t, io, &io_tree)
323                         if (io->flags & IO_WRITE && send(io->fd, NULL, 0, 0) == 0) {
324                                 writeable_io = io;
325                                 break;
326                         }
327                 if (writeable_io) {
328                         writeable_io->cb(writeable_io->data, IO_WRITE);
329                         continue;
330                 }
331
332                 WSAEVENT* events = xmalloc(event_count * sizeof(*events));
333                 DWORD event_index = 0;
334                 for splay_each(io_t, io, &io_tree) {
335                         events[event_index] = io->event;
336                         event_index++;
337                 }
338
339                 DWORD result = WSAWaitForMultipleEvents(event_count, events, FALSE, timeout_ms, FALSE);
340
341                 WSAEVENT event;
342                 if (result >= WSA_WAIT_EVENT_0 && result < WSA_WAIT_EVENT_0 + event_count)
343                         event = events[result - WSA_WAIT_EVENT_0];
344                 free(events);
345                 if (result == WSA_WAIT_TIMEOUT)
346                         continue;
347                 if (result < WSA_WAIT_EVENT_0 || result >= WSA_WAIT_EVENT_0 + event_count)
348                         return false;
349
350                 io_t *io = splay_search(&io_tree, &((io_t){.event = event}));
351                 if (!io)
352                         abort();
353
354                 if (io->fd == -1) {
355                         io->cb(io->data, 0);
356                 } else {
357                         WSANETWORKEVENTS network_events;
358                         if (WSAEnumNetworkEvents(io->fd, io->event, &network_events) != 0)
359                                 return false;
360                         if (network_events.lNetworkEvents & WRITE_EVENTS)
361                                 io->cb(io->data, IO_WRITE);
362                         if (network_events.lNetworkEvents & READ_EVENTS)
363                                 io->cb(io->data, IO_READ);
364                 }
365         }
366 #endif
367
368         return true;
369 }
370
371 void event_exit(void) {
372         running = false;
373 }