13 void (*callback) (flxNetlink *nl, struct nlmsghdr *n, gpointer userdata);
17 gboolean flx_netlink_work(flxNetlink *nl, gboolean block) {
21 guint8 replybuf[64*1024];
23 struct nlmsghdr *p = (struct nlmsghdr *) replybuf;
25 if ((bytes = recv(nl->fd, replybuf, sizeof(replybuf), block ? 0 : MSG_DONTWAIT)) < 0) {
27 if (errno == EAGAIN || errno == EINTR)
30 g_warning("NETLINK: recv() failed");
35 for (; bytes > 0; p = NLMSG_NEXT(p, bytes)) {
36 if (!NLMSG_OK(p, (size_t) bytes)) {
37 g_warning("NETLINK: packet truncated");
41 nl->callback(nl, p, nl->userdata);
52 static gboolean prepare_func(GSource *source, gint *timeout) {
60 static gboolean check_func(GSource *source) {
64 nl = *((flxNetlink**) (((guint8*) source) + sizeof(GSource)));
67 return nl->poll_fd.revents & (G_IO_IN|G_IO_HUP|G_IO_ERR);
70 static gboolean dispatch_func(GSource *source, GSourceFunc callback, gpointer user_data) {
74 nl = *((flxNetlink**) (((guint8*) source) + sizeof(GSource)));
77 return flx_netlink_work(nl, FALSE);
80 flxNetlink *flx_netlink_new(GMainContext *context, gint priority, guint32 groups, void (*cb) (flxNetlink *nl, struct nlmsghdr *n, gpointer userdata), gpointer userdata) {
82 struct sockaddr_nl addr;
85 static GSourceFuncs source_funcs = {
97 if ((fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0) {
98 g_critical("NETLINK: socket(PF_NETLINK): %s", strerror(errno));
102 memset(&addr, 0, sizeof(addr));
103 addr.nl_family = AF_NETLINK;
104 addr.nl_groups = groups;
105 addr.nl_pid = getpid();
107 if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
109 g_critical("bind(): %s", strerror(errno));
113 nl = g_new(flxNetlink, 1);
114 nl->context = context;
115 g_main_context_ref(context);
119 nl->userdata = userdata;
121 nl->source = g_source_new(&source_funcs, sizeof(GSource) + sizeof(flxNetlink*));
122 *((flxNetlink**) (((guint8*) nl->source) + sizeof(GSource))) = nl;
124 g_source_set_priority(nl->source, priority);
126 memset(&nl->poll_fd, 0, sizeof(GPollFD));
128 nl->poll_fd.events = G_IO_IN|G_IO_ERR|G_IO_HUP;
129 g_source_add_poll(nl->source, &nl->poll_fd);
131 g_source_attach(nl->source, nl->context);
136 void flx_netlink_free(flxNetlink *nl) {
139 g_source_destroy(nl->source);
140 g_source_unref(nl->source);
141 g_main_context_unref(nl->context);
146 int flx_netlink_send(flxNetlink *nl, struct nlmsghdr *m, guint *ret_seq) {
150 m->nlmsg_seq = nl->seq++;
151 m->nlmsg_flags |= NLM_F_ACK;
153 if (send(nl->fd, m, m->nlmsg_len, 0) < 0) {
154 g_warning("NETLINK: send(): %s\n", strerror(errno));
159 *ret_seq = m->nlmsg_seq;