libubox: replace strtok with _r version.
[project/libubox.git] / uloop.c
1 /*
2 * uloop - event loop implementation
3 *
4 * Copyright (C) 2010-2016 Felix Fietkau <nbd@openwrt.org>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18 #include <sys/time.h>
19 #include <sys/types.h>
20
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <poll.h>
26 #include <string.h>
27 #include <fcntl.h>
28 #include <stdbool.h>
29
30 #include "uloop.h"
31 #include "utils.h"
32
33 #ifdef USE_KQUEUE
34 #include <sys/event.h>
35 #endif
36 #ifdef USE_EPOLL
37 #include <sys/epoll.h>
38 #endif
39 #include <sys/wait.h>
40
41 struct uloop_fd_event {
42 struct uloop_fd *fd;
43 unsigned int events;
44 };
45
46 struct uloop_fd_stack {
47 struct uloop_fd_stack *next;
48 struct uloop_fd *fd;
49 unsigned int events;
50 };
51
52 static struct uloop_fd_stack *fd_stack = NULL;
53
54 #define ULOOP_MAX_EVENTS 10
55
56 static struct list_head timeouts = LIST_HEAD_INIT(timeouts);
57 static struct list_head processes = LIST_HEAD_INIT(processes);
58
59 static int poll_fd = -1;
60 bool uloop_cancelled = false;
61 static int uloop_status = 0;
62 static bool do_sigchld = false;
63
64 static struct uloop_fd_event cur_fds[ULOOP_MAX_EVENTS];
65 static int cur_fd, cur_nfds;
66
67 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags);
68
69 #ifdef USE_KQUEUE
70 #include "uloop-kqueue.c"
71 #endif
72
73 #ifdef USE_EPOLL
74 #include "uloop-epoll.c"
75 #endif
76
77 static void waker_consume(struct uloop_fd *fd, unsigned int events)
78 {
79 char buf[4];
80
81 while (read(fd->fd, buf, 4) > 0)
82 ;
83 }
84
85 static int waker_pipe = -1;
86 static struct uloop_fd waker_fd = {
87 .fd = -1,
88 .cb = waker_consume,
89 };
90
91 static void waker_init_fd(int fd)
92 {
93 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
94 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
95 }
96
97 static int waker_init(void)
98 {
99 int fds[2];
100
101 if (waker_pipe >= 0)
102 return 0;
103
104 if (pipe(fds) < 0)
105 return -1;
106
107 waker_init_fd(fds[0]);
108 waker_init_fd(fds[1]);
109 waker_pipe = fds[1];
110
111 waker_fd.fd = fds[0];
112 waker_fd.cb = waker_consume;
113 uloop_fd_add(&waker_fd, ULOOP_READ);
114
115 return 0;
116 }
117
118 int uloop_init(void)
119 {
120 if (uloop_init_pollfd() < 0)
121 return -1;
122
123 if (waker_init() < 0) {
124 uloop_done();
125 return -1;
126 }
127
128 return 0;
129 }
130
131 static bool uloop_fd_stack_event(struct uloop_fd *fd, int events)
132 {
133 struct uloop_fd_stack *cur;
134
135 /*
136 * Do not buffer events for level-triggered fds, they will keep firing.
137 * Caller needs to take care of recursion issues.
138 */
139 if (!(fd->flags & ULOOP_EDGE_TRIGGER))
140 return false;
141
142 for (cur = fd_stack; cur; cur = cur->next) {
143 if (cur->fd != fd)
144 continue;
145
146 if (events < 0)
147 cur->fd = NULL;
148 else
149 cur->events |= events | ULOOP_EVENT_BUFFERED;
150
151 return true;
152 }
153
154 return false;
155 }
156
157 static void uloop_run_events(int timeout)
158 {
159 struct uloop_fd_event *cur;
160 struct uloop_fd *fd;
161
162 if (!cur_nfds) {
163 cur_fd = 0;
164 cur_nfds = uloop_fetch_events(timeout);
165 if (cur_nfds < 0)
166 cur_nfds = 0;
167 }
168
169 while (cur_nfds > 0) {
170 struct uloop_fd_stack stack_cur;
171 unsigned int events;
172
173 cur = &cur_fds[cur_fd++];
174 cur_nfds--;
175
176 fd = cur->fd;
177 events = cur->events;
178 if (!fd)
179 continue;
180
181 if (!fd->cb)
182 continue;
183
184 if (uloop_fd_stack_event(fd, cur->events))
185 continue;
186
187 stack_cur.next = fd_stack;
188 stack_cur.fd = fd;
189 fd_stack = &stack_cur;
190 do {
191 stack_cur.events = 0;
192 fd->cb(fd, events);
193 events = stack_cur.events & ULOOP_EVENT_MASK;
194 } while (stack_cur.fd && events);
195 fd_stack = stack_cur.next;
196
197 return;
198 }
199 }
200
201 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags)
202 {
203 unsigned int fl;
204 int ret;
205
206 if (!(flags & (ULOOP_READ | ULOOP_WRITE)))
207 return uloop_fd_delete(sock);
208
209 if (!sock->registered && !(flags & ULOOP_BLOCKING)) {
210 fl = fcntl(sock->fd, F_GETFL, 0);
211 fl |= O_NONBLOCK;
212 fcntl(sock->fd, F_SETFL, fl);
213 }
214
215 ret = register_poll(sock, flags);
216 if (ret < 0)
217 goto out;
218
219 sock->registered = true;
220 sock->eof = false;
221 sock->error = false;
222
223 out:
224 return ret;
225 }
226
227 int uloop_fd_delete(struct uloop_fd *fd)
228 {
229 int i;
230
231 for (i = 0; i < cur_nfds; i++) {
232 if (cur_fds[cur_fd + i].fd != fd)
233 continue;
234
235 cur_fds[cur_fd + i].fd = NULL;
236 }
237
238 if (!fd->registered)
239 return 0;
240
241 fd->registered = false;
242 uloop_fd_stack_event(fd, -1);
243 return __uloop_fd_delete(fd);
244 }
245
246 static int tv_diff(struct timeval *t1, struct timeval *t2)
247 {
248 return
249 (t1->tv_sec - t2->tv_sec) * 1000 +
250 (t1->tv_usec - t2->tv_usec) / 1000;
251 }
252
253 int uloop_timeout_add(struct uloop_timeout *timeout)
254 {
255 struct uloop_timeout *tmp;
256 struct list_head *h = &timeouts;
257
258 if (timeout->pending)
259 return -1;
260
261 list_for_each_entry(tmp, &timeouts, list) {
262 if (tv_diff(&tmp->time, &timeout->time) > 0) {
263 h = &tmp->list;
264 break;
265 }
266 }
267
268 list_add_tail(&timeout->list, h);
269 timeout->pending = true;
270
271 return 0;
272 }
273
274 static void uloop_gettime(struct timeval *tv)
275 {
276 struct timespec ts;
277
278 clock_gettime(CLOCK_MONOTONIC, &ts);
279 tv->tv_sec = ts.tv_sec;
280 tv->tv_usec = ts.tv_nsec / 1000;
281 }
282
283 int uloop_timeout_set(struct uloop_timeout *timeout, int msecs)
284 {
285 struct timeval *time = &timeout->time;
286
287 if (timeout->pending)
288 uloop_timeout_cancel(timeout);
289
290 uloop_gettime(time);
291
292 time->tv_sec += msecs / 1000;
293 time->tv_usec += (msecs % 1000) * 1000;
294
295 if (time->tv_usec > 1000000) {
296 time->tv_sec++;
297 time->tv_usec -= 1000000;
298 }
299
300 return uloop_timeout_add(timeout);
301 }
302
303 int uloop_timeout_cancel(struct uloop_timeout *timeout)
304 {
305 if (!timeout->pending)
306 return -1;
307
308 list_del(&timeout->list);
309 timeout->pending = false;
310
311 return 0;
312 }
313
314 int uloop_timeout_remaining(struct uloop_timeout *timeout)
315 {
316 struct timeval now;
317
318 if (!timeout->pending)
319 return -1;
320
321 uloop_gettime(&now);
322
323 return tv_diff(&timeout->time, &now);
324 }
325
326 int uloop_process_add(struct uloop_process *p)
327 {
328 struct uloop_process *tmp;
329 struct list_head *h = &processes;
330
331 if (p->pending)
332 return -1;
333
334 list_for_each_entry(tmp, &processes, list) {
335 if (tmp->pid > p->pid) {
336 h = &tmp->list;
337 break;
338 }
339 }
340
341 list_add_tail(&p->list, h);
342 p->pending = true;
343
344 return 0;
345 }
346
347 int uloop_process_delete(struct uloop_process *p)
348 {
349 if (!p->pending)
350 return -1;
351
352 list_del(&p->list);
353 p->pending = false;
354
355 return 0;
356 }
357
358 static void uloop_handle_processes(void)
359 {
360 struct uloop_process *p, *tmp;
361 pid_t pid;
362 int ret;
363
364 do_sigchld = false;
365
366 while (1) {
367 pid = waitpid(-1, &ret, WNOHANG);
368 if (pid < 0 && errno == EINTR)
369 continue;
370
371 if (pid <= 0)
372 return;
373
374 list_for_each_entry_safe(p, tmp, &processes, list) {
375 if (p->pid < pid)
376 continue;
377
378 if (p->pid > pid)
379 break;
380
381 uloop_process_delete(p);
382 p->cb(p, ret);
383 }
384 }
385
386 }
387
388 static void uloop_signal_wake(void)
389 {
390 do {
391 if (write(waker_pipe, "w", 1) < 0) {
392 if (errno == EINTR)
393 continue;
394 }
395 break;
396 } while (1);
397 }
398
399 static void uloop_handle_sigint(int signo)
400 {
401 uloop_status = signo;
402 uloop_cancelled = true;
403 uloop_signal_wake();
404 }
405
406 static void uloop_sigchld(int signo)
407 {
408 do_sigchld = true;
409 uloop_signal_wake();
410 }
411
412 static void uloop_install_handler(int signum, void (*handler)(int), struct sigaction* old, bool add)
413 {
414 struct sigaction s;
415 struct sigaction *act;
416
417 act = NULL;
418 sigaction(signum, NULL, &s);
419
420 if (add) {
421 if (s.sa_handler == SIG_DFL) { /* Do not override existing custom signal handlers */
422 memcpy(old, &s, sizeof(struct sigaction));
423 s.sa_handler = handler;
424 s.sa_flags = 0;
425 act = &s;
426 }
427 }
428 else if (s.sa_handler == handler) { /* Do not restore if someone modified our handler */
429 act = old;
430 }
431
432 if (act != NULL)
433 sigaction(signum, act, NULL);
434 }
435
436 static void uloop_ignore_signal(int signum, bool ignore)
437 {
438 struct sigaction s;
439 void *new_handler = NULL;
440
441 sigaction(signum, NULL, &s);
442
443 if (ignore) {
444 if (s.sa_handler == SIG_DFL) /* Ignore only if there isn't any custom handler */
445 new_handler = SIG_IGN;
446 } else {
447 if (s.sa_handler == SIG_IGN) /* Restore only if noone modified our SIG_IGN */
448 new_handler = SIG_DFL;
449 }
450
451 if (new_handler) {
452 s.sa_handler = new_handler;
453 s.sa_flags = 0;
454 sigaction(signum, &s, NULL);
455 }
456 }
457
458 static void uloop_setup_signals(bool add)
459 {
460 static struct sigaction old_sigint, old_sigchld, old_sigterm;
461
462 uloop_install_handler(SIGINT, uloop_handle_sigint, &old_sigint, add);
463 uloop_install_handler(SIGTERM, uloop_handle_sigint, &old_sigterm, add);
464 uloop_install_handler(SIGCHLD, uloop_sigchld, &old_sigchld, add);
465
466 uloop_ignore_signal(SIGPIPE, add);
467 }
468
469 static int uloop_get_next_timeout(struct timeval *tv)
470 {
471 struct uloop_timeout *timeout;
472 int diff;
473
474 if (list_empty(&timeouts))
475 return -1;
476
477 timeout = list_first_entry(&timeouts, struct uloop_timeout, list);
478 diff = tv_diff(&timeout->time, tv);
479 if (diff < 0)
480 return 0;
481
482 return diff;
483 }
484
485 static void uloop_process_timeouts(struct timeval *tv)
486 {
487 struct uloop_timeout *t;
488
489 while (!list_empty(&timeouts)) {
490 t = list_first_entry(&timeouts, struct uloop_timeout, list);
491
492 if (tv_diff(&t->time, tv) > 0)
493 break;
494
495 uloop_timeout_cancel(t);
496 if (t->cb)
497 t->cb(t);
498 }
499 }
500
501 static void uloop_clear_timeouts(void)
502 {
503 struct uloop_timeout *t, *tmp;
504
505 list_for_each_entry_safe(t, tmp, &timeouts, list)
506 uloop_timeout_cancel(t);
507 }
508
509 static void uloop_clear_processes(void)
510 {
511 struct uloop_process *p, *tmp;
512
513 list_for_each_entry_safe(p, tmp, &processes, list)
514 uloop_process_delete(p);
515 }
516
517 int uloop_run(void)
518 {
519 static int recursive_calls = 0;
520 struct timeval tv;
521
522 /*
523 * Handlers are only updated for the first call to uloop_run() (and restored
524 * when this call is done).
525 */
526 if (!recursive_calls++)
527 uloop_setup_signals(true);
528
529 uloop_status = 0;
530 uloop_cancelled = false;
531 while (!uloop_cancelled)
532 {
533 uloop_gettime(&tv);
534 uloop_process_timeouts(&tv);
535
536 if (do_sigchld)
537 uloop_handle_processes();
538
539 if (uloop_cancelled)
540 break;
541
542 uloop_gettime(&tv);
543 uloop_run_events(uloop_get_next_timeout(&tv));
544 }
545
546 if (!--recursive_calls)
547 uloop_setup_signals(false);
548
549 return uloop_status;
550 }
551
552 void uloop_done(void)
553 {
554 if (poll_fd >= 0) {
555 close(poll_fd);
556 poll_fd = -1;
557 }
558
559 if (waker_pipe >= 0) {
560 uloop_fd_delete(&waker_fd);
561 close(waker_pipe);
562 close(waker_fd.fd);
563 waker_pipe = -1;
564 }
565
566 uloop_clear_timeouts();
567 uloop_clear_processes();
568 }