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