Update required Autoconf version in INSTALL.
[sliver-openvswitch.git] / lib / netlink.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include <config.h>
35 #include "netlink.h"
36 #include <assert.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include "dynamic-string.h"
45 #include "netlink-protocol.h"
46 #include "ofpbuf.h"
47 #include "timeval.h"
48 #include "util.h"
49
50 #include "vlog.h"
51 #define THIS_MODULE VLM_netlink
52
53 /* Linux header file confusion causes this to be undefined. */
54 #ifndef SOL_NETLINK
55 #define SOL_NETLINK 270
56 #endif
57
58 /* A single (bad) Netlink message can in theory dump out many, many log
59  * messages, so the burst size is set quite high here to avoid missing useful
60  * information.  Also, at high logging levels we log *all* Netlink messages. */
61 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
62
63 static void log_nlmsg(const char *function, int error,
64                       const void *message, size_t size);
65 \f
66 /* Netlink sockets. */
67
68 struct nl_sock
69 {
70     int fd;
71     uint32_t pid;
72 };
73
74 /* Next nlmsghdr sequence number.
75  * 
76  * This implementation uses sequence numbers that are unique process-wide, to
77  * avoid a hypothetical race: send request, close socket, open new socket that
78  * reuses the old socket's PID value, send request on new socket, receive reply
79  * from kernel to old socket but with same PID and sequence number.  (This race
80  * could be avoided other ways, e.g. by preventing PIDs from being quickly
81  * reused). */
82 static uint32_t next_seq;
83
84 static int alloc_pid(uint32_t *);
85 static void free_pid(uint32_t);
86
87 /* Creates a new netlink socket for the given netlink 'protocol'
88  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
89  * new socket if successful, otherwise returns a positive errno value.
90  *
91  * If 'multicast_group' is nonzero, the new socket subscribes to the specified
92  * netlink multicast group.  (A netlink socket may listen to an arbitrary
93  * number of multicast groups, but so far we only need one at a time.)
94  *
95  * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
96  * receive buffer size, respectively.
97  */
98 int
99 nl_sock_create(int protocol, int multicast_group,
100                size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
101 {
102     struct nl_sock *sock;
103     struct sockaddr_nl local, remote;
104     int retval = 0;
105
106     if (next_seq == 0) {
107         /* Pick initial sequence number. */
108         next_seq = getpid() ^ time_now();
109     }
110
111     *sockp = NULL;
112     sock = malloc(sizeof *sock);
113     if (sock == NULL) {
114         return ENOMEM;
115     }
116
117     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
118     if (sock->fd < 0) {
119         VLOG_ERR("fcntl: %s", strerror(errno));
120         goto error;
121     }
122
123     retval = alloc_pid(&sock->pid);
124     if (retval) {
125         goto error;
126     }
127
128     if (so_sndbuf != 0
129         && setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
130                       &so_sndbuf, sizeof so_sndbuf) < 0) {
131         VLOG_ERR("setsockopt(SO_SNDBUF,%zu): %s", so_sndbuf, strerror(errno));
132         goto error_free_pid;
133     }
134
135     if (so_rcvbuf != 0
136         && setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
137                       &so_rcvbuf, sizeof so_rcvbuf) < 0) {
138         VLOG_ERR("setsockopt(SO_RCVBUF,%zu): %s", so_rcvbuf, strerror(errno));
139         goto error_free_pid;
140     }
141
142     /* Bind local address as our selected pid. */
143     memset(&local, 0, sizeof local);
144     local.nl_family = AF_NETLINK;
145     local.nl_pid = sock->pid;
146     if (multicast_group > 0 && multicast_group <= 32) {
147         /* This method of joining multicast groups is supported by old kernels,
148          * but it only allows 32 multicast groups per protocol. */
149         local.nl_groups |= 1ul << (multicast_group - 1);
150     }
151     if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
152         VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
153         goto error_free_pid;
154     }
155
156     /* Bind remote address as the kernel (pid 0). */
157     memset(&remote, 0, sizeof remote);
158     remote.nl_family = AF_NETLINK;
159     remote.nl_pid = 0;
160     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
161         VLOG_ERR("connect(0): %s", strerror(errno));
162         goto error_free_pid;
163     }
164
165     /* Older kernel headers failed to define this macro.  We want our programs
166      * to support the newer kernel features even if compiled with older
167      * headers, so define it ourselves in such a case. */
168 #ifndef NETLINK_ADD_MEMBERSHIP
169 #define NETLINK_ADD_MEMBERSHIP 1
170 #endif
171
172     /* This method of joining multicast groups is only supported by newish
173      * kernels, but it allows for an arbitrary number of multicast groups. */
174     if (multicast_group > 32
175         && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
176                       &multicast_group, sizeof multicast_group) < 0) {
177         VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
178                  multicast_group, strerror(errno));
179         goto error_free_pid;
180     }
181
182     *sockp = sock;
183     return 0;
184
185 error_free_pid:
186     free_pid(sock->pid);
187 error:
188     if (retval == 0) {
189         retval = errno;
190         if (retval == 0) {
191             retval = EINVAL;
192         }
193     }
194     if (sock->fd >= 0) {
195         close(sock->fd);
196     }
197     free(sock);
198     return retval;
199 }
200
201 /* Destroys netlink socket 'sock'. */
202 void
203 nl_sock_destroy(struct nl_sock *sock) 
204 {
205     if (sock) {
206         close(sock->fd);
207         free_pid(sock->pid);
208         free(sock);
209     }
210 }
211
212 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
213  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size before the
214  * message is sent.
215  *
216  * Returns 0 if successful, otherwise a positive errno value.  If
217  * 'wait' is true, then the send will wait until buffer space is ready;
218  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
219 int
220 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait) 
221 {
222     int error;
223
224     nl_msg_nlmsghdr(msg)->nlmsg_len = msg->size;
225     do {
226         int retval;
227         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
228         error = retval < 0 ? errno : 0;
229     } while (error == EINTR);
230     log_nlmsg(__func__, error, msg->data, msg->size);
231     return error;
232 }
233
234 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
235  * a single Netlink message.  (The message must be fully formed and not require
236  * finalization of its nlmsg_len field.)
237  *
238  * Returns 0 if successful, otherwise a positive errno value.  If 'wait' is
239  * true, then the send will wait until buffer space is ready; otherwise,
240  * returns EAGAIN if the 'sock' send buffer is full. */
241 int
242 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
243               bool wait) 
244 {
245     struct msghdr msg;
246     int error;
247
248     memset(&msg, 0, sizeof msg);
249     msg.msg_iov = (struct iovec *) iov;
250     msg.msg_iovlen = n_iov;
251     do {
252         int retval;
253         retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
254         error = retval < 0 ? errno : 0;
255     } while (error == EINTR);
256     if (error != EAGAIN) {
257         log_nlmsg(__func__, error, iov[0].iov_base, iov[0].iov_len);
258     }
259     return error;
260 }
261
262 /* Tries to receive a netlink message from the kernel on 'sock'.  If
263  * successful, stores the received message into '*bufp' and returns 0.  The
264  * caller is responsible for destroying the message with ofpbuf_delete().  On
265  * failure, returns a positive errno value and stores a null pointer into
266  * '*bufp'.
267  *
268  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
269  * returns EAGAIN if the 'sock' receive buffer is empty. */
270 int
271 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait) 
272 {
273     uint8_t tmp;
274     ssize_t bufsize = 2048;
275     ssize_t nbytes, nbytes2;
276     struct ofpbuf *buf;
277     struct nlmsghdr *nlmsghdr;
278     struct iovec iov;
279     struct msghdr msg = {
280         .msg_name = NULL,
281         .msg_namelen = 0,
282         .msg_iov = &iov,
283         .msg_iovlen = 1,
284         .msg_control = NULL,
285         .msg_controllen = 0,
286         .msg_flags = 0
287     };
288
289     buf = ofpbuf_new(bufsize);
290     *bufp = NULL;
291
292 try_again:
293     /* Attempt to read the message.  We don't know the size of the data
294      * yet, so we take a guess at 2048.  If we're wrong, we keep trying
295      * and doubling the buffer size each time. 
296      */
297     nlmsghdr = ofpbuf_put_uninit(buf, bufsize);
298     iov.iov_base = nlmsghdr;
299     iov.iov_len = bufsize;
300     do {
301         nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK); 
302     } while (nbytes < 0 && errno == EINTR);
303     if (nbytes < 0) {
304         ofpbuf_delete(buf);
305         return errno;
306     }
307     if (msg.msg_flags & MSG_TRUNC) {
308         bufsize *= 2;
309         ofpbuf_reinit(buf, bufsize);
310         goto try_again;
311     }
312     buf->size = nbytes;
313
314     /* We successfully read the message, so recv again to clear the queue */
315     iov.iov_base = &tmp;
316     iov.iov_len = 1;
317     do {
318         nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
319     } while (nbytes2 < 0 && errno == EINTR);
320     if (nbytes2 < 0) {
321         if (errno == ENOBUFS) {
322             /* The kernel is notifying us that a message it tried to send to us
323              * was dropped.  We have to pass this along to the caller in case
324              * it wants to retry a request.  So kill the buffer, which we can
325              * re-read next time. */
326             ofpbuf_delete(buf);
327             return ENOBUFS;
328         } else {
329             VLOG_ERR_RL(&rl, "failed to remove nlmsg from socket: %s\n",
330                         strerror(errno));
331         }
332     }
333     if (nbytes < sizeof *nlmsghdr
334         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
335         || nlmsghdr->nlmsg_len > nbytes) {
336         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
337                     bufsize, NLMSG_HDRLEN);
338         ofpbuf_delete(buf);
339         return EPROTO;
340     }
341     *bufp = buf;
342     log_nlmsg(__func__, 0, buf->data, buf->size);
343     return 0;
344 }
345
346 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
347  * successful, stores the reply into '*replyp' and returns 0.  The caller is
348  * responsible for destroying the reply with ofpbuf_delete().  On failure,
349  * returns a positive errno value and stores a null pointer into '*replyp'.
350  *
351  * Bare Netlink is an unreliable transport protocol.  This function layers
352  * reliable delivery and reply semantics on top of bare Netlink.
353  * 
354  * In Netlink, sending a request to the kernel is reliable enough, because the
355  * kernel will tell us if the message cannot be queued (and we will in that
356  * case put it on the transmit queue and wait until it can be delivered).
357  * 
358  * Receiving the reply is the real problem: if the socket buffer is full when
359  * the kernel tries to send the reply, the reply will be dropped.  However, the
360  * kernel sets a flag that a reply has been dropped.  The next call to recv
361  * then returns ENOBUFS.  We can then re-send the request.
362  *
363  * Caveats:
364  *
365  *      1. Netlink depends on sequence numbers to match up requests and
366  *         replies.  The sender of a request supplies a sequence number, and
367  *         the reply echos back that sequence number.
368  *
369  *         This is fine, but (1) some kernel netlink implementations are
370  *         broken, in that they fail to echo sequence numbers and (2) this
371  *         function will drop packets with non-matching sequence numbers, so
372  *         that only a single request can be usefully transacted at a time.
373  *
374  *      2. Resending the request causes it to be re-executed, so the request
375  *         needs to be idempotent.
376  */
377 int
378 nl_sock_transact(struct nl_sock *sock,
379                  const struct ofpbuf *request, struct ofpbuf **replyp) 
380 {
381     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
382     struct nlmsghdr *nlmsghdr;
383     struct ofpbuf *reply;
384     int retval;
385
386     *replyp = NULL;
387
388     /* Ensure that we get a reply even if this message doesn't ordinarily call
389      * for one. */
390     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
391     
392 send:
393     retval = nl_sock_send(sock, request, true);
394     if (retval) {
395         return retval;
396     }
397
398 recv:
399     retval = nl_sock_recv(sock, &reply, true);
400     if (retval) {
401         if (retval == ENOBUFS) {
402             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
403             goto send;
404         } else {
405             return retval;
406         }
407     }
408     nlmsghdr = nl_msg_nlmsghdr(reply);
409     if (seq != nlmsghdr->nlmsg_seq) {
410         VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
411                     nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
412         ofpbuf_delete(reply);
413         goto recv;
414     }
415     if (nl_msg_nlmsgerr(reply, &retval)) {
416         if (retval) {
417             VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
418                         retval, strerror(retval));
419         }
420         return retval != EAGAIN ? retval : EPROTO;
421     }
422
423     *replyp = reply;
424     return 0;
425 }
426
427 /* Returns 'sock''s underlying file descriptor. */
428 int
429 nl_sock_fd(const struct nl_sock *sock) 
430 {
431     return sock->fd;
432 }
433 \f
434 /* Netlink messages. */
435
436 /* Returns the nlmsghdr at the head of 'msg'.
437  *
438  * 'msg' must be at least as large as a nlmsghdr. */
439 struct nlmsghdr *
440 nl_msg_nlmsghdr(const struct ofpbuf *msg) 
441 {
442     return ofpbuf_at_assert(msg, 0, NLMSG_HDRLEN);
443 }
444
445 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
446  *
447  * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
448  * and a genlmsghdr. */
449 struct genlmsghdr *
450 nl_msg_genlmsghdr(const struct ofpbuf *msg) 
451 {
452     return ofpbuf_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
453 }
454
455 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
456  * message, otherwise a positive errno value, and returns true.  If 'buffer' is
457  * not an NLMSG_ERROR message, returns false.
458  *
459  * 'msg' must be at least as large as a nlmsghdr. */
460 bool
461 nl_msg_nlmsgerr(const struct ofpbuf *msg, int *errorp) 
462 {
463     if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
464         struct nlmsgerr *err = ofpbuf_at(msg, NLMSG_HDRLEN, sizeof *err);
465         int code = EPROTO;
466         if (!err) {
467             VLOG_ERR_RL(&rl, "received invalid nlmsgerr (%zd bytes < %zd)",
468                         msg->size, NLMSG_HDRLEN + sizeof *err);
469         } else if (err->error <= 0 && err->error > INT_MIN) {
470             code = -err->error;
471         }
472         if (errorp) {
473             *errorp = code;
474         }
475         return true;
476     } else {
477         return false;
478     }
479 }
480
481 /* Ensures that 'b' has room for at least 'size' bytes plus netlink padding at
482  * its tail end, reallocating and copying its data if necessary. */
483 void
484 nl_msg_reserve(struct ofpbuf *msg, size_t size) 
485 {
486     ofpbuf_prealloc_tailroom(msg, NLMSG_ALIGN(size));
487 }
488
489 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
490  * Uses the given 'type' and 'flags'.  'sock' is used to obtain a PID and
491  * sequence number for proper routing of replies.  'expected_payload' should be
492  * an estimate of the number of payload bytes to be supplied; if the size of
493  * the payload is unknown a value of 0 is acceptable.
494  *
495  * 'type' is ordinarily an enumerated value specific to the Netlink protocol
496  * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol).  For Generic Netlink, 'type'
497  * is the family number obtained via nl_lookup_genl_family().
498  *
499  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
500  * is often NLM_F_REQUEST indicating that a request is being made, commonly
501  * or'd with NLM_F_ACK to request an acknowledgement.
502  *
503  * nl_msg_put_genlmsghdr is more convenient for composing a Generic Netlink
504  * message. */
505 void
506 nl_msg_put_nlmsghdr(struct ofpbuf *msg, struct nl_sock *sock,
507                     size_t expected_payload, uint32_t type, uint32_t flags) 
508 {
509     struct nlmsghdr *nlmsghdr;
510
511     assert(msg->size == 0);
512
513     nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
514     nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
515     nlmsghdr->nlmsg_len = 0;
516     nlmsghdr->nlmsg_type = type;
517     nlmsghdr->nlmsg_flags = flags;
518     nlmsghdr->nlmsg_seq = ++next_seq;
519     nlmsghdr->nlmsg_pid = sock->pid;
520 }
521
522 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
523  * initially empty.  'sock' is used to obtain a PID and sequence number for
524  * proper routing of replies.  'expected_payload' should be an estimate of the
525  * number of payload bytes to be supplied; if the size of the payload is
526  * unknown a value of 0 is acceptable.
527  *
528  * 'family' is the family number obtained via nl_lookup_genl_family().
529  *
530  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
531  * is often NLM_F_REQUEST indicating that a request is being made, commonly
532  * or'd with NLM_F_ACK to request an acknowledgement.
533  *
534  * 'cmd' is an enumerated value specific to the Generic Netlink family
535  * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
536  *
537  * 'version' is a version number specific to the family and command (often 1).
538  *
539  * nl_msg_put_nlmsghdr should be used to compose Netlink messages that are not
540  * Generic Netlink messages. */
541 void
542 nl_msg_put_genlmsghdr(struct ofpbuf *msg, struct nl_sock *sock,
543                       size_t expected_payload, int family, uint32_t flags,
544                       uint8_t cmd, uint8_t version)
545 {
546     struct genlmsghdr *genlmsghdr;
547
548     nl_msg_put_nlmsghdr(msg, sock, GENL_HDRLEN + expected_payload,
549                         family, flags);
550     assert(msg->size == NLMSG_HDRLEN);
551     genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
552     genlmsghdr->cmd = cmd;
553     genlmsghdr->version = version;
554     genlmsghdr->reserved = 0;
555 }
556
557 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
558  * the tail end of 'msg'.  Data in 'msg' is reallocated and copied if
559  * necessary. */
560 void
561 nl_msg_put(struct ofpbuf *msg, const void *data, size_t size) 
562 {
563     memcpy(nl_msg_put_uninit(msg, size), data, size);
564 }
565
566 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
567  * end of 'msg', reallocating and copying its data if necessary.  Returns a
568  * pointer to the first byte of the new data, which is left uninitialized. */
569 void *
570 nl_msg_put_uninit(struct ofpbuf *msg, size_t size) 
571 {
572     size_t pad = NLMSG_ALIGN(size) - size;
573     char *p = ofpbuf_put_uninit(msg, size + pad);
574     if (pad) {
575         memset(p + size, 0, pad); 
576     }
577     return p;
578 }
579
580 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
581  * data as its payload, plus Netlink padding if needed, to the tail end of
582  * 'msg', reallocating and copying its data if necessary.  Returns a pointer to
583  * the first byte of data in the attribute, which is left uninitialized. */
584 void *
585 nl_msg_put_unspec_uninit(struct ofpbuf *msg, uint16_t type, size_t size) 
586 {
587     size_t total_size = NLA_HDRLEN + size;
588     struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
589     assert(NLA_ALIGN(total_size) <= UINT16_MAX);
590     nla->nla_len = total_size;
591     nla->nla_type = type;
592     return nla + 1;
593 }
594
595 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
596  * 'data' as its payload, to the tail end of 'msg', reallocating and copying
597  * its data if necessary.  Returns a pointer to the first byte of data in the
598  * attribute, which is left uninitialized. */
599 void
600 nl_msg_put_unspec(struct ofpbuf *msg, uint16_t type,
601                   const void *data, size_t size) 
602 {
603     memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
604 }
605
606 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
607  * (Some Netlink protocols use the presence or absence of an attribute as a
608  * Boolean flag.) */
609 void
610 nl_msg_put_flag(struct ofpbuf *msg, uint16_t type) 
611 {
612     nl_msg_put_unspec(msg, type, NULL, 0);
613 }
614
615 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
616  * to 'msg'. */
617 void
618 nl_msg_put_u8(struct ofpbuf *msg, uint16_t type, uint8_t value) 
619 {
620     nl_msg_put_unspec(msg, type, &value, sizeof value);
621 }
622
623 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
624  * to 'msg'. */
625 void
626 nl_msg_put_u16(struct ofpbuf *msg, uint16_t type, uint16_t value)
627 {
628     nl_msg_put_unspec(msg, type, &value, sizeof value);
629 }
630
631 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
632  * to 'msg'. */
633 void
634 nl_msg_put_u32(struct ofpbuf *msg, uint16_t type, uint32_t value)
635 {
636     nl_msg_put_unspec(msg, type, &value, sizeof value);
637 }
638
639 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
640  * to 'msg'. */
641 void
642 nl_msg_put_u64(struct ofpbuf *msg, uint16_t type, uint64_t value)
643 {
644     nl_msg_put_unspec(msg, type, &value, sizeof value);
645 }
646
647 /* Appends a Netlink attribute of the given 'type' and the given
648  * null-terminated string 'value' to 'msg'. */
649 void
650 nl_msg_put_string(struct ofpbuf *msg, uint16_t type, const char *value)
651 {
652     nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
653 }
654
655 /* Appends a Netlink attribute of the given 'type' and the given buffered
656  * netlink message in 'nested_msg' to 'msg'.  The nlmsg_len field in
657  * 'nested_msg' is finalized to match 'nested_msg->size'. */
658 void
659 nl_msg_put_nested(struct ofpbuf *msg,
660                   uint16_t type, struct ofpbuf *nested_msg)
661 {
662     nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
663     nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
664 }
665
666 /* Returns the first byte in the payload of attribute 'nla'. */
667 const void *
668 nl_attr_get(const struct nlattr *nla) 
669 {
670     assert(nla->nla_len >= NLA_HDRLEN);
671     return nla + 1;
672 }
673
674 /* Returns the number of bytes in the payload of attribute 'nla'. */
675 size_t
676 nl_attr_get_size(const struct nlattr *nla) 
677 {
678     assert(nla->nla_len >= NLA_HDRLEN);
679     return nla->nla_len - NLA_HDRLEN;
680 }
681
682 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
683  * first byte of the payload. */
684 const void *
685 nl_attr_get_unspec(const struct nlattr *nla, size_t size) 
686 {
687     assert(nla->nla_len >= NLA_HDRLEN + size);
688     return nla + 1;
689 }
690
691 /* Returns true if 'nla' is nonnull.  (Some Netlink protocols use the presence
692  * or absence of an attribute as a Boolean flag.) */
693 bool
694 nl_attr_get_flag(const struct nlattr *nla) 
695 {
696     return nla != NULL;
697 }
698
699 #define NL_ATTR_GET_AS(NLA, TYPE) \
700         (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
701
702 /* Returns the 8-bit value in 'nla''s payload.
703  *
704  * Asserts that 'nla''s payload is at least 1 byte long. */
705 uint8_t
706 nl_attr_get_u8(const struct nlattr *nla) 
707 {
708     return NL_ATTR_GET_AS(nla, uint8_t);
709 }
710
711 /* Returns the 16-bit value in 'nla''s payload.
712  *
713  * Asserts that 'nla''s payload is at least 2 bytes long. */
714 uint16_t
715 nl_attr_get_u16(const struct nlattr *nla) 
716 {
717     return NL_ATTR_GET_AS(nla, uint16_t);
718 }
719
720 /* Returns the 32-bit value in 'nla''s payload.
721  *
722  * Asserts that 'nla''s payload is at least 4 bytes long. */
723 uint32_t
724 nl_attr_get_u32(const struct nlattr *nla) 
725 {
726     return NL_ATTR_GET_AS(nla, uint32_t);
727 }
728
729 /* Returns the 64-bit value in 'nla''s payload.
730  *
731  * Asserts that 'nla''s payload is at least 8 bytes long. */
732 uint64_t
733 nl_attr_get_u64(const struct nlattr *nla) 
734 {
735     return NL_ATTR_GET_AS(nla, uint64_t);
736 }
737
738 /* Returns the null-terminated string value in 'nla''s payload.
739  *
740  * Asserts that 'nla''s payload contains a null-terminated string. */
741 const char *
742 nl_attr_get_string(const struct nlattr *nla) 
743 {
744     assert(nla->nla_len > NLA_HDRLEN);
745     assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
746     return nl_attr_get(nla);
747 }
748
749 /* Default minimum and maximum payload sizes for each type of attribute. */
750 static const size_t attr_len_range[][2] = {
751     [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
752     [NL_A_U8] = { 1, 1 },
753     [NL_A_U16] = { 2, 2 },
754     [NL_A_U32] = { 4, 4 },
755     [NL_A_U64] = { 8, 8 },
756     [NL_A_STRING] = { 1, SIZE_MAX },
757     [NL_A_FLAG] = { 0, SIZE_MAX },
758     [NL_A_NESTED] = { NLMSG_HDRLEN, SIZE_MAX },
759 };
760
761 /* Parses the Generic Netlink payload of 'msg' as a sequence of Netlink
762  * attributes.  'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
763  * with nla_type == i is parsed; a pointer to attribute i is stored in
764  * attrs[i].  Returns true if successful, false on failure. */
765 bool
766 nl_policy_parse(const struct ofpbuf *msg, const struct nl_policy policy[],
767                 struct nlattr *attrs[], size_t n_attrs)
768 {
769     void *p, *tail;
770     size_t n_required;
771     size_t i;
772
773     n_required = 0;
774     for (i = 0; i < n_attrs; i++) {
775         attrs[i] = NULL;
776
777         assert(policy[i].type < N_NL_ATTR_TYPES);
778         if (policy[i].type != NL_A_NO_ATTR
779             && policy[i].type != NL_A_FLAG
780             && !policy[i].optional) {
781             n_required++;
782         }
783     }
784
785     p = ofpbuf_at(msg, NLMSG_HDRLEN + GENL_HDRLEN, 0);
786     if (p == NULL) {
787         VLOG_DBG_RL(&rl, "missing headers in nl_policy_parse");
788         return false;
789     }
790     tail = ofpbuf_tail(msg);
791
792     while (p < tail) {
793         size_t offset = (char*)p - (char*)msg->data;
794         struct nlattr *nla = p;
795         size_t len, aligned_len;
796         uint16_t type;
797
798         /* Make sure its claimed length is plausible. */
799         if (nla->nla_len < NLA_HDRLEN) {
800             VLOG_DBG_RL(&rl, "%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
801                         offset, nla->nla_len);
802             return false;
803         }
804         len = nla->nla_len - NLA_HDRLEN;
805         aligned_len = NLA_ALIGN(len);
806         if (aligned_len > (char*)tail - (char*)p) {
807             VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" aligned data len (%zu) "
808                         "> bytes left (%tu)",
809                         offset, nla->nla_type, aligned_len,
810                         (char*)tail - (char*)p);
811             return false;
812         }
813
814         type = nla->nla_type;
815         if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
816             const struct nl_policy *p = &policy[type];
817             size_t min_len, max_len;
818
819             /* Validate length and content. */
820             min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
821             max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
822             if (len < min_len || len > max_len) {
823                 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" length %zu not in "
824                             "allowed range %zu...%zu",
825                             offset, type, len, min_len, max_len);
826                 return false;
827             }
828             if (p->type == NL_A_STRING) {
829                 if (((char *) nla)[nla->nla_len - 1]) {
830                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" lacks null at end",
831                                 offset, type);
832                     return false;
833                 }
834                 if (memchr(nla + 1, '\0', len - 1) != NULL) {
835                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" has bad length",
836                                 offset, type);
837                     return false;
838                 }
839             }
840             if (!p->optional && attrs[type] == NULL) {
841                 assert(n_required > 0);
842                 --n_required;
843             }
844             attrs[type] = nla;
845         } else {
846             /* Skip attribute type that we don't care about. */
847         }
848         p = (char*)p + NLA_ALIGN(nla->nla_len);
849     }
850     if (n_required) {
851         VLOG_DBG_RL(&rl, "%zu required attrs missing", n_required);
852         return false;
853     }
854     return true;
855 }
856 \f
857 /* Miscellaneous.  */
858
859 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = { 
860     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
861 };
862
863 static int do_lookup_genl_family(const char *name) 
864 {
865     struct nl_sock *sock;
866     struct ofpbuf request, *reply;
867     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
868     int retval;
869
870     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
871     if (retval) {
872         return -retval;
873     }
874
875     ofpbuf_init(&request, 0);
876     nl_msg_put_genlmsghdr(&request, sock, 0, GENL_ID_CTRL, NLM_F_REQUEST,
877                           CTRL_CMD_GETFAMILY, 1);
878     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
879     retval = nl_sock_transact(sock, &request, &reply);
880     ofpbuf_uninit(&request);
881     if (retval) {
882         nl_sock_destroy(sock);
883         return -retval;
884     }
885
886     if (!nl_policy_parse(reply, family_policy, attrs,
887                          ARRAY_SIZE(family_policy))) {
888         nl_sock_destroy(sock);
889         ofpbuf_delete(reply);
890         return -EPROTO;
891     }
892
893     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
894     if (retval == 0) {
895         retval = -EPROTO;
896     }
897     nl_sock_destroy(sock);
898     ofpbuf_delete(reply);
899     return retval;
900 }
901
902 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
903  * number and stores it in '*number'.  If successful, returns 0 and the caller
904  * may use '*number' as the family number.  On failure, returns a positive
905  * errno value and '*number' caches the errno value. */
906 int
907 nl_lookup_genl_family(const char *name, int *number) 
908 {
909     if (*number == 0) {
910         *number = do_lookup_genl_family(name);
911         assert(*number != 0);
912     }
913     return *number > 0 ? 0 : -*number;
914 }
915 \f
916 /* Netlink PID.
917  *
918  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
919  * programs that have a single Netlink socket use their Unix process ID as PID,
920  * and programs with multiple Netlink sockets add a unique per-socket
921  * identifier in the bits above the Unix process ID.
922  *
923  * The kernel has Netlink PID 0.
924  */
925
926 /* Parameters for how many bits in the PID should come from the Unix process ID
927  * and how many unique per-socket. */
928 #define SOCKET_BITS 10
929 #define MAX_SOCKETS (1u << SOCKET_BITS)
930
931 #define PROCESS_BITS (32 - SOCKET_BITS)
932 #define MAX_PROCESSES (1u << PROCESS_BITS)
933 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
934
935 /* Bit vector of unused socket identifiers. */
936 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
937
938 /* Allocates and returns a new Netlink PID. */
939 static int
940 alloc_pid(uint32_t *pid)
941 {
942     int i;
943
944     for (i = 0; i < MAX_SOCKETS; i++) {
945         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
946             avail_sockets[i / 32] |= 1u << (i % 32);
947             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
948             return 0;
949         }
950     }
951     VLOG_ERR("netlink pid space exhausted");
952     return ENOBUFS;
953 }
954
955 /* Makes the specified 'pid' available for reuse. */
956 static void
957 free_pid(uint32_t pid)
958 {
959     int sock = pid >> PROCESS_BITS;
960     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
961     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
962 }
963 \f
964 static void
965 nlmsghdr_to_string(const struct nlmsghdr *h, struct ds *ds)
966 {
967     struct nlmsg_flag {
968         unsigned int bits;
969         const char *name;
970     };
971     static const struct nlmsg_flag flags[] = { 
972         { NLM_F_REQUEST, "REQUEST" },
973         { NLM_F_MULTI, "MULTI" },
974         { NLM_F_ACK, "ACK" },
975         { NLM_F_ECHO, "ECHO" },
976         { NLM_F_DUMP, "DUMP" },
977         { NLM_F_ROOT, "ROOT" },
978         { NLM_F_MATCH, "MATCH" },
979         { NLM_F_ATOMIC, "ATOMIC" },
980     };
981     const struct nlmsg_flag *flag;
982     uint16_t flags_left;
983
984     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
985                   h->nlmsg_len, h->nlmsg_type);
986     if (h->nlmsg_type == NLMSG_NOOP) {
987         ds_put_cstr(ds, "(no-op)");
988     } else if (h->nlmsg_type == NLMSG_ERROR) {
989         ds_put_cstr(ds, "(error)");
990     } else if (h->nlmsg_type == NLMSG_DONE) {
991         ds_put_cstr(ds, "(done)");
992     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
993         ds_put_cstr(ds, "(overrun)");
994     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
995         ds_put_cstr(ds, "(reserved)");
996     } else {
997         ds_put_cstr(ds, "(family-defined)");
998     }
999     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1000     flags_left = h->nlmsg_flags;
1001     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1002         if ((flags_left & flag->bits) == flag->bits) {
1003             ds_put_format(ds, "[%s]", flag->name);
1004             flags_left &= ~flag->bits;
1005         }
1006     }
1007     if (flags_left) {
1008         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1009     }
1010     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
1011                   h->nlmsg_seq, h->nlmsg_pid,
1012                   (int) (h->nlmsg_pid & PROCESS_MASK),
1013                   (int) (h->nlmsg_pid >> PROCESS_BITS));
1014 }
1015
1016 static char *
1017 nlmsg_to_string(const struct ofpbuf *buffer)
1018 {
1019     struct ds ds = DS_EMPTY_INITIALIZER;
1020     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1021     if (h) {
1022         nlmsghdr_to_string(h, &ds);
1023         if (h->nlmsg_type == NLMSG_ERROR) {
1024             const struct nlmsgerr *e;
1025             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1026                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1027             if (e) {
1028                 ds_put_format(&ds, " error(%d", e->error);
1029                 if (e->error < 0) {
1030                     ds_put_format(&ds, "(%s)", strerror(-e->error));
1031                 }
1032                 ds_put_cstr(&ds, ", in-reply-to(");
1033                 nlmsghdr_to_string(&e->msg, &ds);
1034                 ds_put_cstr(&ds, "))");
1035             } else {
1036                 ds_put_cstr(&ds, " error(truncated)");
1037             }
1038         } else if (h->nlmsg_type == NLMSG_DONE) {
1039             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1040             if (error) {
1041                 ds_put_format(&ds, " done(%d", *error);
1042                 if (*error < 0) {
1043                     ds_put_format(&ds, "(%s)", strerror(-*error));
1044                 }
1045                 ds_put_cstr(&ds, ")");
1046             } else {
1047                 ds_put_cstr(&ds, " done(truncated)");
1048             }
1049         }
1050     } else {
1051         ds_put_cstr(&ds, "nl(truncated)");
1052     }
1053     return ds.string;
1054 }
1055
1056 static void
1057 log_nlmsg(const char *function, int error,
1058           const void *message, size_t size)
1059 {
1060     struct ofpbuf buffer;
1061     char *nlmsg;
1062
1063     if (!VLOG_IS_DBG_ENABLED()) {
1064         return;
1065     }
1066
1067     buffer.data = (void *) message;
1068     buffer.size = size;
1069     nlmsg = nlmsg_to_string(&buffer);
1070     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
1071     free(nlmsg);
1072 }
1073