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