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