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