blob: 4af167047ec9d8ef5b1266040c7e4d3c1de0c416 [file] [log] [blame]
Harald Welte52b1f982008-12-23 20:25:15 +00001/* select filedescriptor handling, taken from:
2 * userspace logging daemon for the iptables ULOG target
3 * of the linux 2.4 netfilter subsystem.
4 *
5 * (C) 2000-2008 by Harald Welte <laforge@gnumonks.org>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2
9 * as published by the Free Software Foundation
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include <fcntl.h>
22#include <openbsc/select.h>
23#include <openbsc/linuxlist.h>
24
25static int maxfd = 0;
26static LLIST_HEAD(bsc_fds);
27
28int bsc_register_fd(struct bsc_fd *fd)
29{
30 int flags;
31
32 /* make FD nonblocking */
33 flags = fcntl(fd->fd, F_GETFL);
34 if (flags < 0)
Harald Welte8470bf22008-12-25 23:28:35 +000035 return flags;
Harald Welte52b1f982008-12-23 20:25:15 +000036 flags |= O_NONBLOCK;
37 flags = fcntl(fd->fd, F_SETFL, flags);
38 if (flags < 0)
Harald Welte8470bf22008-12-25 23:28:35 +000039 return flags;
Harald Welte52b1f982008-12-23 20:25:15 +000040
41 /* Register FD */
42 if (fd->fd > maxfd)
43 maxfd = fd->fd;
44
45 llist_add_tail(&fd->list, &bsc_fds);
46
47 return 0;
48}
49
50void bsc_unregister_fd(struct bsc_fd *fd)
51{
52 llist_del(&fd->list);
53}
54
55int bsc_select_main()
56{
57 struct bsc_fd *ufd;
58 fd_set readset, writeset, exceptset;
59 int i;
60
61 FD_ZERO(&readset);
62 FD_ZERO(&writeset);
63 FD_ZERO(&exceptset);
64
65 /* prepare read and write fdsets */
66 llist_for_each_entry(ufd, &bsc_fds, list) {
67 if (ufd->when & BSC_FD_READ)
68 FD_SET(ufd->fd, &readset);
69
70 if (ufd->when & BSC_FD_WRITE)
71 FD_SET(ufd->fd, &writeset);
72
73 if (ufd->when & BSC_FD_EXCEPT)
74 FD_SET(ufd->fd, &exceptset);
75 }
76
77 i = select(maxfd+1, &readset, &writeset, &exceptset, NULL);
78 if (i > 0) {
79 /* call registered callback functions */
80 llist_for_each_entry(ufd, &bsc_fds, list) {
81 int flags = 0;
82
83 if (FD_ISSET(ufd->fd, &readset))
84 flags |= BSC_FD_READ;
85
86 if (FD_ISSET(ufd->fd, &writeset))
87 flags |= BSC_FD_WRITE;
88
89 if (FD_ISSET(ufd->fd, &exceptset))
90 flags |= BSC_FD_EXCEPT;
91
92 if (flags)
93 ufd->cb(ufd, flags);
94 }
95 }
96 return i;
97}