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