13 void (*callback) (flxNetlink *nl, struct nlmsghdr *n, gpointer userdata);
15 GSourceFuncs source_funcs;
18 static gboolean work(flxNetlink *nl) {
22 guint8 replybuf[64*1024];
24 struct nlmsghdr *p = (struct nlmsghdr *) replybuf;
26 if ((bytes = recv(nl->fd, replybuf, sizeof(replybuf), MSG_DONTWAIT)) < 0) {
28 if (errno == EAGAIN || errno == EINTR)
31 g_warning("NETLINK: recv() failed");
36 for (; bytes > 0; p = NLMSG_NEXT(p, bytes)) {
37 if (!NLMSG_OK(p, bytes)) {
38 g_warning("NETLINK: packet truncated");
42 nl->callback(nl, p, nl->userdata);
50 static gboolean prepare_func(GSource *source, gint *timeout) {
58 static gboolean check_func(GSource *source) {
62 nl = *((flxNetlink**) (((guint8*) source) + sizeof(GSource)));
65 return nl->poll_fd.revents & G_IO_IN;
68 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
72 nl = *((flxNetlink**) (((guint8*) source) + sizeof(GSource)));
78 flxNetlink *flx_netlink_new(GMainContext *context, guint32 groups, void (*cb) (flxNetlink *nl, struct nlmsghdr *n, gpointer userdata), gpointer userdata) {
80 struct sockaddr_nl addr;
86 if ((fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0) {
87 g_critical("NETLINK: socket(PF_NETLINK): %s", strerror(errno));
91 memset(&addr, 0, sizeof(addr));
92 addr.nl_family = AF_NETLINK;
93 addr.nl_groups = groups;
94 addr.nl_pid = getpid();
96 if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
98 g_critical("bind(): %s", strerror(errno));
102 nl = g_new(flxNetlink, 1);
103 nl->context = context;
104 g_main_context_ref(context);
108 nl->userdata = userdata;
110 memset(&nl->source_funcs, 0, sizeof(nl->source_funcs));
111 nl->source_funcs.prepare = prepare_func;
112 nl->source_funcs.check = check_func;
113 nl->source_funcs.dispatch = dispatch_func,
115 nl->source = g_source_new(&nl->source_funcs, sizeof(GSource) + sizeof(flxNetlink*));
116 *((flxNetlink**) (((guint8*) nl->source) + sizeof(GSource))) = nl;
118 memset(&nl->poll_fd, 0, sizeof(GPollFD));
120 nl->poll_fd.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
121 g_source_add_poll(nl->source, &nl->poll_fd);
123 g_source_attach(nl->source, nl->context);
128 void flx_netlink_free(flxNetlink *nl) {
131 g_source_destroy(nl->source);
132 g_source_unref(nl->source);
133 g_main_context_unref(nl->context);
138 int flx_netlink_send(flxNetlink *nl, struct nlmsghdr *m, guint *ret_seq) {
142 m->nlmsg_seq = nl->seq++;
143 m->nlmsg_flags |= NLM_F_ACK;
145 if (send(nl->fd, m, m->nlmsg_len, 0) < 0) {
146 g_warning("NETLINK: send(): %s\n", strerror(errno));
151 *ret_seq = m->nlmsg_seq;