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