13 void (*callback) (flxNetlink *nl, struct nlmsghdr *n, gpointer userdata);
16 static gboolean work(flxNetlink *nl) {
20 guint8 replybuf[64*1024];
22 struct nlmsghdr *p = (struct nlmsghdr *) replybuf;
24 if ((bytes = recv(nl->fd, replybuf, sizeof(replybuf), MSG_DONTWAIT)) < 0) {
26 if (errno == EAGAIN || errno == EINTR)
29 g_warning("NETLINK: recv() failed");
34 for (; bytes > 0; p = NLMSG_NEXT(p, bytes)) {
35 if (!NLMSG_OK(p, bytes)) {
36 g_warning("NETLINK: packet truncated");
40 nl->callback(nl, p, nl->userdata);
48 static gboolean prepare_func(GSource *source, gint *timeout) {
56 static gboolean check_func(GSource *source) {
60 nl = *((flxNetlink**) (((guint8*) source) + sizeof(GSource)));
63 return nl->poll_fd.revents & (G_IO_IN|G_IO_HUP|G_IO_ERR);
66 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
70 nl = *((flxNetlink**) (((guint8*) source) + sizeof(GSource)));
76 flxNetlink *flx_netlink_new(GMainContext *context, guint32 groups, void (*cb) (flxNetlink *nl, struct nlmsghdr *n, gpointer userdata), gpointer userdata) {
78 struct sockaddr_nl addr;
81 static GSourceFuncs source_funcs = {
93 if ((fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0) {
94 g_critical("NETLINK: socket(PF_NETLINK): %s", strerror(errno));
98 memset(&addr, 0, sizeof(addr));
99 addr.nl_family = AF_NETLINK;
100 addr.nl_groups = groups;
101 addr.nl_pid = getpid();
103 if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
105 g_critical("bind(): %s", strerror(errno));
109 nl = g_new(flxNetlink, 1);
110 nl->context = context;
111 g_main_context_ref(context);
115 nl->userdata = userdata;
117 nl->source = g_source_new(&source_funcs, sizeof(GSource) + sizeof(flxNetlink*));
118 *((flxNetlink**) (((guint8*) nl->source) + sizeof(GSource))) = nl;
120 memset(&nl->poll_fd, 0, sizeof(GPollFD));
122 nl->poll_fd.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
123 g_source_add_poll(nl->source, &nl->poll_fd);
125 g_source_attach(nl->source, nl->context);
130 void flx_netlink_free(flxNetlink *nl) {
133 g_source_destroy(nl->source);
134 g_source_unref(nl->source);
135 g_main_context_unref(nl->context);
140 int flx_netlink_send(flxNetlink *nl, struct nlmsghdr *m, guint *ret_seq) {
144 m->nlmsg_seq = nl->seq++;
145 m->nlmsg_flags |= NLM_F_ACK;
147 if (send(nl->fd, m, m->nlmsg_len, 0) < 0) {
148 g_warning("NETLINK: send(): %s\n", strerror(errno));
153 *ret_seq = m->nlmsg_seq;