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