treewide: Remove trailing whitespace
[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 #include "vlog.h"
35
36 VLOG_DEFINE_THIS_MODULE(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 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
449  * 'sock', and initializes 'dump' to reflect the state of the operation.
450  *
451  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
452  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
453  * NLM_F_ACK will be set in nlmsg_flags.
454  *
455  * The properties of Netlink make dump operations reliable as long as all of
456  * the following are true:
457  *
458  *   - At most a single dump is in progress at a time on a given nl_sock.
459  *
460  *   - The nl_sock is not subscribed to any multicast groups.
461  *
462  *   - The nl_sock is not used to send any other messages before the dump
463  *     operation is complete.
464  *
465  * This function provides no status indication.  An error status for the entire
466  * dump operation is provided when it is completed by calling nl_dump_done().
467  *
468  * The caller is responsible for destroying 'request'.  The caller must not
469  * close 'sock' before it completes the dump operation (by calling
470  * nl_dump_done()).
471  */
472 void
473 nl_dump_start(struct nl_dump *dump,
474               struct nl_sock *sock, const struct ofpbuf *request)
475 {
476     struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
477     nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
478     dump->seq = nlmsghdr->nlmsg_seq;
479     dump->sock = sock;
480     dump->status = nl_sock_send(sock, request, true);
481     dump->buffer = NULL;
482 }
483
484 /* Helper function for nl_dump_next(). */
485 static int
486 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
487 {
488     struct nlmsghdr *nlmsghdr;
489     struct ofpbuf *buffer;
490     int retval;
491
492     retval = nl_sock_recv(dump->sock, bufferp, true);
493     if (retval) {
494         return retval == EINTR ? EAGAIN : retval;
495     }
496     buffer = *bufferp;
497
498     nlmsghdr = nl_msg_nlmsghdr(buffer);
499     if (dump->seq != nlmsghdr->nlmsg_seq) {
500         VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
501                     nlmsghdr->nlmsg_seq, dump->seq);
502         return EAGAIN;
503     }
504
505     if (nl_msg_nlmsgerr(buffer, &retval)) {
506         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
507                      strerror(retval));
508         return retval && retval != EAGAIN ? retval : EPROTO;
509     }
510
511     return 0;
512 }
513
514 /* Attempts to retrieve another reply from 'dump', which must have been
515  * initialized with nl_dump_start().
516  *
517  * If successful, returns true and points 'reply->data' and 'reply->size' to
518  * the message that was retrieved.  The caller must not modify 'reply' (because
519  * it points into the middle of a larger buffer).
520  *
521  * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
522  * to 0.  Failure might indicate an actual error or merely the end of replies.
523  * An error status for the entire dump operation is provided when it is
524  * completed by calling nl_dump_done().
525  */
526 bool
527 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
528 {
529     struct nlmsghdr *nlmsghdr;
530
531     reply->data = NULL;
532     reply->size = 0;
533     if (dump->status) {
534         return false;
535     }
536
537     if (dump->buffer && !dump->buffer->size) {
538         ofpbuf_delete(dump->buffer);
539         dump->buffer = NULL;
540     }
541     while (!dump->buffer) {
542         int retval = nl_dump_recv(dump, &dump->buffer);
543         if (retval) {
544             ofpbuf_delete(dump->buffer);
545             dump->buffer = NULL;
546             if (retval != EAGAIN) {
547                 dump->status = retval;
548                 return false;
549             }
550         }
551     }
552
553     nlmsghdr = nl_msg_next(dump->buffer, reply);
554     if (!nlmsghdr) {
555         VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
556         dump->status = EPROTO;
557         return false;
558     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
559         dump->status = EOF;
560         return false;
561     }
562
563     return true;
564 }
565
566 /* Completes Netlink dump operation 'dump', which must have been initialized
567  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
568  * otherwise a positive errno value describing the problem. */
569 int
570 nl_dump_done(struct nl_dump *dump)
571 {
572     /* Drain any remaining messages that the client didn't read.  Otherwise the
573      * kernel will continue to queue them up and waste buffer space. */
574     while (!dump->status) {
575         struct ofpbuf reply;
576         if (!nl_dump_next(dump, &reply)) {
577             assert(dump->status);
578         }
579     }
580
581     ofpbuf_delete(dump->buffer);
582     return dump->status == EOF ? 0 : dump->status;
583 }
584
585 /* Causes poll_block() to wake up when any of the specified 'events' (which is
586  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
587 void
588 nl_sock_wait(const struct nl_sock *sock, short int events)
589 {
590     poll_fd_wait(sock->fd, events);
591 }
592 \f
593 /* Netlink messages. */
594
595 /* Returns the nlmsghdr at the head of 'msg'.
596  *
597  * 'msg' must be at least as large as a nlmsghdr. */
598 struct nlmsghdr *
599 nl_msg_nlmsghdr(const struct ofpbuf *msg)
600 {
601     return ofpbuf_at_assert(msg, 0, NLMSG_HDRLEN);
602 }
603
604 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
605  *
606  * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
607  * and a genlmsghdr. */
608 struct genlmsghdr *
609 nl_msg_genlmsghdr(const struct ofpbuf *msg)
610 {
611     return ofpbuf_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
612 }
613
614 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
615  * message, otherwise a positive errno value, and returns true.  If 'buffer' is
616  * not an NLMSG_ERROR message, returns false.
617  *
618  * 'msg' must be at least as large as a nlmsghdr. */
619 bool
620 nl_msg_nlmsgerr(const struct ofpbuf *msg, int *errorp)
621 {
622     if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
623         struct nlmsgerr *err = ofpbuf_at(msg, NLMSG_HDRLEN, sizeof *err);
624         int code = EPROTO;
625         if (!err) {
626             VLOG_ERR_RL(&rl, "received invalid nlmsgerr (%zd bytes < %zd)",
627                         msg->size, NLMSG_HDRLEN + sizeof *err);
628         } else if (err->error <= 0 && err->error > INT_MIN) {
629             code = -err->error;
630         }
631         if (errorp) {
632             *errorp = code;
633         }
634         return true;
635     } else {
636         return false;
637     }
638 }
639
640 /* Ensures that 'b' has room for at least 'size' bytes plus netlink padding at
641  * its tail end, reallocating and copying its data if necessary. */
642 void
643 nl_msg_reserve(struct ofpbuf *msg, size_t size)
644 {
645     ofpbuf_prealloc_tailroom(msg, NLMSG_ALIGN(size));
646 }
647
648 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
649  * Uses the given 'type' and 'flags'.  'expected_payload' should be
650  * an estimate of the number of payload bytes to be supplied; if the size of
651  * the payload is unknown a value of 0 is acceptable.
652  *
653  * 'type' is ordinarily an enumerated value specific to the Netlink protocol
654  * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol).  For Generic Netlink, 'type'
655  * is the family number obtained via nl_lookup_genl_family().
656  *
657  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
658  * is often NLM_F_REQUEST indicating that a request is being made, commonly
659  * or'd with NLM_F_ACK to request an acknowledgement.
660  *
661  * Sets the new nlmsghdr's nlmsg_pid field to 0 for now.  nl_sock_send() will
662  * fill it in just before sending the message.
663  *
664  * nl_msg_put_genlmsghdr() is more convenient for composing a Generic Netlink
665  * message. */
666 void
667 nl_msg_put_nlmsghdr(struct ofpbuf *msg,
668                     size_t expected_payload, uint32_t type, uint32_t flags)
669 {
670     struct nlmsghdr *nlmsghdr;
671
672     assert(msg->size == 0);
673
674     nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
675     nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
676     nlmsghdr->nlmsg_len = 0;
677     nlmsghdr->nlmsg_type = type;
678     nlmsghdr->nlmsg_flags = flags;
679     nlmsghdr->nlmsg_seq = ++next_seq;
680     nlmsghdr->nlmsg_pid = 0;
681 }
682
683 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
684  * initially empty.  'expected_payload' should be an estimate of the number of
685  * payload bytes to be supplied; if the size of the payload is unknown a value
686  * of 0 is acceptable.
687  *
688  * 'family' is the family number obtained via nl_lookup_genl_family().
689  *
690  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
691  * is often NLM_F_REQUEST indicating that a request is being made, commonly
692  * or'd with NLM_F_ACK to request an acknowledgement.
693  *
694  * 'cmd' is an enumerated value specific to the Generic Netlink family
695  * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
696  *
697  * 'version' is a version number specific to the family and command (often 1).
698  *
699  * Sets the new nlmsghdr's nlmsg_pid field to 0 for now.  nl_sock_send() will
700  * fill it in just before sending the message.
701  *
702  * nl_msg_put_nlmsghdr() should be used to compose Netlink messages that are
703  * not Generic Netlink messages. */
704 void
705 nl_msg_put_genlmsghdr(struct ofpbuf *msg, size_t expected_payload,
706                       int family, uint32_t flags, uint8_t cmd, uint8_t version)
707 {
708     struct genlmsghdr *genlmsghdr;
709
710     nl_msg_put_nlmsghdr(msg, GENL_HDRLEN + expected_payload, family, flags);
711     assert(msg->size == NLMSG_HDRLEN);
712     genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
713     genlmsghdr->cmd = cmd;
714     genlmsghdr->version = version;
715     genlmsghdr->reserved = 0;
716 }
717
718 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
719  * the tail end of 'msg'.  Data in 'msg' is reallocated and copied if
720  * necessary. */
721 void
722 nl_msg_put(struct ofpbuf *msg, const void *data, size_t size)
723 {
724     memcpy(nl_msg_put_uninit(msg, size), data, size);
725 }
726
727 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
728  * end of 'msg', reallocating and copying its data if necessary.  Returns a
729  * pointer to the first byte of the new data, which is left uninitialized. */
730 void *
731 nl_msg_put_uninit(struct ofpbuf *msg, size_t size)
732 {
733     size_t pad = NLMSG_ALIGN(size) - size;
734     char *p = ofpbuf_put_uninit(msg, size + pad);
735     if (pad) {
736         memset(p + size, 0, pad);
737     }
738     return p;
739 }
740
741 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
742  * data as its payload, plus Netlink padding if needed, to the tail end of
743  * 'msg', reallocating and copying its data if necessary.  Returns a pointer to
744  * the first byte of data in the attribute, which is left uninitialized. */
745 void *
746 nl_msg_put_unspec_uninit(struct ofpbuf *msg, uint16_t type, size_t size)
747 {
748     size_t total_size = NLA_HDRLEN + size;
749     struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
750     assert(NLA_ALIGN(total_size) <= UINT16_MAX);
751     nla->nla_len = total_size;
752     nla->nla_type = type;
753     return nla + 1;
754 }
755
756 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
757  * 'data' as its payload, to the tail end of 'msg', reallocating and copying
758  * its data if necessary.  Returns a pointer to the first byte of data in the
759  * attribute, which is left uninitialized. */
760 void
761 nl_msg_put_unspec(struct ofpbuf *msg, uint16_t type,
762                   const void *data, size_t size)
763 {
764     memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
765 }
766
767 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
768  * (Some Netlink protocols use the presence or absence of an attribute as a
769  * Boolean flag.) */
770 void
771 nl_msg_put_flag(struct ofpbuf *msg, uint16_t type)
772 {
773     nl_msg_put_unspec(msg, type, NULL, 0);
774 }
775
776 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
777  * to 'msg'. */
778 void
779 nl_msg_put_u8(struct ofpbuf *msg, uint16_t type, uint8_t value)
780 {
781     nl_msg_put_unspec(msg, type, &value, sizeof value);
782 }
783
784 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
785  * to 'msg'. */
786 void
787 nl_msg_put_u16(struct ofpbuf *msg, uint16_t type, uint16_t value)
788 {
789     nl_msg_put_unspec(msg, type, &value, sizeof value);
790 }
791
792 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
793  * to 'msg'. */
794 void
795 nl_msg_put_u32(struct ofpbuf *msg, uint16_t type, uint32_t value)
796 {
797     nl_msg_put_unspec(msg, type, &value, sizeof value);
798 }
799
800 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
801  * to 'msg'. */
802 void
803 nl_msg_put_u64(struct ofpbuf *msg, uint16_t type, uint64_t value)
804 {
805     nl_msg_put_unspec(msg, type, &value, sizeof value);
806 }
807
808 /* Appends a Netlink attribute of the given 'type' and the given
809  * null-terminated string 'value' to 'msg'. */
810 void
811 nl_msg_put_string(struct ofpbuf *msg, uint16_t type, const char *value)
812 {
813     nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
814 }
815
816 /* Adds the header for nested Netlink attributes to 'msg', with the specified
817  * 'type', and returns the header's offset within 'msg'.  The caller should add
818  * the content for the nested Netlink attribute to 'msg' (e.g. using the other
819  * nl_msg_*() functions), and then pass the returned offset to
820  * nl_msg_end_nested() to finish up the nested attributes. */
821 size_t
822 nl_msg_start_nested(struct ofpbuf *msg, uint16_t type)
823 {
824     size_t offset = msg->size;
825     nl_msg_put_unspec(msg, type, NULL, 0);
826     return offset;
827 }
828
829 /* Finalizes a nested Netlink attribute in 'msg'.  'offset' should be the value
830  * returned by nl_msg_start_nested(). */
831 void
832 nl_msg_end_nested(struct ofpbuf *msg, size_t offset)
833 {
834     struct nlattr *attr = ofpbuf_at_assert(msg, offset, sizeof *attr);
835     attr->nla_len = msg->size - offset;
836 }
837
838 /* Appends a nested Netlink attribute of the given 'type', with the 'size'
839  * bytes of content starting at 'data', to 'msg'. */
840 void
841 nl_msg_put_nested(struct ofpbuf *msg,
842                   uint16_t type, const void *data, size_t size)
843 {
844     size_t offset = nl_msg_start_nested(msg, type);
845     nl_msg_put(msg, data, size);
846     nl_msg_end_nested(msg, offset);
847 }
848
849 /* If 'buffer' begins with a valid "struct nlmsghdr", pulls the header and its
850  * payload off 'buffer', stores header and payload in 'msg->data' and
851  * 'msg->size', and returns a pointer to the header.
852  *
853  * If 'buffer' does not begin with a "struct nlmsghdr" or begins with one that
854  * is invalid, returns NULL without modifying 'buffer'. */
855 struct nlmsghdr *
856 nl_msg_next(struct ofpbuf *buffer, struct ofpbuf *msg)
857 {
858     if (buffer->size >= sizeof(struct nlmsghdr)) {
859         struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(buffer);
860         size_t len = nlmsghdr->nlmsg_len;
861         if (len >= sizeof *nlmsghdr && len <= buffer->size) {
862             msg->data = nlmsghdr;
863             msg->size = len;
864             ofpbuf_pull(buffer, len);
865             return nlmsghdr;
866         }
867     }
868
869     msg->data = NULL;
870     msg->size = 0;
871     return NULL;
872 }
873 \f
874 /* Attributes. */
875
876 /* Returns the first byte in the payload of attribute 'nla'. */
877 const void *
878 nl_attr_get(const struct nlattr *nla)
879 {
880     assert(nla->nla_len >= NLA_HDRLEN);
881     return nla + 1;
882 }
883
884 /* Returns the number of bytes in the payload of attribute 'nla'. */
885 size_t
886 nl_attr_get_size(const struct nlattr *nla)
887 {
888     assert(nla->nla_len >= NLA_HDRLEN);
889     return nla->nla_len - NLA_HDRLEN;
890 }
891
892 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
893  * first byte of the payload. */
894 const void *
895 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
896 {
897     assert(nla->nla_len >= NLA_HDRLEN + size);
898     return nla + 1;
899 }
900
901 /* Returns true if 'nla' is nonnull.  (Some Netlink protocols use the presence
902  * or absence of an attribute as a Boolean flag.) */
903 bool
904 nl_attr_get_flag(const struct nlattr *nla)
905 {
906     return nla != NULL;
907 }
908
909 #define NL_ATTR_GET_AS(NLA, TYPE) \
910         (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
911
912 /* Returns the 8-bit value in 'nla''s payload.
913  *
914  * Asserts that 'nla''s payload is at least 1 byte long. */
915 uint8_t
916 nl_attr_get_u8(const struct nlattr *nla)
917 {
918     return NL_ATTR_GET_AS(nla, uint8_t);
919 }
920
921 /* Returns the 16-bit value in 'nla''s payload.
922  *
923  * Asserts that 'nla''s payload is at least 2 bytes long. */
924 uint16_t
925 nl_attr_get_u16(const struct nlattr *nla)
926 {
927     return NL_ATTR_GET_AS(nla, uint16_t);
928 }
929
930 /* Returns the 32-bit value in 'nla''s payload.
931  *
932  * Asserts that 'nla''s payload is at least 4 bytes long. */
933 uint32_t
934 nl_attr_get_u32(const struct nlattr *nla)
935 {
936     return NL_ATTR_GET_AS(nla, uint32_t);
937 }
938
939 /* Returns the 64-bit value in 'nla''s payload.
940  *
941  * Asserts that 'nla''s payload is at least 8 bytes long. */
942 uint64_t
943 nl_attr_get_u64(const struct nlattr *nla)
944 {
945     return NL_ATTR_GET_AS(nla, uint64_t);
946 }
947
948 /* Returns the null-terminated string value in 'nla''s payload.
949  *
950  * Asserts that 'nla''s payload contains a null-terminated string. */
951 const char *
952 nl_attr_get_string(const struct nlattr *nla)
953 {
954     assert(nla->nla_len > NLA_HDRLEN);
955     assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
956     return nl_attr_get(nla);
957 }
958
959 /* Initializes 'nested' to the payload of 'nla'.  Doesn't initialize every
960  * field in 'nested', but enough to poke around with it in a read-only way. */
961 void
962 nl_attr_get_nested(const struct nlattr *nla, struct ofpbuf *nested)
963 {
964     nested->data = (void *) nl_attr_get(nla);
965     nested->size = nl_attr_get_size(nla);
966 }
967
968 /* Default minimum and maximum payload sizes for each type of attribute. */
969 static const size_t attr_len_range[][2] = {
970     [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
971     [NL_A_U8] = { 1, 1 },
972     [NL_A_U16] = { 2, 2 },
973     [NL_A_U32] = { 4, 4 },
974     [NL_A_U64] = { 8, 8 },
975     [NL_A_STRING] = { 1, SIZE_MAX },
976     [NL_A_FLAG] = { 0, SIZE_MAX },
977     [NL_A_NESTED] = { 0, SIZE_MAX },
978 };
979
980 /* Parses the 'msg' starting at the given 'nla_offset' as a sequence of Netlink
981  * attributes.  'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
982  * with nla_type == i is parsed; a pointer to attribute i is stored in
983  * attrs[i].  Returns true if successful, false on failure.
984  *
985  * If the Netlink attributes in 'msg' follow a Netlink header and a Generic
986  * Netlink header, then 'nla_offset' should be NLMSG_HDRLEN + GENL_HDRLEN. */
987 bool
988 nl_policy_parse(const struct ofpbuf *msg, size_t nla_offset,
989                 const struct nl_policy policy[],
990                 struct nlattr *attrs[], size_t n_attrs)
991 {
992     void *p, *tail;
993     size_t n_required;
994     size_t i;
995
996     n_required = 0;
997     for (i = 0; i < n_attrs; i++) {
998         attrs[i] = NULL;
999
1000         assert(policy[i].type < N_NL_ATTR_TYPES);
1001         if (policy[i].type != NL_A_NO_ATTR
1002             && policy[i].type != NL_A_FLAG
1003             && !policy[i].optional) {
1004             n_required++;
1005         }
1006     }
1007
1008     p = ofpbuf_at(msg, nla_offset, 0);
1009     if (p == NULL) {
1010         VLOG_DBG_RL(&rl, "missing headers in nl_policy_parse");
1011         return false;
1012     }
1013     tail = ofpbuf_tail(msg);
1014
1015     while (p < tail) {
1016         size_t offset = (char*)p - (char*)msg->data;
1017         struct nlattr *nla = p;
1018         size_t len, aligned_len;
1019         uint16_t type;
1020
1021         /* Make sure its claimed length is plausible. */
1022         if (nla->nla_len < NLA_HDRLEN) {
1023             VLOG_DBG_RL(&rl, "%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
1024                         offset, nla->nla_len);
1025             return false;
1026         }
1027         len = nla->nla_len - NLA_HDRLEN;
1028         aligned_len = NLA_ALIGN(len);
1029         if (aligned_len > (char*)tail - (char*)p) {
1030             VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" aligned data len (%zu) "
1031                         "> bytes left (%tu)",
1032                         offset, nla->nla_type, aligned_len,
1033                         (char*)tail - (char*)p);
1034             return false;
1035         }
1036
1037         type = nla->nla_type;
1038         if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
1039             const struct nl_policy *p = &policy[type];
1040             size_t min_len, max_len;
1041
1042             /* Validate length and content. */
1043             min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
1044             max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
1045             if (len < min_len || len > max_len) {
1046                 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" length %zu not in "
1047                             "allowed range %zu...%zu",
1048                             offset, type, len, min_len, max_len);
1049                 return false;
1050             }
1051             if (p->type == NL_A_STRING) {
1052                 if (((char *) nla)[nla->nla_len - 1]) {
1053                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" lacks null at end",
1054                                 offset, type);
1055                     return false;
1056                 }
1057                 if (memchr(nla + 1, '\0', len - 1) != NULL) {
1058                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" has bad length",
1059                                 offset, type);
1060                     return false;
1061                 }
1062             }
1063             if (!p->optional && attrs[type] == NULL) {
1064                 assert(n_required > 0);
1065                 --n_required;
1066             }
1067             attrs[type] = nla;
1068         } else {
1069             /* Skip attribute type that we don't care about. */
1070         }
1071         p = (char*)p + NLA_ALIGN(nla->nla_len);
1072     }
1073     if (n_required) {
1074         VLOG_DBG_RL(&rl, "%zu required attrs missing", n_required);
1075         return false;
1076     }
1077     return true;
1078 }
1079
1080 /* Parses the Netlink attributes within 'nla'.  'policy[i]', for 0 <= i <
1081  * n_attrs, specifies how the attribute with nla_type == i is parsed; a pointer
1082  * to attribute i is stored in attrs[i].  Returns true if successful, false on
1083  * failure. */
1084 bool
1085 nl_parse_nested(const struct nlattr *nla, const struct nl_policy policy[],
1086                 struct nlattr *attrs[], size_t n_attrs)
1087 {
1088     struct ofpbuf buf;
1089
1090     nl_attr_get_nested(nla, &buf);
1091     return nl_policy_parse(&buf, 0, policy, attrs, n_attrs);
1092 }
1093 \f
1094 /* Miscellaneous.  */
1095
1096 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1097     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1098 };
1099
1100 static int do_lookup_genl_family(const char *name)
1101 {
1102     struct nl_sock *sock;
1103     struct ofpbuf request, *reply;
1104     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1105     int retval;
1106
1107     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
1108     if (retval) {
1109         return -retval;
1110     }
1111
1112     ofpbuf_init(&request, 0);
1113     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1114                           CTRL_CMD_GETFAMILY, 1);
1115     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1116     retval = nl_sock_transact(sock, &request, &reply);
1117     ofpbuf_uninit(&request);
1118     if (retval) {
1119         nl_sock_destroy(sock);
1120         return -retval;
1121     }
1122
1123     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1124                          family_policy, attrs, ARRAY_SIZE(family_policy))) {
1125         nl_sock_destroy(sock);
1126         ofpbuf_delete(reply);
1127         return -EPROTO;
1128     }
1129
1130     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1131     if (retval == 0) {
1132         retval = -EPROTO;
1133     }
1134     nl_sock_destroy(sock);
1135     ofpbuf_delete(reply);
1136     return retval;
1137 }
1138
1139 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1140  * number and stores it in '*number'.  If successful, returns 0 and the caller
1141  * may use '*number' as the family number.  On failure, returns a positive
1142  * errno value and '*number' caches the errno value. */
1143 int
1144 nl_lookup_genl_family(const char *name, int *number)
1145 {
1146     if (*number == 0) {
1147         *number = do_lookup_genl_family(name);
1148         assert(*number != 0);
1149     }
1150     return *number > 0 ? 0 : -*number;
1151 }
1152 \f
1153 /* Netlink PID.
1154  *
1155  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
1156  * programs that have a single Netlink socket use their Unix process ID as PID,
1157  * and programs with multiple Netlink sockets add a unique per-socket
1158  * identifier in the bits above the Unix process ID.
1159  *
1160  * The kernel has Netlink PID 0.
1161  */
1162
1163 /* Parameters for how many bits in the PID should come from the Unix process ID
1164  * and how many unique per-socket. */
1165 #define SOCKET_BITS 10
1166 #define MAX_SOCKETS (1u << SOCKET_BITS)
1167
1168 #define PROCESS_BITS (32 - SOCKET_BITS)
1169 #define MAX_PROCESSES (1u << PROCESS_BITS)
1170 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
1171
1172 /* Bit vector of unused socket identifiers. */
1173 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
1174
1175 /* Allocates and returns a new Netlink PID. */
1176 static int
1177 alloc_pid(uint32_t *pid)
1178 {
1179     int i;
1180
1181     for (i = 0; i < MAX_SOCKETS; i++) {
1182         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
1183             avail_sockets[i / 32] |= 1u << (i % 32);
1184             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
1185             return 0;
1186         }
1187     }
1188     VLOG_ERR("netlink pid space exhausted");
1189     return ENOBUFS;
1190 }
1191
1192 /* Makes the specified 'pid' available for reuse. */
1193 static void
1194 free_pid(uint32_t pid)
1195 {
1196     int sock = pid >> PROCESS_BITS;
1197     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
1198     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
1199 }
1200 \f
1201 static void
1202 nlmsghdr_to_string(const struct nlmsghdr *h, struct ds *ds)
1203 {
1204     struct nlmsg_flag {
1205         unsigned int bits;
1206         const char *name;
1207     };
1208     static const struct nlmsg_flag flags[] = {
1209         { NLM_F_REQUEST, "REQUEST" },
1210         { NLM_F_MULTI, "MULTI" },
1211         { NLM_F_ACK, "ACK" },
1212         { NLM_F_ECHO, "ECHO" },
1213         { NLM_F_DUMP, "DUMP" },
1214         { NLM_F_ROOT, "ROOT" },
1215         { NLM_F_MATCH, "MATCH" },
1216         { NLM_F_ATOMIC, "ATOMIC" },
1217     };
1218     const struct nlmsg_flag *flag;
1219     uint16_t flags_left;
1220
1221     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1222                   h->nlmsg_len, h->nlmsg_type);
1223     if (h->nlmsg_type == NLMSG_NOOP) {
1224         ds_put_cstr(ds, "(no-op)");
1225     } else if (h->nlmsg_type == NLMSG_ERROR) {
1226         ds_put_cstr(ds, "(error)");
1227     } else if (h->nlmsg_type == NLMSG_DONE) {
1228         ds_put_cstr(ds, "(done)");
1229     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1230         ds_put_cstr(ds, "(overrun)");
1231     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1232         ds_put_cstr(ds, "(reserved)");
1233     } else {
1234         ds_put_cstr(ds, "(family-defined)");
1235     }
1236     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1237     flags_left = h->nlmsg_flags;
1238     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1239         if ((flags_left & flag->bits) == flag->bits) {
1240             ds_put_format(ds, "[%s]", flag->name);
1241             flags_left &= ~flag->bits;
1242         }
1243     }
1244     if (flags_left) {
1245         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1246     }
1247     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
1248                   h->nlmsg_seq, h->nlmsg_pid,
1249                   (int) (h->nlmsg_pid & PROCESS_MASK),
1250                   (int) (h->nlmsg_pid >> PROCESS_BITS));
1251 }
1252
1253 static char *
1254 nlmsg_to_string(const struct ofpbuf *buffer)
1255 {
1256     struct ds ds = DS_EMPTY_INITIALIZER;
1257     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1258     if (h) {
1259         nlmsghdr_to_string(h, &ds);
1260         if (h->nlmsg_type == NLMSG_ERROR) {
1261             const struct nlmsgerr *e;
1262             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1263                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1264             if (e) {
1265                 ds_put_format(&ds, " error(%d", e->error);
1266                 if (e->error < 0) {
1267                     ds_put_format(&ds, "(%s)", strerror(-e->error));
1268                 }
1269                 ds_put_cstr(&ds, ", in-reply-to(");
1270                 nlmsghdr_to_string(&e->msg, &ds);
1271                 ds_put_cstr(&ds, "))");
1272             } else {
1273                 ds_put_cstr(&ds, " error(truncated)");
1274             }
1275         } else if (h->nlmsg_type == NLMSG_DONE) {
1276             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1277             if (error) {
1278                 ds_put_format(&ds, " done(%d", *error);
1279                 if (*error < 0) {
1280                     ds_put_format(&ds, "(%s)", strerror(-*error));
1281                 }
1282                 ds_put_cstr(&ds, ")");
1283             } else {
1284                 ds_put_cstr(&ds, " done(truncated)");
1285             }
1286         }
1287     } else {
1288         ds_put_cstr(&ds, "nl(truncated)");
1289     }
1290     return ds.string;
1291 }
1292
1293 static void
1294 log_nlmsg(const char *function, int error,
1295           const void *message, size_t size)
1296 {
1297     struct ofpbuf buffer;
1298     char *nlmsg;
1299
1300     if (!VLOG_IS_DBG_ENABLED()) {
1301         return;
1302     }
1303
1304     buffer.data = (void *) message;
1305     buffer.size = size;
1306     nlmsg = nlmsg_to_string(&buffer);
1307     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
1308     free(nlmsg);
1309 }
1310