ofpbuf: New function ofpbuf_use_const().
[cascardo/ovs.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 "stress.h"
33 #include "timeval.h"
34 #include "util.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(netlink);
38
39 COVERAGE_DEFINE(netlink_overflow);
40 COVERAGE_DEFINE(netlink_received);
41 COVERAGE_DEFINE(netlink_recv_retry);
42 COVERAGE_DEFINE(netlink_send);
43 COVERAGE_DEFINE(netlink_sent);
44
45 /* Linux header file confusion causes this to be undefined. */
46 #ifndef SOL_NETLINK
47 #define SOL_NETLINK 270
48 #endif
49
50 /* A single (bad) Netlink message can in theory dump out many, many log
51  * messages, so the burst size is set quite high here to avoid missing useful
52  * information.  Also, at high logging levels we log *all* Netlink messages. */
53 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
54
55 static void log_nlmsg(const char *function, int error,
56                       const void *message, size_t size);
57 \f
58 /* Netlink sockets. */
59
60 struct nl_sock
61 {
62     int fd;
63     uint32_t pid;
64 };
65
66 /* Next nlmsghdr sequence number.
67  *
68  * This implementation uses sequence numbers that are unique process-wide, to
69  * avoid a hypothetical race: send request, close socket, open new socket that
70  * reuses the old socket's PID value, send request on new socket, receive reply
71  * from kernel to old socket but with same PID and sequence number.  (This race
72  * could be avoided other ways, e.g. by preventing PIDs from being quickly
73  * reused). */
74 static uint32_t next_seq;
75
76 static int alloc_pid(uint32_t *);
77 static void free_pid(uint32_t);
78
79 /* Creates a new netlink socket for the given netlink 'protocol'
80  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
81  * new socket if successful, otherwise returns a positive errno value.
82  *
83  * If 'multicast_group' is nonzero, the new socket subscribes to the specified
84  * netlink multicast group.  (A netlink socket may listen to an arbitrary
85  * number of multicast groups, but so far we only need one at a time.)
86  *
87  * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
88  * receive buffer size, respectively.
89  */
90 int
91 nl_sock_create(int protocol, int multicast_group,
92                size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
93 {
94     struct nl_sock *sock;
95     struct sockaddr_nl local, remote;
96     int retval = 0;
97
98     if (next_seq == 0) {
99         /* Pick initial sequence number. */
100         next_seq = getpid() ^ time_wall();
101     }
102
103     *sockp = NULL;
104     sock = malloc(sizeof *sock);
105     if (sock == NULL) {
106         return ENOMEM;
107     }
108
109     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
110     if (sock->fd < 0) {
111         VLOG_ERR("fcntl: %s", strerror(errno));
112         goto error;
113     }
114
115     retval = alloc_pid(&sock->pid);
116     if (retval) {
117         goto error;
118     }
119
120     if (so_sndbuf != 0
121         && setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
122                       &so_sndbuf, sizeof so_sndbuf) < 0) {
123         VLOG_ERR("setsockopt(SO_SNDBUF,%zu): %s", so_sndbuf, strerror(errno));
124         goto error_free_pid;
125     }
126
127     if (so_rcvbuf != 0
128         && setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
129                       &so_rcvbuf, sizeof so_rcvbuf) < 0) {
130         VLOG_ERR("setsockopt(SO_RCVBUF,%zu): %s", so_rcvbuf, strerror(errno));
131         goto error_free_pid;
132     }
133
134     /* Bind local address as our selected pid. */
135     memset(&local, 0, sizeof local);
136     local.nl_family = AF_NETLINK;
137     local.nl_pid = sock->pid;
138     if (multicast_group > 0 && multicast_group <= 32) {
139         /* This method of joining multicast groups is supported by old kernels,
140          * but it only allows 32 multicast groups per protocol. */
141         local.nl_groups |= 1ul << (multicast_group - 1);
142     }
143     if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
144         VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
145         goto error_free_pid;
146     }
147
148     /* Bind remote address as the kernel (pid 0). */
149     memset(&remote, 0, sizeof remote);
150     remote.nl_family = AF_NETLINK;
151     remote.nl_pid = 0;
152     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
153         VLOG_ERR("connect(0): %s", strerror(errno));
154         goto error_free_pid;
155     }
156
157     /* Older kernel headers failed to define this macro.  We want our programs
158      * to support the newer kernel features even if compiled with older
159      * headers, so define it ourselves in such a case. */
160 #ifndef NETLINK_ADD_MEMBERSHIP
161 #define NETLINK_ADD_MEMBERSHIP 1
162 #endif
163
164     /* This method of joining multicast groups is only supported by newish
165      * kernels, but it allows for an arbitrary number of multicast groups. */
166     if (multicast_group > 32
167         && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
168                       &multicast_group, sizeof multicast_group) < 0) {
169         VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
170                  multicast_group, strerror(errno));
171         goto error_free_pid;
172     }
173
174     *sockp = sock;
175     return 0;
176
177 error_free_pid:
178     free_pid(sock->pid);
179 error:
180     if (retval == 0) {
181         retval = errno;
182         if (retval == 0) {
183             retval = EINVAL;
184         }
185     }
186     if (sock->fd >= 0) {
187         close(sock->fd);
188     }
189     free(sock);
190     return retval;
191 }
192
193 /* Destroys netlink socket 'sock'. */
194 void
195 nl_sock_destroy(struct nl_sock *sock)
196 {
197     if (sock) {
198         close(sock->fd);
199         free_pid(sock->pid);
200         free(sock);
201     }
202 }
203
204 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
205  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, and
206  * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
207  *
208  * Returns 0 if successful, otherwise a positive errno value.  If
209  * 'wait' is true, then the send will wait until buffer space is ready;
210  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
211 int
212 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
213 {
214     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
215     int error;
216
217     nlmsg->nlmsg_len = msg->size;
218     nlmsg->nlmsg_pid = sock->pid;
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     if (!error) {
226         COVERAGE_INC(netlink_sent);
227     }
228     return error;
229 }
230
231 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
232  * a single Netlink message.  (The message must be fully formed and not require
233  * finalization of its nlmsg_len or nlmsg_pid fields.)
234  *
235  * Returns 0 if successful, otherwise a positive errno value.  If 'wait' is
236  * true, then the send will wait until buffer space is ready; otherwise,
237  * returns EAGAIN if the 'sock' send buffer is full. */
238 int
239 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
240               bool wait)
241 {
242     struct msghdr msg;
243     int error;
244
245     COVERAGE_INC(netlink_send);
246     memset(&msg, 0, sizeof msg);
247     msg.msg_iov = (struct iovec *) iov;
248     msg.msg_iovlen = n_iov;
249     do {
250         int retval;
251         retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
252         error = retval < 0 ? errno : 0;
253     } while (error == EINTR);
254     if (error != EAGAIN) {
255         log_nlmsg(__func__, error, iov[0].iov_base, iov[0].iov_len);
256         if (!error) {
257             COVERAGE_INC(netlink_sent);
258         }
259     }
260     return error;
261 }
262
263 /* This stress option is useful for testing that OVS properly tolerates
264  * -ENOBUFS on NetLink sockets.  Such errors are unavoidable because they can
265  * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
266  * reply to a request.  They can also occur if messages arrive on a multicast
267  * channel faster than OVS can process them. */
268 STRESS_OPTION(
269     netlink_overflow, "simulate netlink socket receive buffer overflow",
270     5, 1, -1, 100);
271
272 /* Tries to receive a netlink message from the kernel on 'sock'.  If
273  * successful, stores the received message into '*bufp' and returns 0.  The
274  * caller is responsible for destroying the message with ofpbuf_delete().  On
275  * failure, returns a positive errno value and stores a null pointer into
276  * '*bufp'.
277  *
278  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
279  * returns EAGAIN if the 'sock' receive buffer is empty. */
280 int
281 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
282 {
283     uint8_t tmp;
284     ssize_t bufsize = 2048;
285     ssize_t nbytes, nbytes2;
286     struct ofpbuf *buf;
287     struct nlmsghdr *nlmsghdr;
288     struct iovec iov;
289     struct msghdr msg = {
290         .msg_name = NULL,
291         .msg_namelen = 0,
292         .msg_iov = &iov,
293         .msg_iovlen = 1,
294         .msg_control = NULL,
295         .msg_controllen = 0,
296         .msg_flags = 0
297     };
298
299     buf = ofpbuf_new(bufsize);
300     *bufp = NULL;
301
302 try_again:
303     /* Attempt to read the message.  We don't know the size of the data
304      * yet, so we take a guess at 2048.  If we're wrong, we keep trying
305      * and doubling the buffer size each time.
306      */
307     nlmsghdr = ofpbuf_put_uninit(buf, bufsize);
308     iov.iov_base = nlmsghdr;
309     iov.iov_len = bufsize;
310     do {
311         nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
312     } while (nbytes < 0 && errno == EINTR);
313     if (nbytes < 0) {
314         ofpbuf_delete(buf);
315         return errno;
316     }
317     if (msg.msg_flags & MSG_TRUNC) {
318         COVERAGE_INC(netlink_recv_retry);
319         bufsize *= 2;
320         ofpbuf_reinit(buf, bufsize);
321         goto try_again;
322     }
323     buf->size = nbytes;
324
325     /* We successfully read the message, so recv again to clear the queue */
326     iov.iov_base = &tmp;
327     iov.iov_len = 1;
328     do {
329         nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
330     } while (nbytes2 < 0 && errno == EINTR);
331     if (nbytes2 < 0) {
332         if (errno == ENOBUFS) {
333             /* The kernel is notifying us that a message it tried to send to us
334              * was dropped.  We have to pass this along to the caller in case
335              * it wants to retry a request.  So kill the buffer, which we can
336              * re-read next time. */
337             COVERAGE_INC(netlink_overflow);
338             ofpbuf_delete(buf);
339             return ENOBUFS;
340         } else {
341             VLOG_ERR_RL(&rl, "failed to remove nlmsg from socket: %s\n",
342                         strerror(errno));
343         }
344     }
345     if (nbytes < sizeof *nlmsghdr
346         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
347         || nlmsghdr->nlmsg_len > nbytes) {
348         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
349                     bufsize, NLMSG_HDRLEN);
350         ofpbuf_delete(buf);
351         return EPROTO;
352     }
353
354     if (STRESS(netlink_overflow)) {
355         ofpbuf_delete(buf);
356         return ENOBUFS;
357     }
358
359     *bufp = buf;
360     log_nlmsg(__func__, 0, buf->data, buf->size);
361     COVERAGE_INC(netlink_received);
362
363     return 0;
364 }
365
366 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
367  * successful, returns 0.  On failure, returns a positive errno value.
368  *
369  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
370  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
371  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
372  * reply, if any, is discarded.
373  *
374  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
375  * be set to 'sock''s pid, before the message is sent.  NLM_F_ACK will be set
376  * in nlmsg_flags.
377  *
378  * The caller is responsible for destroying 'request'.
379  *
380  * Bare Netlink is an unreliable transport protocol.  This function layers
381  * reliable delivery and reply semantics on top of bare Netlink.
382  *
383  * In Netlink, sending a request to the kernel is reliable enough, because the
384  * kernel will tell us if the message cannot be queued (and we will in that
385  * case put it on the transmit queue and wait until it can be delivered).
386  *
387  * Receiving the reply is the real problem: if the socket buffer is full when
388  * the kernel tries to send the reply, the reply will be dropped.  However, the
389  * kernel sets a flag that a reply has been dropped.  The next call to recv
390  * then returns ENOBUFS.  We can then re-send the request.
391  *
392  * Caveats:
393  *
394  *      1. Netlink depends on sequence numbers to match up requests and
395  *         replies.  The sender of a request supplies a sequence number, and
396  *         the reply echos back that sequence number.
397  *
398  *         This is fine, but (1) some kernel netlink implementations are
399  *         broken, in that they fail to echo sequence numbers and (2) this
400  *         function will drop packets with non-matching sequence numbers, so
401  *         that only a single request can be usefully transacted at a time.
402  *
403  *      2. Resending the request causes it to be re-executed, so the request
404  *         needs to be idempotent.
405  */
406 int
407 nl_sock_transact(struct nl_sock *sock,
408                  const struct ofpbuf *request, struct ofpbuf **replyp)
409 {
410     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
411     struct nlmsghdr *nlmsghdr;
412     struct ofpbuf *reply;
413     int retval;
414
415     if (replyp) {
416         *replyp = NULL;
417     }
418
419     /* Ensure that we get a reply even if this message doesn't ordinarily call
420      * for one. */
421     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
422
423 send:
424     retval = nl_sock_send(sock, request, true);
425     if (retval) {
426         return retval;
427     }
428
429 recv:
430     retval = nl_sock_recv(sock, &reply, true);
431     if (retval) {
432         if (retval == ENOBUFS) {
433             COVERAGE_INC(netlink_overflow);
434             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
435             goto send;
436         } else {
437             return retval;
438         }
439     }
440     nlmsghdr = nl_msg_nlmsghdr(reply);
441     if (seq != nlmsghdr->nlmsg_seq) {
442         VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
443                     nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
444         ofpbuf_delete(reply);
445         goto recv;
446     }
447
448     /* If the reply is an error, discard the reply and return the error code.
449      *
450      * Except: if the reply is just an acknowledgement (error code of 0), and
451      * the caller is interested in the reply (replyp != NULL), pass the reply
452      * up to the caller.  Otherwise the caller will get a return value of 0
453      * and null '*replyp', which makes unwary callers likely to segfault. */
454     if (nl_msg_nlmsgerr(reply, &retval) && (retval || !replyp)) {
455         ofpbuf_delete(reply);
456         if (retval) {
457             VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
458                         retval, strerror(retval));
459         }
460         return retval != EAGAIN ? retval : EPROTO;
461     }
462
463     if (replyp) {
464         *replyp = reply;
465     } else {
466         ofpbuf_delete(reply);
467     }
468     return 0;
469 }
470
471 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
472  * 'sock', and initializes 'dump' to reflect the state of the operation.
473  *
474  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
475  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
476  * NLM_F_ACK will be set in nlmsg_flags.
477  *
478  * The properties of Netlink make dump operations reliable as long as all of
479  * the following are true:
480  *
481  *   - At most a single dump is in progress at a time on a given nl_sock.
482  *
483  *   - The nl_sock is not subscribed to any multicast groups.
484  *
485  *   - The nl_sock is not used to send any other messages before the dump
486  *     operation is complete.
487  *
488  * This function provides no status indication.  An error status for the entire
489  * dump operation is provided when it is completed by calling nl_dump_done().
490  *
491  * The caller is responsible for destroying 'request'.  The caller must not
492  * close 'sock' before it completes the dump operation (by calling
493  * nl_dump_done()).
494  */
495 void
496 nl_dump_start(struct nl_dump *dump,
497               struct nl_sock *sock, const struct ofpbuf *request)
498 {
499     struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
500     nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
501     dump->seq = nlmsghdr->nlmsg_seq;
502     dump->sock = sock;
503     dump->status = nl_sock_send(sock, request, true);
504     dump->buffer = NULL;
505 }
506
507 /* Helper function for nl_dump_next(). */
508 static int
509 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
510 {
511     struct nlmsghdr *nlmsghdr;
512     struct ofpbuf *buffer;
513     int retval;
514
515     retval = nl_sock_recv(dump->sock, bufferp, true);
516     if (retval) {
517         return retval == EINTR ? EAGAIN : retval;
518     }
519     buffer = *bufferp;
520
521     nlmsghdr = nl_msg_nlmsghdr(buffer);
522     if (dump->seq != nlmsghdr->nlmsg_seq) {
523         VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
524                     nlmsghdr->nlmsg_seq, dump->seq);
525         return EAGAIN;
526     }
527
528     if (nl_msg_nlmsgerr(buffer, &retval)) {
529         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
530                      strerror(retval));
531         return retval && retval != EAGAIN ? retval : EPROTO;
532     }
533
534     return 0;
535 }
536
537 /* Attempts to retrieve another reply from 'dump', which must have been
538  * initialized with nl_dump_start().
539  *
540  * If successful, returns true and points 'reply->data' and 'reply->size' to
541  * the message that was retrieved.  The caller must not modify 'reply' (because
542  * it points into the middle of a larger buffer).
543  *
544  * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
545  * to 0.  Failure might indicate an actual error or merely the end of replies.
546  * An error status for the entire dump operation is provided when it is
547  * completed by calling nl_dump_done().
548  */
549 bool
550 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
551 {
552     struct nlmsghdr *nlmsghdr;
553
554     reply->data = NULL;
555     reply->size = 0;
556     if (dump->status) {
557         return false;
558     }
559
560     if (dump->buffer && !dump->buffer->size) {
561         ofpbuf_delete(dump->buffer);
562         dump->buffer = NULL;
563     }
564     while (!dump->buffer) {
565         int retval = nl_dump_recv(dump, &dump->buffer);
566         if (retval) {
567             ofpbuf_delete(dump->buffer);
568             dump->buffer = NULL;
569             if (retval != EAGAIN) {
570                 dump->status = retval;
571                 return false;
572             }
573         }
574     }
575
576     nlmsghdr = nl_msg_next(dump->buffer, reply);
577     if (!nlmsghdr) {
578         VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
579         dump->status = EPROTO;
580         return false;
581     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
582         dump->status = EOF;
583         return false;
584     }
585
586     return true;
587 }
588
589 /* Completes Netlink dump operation 'dump', which must have been initialized
590  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
591  * otherwise a positive errno value describing the problem. */
592 int
593 nl_dump_done(struct nl_dump *dump)
594 {
595     /* Drain any remaining messages that the client didn't read.  Otherwise the
596      * kernel will continue to queue them up and waste buffer space. */
597     while (!dump->status) {
598         struct ofpbuf reply;
599         if (!nl_dump_next(dump, &reply)) {
600             assert(dump->status);
601         }
602     }
603
604     ofpbuf_delete(dump->buffer);
605     return dump->status == EOF ? 0 : dump->status;
606 }
607
608 /* Causes poll_block() to wake up when any of the specified 'events' (which is
609  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
610 void
611 nl_sock_wait(const struct nl_sock *sock, short int events)
612 {
613     poll_fd_wait(sock->fd, events);
614 }
615 \f
616 /* Netlink messages. */
617
618 /* Returns the nlmsghdr at the head of 'msg'.
619  *
620  * 'msg' must be at least as large as a nlmsghdr. */
621 struct nlmsghdr *
622 nl_msg_nlmsghdr(const struct ofpbuf *msg)
623 {
624     return ofpbuf_at_assert(msg, 0, NLMSG_HDRLEN);
625 }
626
627 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
628  *
629  * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
630  * and a genlmsghdr. */
631 struct genlmsghdr *
632 nl_msg_genlmsghdr(const struct ofpbuf *msg)
633 {
634     return ofpbuf_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
635 }
636
637 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
638  * message, otherwise a positive errno value, and returns true.  If 'buffer' is
639  * not an NLMSG_ERROR message, returns false.
640  *
641  * 'msg' must be at least as large as a nlmsghdr. */
642 bool
643 nl_msg_nlmsgerr(const struct ofpbuf *msg, int *errorp)
644 {
645     if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
646         struct nlmsgerr *err = ofpbuf_at(msg, NLMSG_HDRLEN, sizeof *err);
647         int code = EPROTO;
648         if (!err) {
649             VLOG_ERR_RL(&rl, "received invalid nlmsgerr (%zd bytes < %zd)",
650                         msg->size, NLMSG_HDRLEN + sizeof *err);
651         } else if (err->error <= 0 && err->error > INT_MIN) {
652             code = -err->error;
653         }
654         if (errorp) {
655             *errorp = code;
656         }
657         return true;
658     } else {
659         return false;
660     }
661 }
662
663 /* Ensures that 'b' has room for at least 'size' bytes plus netlink padding at
664  * its tail end, reallocating and copying its data if necessary. */
665 void
666 nl_msg_reserve(struct ofpbuf *msg, size_t size)
667 {
668     ofpbuf_prealloc_tailroom(msg, NLMSG_ALIGN(size));
669 }
670
671 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
672  * Uses the given 'type' and 'flags'.  'expected_payload' should be
673  * an estimate of the number of payload bytes to be supplied; if the size of
674  * the payload is unknown a value of 0 is acceptable.
675  *
676  * 'type' is ordinarily an enumerated value specific to the Netlink protocol
677  * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol).  For Generic Netlink, 'type'
678  * is the family number obtained via nl_lookup_genl_family().
679  *
680  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
681  * is often NLM_F_REQUEST indicating that a request is being made, commonly
682  * or'd with NLM_F_ACK to request an acknowledgement.
683  *
684  * Sets the new nlmsghdr's nlmsg_pid field to 0 for now.  nl_sock_send() will
685  * fill it in just before sending the message.
686  *
687  * nl_msg_put_genlmsghdr() is more convenient for composing a Generic Netlink
688  * message. */
689 void
690 nl_msg_put_nlmsghdr(struct ofpbuf *msg,
691                     size_t expected_payload, uint32_t type, uint32_t flags)
692 {
693     struct nlmsghdr *nlmsghdr;
694
695     assert(msg->size == 0);
696
697     nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
698     nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
699     nlmsghdr->nlmsg_len = 0;
700     nlmsghdr->nlmsg_type = type;
701     nlmsghdr->nlmsg_flags = flags;
702     nlmsghdr->nlmsg_seq = ++next_seq;
703     nlmsghdr->nlmsg_pid = 0;
704 }
705
706 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
707  * initially empty.  'expected_payload' should be an estimate of the number of
708  * payload bytes to be supplied; if the size of the payload is unknown a value
709  * of 0 is acceptable.
710  *
711  * 'family' is the family number obtained via nl_lookup_genl_family().
712  *
713  * 'flags' is a bit-mask that indicates what kind of request is being made.  It
714  * is often NLM_F_REQUEST indicating that a request is being made, commonly
715  * or'd with NLM_F_ACK to request an acknowledgement.
716  *
717  * 'cmd' is an enumerated value specific to the Generic Netlink family
718  * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
719  *
720  * 'version' is a version number specific to the family and command (often 1).
721  *
722  * Sets the new nlmsghdr's nlmsg_pid field to 0 for now.  nl_sock_send() will
723  * fill it in just before sending the message.
724  *
725  * nl_msg_put_nlmsghdr() should be used to compose Netlink messages that are
726  * not Generic Netlink messages. */
727 void
728 nl_msg_put_genlmsghdr(struct ofpbuf *msg, size_t expected_payload,
729                       int family, uint32_t flags, uint8_t cmd, uint8_t version)
730 {
731     struct genlmsghdr *genlmsghdr;
732
733     nl_msg_put_nlmsghdr(msg, GENL_HDRLEN + expected_payload, family, flags);
734     assert(msg->size == NLMSG_HDRLEN);
735     genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
736     genlmsghdr->cmd = cmd;
737     genlmsghdr->version = version;
738     genlmsghdr->reserved = 0;
739 }
740
741 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
742  * the tail end of 'msg'.  Data in 'msg' is reallocated and copied if
743  * necessary. */
744 void
745 nl_msg_put(struct ofpbuf *msg, const void *data, size_t size)
746 {
747     memcpy(nl_msg_put_uninit(msg, size), data, size);
748 }
749
750 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
751  * end of 'msg', reallocating and copying its data if necessary.  Returns a
752  * pointer to the first byte of the new data, which is left uninitialized. */
753 void *
754 nl_msg_put_uninit(struct ofpbuf *msg, size_t size)
755 {
756     size_t pad = NLMSG_ALIGN(size) - size;
757     char *p = ofpbuf_put_uninit(msg, size + pad);
758     if (pad) {
759         memset(p + size, 0, pad);
760     }
761     return p;
762 }
763
764 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
765  * data as its payload, plus Netlink padding if needed, to the tail end of
766  * 'msg', reallocating and copying its data if necessary.  Returns a pointer to
767  * the first byte of data in the attribute, which is left uninitialized. */
768 void *
769 nl_msg_put_unspec_uninit(struct ofpbuf *msg, uint16_t type, size_t size)
770 {
771     size_t total_size = NLA_HDRLEN + size;
772     struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
773     assert(NLA_ALIGN(total_size) <= UINT16_MAX);
774     nla->nla_len = total_size;
775     nla->nla_type = type;
776     return nla + 1;
777 }
778
779 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
780  * 'data' as its payload, to the tail end of 'msg', reallocating and copying
781  * its data if necessary.  Returns a pointer to the first byte of data in the
782  * attribute, which is left uninitialized. */
783 void
784 nl_msg_put_unspec(struct ofpbuf *msg, uint16_t type,
785                   const void *data, size_t size)
786 {
787     memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
788 }
789
790 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
791  * (Some Netlink protocols use the presence or absence of an attribute as a
792  * Boolean flag.) */
793 void
794 nl_msg_put_flag(struct ofpbuf *msg, uint16_t type)
795 {
796     nl_msg_put_unspec(msg, type, NULL, 0);
797 }
798
799 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
800  * to 'msg'. */
801 void
802 nl_msg_put_u8(struct ofpbuf *msg, uint16_t type, uint8_t value)
803 {
804     nl_msg_put_unspec(msg, type, &value, sizeof value);
805 }
806
807 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
808  * to 'msg'. */
809 void
810 nl_msg_put_u16(struct ofpbuf *msg, uint16_t type, uint16_t value)
811 {
812     nl_msg_put_unspec(msg, type, &value, sizeof value);
813 }
814
815 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
816  * to 'msg'. */
817 void
818 nl_msg_put_u32(struct ofpbuf *msg, uint16_t type, uint32_t value)
819 {
820     nl_msg_put_unspec(msg, type, &value, sizeof value);
821 }
822
823 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
824  * to 'msg'. */
825 void
826 nl_msg_put_u64(struct ofpbuf *msg, uint16_t type, uint64_t value)
827 {
828     nl_msg_put_unspec(msg, type, &value, sizeof value);
829 }
830
831 /* Appends a Netlink attribute of the given 'type' and the given
832  * null-terminated string 'value' to 'msg'. */
833 void
834 nl_msg_put_string(struct ofpbuf *msg, uint16_t type, const char *value)
835 {
836     nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
837 }
838
839 /* Adds the header for nested Netlink attributes to 'msg', with the specified
840  * 'type', and returns the header's offset within 'msg'.  The caller should add
841  * the content for the nested Netlink attribute to 'msg' (e.g. using the other
842  * nl_msg_*() functions), and then pass the returned offset to
843  * nl_msg_end_nested() to finish up the nested attributes. */
844 size_t
845 nl_msg_start_nested(struct ofpbuf *msg, uint16_t type)
846 {
847     size_t offset = msg->size;
848     nl_msg_put_unspec(msg, type, NULL, 0);
849     return offset;
850 }
851
852 /* Finalizes a nested Netlink attribute in 'msg'.  'offset' should be the value
853  * returned by nl_msg_start_nested(). */
854 void
855 nl_msg_end_nested(struct ofpbuf *msg, size_t offset)
856 {
857     struct nlattr *attr = ofpbuf_at_assert(msg, offset, sizeof *attr);
858     attr->nla_len = msg->size - offset;
859 }
860
861 /* Appends a nested Netlink attribute of the given 'type', with the 'size'
862  * bytes of content starting at 'data', to 'msg'. */
863 void
864 nl_msg_put_nested(struct ofpbuf *msg,
865                   uint16_t type, const void *data, size_t size)
866 {
867     size_t offset = nl_msg_start_nested(msg, type);
868     nl_msg_put(msg, data, size);
869     nl_msg_end_nested(msg, offset);
870 }
871
872 /* If 'buffer' begins with a valid "struct nlmsghdr", pulls the header and its
873  * payload off 'buffer', stores header and payload in 'msg->data' and
874  * 'msg->size', and returns a pointer to the header.
875  *
876  * If 'buffer' does not begin with a "struct nlmsghdr" or begins with one that
877  * is invalid, returns NULL without modifying 'buffer'. */
878 struct nlmsghdr *
879 nl_msg_next(struct ofpbuf *buffer, struct ofpbuf *msg)
880 {
881     if (buffer->size >= sizeof(struct nlmsghdr)) {
882         struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(buffer);
883         size_t len = nlmsghdr->nlmsg_len;
884         if (len >= sizeof *nlmsghdr && len <= buffer->size) {
885             ofpbuf_use_const(msg, nlmsghdr, len);
886             ofpbuf_pull(buffer, len);
887             return nlmsghdr;
888         }
889     }
890
891     msg->data = NULL;
892     msg->size = 0;
893     return NULL;
894 }
895 \f
896 /* Attributes. */
897
898 /* Returns the first byte in the payload of attribute 'nla'. */
899 const void *
900 nl_attr_get(const struct nlattr *nla)
901 {
902     assert(nla->nla_len >= NLA_HDRLEN);
903     return nla + 1;
904 }
905
906 /* Returns the number of bytes in the payload of attribute 'nla'. */
907 size_t
908 nl_attr_get_size(const struct nlattr *nla)
909 {
910     assert(nla->nla_len >= NLA_HDRLEN);
911     return nla->nla_len - NLA_HDRLEN;
912 }
913
914 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
915  * first byte of the payload. */
916 const void *
917 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
918 {
919     assert(nla->nla_len >= NLA_HDRLEN + size);
920     return nla + 1;
921 }
922
923 /* Returns true if 'nla' is nonnull.  (Some Netlink protocols use the presence
924  * or absence of an attribute as a Boolean flag.) */
925 bool
926 nl_attr_get_flag(const struct nlattr *nla)
927 {
928     return nla != NULL;
929 }
930
931 #define NL_ATTR_GET_AS(NLA, TYPE) \
932         (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
933
934 /* Returns the 8-bit value in 'nla''s payload.
935  *
936  * Asserts that 'nla''s payload is at least 1 byte long. */
937 uint8_t
938 nl_attr_get_u8(const struct nlattr *nla)
939 {
940     return NL_ATTR_GET_AS(nla, uint8_t);
941 }
942
943 /* Returns the 16-bit value in 'nla''s payload.
944  *
945  * Asserts that 'nla''s payload is at least 2 bytes long. */
946 uint16_t
947 nl_attr_get_u16(const struct nlattr *nla)
948 {
949     return NL_ATTR_GET_AS(nla, uint16_t);
950 }
951
952 /* Returns the 32-bit value in 'nla''s payload.
953  *
954  * Asserts that 'nla''s payload is at least 4 bytes long. */
955 uint32_t
956 nl_attr_get_u32(const struct nlattr *nla)
957 {
958     return NL_ATTR_GET_AS(nla, uint32_t);
959 }
960
961 /* Returns the 64-bit value in 'nla''s payload.
962  *
963  * Asserts that 'nla''s payload is at least 8 bytes long. */
964 uint64_t
965 nl_attr_get_u64(const struct nlattr *nla)
966 {
967     return NL_ATTR_GET_AS(nla, uint64_t);
968 }
969
970 /* Returns the null-terminated string value in 'nla''s payload.
971  *
972  * Asserts that 'nla''s payload contains a null-terminated string. */
973 const char *
974 nl_attr_get_string(const struct nlattr *nla)
975 {
976     assert(nla->nla_len > NLA_HDRLEN);
977     assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
978     return nl_attr_get(nla);
979 }
980
981 /* Initializes 'nested' to the payload of 'nla'. */
982 void
983 nl_attr_get_nested(const struct nlattr *nla, struct ofpbuf *nested)
984 {
985     ofpbuf_use_const(nested, nl_attr_get(nla), nl_attr_get_size(nla));
986 }
987
988 /* Default minimum and maximum payload sizes for each type of attribute. */
989 static const size_t attr_len_range[][2] = {
990     [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
991     [NL_A_U8] = { 1, 1 },
992     [NL_A_U16] = { 2, 2 },
993     [NL_A_U32] = { 4, 4 },
994     [NL_A_U64] = { 8, 8 },
995     [NL_A_STRING] = { 1, SIZE_MAX },
996     [NL_A_FLAG] = { 0, SIZE_MAX },
997     [NL_A_NESTED] = { 0, SIZE_MAX },
998 };
999
1000 /* Parses the 'msg' starting at the given 'nla_offset' as a sequence of Netlink
1001  * attributes.  'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
1002  * with nla_type == i is parsed; a pointer to attribute i is stored in
1003  * attrs[i].  Returns true if successful, false on failure.
1004  *
1005  * If the Netlink attributes in 'msg' follow a Netlink header and a Generic
1006  * Netlink header, then 'nla_offset' should be NLMSG_HDRLEN + GENL_HDRLEN. */
1007 bool
1008 nl_policy_parse(const struct ofpbuf *msg, size_t nla_offset,
1009                 const struct nl_policy policy[],
1010                 struct nlattr *attrs[], size_t n_attrs)
1011 {
1012     void *p, *tail;
1013     size_t n_required;
1014     size_t i;
1015
1016     n_required = 0;
1017     for (i = 0; i < n_attrs; i++) {
1018         attrs[i] = NULL;
1019
1020         assert(policy[i].type < N_NL_ATTR_TYPES);
1021         if (policy[i].type != NL_A_NO_ATTR
1022             && policy[i].type != NL_A_FLAG
1023             && !policy[i].optional) {
1024             n_required++;
1025         }
1026     }
1027
1028     p = ofpbuf_at(msg, nla_offset, 0);
1029     if (p == NULL) {
1030         VLOG_DBG_RL(&rl, "missing headers in nl_policy_parse");
1031         return false;
1032     }
1033     tail = ofpbuf_tail(msg);
1034
1035     while (p < tail) {
1036         size_t offset = (char*)p - (char*)msg->data;
1037         struct nlattr *nla = p;
1038         size_t len, aligned_len;
1039         uint16_t type;
1040
1041         /* Make sure its claimed length is plausible. */
1042         if (nla->nla_len < NLA_HDRLEN) {
1043             VLOG_DBG_RL(&rl, "%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
1044                         offset, nla->nla_len);
1045             return false;
1046         }
1047         len = nla->nla_len - NLA_HDRLEN;
1048         aligned_len = NLA_ALIGN(len);
1049         if (aligned_len > (char*)tail - (char*)p) {
1050             VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" aligned data len (%zu) "
1051                         "> bytes left (%tu)",
1052                         offset, nla->nla_type, aligned_len,
1053                         (char*)tail - (char*)p);
1054             return false;
1055         }
1056
1057         type = nla->nla_type;
1058         if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
1059             const struct nl_policy *e = &policy[type];
1060             size_t min_len, max_len;
1061
1062             /* Validate length and content. */
1063             min_len = e->min_len ? e->min_len : attr_len_range[e->type][0];
1064             max_len = e->max_len ? e->max_len : attr_len_range[e->type][1];
1065             if (len < min_len || len > max_len) {
1066                 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" length %zu not in "
1067                             "allowed range %zu...%zu",
1068                             offset, type, len, min_len, max_len);
1069                 return false;
1070             }
1071             if (e->type == NL_A_STRING) {
1072                 if (((char *) nla)[nla->nla_len - 1]) {
1073                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" lacks null at end",
1074                                 offset, type);
1075                     return false;
1076                 }
1077                 if (memchr(nla + 1, '\0', len - 1) != NULL) {
1078                     VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" has bad length",
1079                                 offset, type);
1080                     return false;
1081                 }
1082             }
1083             if (!e->optional && attrs[type] == NULL) {
1084                 assert(n_required > 0);
1085                 --n_required;
1086             }
1087             attrs[type] = nla;
1088         } else {
1089             /* Skip attribute type that we don't care about. */
1090         }
1091         p = (char*)p + NLA_ALIGN(nla->nla_len);
1092     }
1093     if (n_required) {
1094         VLOG_DBG_RL(&rl, "%zu required attrs missing", n_required);
1095         return false;
1096     }
1097     return true;
1098 }
1099
1100 /* Parses the Netlink attributes within 'nla'.  'policy[i]', for 0 <= i <
1101  * n_attrs, specifies how the attribute with nla_type == i is parsed; a pointer
1102  * to attribute i is stored in attrs[i].  Returns true if successful, false on
1103  * failure. */
1104 bool
1105 nl_parse_nested(const struct nlattr *nla, const struct nl_policy policy[],
1106                 struct nlattr *attrs[], size_t n_attrs)
1107 {
1108     struct ofpbuf buf;
1109
1110     nl_attr_get_nested(nla, &buf);
1111     return nl_policy_parse(&buf, 0, policy, attrs, n_attrs);
1112 }
1113 \f
1114 /* Miscellaneous.  */
1115
1116 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1117     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1118 };
1119
1120 static int do_lookup_genl_family(const char *name)
1121 {
1122     struct nl_sock *sock;
1123     struct ofpbuf request, *reply;
1124     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1125     int retval;
1126
1127     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
1128     if (retval) {
1129         return -retval;
1130     }
1131
1132     ofpbuf_init(&request, 0);
1133     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1134                           CTRL_CMD_GETFAMILY, 1);
1135     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1136     retval = nl_sock_transact(sock, &request, &reply);
1137     ofpbuf_uninit(&request);
1138     if (retval) {
1139         nl_sock_destroy(sock);
1140         return -retval;
1141     }
1142
1143     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1144                          family_policy, attrs, ARRAY_SIZE(family_policy))) {
1145         nl_sock_destroy(sock);
1146         ofpbuf_delete(reply);
1147         return -EPROTO;
1148     }
1149
1150     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1151     if (retval == 0) {
1152         retval = -EPROTO;
1153     }
1154     nl_sock_destroy(sock);
1155     ofpbuf_delete(reply);
1156     return retval;
1157 }
1158
1159 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1160  * number and stores it in '*number'.  If successful, returns 0 and the caller
1161  * may use '*number' as the family number.  On failure, returns a positive
1162  * errno value and '*number' caches the errno value. */
1163 int
1164 nl_lookup_genl_family(const char *name, int *number)
1165 {
1166     if (*number == 0) {
1167         *number = do_lookup_genl_family(name);
1168         assert(*number != 0);
1169     }
1170     return *number > 0 ? 0 : -*number;
1171 }
1172 \f
1173 /* Netlink PID.
1174  *
1175  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
1176  * programs that have a single Netlink socket use their Unix process ID as PID,
1177  * and programs with multiple Netlink sockets add a unique per-socket
1178  * identifier in the bits above the Unix process ID.
1179  *
1180  * The kernel has Netlink PID 0.
1181  */
1182
1183 /* Parameters for how many bits in the PID should come from the Unix process ID
1184  * and how many unique per-socket. */
1185 #define SOCKET_BITS 10
1186 #define MAX_SOCKETS (1u << SOCKET_BITS)
1187
1188 #define PROCESS_BITS (32 - SOCKET_BITS)
1189 #define MAX_PROCESSES (1u << PROCESS_BITS)
1190 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
1191
1192 /* Bit vector of unused socket identifiers. */
1193 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
1194
1195 /* Allocates and returns a new Netlink PID. */
1196 static int
1197 alloc_pid(uint32_t *pid)
1198 {
1199     int i;
1200
1201     for (i = 0; i < MAX_SOCKETS; i++) {
1202         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
1203             avail_sockets[i / 32] |= 1u << (i % 32);
1204             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
1205             return 0;
1206         }
1207     }
1208     VLOG_ERR("netlink pid space exhausted");
1209     return ENOBUFS;
1210 }
1211
1212 /* Makes the specified 'pid' available for reuse. */
1213 static void
1214 free_pid(uint32_t pid)
1215 {
1216     int sock = pid >> PROCESS_BITS;
1217     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
1218     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
1219 }
1220 \f
1221 static void
1222 nlmsghdr_to_string(const struct nlmsghdr *h, struct ds *ds)
1223 {
1224     struct nlmsg_flag {
1225         unsigned int bits;
1226         const char *name;
1227     };
1228     static const struct nlmsg_flag flags[] = {
1229         { NLM_F_REQUEST, "REQUEST" },
1230         { NLM_F_MULTI, "MULTI" },
1231         { NLM_F_ACK, "ACK" },
1232         { NLM_F_ECHO, "ECHO" },
1233         { NLM_F_DUMP, "DUMP" },
1234         { NLM_F_ROOT, "ROOT" },
1235         { NLM_F_MATCH, "MATCH" },
1236         { NLM_F_ATOMIC, "ATOMIC" },
1237     };
1238     const struct nlmsg_flag *flag;
1239     uint16_t flags_left;
1240
1241     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1242                   h->nlmsg_len, h->nlmsg_type);
1243     if (h->nlmsg_type == NLMSG_NOOP) {
1244         ds_put_cstr(ds, "(no-op)");
1245     } else if (h->nlmsg_type == NLMSG_ERROR) {
1246         ds_put_cstr(ds, "(error)");
1247     } else if (h->nlmsg_type == NLMSG_DONE) {
1248         ds_put_cstr(ds, "(done)");
1249     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1250         ds_put_cstr(ds, "(overrun)");
1251     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1252         ds_put_cstr(ds, "(reserved)");
1253     } else {
1254         ds_put_cstr(ds, "(family-defined)");
1255     }
1256     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1257     flags_left = h->nlmsg_flags;
1258     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1259         if ((flags_left & flag->bits) == flag->bits) {
1260             ds_put_format(ds, "[%s]", flag->name);
1261             flags_left &= ~flag->bits;
1262         }
1263     }
1264     if (flags_left) {
1265         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1266     }
1267     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
1268                   h->nlmsg_seq, h->nlmsg_pid,
1269                   (int) (h->nlmsg_pid & PROCESS_MASK),
1270                   (int) (h->nlmsg_pid >> PROCESS_BITS));
1271 }
1272
1273 static char *
1274 nlmsg_to_string(const struct ofpbuf *buffer)
1275 {
1276     struct ds ds = DS_EMPTY_INITIALIZER;
1277     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1278     if (h) {
1279         nlmsghdr_to_string(h, &ds);
1280         if (h->nlmsg_type == NLMSG_ERROR) {
1281             const struct nlmsgerr *e;
1282             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1283                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1284             if (e) {
1285                 ds_put_format(&ds, " error(%d", e->error);
1286                 if (e->error < 0) {
1287                     ds_put_format(&ds, "(%s)", strerror(-e->error));
1288                 }
1289                 ds_put_cstr(&ds, ", in-reply-to(");
1290                 nlmsghdr_to_string(&e->msg, &ds);
1291                 ds_put_cstr(&ds, "))");
1292             } else {
1293                 ds_put_cstr(&ds, " error(truncated)");
1294             }
1295         } else if (h->nlmsg_type == NLMSG_DONE) {
1296             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1297             if (error) {
1298                 ds_put_format(&ds, " done(%d", *error);
1299                 if (*error < 0) {
1300                     ds_put_format(&ds, "(%s)", strerror(-*error));
1301                 }
1302                 ds_put_cstr(&ds, ")");
1303             } else {
1304                 ds_put_cstr(&ds, " done(truncated)");
1305             }
1306         }
1307     } else {
1308         ds_put_cstr(&ds, "nl(truncated)");
1309     }
1310     return ds.string;
1311 }
1312
1313 static void
1314 log_nlmsg(const char *function, int error,
1315           const void *message, size_t size)
1316 {
1317     struct ofpbuf buffer;
1318     char *nlmsg;
1319
1320     if (!VLOG_IS_DBG_ENABLED()) {
1321         return;
1322     }
1323
1324     ofpbuf_use_const(&buffer, message, size);
1325     nlmsg = nlmsg_to_string(&buffer);
1326     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
1327     free(nlmsg);
1328 }
1329