netlink-socket: New function nl_lookup_genl_mcgroup().
[cascardo/ovs.git] / lib / netlink-socket.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "netlink-socket.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "hash.h"
28 #include "hmap.h"
29 #include "netlink.h"
30 #include "netlink-protocol.h"
31 #include "ofpbuf.h"
32 #include "poll-loop.h"
33 #include "socket-util.h"
34 #include "stress.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(netlink_socket);
38
39 COVERAGE_DEFINE(netlink_overflow);
40 COVERAGE_DEFINE(netlink_received);
41 COVERAGE_DEFINE(netlink_recv_jumbo);
42 COVERAGE_DEFINE(netlink_send);
43 COVERAGE_DEFINE(netlink_sent);
44
45 /* Linux header file confusion causes this to be undefined. */
46 #ifndef SOL_NETLINK
47 #define SOL_NETLINK 270
48 #endif
49
50 /* A single (bad) Netlink message can in theory dump out many, many log
51  * messages, so the burst size is set quite high here to avoid missing useful
52  * information.  Also, at high logging levels we log *all* Netlink messages. */
53 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
54
55 static void log_nlmsg(const char *function, int error,
56                       const void *message, size_t size, int protocol);
57 \f
58 /* Netlink sockets. */
59
60 struct nl_sock
61 {
62     int fd;
63     uint32_t pid;
64     int protocol;
65     bool any_groups;
66     struct nl_dump *dump;
67 };
68
69 static int alloc_pid(uint32_t *);
70 static void free_pid(uint32_t);
71 static int nl_sock_cow__(struct nl_sock *);
72
73 /* Creates a new netlink socket for the given netlink 'protocol'
74  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
75  * new socket if successful, otherwise returns a positive errno value.  */
76 int
77 nl_sock_create(int protocol, struct nl_sock **sockp)
78 {
79     struct nl_sock *sock;
80     struct sockaddr_nl local, remote;
81     int retval = 0;
82
83     *sockp = NULL;
84     sock = malloc(sizeof *sock);
85     if (sock == NULL) {
86         return ENOMEM;
87     }
88
89     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
90     if (sock->fd < 0) {
91         VLOG_ERR("fcntl: %s", strerror(errno));
92         goto error;
93     }
94     sock->protocol = protocol;
95     sock->any_groups = false;
96     sock->dump = NULL;
97
98     retval = alloc_pid(&sock->pid);
99     if (retval) {
100         goto error;
101     }
102
103     /* Bind local address as our selected pid. */
104     memset(&local, 0, sizeof local);
105     local.nl_family = AF_NETLINK;
106     local.nl_pid = sock->pid;
107     if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
108         VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
109         goto error_free_pid;
110     }
111
112     /* Bind remote address as the kernel (pid 0). */
113     memset(&remote, 0, sizeof remote);
114     remote.nl_family = AF_NETLINK;
115     remote.nl_pid = 0;
116     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
117         VLOG_ERR("connect(0): %s", strerror(errno));
118         goto error_free_pid;
119     }
120
121     *sockp = sock;
122     return 0;
123
124 error_free_pid:
125     free_pid(sock->pid);
126 error:
127     if (retval == 0) {
128         retval = errno;
129         if (retval == 0) {
130             retval = EINVAL;
131         }
132     }
133     if (sock->fd >= 0) {
134         close(sock->fd);
135     }
136     free(sock);
137     return retval;
138 }
139
140 /* Creates a new netlink socket for the same protocol as 'src'.  Returns 0 and
141  * sets '*sockp' to the new socket if successful, otherwise returns a positive
142  * errno value.  */
143 int
144 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
145 {
146     return nl_sock_create(src->protocol, sockp);
147 }
148
149 /* Destroys netlink socket 'sock'. */
150 void
151 nl_sock_destroy(struct nl_sock *sock)
152 {
153     if (sock) {
154         if (sock->dump) {
155             sock->dump = NULL;
156         } else {
157             close(sock->fd);
158             free_pid(sock->pid);
159             free(sock);
160         }
161     }
162 }
163
164 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
165  * successful, otherwise a positive errno value.
166  *
167  * Multicast group numbers are always positive.
168  *
169  * It is not an error to attempt to join a multicast group to which a socket
170  * already belongs. */
171 int
172 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
173 {
174     int error = nl_sock_cow__(sock);
175     if (error) {
176         return error;
177     }
178     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
179                    &multicast_group, sizeof multicast_group) < 0) {
180         VLOG_WARN("could not join multicast group %u (%s)",
181                   multicast_group, strerror(errno));
182         return errno;
183     }
184     sock->any_groups = true;
185     return 0;
186 }
187
188 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
189  * successful, otherwise a positive errno value.
190  *
191  * Multicast group numbers are always positive.
192  *
193  * It is not an error to attempt to leave a multicast group to which a socket
194  * does not belong.
195  *
196  * On success, reading from 'sock' will still return any messages that were
197  * received on 'multicast_group' before the group was left. */
198 int
199 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
200 {
201     assert(!sock->dump);
202     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
203                    &multicast_group, sizeof multicast_group) < 0) {
204         VLOG_WARN("could not leave multicast group %u (%s)",
205                   multicast_group, strerror(errno));
206         return errno;
207     }
208     return 0;
209 }
210
211 static int
212 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
213 {
214     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
215     int error;
216
217     nlmsg->nlmsg_len = msg->size;
218     nlmsg->nlmsg_pid = sock->pid;
219     do {
220         int retval;
221         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
222         error = retval < 0 ? errno : 0;
223     } while (error == EINTR);
224     log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
225     if (!error) {
226         COVERAGE_INC(netlink_sent);
227     }
228     return error;
229 }
230
231 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
232  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, and
233  * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
234  *
235  * Returns 0 if successful, otherwise a positive errno value.  If
236  * 'wait' is true, then the send will wait until buffer space is ready;
237  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
238 int
239 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
240 {
241     int error = nl_sock_cow__(sock);
242     if (error) {
243         return error;
244     }
245     return nl_sock_send__(sock, msg, wait);
246 }
247
248 /* This stress option is useful for testing that OVS properly tolerates
249  * -ENOBUFS on NetLink sockets.  Such errors are unavoidable because they can
250  * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
251  * reply to a request.  They can also occur if messages arrive on a multicast
252  * channel faster than OVS can process them. */
253 STRESS_OPTION(
254     netlink_overflow, "simulate netlink socket receive buffer overflow",
255     5, 1, -1, 100);
256
257 static int
258 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
259 {
260     /* We can't accurately predict the size of the data to be received.  Most
261      * received data will fit in a 2 kB buffer, so we allocate that much space.
262      * In case the data is actually bigger than that, we make available enough
263      * additional space to allow Netlink messages to be up to 64 kB long (a
264      * reasonable figure since that's the maximum length of a Netlink
265      * attribute). */
266     enum { MAX_SIZE = 65536 };
267     enum { HEAD_SIZE = 2048 };
268     enum { TAIL_SIZE = MAX_SIZE - HEAD_SIZE };
269
270     struct nlmsghdr *nlmsghdr;
271     uint8_t tail[TAIL_SIZE];
272     struct iovec iov[2];
273     struct ofpbuf *buf;
274     struct msghdr msg;
275     ssize_t retval;
276
277     *bufp = NULL;
278
279     buf = ofpbuf_new(HEAD_SIZE);
280     iov[0].iov_base = buf->data;
281     iov[0].iov_len = HEAD_SIZE;
282     iov[1].iov_base = tail;
283     iov[1].iov_len = TAIL_SIZE;
284
285     memset(&msg, 0, sizeof msg);
286     msg.msg_iov = iov;
287     msg.msg_iovlen = 2;
288
289     do {
290         retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
291     } while (retval < 0 && errno == EINTR);
292
293     if (retval < 0) {
294         int error = errno;
295         if (error == ENOBUFS) {
296             /* Socket receive buffer overflow dropped one or more messages that
297              * the kernel tried to send to us. */
298             COVERAGE_INC(netlink_overflow);
299         }
300         ofpbuf_delete(buf);
301         return error;
302     }
303
304     if (msg.msg_flags & MSG_TRUNC) {
305         VLOG_ERR_RL(&rl, "truncated message (longer than %d bytes)", MAX_SIZE);
306         ofpbuf_delete(buf);
307         return E2BIG;
308     }
309
310     ofpbuf_put_uninit(buf, MIN(retval, HEAD_SIZE));
311     if (retval > HEAD_SIZE) {
312         COVERAGE_INC(netlink_recv_jumbo);
313         ofpbuf_put(buf, tail, retval - HEAD_SIZE);
314     }
315
316     nlmsghdr = buf->data;
317     if (retval < sizeof *nlmsghdr
318         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
319         || nlmsghdr->nlmsg_len > retval) {
320         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
321                     retval, NLMSG_HDRLEN);
322         ofpbuf_delete(buf);
323         return EPROTO;
324     }
325
326     if (STRESS(netlink_overflow)) {
327         ofpbuf_delete(buf);
328         return ENOBUFS;
329     }
330
331     *bufp = buf;
332     log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
333     COVERAGE_INC(netlink_received);
334
335     return 0;
336 }
337
338 /* Tries to receive a netlink message from the kernel on 'sock'.  If
339  * successful, stores the received message into '*bufp' and returns 0.  The
340  * caller is responsible for destroying the message with ofpbuf_delete().  On
341  * failure, returns a positive errno value and stores a null pointer into
342  * '*bufp'.
343  *
344  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
345  * returns EAGAIN if the 'sock' receive buffer is empty. */
346 int
347 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
348 {
349     int error = nl_sock_cow__(sock);
350     if (error) {
351         return error;
352     }
353     return nl_sock_recv__(sock, bufp, wait);
354 }
355
356 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
357  * successful, returns 0.  On failure, returns a positive errno value.
358  *
359  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
360  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
361  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
362  * reply, if any, is discarded.
363  *
364  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
365  * be set to 'sock''s pid, before the message is sent.  NLM_F_ACK will be set
366  * in nlmsg_flags.
367  *
368  * The caller is responsible for destroying 'request'.
369  *
370  * Bare Netlink is an unreliable transport protocol.  This function layers
371  * reliable delivery and reply semantics on top of bare Netlink.
372  *
373  * In Netlink, sending a request to the kernel is reliable enough, because the
374  * kernel will tell us if the message cannot be queued (and we will in that
375  * case put it on the transmit queue and wait until it can be delivered).
376  *
377  * Receiving the reply is the real problem: if the socket buffer is full when
378  * the kernel tries to send the reply, the reply will be dropped.  However, the
379  * kernel sets a flag that a reply has been dropped.  The next call to recv
380  * then returns ENOBUFS.  We can then re-send the request.
381  *
382  * Caveats:
383  *
384  *      1. Netlink depends on sequence numbers to match up requests and
385  *         replies.  The sender of a request supplies a sequence number, and
386  *         the reply echos back that sequence number.
387  *
388  *         This is fine, but (1) some kernel netlink implementations are
389  *         broken, in that they fail to echo sequence numbers and (2) this
390  *         function will drop packets with non-matching sequence numbers, so
391  *         that only a single request can be usefully transacted at a time.
392  *
393  *      2. Resending the request causes it to be re-executed, so the request
394  *         needs to be idempotent.
395  */
396 int
397 nl_sock_transact(struct nl_sock *sock,
398                  const struct ofpbuf *request, struct ofpbuf **replyp)
399 {
400     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
401     struct nlmsghdr *nlmsghdr;
402     struct ofpbuf *reply;
403     int retval;
404
405     if (replyp) {
406         *replyp = NULL;
407     }
408
409     /* Ensure that we get a reply even if this message doesn't ordinarily call
410      * for one. */
411     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
412
413 send:
414     retval = nl_sock_send(sock, request, true);
415     if (retval) {
416         return retval;
417     }
418
419 recv:
420     retval = nl_sock_recv(sock, &reply, true);
421     if (retval) {
422         if (retval == ENOBUFS) {
423             COVERAGE_INC(netlink_overflow);
424             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
425             goto send;
426         } else {
427             return retval;
428         }
429     }
430     nlmsghdr = nl_msg_nlmsghdr(reply);
431     if (seq != nlmsghdr->nlmsg_seq) {
432         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
433                     nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
434         ofpbuf_delete(reply);
435         goto recv;
436     }
437
438     /* If the reply is an error, discard the reply and return the error code.
439      *
440      * Except: if the reply is just an acknowledgement (error code of 0), and
441      * the caller is interested in the reply (replyp != NULL), pass the reply
442      * up to the caller.  Otherwise the caller will get a return value of 0
443      * and null '*replyp', which makes unwary callers likely to segfault. */
444     if (nl_msg_nlmsgerr(reply, &retval) && (retval || !replyp)) {
445         ofpbuf_delete(reply);
446         if (retval) {
447             VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
448                         retval, strerror(retval));
449         }
450         return retval != EAGAIN ? retval : EPROTO;
451     }
452
453     if (replyp) {
454         *replyp = reply;
455     } else {
456         ofpbuf_delete(reply);
457     }
458     return 0;
459 }
460
461 /* Drain all the messages currently in 'sock''s receive queue. */
462 int
463 nl_sock_drain(struct nl_sock *sock)
464 {
465     int error = nl_sock_cow__(sock);
466     if (error) {
467         return error;
468     }
469     return drain_rcvbuf(sock->fd);
470 }
471
472 /* The client is attempting some operation on 'sock'.  If 'sock' has an ongoing
473  * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
474  * old fd over to the dump. */
475 static int
476 nl_sock_cow__(struct nl_sock *sock)
477 {
478     struct nl_sock *copy;
479     uint32_t tmp_pid;
480     int tmp_fd;
481     int error;
482
483     if (!sock->dump) {
484         return 0;
485     }
486
487     error = nl_sock_clone(sock, &copy);
488     if (error) {
489         return error;
490     }
491
492     tmp_fd = sock->fd;
493     sock->fd = copy->fd;
494     copy->fd = tmp_fd;
495
496     tmp_pid = sock->pid;
497     sock->pid = copy->pid;
498     copy->pid = tmp_pid;
499
500     sock->dump->sock = copy;
501     sock->dump = NULL;
502
503     return 0;
504 }
505
506 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
507  * 'sock', and initializes 'dump' to reflect the state of the operation.
508  *
509  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
510  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
511  * NLM_F_ACK will be set in nlmsg_flags.
512  *
513  * This Netlink socket library is designed to ensure that the dump is reliable
514  * and that it will not interfere with other operations on 'sock', including
515  * destroying or sending and receiving messages on 'sock'.  One corner case is
516  * not handled:
517  *
518  *   - If 'sock' has been used to send a request (e.g. with nl_sock_send())
519  *     whose response has not yet been received (e.g. with nl_sock_recv()).
520  *     This is unusual: usually nl_sock_transact() is used to send a message
521  *     and receive its reply all in one go.
522  *
523  * This function provides no status indication.  An error status for the entire
524  * dump operation is provided when it is completed by calling nl_dump_done().
525  *
526  * The caller is responsible for destroying 'request'.
527  *
528  * The new 'dump' is independent of 'sock'.  'sock' and 'dump' may be destroyed
529  * in either order.
530  */
531 void
532 nl_dump_start(struct nl_dump *dump,
533               struct nl_sock *sock, const struct ofpbuf *request)
534 {
535     struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
536     nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
537     dump->seq = nlmsghdr->nlmsg_seq;
538     dump->buffer = NULL;
539     if (sock->any_groups || sock->dump) {
540         /* 'sock' might belong to some multicast group, or it already has an
541          * onoging dump.  Clone the socket to avoid possibly intermixing
542          * multicast messages or previous dump results with our results. */
543         dump->status = nl_sock_clone(sock, &dump->sock);
544         if (dump->status) {
545             return;
546         }
547     } else {
548         sock->dump = dump;
549         dump->sock = sock;
550         dump->status = 0;
551     }
552     dump->status = nl_sock_send__(sock, request, true);
553 }
554
555 /* Helper function for nl_dump_next(). */
556 static int
557 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
558 {
559     struct nlmsghdr *nlmsghdr;
560     struct ofpbuf *buffer;
561     int retval;
562
563     retval = nl_sock_recv__(dump->sock, bufferp, true);
564     if (retval) {
565         return retval == EINTR ? EAGAIN : retval;
566     }
567     buffer = *bufferp;
568
569     nlmsghdr = nl_msg_nlmsghdr(buffer);
570     if (dump->seq != nlmsghdr->nlmsg_seq) {
571         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
572                     nlmsghdr->nlmsg_seq, dump->seq);
573         return EAGAIN;
574     }
575
576     if (nl_msg_nlmsgerr(buffer, &retval)) {
577         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
578                      strerror(retval));
579         return retval && retval != EAGAIN ? retval : EPROTO;
580     }
581
582     return 0;
583 }
584
585 /* Attempts to retrieve another reply from 'dump', which must have been
586  * initialized with nl_dump_start().
587  *
588  * If successful, returns true and points 'reply->data' and 'reply->size' to
589  * the message that was retrieved.  The caller must not modify 'reply' (because
590  * it points into the middle of a larger buffer).
591  *
592  * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
593  * to 0.  Failure might indicate an actual error or merely the end of replies.
594  * An error status for the entire dump operation is provided when it is
595  * completed by calling nl_dump_done().
596  */
597 bool
598 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
599 {
600     struct nlmsghdr *nlmsghdr;
601
602     reply->data = NULL;
603     reply->size = 0;
604     if (dump->status) {
605         return false;
606     }
607
608     if (dump->buffer && !dump->buffer->size) {
609         ofpbuf_delete(dump->buffer);
610         dump->buffer = NULL;
611     }
612     while (!dump->buffer) {
613         int retval = nl_dump_recv(dump, &dump->buffer);
614         if (retval) {
615             ofpbuf_delete(dump->buffer);
616             dump->buffer = NULL;
617             if (retval != EAGAIN) {
618                 dump->status = retval;
619                 return false;
620             }
621         }
622     }
623
624     nlmsghdr = nl_msg_next(dump->buffer, reply);
625     if (!nlmsghdr) {
626         VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
627         dump->status = EPROTO;
628         return false;
629     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
630         dump->status = EOF;
631         return false;
632     }
633
634     return true;
635 }
636
637 /* Completes Netlink dump operation 'dump', which must have been initialized
638  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
639  * otherwise a positive errno value describing the problem. */
640 int
641 nl_dump_done(struct nl_dump *dump)
642 {
643     /* Drain any remaining messages that the client didn't read.  Otherwise the
644      * kernel will continue to queue them up and waste buffer space. */
645     while (!dump->status) {
646         struct ofpbuf reply;
647         if (!nl_dump_next(dump, &reply)) {
648             assert(dump->status);
649         }
650     }
651
652     if (dump->sock) {
653         if (dump->sock->dump) {
654             dump->sock->dump = NULL;
655         } else {
656             nl_sock_destroy(dump->sock);
657         }
658     }
659     ofpbuf_delete(dump->buffer);
660     return dump->status == EOF ? 0 : dump->status;
661 }
662
663 /* Causes poll_block() to wake up when any of the specified 'events' (which is
664  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
665 void
666 nl_sock_wait(const struct nl_sock *sock, short int events)
667 {
668     poll_fd_wait(sock->fd, events);
669 }
670 \f
671 /* Miscellaneous.  */
672
673 struct genl_family {
674     struct hmap_node hmap_node;
675     uint16_t id;
676     char *name;
677 };
678
679 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
680
681 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
682     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
683     [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED},
684 };
685
686 static struct genl_family *
687 find_genl_family_by_id(uint16_t id)
688 {
689     struct genl_family *family;
690
691     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
692                              &genl_families) {
693         if (family->id == id) {
694             return family;
695         }
696     }
697     return NULL;
698 }
699
700 static void
701 define_genl_family(uint16_t id, const char *name)
702 {
703     struct genl_family *family = find_genl_family_by_id(id);
704
705     if (family) {
706         if (!strcmp(family->name, name)) {
707             return;
708         }
709         free(family->name);
710     } else {
711         family = xmalloc(sizeof *family);
712         family->id = id;
713         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
714     }
715     family->name = xstrdup(name);
716 }
717
718 static const char *
719 genl_family_to_name(uint16_t id)
720 {
721     if (id == GENL_ID_CTRL) {
722         return "control";
723     } else {
724         struct genl_family *family = find_genl_family_by_id(id);
725         return family ? family->name : "unknown";
726     }
727 }
728
729 static int
730 do_lookup_genl_family(const char *name, struct nlattr **attrs)
731 {
732     struct nl_sock *sock;
733     struct ofpbuf request, *reply;
734     int retval;
735
736     retval = nl_sock_create(NETLINK_GENERIC, &sock);
737     if (retval) {
738         return -retval;
739     }
740
741     ofpbuf_init(&request, 0);
742     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
743                           CTRL_CMD_GETFAMILY, 1);
744     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
745     retval = nl_sock_transact(sock, &request, &reply);
746     ofpbuf_uninit(&request);
747     if (retval) {
748         nl_sock_destroy(sock);
749         return -retval;
750     }
751
752     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
753                          family_policy, attrs, ARRAY_SIZE(family_policy))) {
754         nl_sock_destroy(sock);
755         ofpbuf_delete(reply);
756         return -EPROTO;
757     }
758
759     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
760     if (retval == 0) {
761         retval = -EPROTO;
762     } else {
763         define_genl_family(retval, name);
764     }
765     nl_sock_destroy(sock);
766     ofpbuf_delete(reply);
767
768     return retval;
769 }
770
771 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
772  * When successful, writes its result to 'multicast_group' and returns 0.
773  * Otherwise, clears 'multicast_group' and returns a positive error code. */
774 int
775 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
776                        unsigned int *multicast_group)
777 {
778     struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
779     struct ofpbuf all_mcs;
780     struct nlattr *mc;
781     unsigned int left;
782     int retval;
783
784     *multicast_group = 0;
785     retval = do_lookup_genl_family(family_name, family_attrs);
786     if (retval <= 0) {
787         assert(retval);
788         return -retval;
789     }
790
791     nl_attr_get_nested(family_attrs[CTRL_ATTR_MCAST_GROUPS], &all_mcs);
792     NL_ATTR_FOR_EACH (mc, left, all_mcs.data, all_mcs.size) {
793         static const struct nl_policy mc_policy[] = {
794             [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
795             [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
796         };
797
798         struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
799         const char *mc_name;
800
801         if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
802             return EPROTO;
803         }
804
805         mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
806         if (!strcmp(group_name, mc_name)) {
807             *multicast_group =
808                 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
809             return 0;
810         }
811     }
812
813     return EPROTO;
814 }
815
816 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
817  * number and stores it in '*number'.  If successful, returns 0 and the caller
818  * may use '*number' as the family number.  On failure, returns a positive
819  * errno value and '*number' caches the errno value. */
820 int
821 nl_lookup_genl_family(const char *name, int *number)
822 {
823     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
824
825     if (*number == 0) {
826         *number = do_lookup_genl_family(name, attrs);
827         assert(*number != 0);
828     }
829     return *number > 0 ? 0 : -*number;
830 }
831 \f
832 /* Netlink PID.
833  *
834  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
835  * programs that have a single Netlink socket use their Unix process ID as PID,
836  * and programs with multiple Netlink sockets add a unique per-socket
837  * identifier in the bits above the Unix process ID.
838  *
839  * The kernel has Netlink PID 0.
840  */
841
842 /* Parameters for how many bits in the PID should come from the Unix process ID
843  * and how many unique per-socket. */
844 #define SOCKET_BITS 10
845 #define MAX_SOCKETS (1u << SOCKET_BITS)
846
847 #define PROCESS_BITS (32 - SOCKET_BITS)
848 #define MAX_PROCESSES (1u << PROCESS_BITS)
849 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
850
851 /* Bit vector of unused socket identifiers. */
852 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
853
854 /* Allocates and returns a new Netlink PID. */
855 static int
856 alloc_pid(uint32_t *pid)
857 {
858     int i;
859
860     for (i = 0; i < MAX_SOCKETS; i++) {
861         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
862             avail_sockets[i / 32] |= 1u << (i % 32);
863             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
864             return 0;
865         }
866     }
867     VLOG_ERR("netlink pid space exhausted");
868     return ENOBUFS;
869 }
870
871 /* Makes the specified 'pid' available for reuse. */
872 static void
873 free_pid(uint32_t pid)
874 {
875     int sock = pid >> PROCESS_BITS;
876     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
877     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
878 }
879 \f
880 static void
881 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
882 {
883     struct nlmsg_flag {
884         unsigned int bits;
885         const char *name;
886     };
887     static const struct nlmsg_flag flags[] = {
888         { NLM_F_REQUEST, "REQUEST" },
889         { NLM_F_MULTI, "MULTI" },
890         { NLM_F_ACK, "ACK" },
891         { NLM_F_ECHO, "ECHO" },
892         { NLM_F_DUMP, "DUMP" },
893         { NLM_F_ROOT, "ROOT" },
894         { NLM_F_MATCH, "MATCH" },
895         { NLM_F_ATOMIC, "ATOMIC" },
896     };
897     const struct nlmsg_flag *flag;
898     uint16_t flags_left;
899
900     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
901                   h->nlmsg_len, h->nlmsg_type);
902     if (h->nlmsg_type == NLMSG_NOOP) {
903         ds_put_cstr(ds, "(no-op)");
904     } else if (h->nlmsg_type == NLMSG_ERROR) {
905         ds_put_cstr(ds, "(error)");
906     } else if (h->nlmsg_type == NLMSG_DONE) {
907         ds_put_cstr(ds, "(done)");
908     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
909         ds_put_cstr(ds, "(overrun)");
910     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
911         ds_put_cstr(ds, "(reserved)");
912     } else if (protocol == NETLINK_GENERIC) {
913         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
914     } else {
915         ds_put_cstr(ds, "(family-defined)");
916     }
917     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
918     flags_left = h->nlmsg_flags;
919     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
920         if ((flags_left & flag->bits) == flag->bits) {
921             ds_put_format(ds, "[%s]", flag->name);
922             flags_left &= ~flag->bits;
923         }
924     }
925     if (flags_left) {
926         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
927     }
928     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
929                   h->nlmsg_seq, h->nlmsg_pid,
930                   (int) (h->nlmsg_pid & PROCESS_MASK),
931                   (int) (h->nlmsg_pid >> PROCESS_BITS));
932 }
933
934 static char *
935 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
936 {
937     struct ds ds = DS_EMPTY_INITIALIZER;
938     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
939     if (h) {
940         nlmsghdr_to_string(h, protocol, &ds);
941         if (h->nlmsg_type == NLMSG_ERROR) {
942             const struct nlmsgerr *e;
943             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
944                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
945             if (e) {
946                 ds_put_format(&ds, " error(%d", e->error);
947                 if (e->error < 0) {
948                     ds_put_format(&ds, "(%s)", strerror(-e->error));
949                 }
950                 ds_put_cstr(&ds, ", in-reply-to(");
951                 nlmsghdr_to_string(&e->msg, protocol, &ds);
952                 ds_put_cstr(&ds, "))");
953             } else {
954                 ds_put_cstr(&ds, " error(truncated)");
955             }
956         } else if (h->nlmsg_type == NLMSG_DONE) {
957             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
958             if (error) {
959                 ds_put_format(&ds, " done(%d", *error);
960                 if (*error < 0) {
961                     ds_put_format(&ds, "(%s)", strerror(-*error));
962                 }
963                 ds_put_cstr(&ds, ")");
964             } else {
965                 ds_put_cstr(&ds, " done(truncated)");
966             }
967         } else if (protocol == NETLINK_GENERIC) {
968             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
969             if (genl) {
970                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
971                               genl->cmd, genl->version);
972             }
973         }
974     } else {
975         ds_put_cstr(&ds, "nl(truncated)");
976     }
977     return ds.string;
978 }
979
980 static void
981 log_nlmsg(const char *function, int error,
982           const void *message, size_t size, int protocol)
983 {
984     struct ofpbuf buffer;
985     char *nlmsg;
986
987     if (!VLOG_IS_DBG_ENABLED()) {
988         return;
989     }
990
991     ofpbuf_use_const(&buffer, message, size);
992     nlmsg = nlmsg_to_string(&buffer, protocol);
993     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
994     free(nlmsg);
995 }
996
997