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