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