Prepare Open vSwitch 1.1.2 release.
[sliver-openvswitch.git] / lib / netlink-socket.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 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-socket.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 #include "coverage.h"
26 #include "dynamic-string.h"
27 #include "hash.h"
28 #include "hmap.h"
29 #include "netlink.h"
30 #include "netlink-protocol.h"
31 #include "ofpbuf.h"
32 #include "poll-loop.h"
33 #include "socket-util.h"
34 #include "stress.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(netlink_socket);
38
39 COVERAGE_DEFINE(netlink_overflow);
40 COVERAGE_DEFINE(netlink_received);
41 COVERAGE_DEFINE(netlink_recv_retry);
42 COVERAGE_DEFINE(netlink_send);
43 COVERAGE_DEFINE(netlink_sent);
44
45 /* Linux header file confusion causes this to be undefined. */
46 #ifndef SOL_NETLINK
47 #define SOL_NETLINK 270
48 #endif
49
50 /* A single (bad) Netlink message can in theory dump out many, many log
51  * messages, so the burst size is set quite high here to avoid missing useful
52  * information.  Also, at high logging levels we log *all* Netlink messages. */
53 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
54
55 static void log_nlmsg(const char *function, int error,
56                       const void *message, size_t size, int protocol);
57 \f
58 /* Netlink sockets. */
59
60 struct nl_sock
61 {
62     int fd;
63     uint32_t pid;
64     int protocol;
65     bool any_groups;
66     struct nl_dump *dump;
67 };
68
69 static int alloc_pid(uint32_t *);
70 static void free_pid(uint32_t);
71 static int nl_sock_cow__(struct nl_sock *);
72
73 /* Creates a new netlink socket for the given netlink 'protocol'
74  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
75  * new socket if successful, otherwise returns a positive errno value.  */
76 int
77 nl_sock_create(int protocol, struct nl_sock **sockp)
78 {
79     struct nl_sock *sock;
80     struct sockaddr_nl local, remote;
81     int retval = 0;
82
83     *sockp = NULL;
84     sock = malloc(sizeof *sock);
85     if (sock == NULL) {
86         return ENOMEM;
87     }
88
89     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
90     if (sock->fd < 0) {
91         VLOG_ERR("fcntl: %s", strerror(errno));
92         goto error;
93     }
94     sock->protocol = protocol;
95     sock->any_groups = false;
96     sock->dump = NULL;
97
98     retval = alloc_pid(&sock->pid);
99     if (retval) {
100         goto error;
101     }
102
103     /* Bind local address as our selected pid. */
104     memset(&local, 0, sizeof local);
105     local.nl_family = AF_NETLINK;
106     local.nl_pid = sock->pid;
107     if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
108         VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
109         goto error_free_pid;
110     }
111
112     /* Bind remote address as the kernel (pid 0). */
113     memset(&remote, 0, sizeof remote);
114     remote.nl_family = AF_NETLINK;
115     remote.nl_pid = 0;
116     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
117         VLOG_ERR("connect(0): %s", strerror(errno));
118         goto error_free_pid;
119     }
120
121     *sockp = sock;
122     return 0;
123
124 error_free_pid:
125     free_pid(sock->pid);
126 error:
127     if (retval == 0) {
128         retval = errno;
129         if (retval == 0) {
130             retval = EINVAL;
131         }
132     }
133     if (sock->fd >= 0) {
134         close(sock->fd);
135     }
136     free(sock);
137     return retval;
138 }
139
140 /* Creates a new netlink socket for the same protocol as 'src'.  Returns 0 and
141  * sets '*sockp' to the new socket if successful, otherwise returns a positive
142  * errno value.  */
143 int
144 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
145 {
146     return nl_sock_create(src->protocol, sockp);
147 }
148
149 /* Destroys netlink socket 'sock'. */
150 void
151 nl_sock_destroy(struct nl_sock *sock)
152 {
153     if (sock) {
154         if (sock->dump) {
155             sock->dump = NULL;
156         } else {
157             close(sock->fd);
158             free_pid(sock->pid);
159             free(sock);
160         }
161     }
162 }
163
164 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
165  * successful, otherwise a positive errno value.
166  *
167  * Multicast group numbers are always positive.
168  *
169  * It is not an error to attempt to join a multicast group to which a socket
170  * already belongs. */
171 int
172 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
173 {
174     int error = nl_sock_cow__(sock);
175     if (error) {
176         return error;
177     }
178     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
179                    &multicast_group, sizeof multicast_group) < 0) {
180         VLOG_WARN("could not join multicast group %u (%s)",
181                   multicast_group, strerror(errno));
182         return errno;
183     }
184     sock->any_groups = true;
185     return 0;
186 }
187
188 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
189  * successful, otherwise a positive errno value.
190  *
191  * Multicast group numbers are always positive.
192  *
193  * It is not an error to attempt to leave a multicast group to which a socket
194  * does not belong.
195  *
196  * On success, reading from 'sock' will still return any messages that were
197  * received on 'multicast_group' before the group was left. */
198 int
199 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
200 {
201     assert(!sock->dump);
202     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
203                    &multicast_group, sizeof multicast_group) < 0) {
204         VLOG_WARN("could not leave multicast group %u (%s)",
205                   multicast_group, strerror(errno));
206         return errno;
207     }
208     return 0;
209 }
210
211 static int
212 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
213 {
214     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
215     int error;
216
217     nlmsg->nlmsg_len = msg->size;
218     nlmsg->nlmsg_pid = sock->pid;
219     do {
220         int retval;
221         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
222         error = retval < 0 ? errno : 0;
223     } while (error == EINTR);
224     log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
225     if (!error) {
226         COVERAGE_INC(netlink_sent);
227     }
228     return error;
229 }
230
231 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
232  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, and
233  * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
234  *
235  * Returns 0 if successful, otherwise a positive errno value.  If
236  * 'wait' is true, then the send will wait until buffer space is ready;
237  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
238 int
239 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
240 {
241     int error = nl_sock_cow__(sock);
242     if (error) {
243         return error;
244     }
245     return nl_sock_send__(sock, msg, wait);
246 }
247
248 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
249  * a single Netlink message.  (The message must be fully formed and not require
250  * finalization of its nlmsg_len or nlmsg_pid fields.)
251  *
252  * Returns 0 if successful, otherwise a positive errno value.  If 'wait' is
253  * true, then the send will wait until buffer space is ready; otherwise,
254  * returns EAGAIN if the 'sock' send buffer is full. */
255 int
256 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
257               bool wait)
258 {
259     struct msghdr msg;
260     int error;
261
262     COVERAGE_INC(netlink_send);
263     memset(&msg, 0, sizeof msg);
264     msg.msg_iov = (struct iovec *) iov;
265     msg.msg_iovlen = n_iov;
266     do {
267         int retval;
268         retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
269         error = retval < 0 ? errno : 0;
270     } while (error == EINTR);
271     if (error != EAGAIN) {
272         log_nlmsg(__func__, error, iov[0].iov_base, iov[0].iov_len,
273                   sock->protocol);
274         if (!error) {
275             COVERAGE_INC(netlink_sent);
276         }
277     }
278     return error;
279 }
280
281 /* This stress option is useful for testing that OVS properly tolerates
282  * -ENOBUFS on NetLink sockets.  Such errors are unavoidable because they can
283  * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
284  * reply to a request.  They can also occur if messages arrive on a multicast
285  * channel faster than OVS can process them. */
286 STRESS_OPTION(
287     netlink_overflow, "simulate netlink socket receive buffer overflow",
288     5, 1, -1, 100);
289
290 static int
291 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
292 {
293     uint8_t tmp;
294     ssize_t bufsize = 2048;
295     ssize_t nbytes, nbytes2;
296     struct ofpbuf *buf;
297     struct nlmsghdr *nlmsghdr;
298     struct iovec iov;
299     struct msghdr msg = {
300         .msg_name = NULL,
301         .msg_namelen = 0,
302         .msg_iov = &iov,
303         .msg_iovlen = 1,
304         .msg_control = NULL,
305         .msg_controllen = 0,
306         .msg_flags = 0
307     };
308
309     buf = ofpbuf_new(bufsize);
310     *bufp = NULL;
311
312 try_again:
313     /* Attempt to read the message.  We don't know the size of the data
314      * yet, so we take a guess at 2048.  If we're wrong, we keep trying
315      * and doubling the buffer size each time.
316      */
317     nlmsghdr = ofpbuf_put_uninit(buf, bufsize);
318     iov.iov_base = nlmsghdr;
319     iov.iov_len = bufsize;
320     do {
321         nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
322     } while (nbytes < 0 && errno == EINTR);
323     if (nbytes < 0) {
324         ofpbuf_delete(buf);
325         return errno;
326     }
327     if (msg.msg_flags & MSG_TRUNC) {
328         COVERAGE_INC(netlink_recv_retry);
329         bufsize *= 2;
330         ofpbuf_reinit(buf, bufsize);
331         goto try_again;
332     }
333     buf->size = nbytes;
334
335     /* We successfully read the message, so recv again to clear the queue */
336     iov.iov_base = &tmp;
337     iov.iov_len = 1;
338     do {
339         nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
340     } while (nbytes2 < 0 && errno == EINTR);
341     if (nbytes2 < 0) {
342         if (errno == ENOBUFS) {
343             /* The kernel is notifying us that a message it tried to send to us
344              * was dropped.  We have to pass this along to the caller in case
345              * it wants to retry a request.  So kill the buffer, which we can
346              * re-read next time. */
347             COVERAGE_INC(netlink_overflow);
348             ofpbuf_delete(buf);
349             return ENOBUFS;
350         } else {
351             VLOG_ERR_RL(&rl, "failed to remove nlmsg from socket: %s\n",
352                         strerror(errno));
353         }
354     }
355     if (nbytes < sizeof *nlmsghdr
356         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
357         || nlmsghdr->nlmsg_len > nbytes) {
358         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
359                     bufsize, NLMSG_HDRLEN);
360         ofpbuf_delete(buf);
361         return EPROTO;
362     }
363
364     if (STRESS(netlink_overflow)) {
365         ofpbuf_delete(buf);
366         return ENOBUFS;
367     }
368
369     *bufp = buf;
370     log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
371     COVERAGE_INC(netlink_received);
372
373     return 0;
374 }
375
376 /* Tries to receive a netlink message from the kernel on 'sock'.  If
377  * successful, stores the received message into '*bufp' and returns 0.  The
378  * caller is responsible for destroying the message with ofpbuf_delete().  On
379  * failure, returns a positive errno value and stores a null pointer into
380  * '*bufp'.
381  *
382  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
383  * returns EAGAIN if the 'sock' receive buffer is empty. */
384 int
385 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
386 {
387     int error = nl_sock_cow__(sock);
388     if (error) {
389         return error;
390     }
391     return nl_sock_recv__(sock, bufp, wait);
392 }
393
394 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
395  * successful, returns 0.  On failure, returns a positive errno value.
396  *
397  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
398  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
399  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
400  * reply, if any, is discarded.
401  *
402  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
403  * be set to 'sock''s pid, before the message is sent.  NLM_F_ACK will be set
404  * in nlmsg_flags.
405  *
406  * The caller is responsible for destroying 'request'.
407  *
408  * Bare Netlink is an unreliable transport protocol.  This function layers
409  * reliable delivery and reply semantics on top of bare Netlink.
410  *
411  * In Netlink, sending a request to the kernel is reliable enough, because the
412  * kernel will tell us if the message cannot be queued (and we will in that
413  * case put it on the transmit queue and wait until it can be delivered).
414  *
415  * Receiving the reply is the real problem: if the socket buffer is full when
416  * the kernel tries to send the reply, the reply will be dropped.  However, the
417  * kernel sets a flag that a reply has been dropped.  The next call to recv
418  * then returns ENOBUFS.  We can then re-send the request.
419  *
420  * Caveats:
421  *
422  *      1. Netlink depends on sequence numbers to match up requests and
423  *         replies.  The sender of a request supplies a sequence number, and
424  *         the reply echos back that sequence number.
425  *
426  *         This is fine, but (1) some kernel netlink implementations are
427  *         broken, in that they fail to echo sequence numbers and (2) this
428  *         function will drop packets with non-matching sequence numbers, so
429  *         that only a single request can be usefully transacted at a time.
430  *
431  *      2. Resending the request causes it to be re-executed, so the request
432  *         needs to be idempotent.
433  */
434 int
435 nl_sock_transact(struct nl_sock *sock,
436                  const struct ofpbuf *request, struct ofpbuf **replyp)
437 {
438     uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
439     struct nlmsghdr *nlmsghdr;
440     struct ofpbuf *reply;
441     int retval;
442
443     if (replyp) {
444         *replyp = NULL;
445     }
446
447     /* Ensure that we get a reply even if this message doesn't ordinarily call
448      * for one. */
449     nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
450
451 send:
452     retval = nl_sock_send(sock, request, true);
453     if (retval) {
454         return retval;
455     }
456
457 recv:
458     retval = nl_sock_recv(sock, &reply, true);
459     if (retval) {
460         if (retval == ENOBUFS) {
461             COVERAGE_INC(netlink_overflow);
462             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
463             goto send;
464         } else {
465             return retval;
466         }
467     }
468     nlmsghdr = nl_msg_nlmsghdr(reply);
469     if (seq != nlmsghdr->nlmsg_seq) {
470         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
471                     nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
472         ofpbuf_delete(reply);
473         goto recv;
474     }
475
476     /* If the reply is an error, discard the reply and return the error code.
477      *
478      * Except: if the reply is just an acknowledgement (error code of 0), and
479      * the caller is interested in the reply (replyp != NULL), pass the reply
480      * up to the caller.  Otherwise the caller will get a return value of 0
481      * and null '*replyp', which makes unwary callers likely to segfault. */
482     if (nl_msg_nlmsgerr(reply, &retval) && (retval || !replyp)) {
483         ofpbuf_delete(reply);
484         if (retval) {
485             VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
486                         retval, strerror(retval));
487         }
488         return retval != EAGAIN ? retval : EPROTO;
489     }
490
491     if (replyp) {
492         *replyp = reply;
493     } else {
494         ofpbuf_delete(reply);
495     }
496     return 0;
497 }
498
499 /* Drain all the messages currently in 'sock''s receive queue. */
500 int
501 nl_sock_drain(struct nl_sock *sock)
502 {
503     int error = nl_sock_cow__(sock);
504     if (error) {
505         return error;
506     }
507     return drain_rcvbuf(sock->fd);
508 }
509
510 /* The client is attempting some operation on 'sock'.  If 'sock' has an ongoing
511  * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
512  * old fd over to the dump. */
513 static int
514 nl_sock_cow__(struct nl_sock *sock)
515 {
516     struct nl_sock *copy;
517     uint32_t tmp_pid;
518     int tmp_fd;
519     int error;
520
521     if (!sock->dump) {
522         return 0;
523     }
524
525     error = nl_sock_clone(sock, &copy);
526     if (error) {
527         return error;
528     }
529
530     tmp_fd = sock->fd;
531     sock->fd = copy->fd;
532     copy->fd = tmp_fd;
533
534     tmp_pid = sock->pid;
535     sock->pid = copy->pid;
536     copy->pid = tmp_pid;
537
538     sock->dump->sock = copy;
539     sock->dump = NULL;
540
541     return 0;
542 }
543
544 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
545  * 'sock', and initializes 'dump' to reflect the state of the operation.
546  *
547  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
548  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
549  * NLM_F_ACK will be set in nlmsg_flags.
550  *
551  * This Netlink socket library is designed to ensure that the dump is reliable
552  * and that it will not interfere with other operations on 'sock', including
553  * destroying or sending and receiving messages on 'sock'.  One corner case is
554  * not handled:
555  *
556  *   - If 'sock' has been used to send a request (e.g. with nl_sock_send())
557  *     whose response has not yet been received (e.g. with nl_sock_recv()).
558  *     This is unusual: usually nl_sock_transact() is used to send a message
559  *     and receive its reply all in one go.
560  *
561  * This function provides no status indication.  An error status for the entire
562  * dump operation is provided when it is completed by calling nl_dump_done().
563  *
564  * The caller is responsible for destroying 'request'.
565  *
566  * The new 'dump' is independent of 'sock'.  'sock' and 'dump' may be destroyed
567  * in either order.
568  */
569 void
570 nl_dump_start(struct nl_dump *dump,
571               struct nl_sock *sock, const struct ofpbuf *request)
572 {
573     struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
574     nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
575     dump->seq = nlmsghdr->nlmsg_seq;
576     dump->buffer = NULL;
577     if (sock->any_groups || sock->dump) {
578         /* 'sock' might belong to some multicast group, or it already has an
579          * onoging dump.  Clone the socket to avoid possibly intermixing
580          * multicast messages or previous dump results with our results. */
581         dump->status = nl_sock_clone(sock, &dump->sock);
582         if (dump->status) {
583             return;
584         }
585     } else {
586         sock->dump = dump;
587         dump->sock = sock;
588         dump->status = 0;
589     }
590     dump->status = nl_sock_send__(sock, request, true);
591 }
592
593 /* Helper function for nl_dump_next(). */
594 static int
595 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
596 {
597     struct nlmsghdr *nlmsghdr;
598     struct ofpbuf *buffer;
599     int retval;
600
601     retval = nl_sock_recv__(dump->sock, bufferp, true);
602     if (retval) {
603         return retval == EINTR ? EAGAIN : retval;
604     }
605     buffer = *bufferp;
606
607     nlmsghdr = nl_msg_nlmsghdr(buffer);
608     if (dump->seq != nlmsghdr->nlmsg_seq) {
609         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
610                     nlmsghdr->nlmsg_seq, dump->seq);
611         return EAGAIN;
612     }
613
614     if (nl_msg_nlmsgerr(buffer, &retval)) {
615         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
616                      strerror(retval));
617         return retval && retval != EAGAIN ? retval : EPROTO;
618     }
619
620     return 0;
621 }
622
623 /* Attempts to retrieve another reply from 'dump', which must have been
624  * initialized with nl_dump_start().
625  *
626  * If successful, returns true and points 'reply->data' and 'reply->size' to
627  * the message that was retrieved.  The caller must not modify 'reply' (because
628  * it points into the middle of a larger buffer).
629  *
630  * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
631  * to 0.  Failure might indicate an actual error or merely the end of replies.
632  * An error status for the entire dump operation is provided when it is
633  * completed by calling nl_dump_done().
634  */
635 bool
636 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
637 {
638     struct nlmsghdr *nlmsghdr;
639
640     reply->data = NULL;
641     reply->size = 0;
642     if (dump->status) {
643         return false;
644     }
645
646     if (dump->buffer && !dump->buffer->size) {
647         ofpbuf_delete(dump->buffer);
648         dump->buffer = NULL;
649     }
650     while (!dump->buffer) {
651         int retval = nl_dump_recv(dump, &dump->buffer);
652         if (retval) {
653             ofpbuf_delete(dump->buffer);
654             dump->buffer = NULL;
655             if (retval != EAGAIN) {
656                 dump->status = retval;
657                 return false;
658             }
659         }
660     }
661
662     nlmsghdr = nl_msg_next(dump->buffer, reply);
663     if (!nlmsghdr) {
664         VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
665         dump->status = EPROTO;
666         return false;
667     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
668         dump->status = EOF;
669         return false;
670     }
671
672     return true;
673 }
674
675 /* Completes Netlink dump operation 'dump', which must have been initialized
676  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
677  * otherwise a positive errno value describing the problem. */
678 int
679 nl_dump_done(struct nl_dump *dump)
680 {
681     /* Drain any remaining messages that the client didn't read.  Otherwise the
682      * kernel will continue to queue them up and waste buffer space. */
683     while (!dump->status) {
684         struct ofpbuf reply;
685         if (!nl_dump_next(dump, &reply)) {
686             assert(dump->status);
687         }
688     }
689
690     if (dump->sock) {
691         if (dump->sock->dump) {
692             dump->sock->dump = NULL;
693         } else {
694             nl_sock_destroy(dump->sock);
695         }
696     }
697     ofpbuf_delete(dump->buffer);
698     return dump->status == EOF ? 0 : dump->status;
699 }
700
701 /* Causes poll_block() to wake up when any of the specified 'events' (which is
702  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
703 void
704 nl_sock_wait(const struct nl_sock *sock, short int events)
705 {
706     poll_fd_wait(sock->fd, events);
707 }
708 \f
709 /* Miscellaneous.  */
710
711 struct genl_family {
712     struct hmap_node hmap_node;
713     uint16_t id;
714     char *name;
715 };
716
717 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
718
719 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
720     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
721 };
722
723 static struct genl_family *
724 find_genl_family_by_id(uint16_t id)
725 {
726     struct genl_family *family;
727
728     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
729                              &genl_families) {
730         if (family->id == id) {
731             return family;
732         }
733     }
734     return NULL;
735 }
736
737 static void
738 define_genl_family(uint16_t id, const char *name)
739 {
740     struct genl_family *family = find_genl_family_by_id(id);
741
742     if (family) {
743         if (!strcmp(family->name, name)) {
744             return;
745         }
746         free(family->name);
747     } else {
748         family = xmalloc(sizeof *family);
749         family->id = id;
750         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
751     }
752     family->name = xstrdup(name);
753 }
754
755 static const char *
756 genl_family_to_name(uint16_t id)
757 {
758     if (id == GENL_ID_CTRL) {
759         return "control";
760     } else {
761         struct genl_family *family = find_genl_family_by_id(id);
762         return family ? family->name : "unknown";
763     }
764 }
765
766 static int do_lookup_genl_family(const char *name)
767 {
768     struct nl_sock *sock;
769     struct ofpbuf request, *reply;
770     struct nlattr *attrs[ARRAY_SIZE(family_policy)];
771     int retval;
772
773     retval = nl_sock_create(NETLINK_GENERIC, &sock);
774     if (retval) {
775         return -retval;
776     }
777
778     ofpbuf_init(&request, 0);
779     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
780                           CTRL_CMD_GETFAMILY, 1);
781     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
782     retval = nl_sock_transact(sock, &request, &reply);
783     ofpbuf_uninit(&request);
784     if (retval) {
785         nl_sock_destroy(sock);
786         return -retval;
787     }
788
789     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
790                          family_policy, attrs, ARRAY_SIZE(family_policy))) {
791         nl_sock_destroy(sock);
792         ofpbuf_delete(reply);
793         return -EPROTO;
794     }
795
796     retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
797     if (retval == 0) {
798         retval = -EPROTO;
799     } else {
800         define_genl_family(retval, name);
801     }
802     nl_sock_destroy(sock);
803     ofpbuf_delete(reply);
804
805     return retval;
806 }
807
808 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
809  * number and stores it in '*number'.  If successful, returns 0 and the caller
810  * may use '*number' as the family number.  On failure, returns a positive
811  * errno value and '*number' caches the errno value. */
812 int
813 nl_lookup_genl_family(const char *name, int *number)
814 {
815     if (*number == 0) {
816         *number = do_lookup_genl_family(name);
817         assert(*number != 0);
818     }
819     return *number > 0 ? 0 : -*number;
820 }
821 \f
822 /* Netlink PID.
823  *
824  * Every Netlink socket must be bound to a unique 32-bit PID.  By convention,
825  * programs that have a single Netlink socket use their Unix process ID as PID,
826  * and programs with multiple Netlink sockets add a unique per-socket
827  * identifier in the bits above the Unix process ID.
828  *
829  * The kernel has Netlink PID 0.
830  */
831
832 /* Parameters for how many bits in the PID should come from the Unix process ID
833  * and how many unique per-socket. */
834 #define SOCKET_BITS 10
835 #define MAX_SOCKETS (1u << SOCKET_BITS)
836
837 #define PROCESS_BITS (32 - SOCKET_BITS)
838 #define MAX_PROCESSES (1u << PROCESS_BITS)
839 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
840
841 /* Bit vector of unused socket identifiers. */
842 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
843
844 /* Allocates and returns a new Netlink PID. */
845 static int
846 alloc_pid(uint32_t *pid)
847 {
848     int i;
849
850     for (i = 0; i < MAX_SOCKETS; i++) {
851         if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
852             avail_sockets[i / 32] |= 1u << (i % 32);
853             *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
854             return 0;
855         }
856     }
857     VLOG_ERR("netlink pid space exhausted");
858     return ENOBUFS;
859 }
860
861 /* Makes the specified 'pid' available for reuse. */
862 static void
863 free_pid(uint32_t pid)
864 {
865     int sock = pid >> PROCESS_BITS;
866     assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
867     avail_sockets[sock / 32] &= ~(1u << (sock % 32));
868 }
869 \f
870 static void
871 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
872 {
873     struct nlmsg_flag {
874         unsigned int bits;
875         const char *name;
876     };
877     static const struct nlmsg_flag flags[] = {
878         { NLM_F_REQUEST, "REQUEST" },
879         { NLM_F_MULTI, "MULTI" },
880         { NLM_F_ACK, "ACK" },
881         { NLM_F_ECHO, "ECHO" },
882         { NLM_F_DUMP, "DUMP" },
883         { NLM_F_ROOT, "ROOT" },
884         { NLM_F_MATCH, "MATCH" },
885         { NLM_F_ATOMIC, "ATOMIC" },
886     };
887     const struct nlmsg_flag *flag;
888     uint16_t flags_left;
889
890     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
891                   h->nlmsg_len, h->nlmsg_type);
892     if (h->nlmsg_type == NLMSG_NOOP) {
893         ds_put_cstr(ds, "(no-op)");
894     } else if (h->nlmsg_type == NLMSG_ERROR) {
895         ds_put_cstr(ds, "(error)");
896     } else if (h->nlmsg_type == NLMSG_DONE) {
897         ds_put_cstr(ds, "(done)");
898     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
899         ds_put_cstr(ds, "(overrun)");
900     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
901         ds_put_cstr(ds, "(reserved)");
902     } else if (protocol == NETLINK_GENERIC) {
903         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
904     } else {
905         ds_put_cstr(ds, "(family-defined)");
906     }
907     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
908     flags_left = h->nlmsg_flags;
909     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
910         if ((flags_left & flag->bits) == flag->bits) {
911             ds_put_format(ds, "[%s]", flag->name);
912             flags_left &= ~flag->bits;
913         }
914     }
915     if (flags_left) {
916         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
917     }
918     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
919                   h->nlmsg_seq, h->nlmsg_pid,
920                   (int) (h->nlmsg_pid & PROCESS_MASK),
921                   (int) (h->nlmsg_pid >> PROCESS_BITS));
922 }
923
924 static char *
925 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
926 {
927     struct ds ds = DS_EMPTY_INITIALIZER;
928     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
929     if (h) {
930         nlmsghdr_to_string(h, protocol, &ds);
931         if (h->nlmsg_type == NLMSG_ERROR) {
932             const struct nlmsgerr *e;
933             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
934                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
935             if (e) {
936                 ds_put_format(&ds, " error(%d", e->error);
937                 if (e->error < 0) {
938                     ds_put_format(&ds, "(%s)", strerror(-e->error));
939                 }
940                 ds_put_cstr(&ds, ", in-reply-to(");
941                 nlmsghdr_to_string(&e->msg, protocol, &ds);
942                 ds_put_cstr(&ds, "))");
943             } else {
944                 ds_put_cstr(&ds, " error(truncated)");
945             }
946         } else if (h->nlmsg_type == NLMSG_DONE) {
947             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
948             if (error) {
949                 ds_put_format(&ds, " done(%d", *error);
950                 if (*error < 0) {
951                     ds_put_format(&ds, "(%s)", strerror(-*error));
952                 }
953                 ds_put_cstr(&ds, ")");
954             } else {
955                 ds_put_cstr(&ds, " done(truncated)");
956             }
957         } else if (protocol == NETLINK_GENERIC) {
958             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
959             if (genl) {
960                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
961                               genl->cmd, genl->version);
962             }
963         }
964     } else {
965         ds_put_cstr(&ds, "nl(truncated)");
966     }
967     return ds.string;
968 }
969
970 static void
971 log_nlmsg(const char *function, int error,
972           const void *message, size_t size, int protocol)
973 {
974     struct ofpbuf buffer;
975     char *nlmsg;
976
977     if (!VLOG_IS_DBG_ENABLED()) {
978         return;
979     }
980
981     ofpbuf_use_const(&buffer, message, size);
982     nlmsg = nlmsg_to_string(&buffer, protocol);
983     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
984     free(nlmsg);
985 }
986
987