netlink-socket: Avoid forcing a reply for final message in a transaction.
[sliver-openvswitch.git] / lib / netlink-socket.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 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 <sys/uio.h>
25 #include <unistd.h>
26 #include "coverage.h"
27 #include "dynamic-string.h"
28 #include "hash.h"
29 #include "hmap.h"
30 #include "netlink.h"
31 #include "netlink-protocol.h"
32 #include "ofpbuf.h"
33 #include "poll-loop.h"
34 #include "socket-util.h"
35 #include "stress.h"
36 #include "util.h"
37 #include "vlog.h"
38
39 VLOG_DEFINE_THIS_MODULE(netlink_socket);
40
41 COVERAGE_DEFINE(netlink_overflow);
42 COVERAGE_DEFINE(netlink_received);
43 COVERAGE_DEFINE(netlink_recv_jumbo);
44 COVERAGE_DEFINE(netlink_send);
45 COVERAGE_DEFINE(netlink_sent);
46
47 /* Linux header file confusion causes this to be undefined. */
48 #ifndef SOL_NETLINK
49 #define SOL_NETLINK 270
50 #endif
51
52 /* A single (bad) Netlink message can in theory dump out many, many log
53  * messages, so the burst size is set quite high here to avoid missing useful
54  * information.  Also, at high logging levels we log *all* Netlink messages. */
55 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
56
57 static void log_nlmsg(const char *function, int error,
58                       const void *message, size_t size, int protocol);
59 \f
60 /* Netlink sockets. */
61
62 struct nl_sock
63 {
64     int fd;
65     uint32_t pid;
66     int protocol;
67     struct nl_dump *dump;
68     unsigned int rcvbuf;        /* Receive buffer size (SO_RCVBUF). */
69 };
70
71 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
72  * of iovecs on the stack. */
73 #define MAX_IOVS 128
74
75 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
76  * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
77  *
78  * Initialized by nl_sock_create(). */
79 static int max_iovs;
80
81 static int nl_sock_cow__(struct nl_sock *);
82
83 /* Creates a new netlink socket for the given netlink 'protocol'
84  * (NETLINK_ROUTE, NETLINK_GENERIC, ...).  Returns 0 and sets '*sockp' to the
85  * new socket if successful, otherwise returns a positive errno value.  */
86 int
87 nl_sock_create(int protocol, struct nl_sock **sockp)
88 {
89     struct nl_sock *sock;
90     struct sockaddr_nl local, remote;
91     socklen_t local_size;
92     int rcvbuf;
93     int retval = 0;
94
95     if (!max_iovs) {
96         int save_errno = errno;
97         errno = 0;
98
99         max_iovs = sysconf(_SC_UIO_MAXIOV);
100         if (max_iovs < _XOPEN_IOV_MAX) {
101             if (max_iovs == -1 && errno) {
102                 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", strerror(errno));
103             }
104             max_iovs = _XOPEN_IOV_MAX;
105         } else if (max_iovs > MAX_IOVS) {
106             max_iovs = MAX_IOVS;
107         }
108
109         errno = save_errno;
110     }
111
112     *sockp = NULL;
113     sock = malloc(sizeof *sock);
114     if (sock == NULL) {
115         return ENOMEM;
116     }
117
118     sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
119     if (sock->fd < 0) {
120         VLOG_ERR("fcntl: %s", strerror(errno));
121         goto error;
122     }
123     sock->protocol = protocol;
124     sock->dump = NULL;
125
126     rcvbuf = 1024 * 1024;
127     if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
128                    &rcvbuf, sizeof rcvbuf)) {
129         VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed (%s)",
130                      rcvbuf, strerror(errno));
131     }
132
133     retval = get_socket_rcvbuf(sock->fd);
134     if (retval < 0) {
135         retval = -retval;
136         goto error;
137     }
138     sock->rcvbuf = retval;
139
140     /* Connect to kernel (pid 0) as remote address. */
141     memset(&remote, 0, sizeof remote);
142     remote.nl_family = AF_NETLINK;
143     remote.nl_pid = 0;
144     if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
145         VLOG_ERR("connect(0): %s", strerror(errno));
146         goto error;
147     }
148
149     /* Obtain pid assigned by kernel. */
150     local_size = sizeof local;
151     if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
152         VLOG_ERR("getsockname: %s", strerror(errno));
153         goto error;
154     }
155     if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
156         VLOG_ERR("getsockname returned bad Netlink name");
157         retval = EINVAL;
158         goto error;
159     }
160     sock->pid = local.nl_pid;
161
162     *sockp = sock;
163     return 0;
164
165 error:
166     if (retval == 0) {
167         retval = errno;
168         if (retval == 0) {
169             retval = EINVAL;
170         }
171     }
172     if (sock->fd >= 0) {
173         close(sock->fd);
174     }
175     free(sock);
176     return retval;
177 }
178
179 /* Creates a new netlink socket for the same protocol as 'src'.  Returns 0 and
180  * sets '*sockp' to the new socket if successful, otherwise returns a positive
181  * errno value.  */
182 int
183 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
184 {
185     return nl_sock_create(src->protocol, sockp);
186 }
187
188 /* Destroys netlink socket 'sock'. */
189 void
190 nl_sock_destroy(struct nl_sock *sock)
191 {
192     if (sock) {
193         if (sock->dump) {
194             sock->dump = NULL;
195         } else {
196             close(sock->fd);
197             free(sock);
198         }
199     }
200 }
201
202 /* Tries to add 'sock' as a listener for 'multicast_group'.  Returns 0 if
203  * successful, otherwise a positive errno value.
204  *
205  * A socket that is subscribed to a multicast group that receives asynchronous
206  * notifications must not be used for Netlink transactions or dumps, because
207  * transactions and dumps can cause notifications to be lost.
208  *
209  * Multicast group numbers are always positive.
210  *
211  * It is not an error to attempt to join a multicast group to which a socket
212  * already belongs. */
213 int
214 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
215 {
216     int error = nl_sock_cow__(sock);
217     if (error) {
218         return error;
219     }
220     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
221                    &multicast_group, sizeof multicast_group) < 0) {
222         VLOG_WARN("could not join multicast group %u (%s)",
223                   multicast_group, strerror(errno));
224         return errno;
225     }
226     return 0;
227 }
228
229 /* Tries to make 'sock' stop listening to 'multicast_group'.  Returns 0 if
230  * successful, otherwise a positive errno value.
231  *
232  * Multicast group numbers are always positive.
233  *
234  * It is not an error to attempt to leave a multicast group to which a socket
235  * does not belong.
236  *
237  * On success, reading from 'sock' will still return any messages that were
238  * received on 'multicast_group' before the group was left. */
239 int
240 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
241 {
242     assert(!sock->dump);
243     if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
244                    &multicast_group, sizeof multicast_group) < 0) {
245         VLOG_WARN("could not leave multicast group %u (%s)",
246                   multicast_group, strerror(errno));
247         return errno;
248     }
249     return 0;
250 }
251
252 static int
253 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
254 {
255     struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
256     int error;
257
258     nlmsg->nlmsg_len = msg->size;
259     nlmsg->nlmsg_pid = sock->pid;
260     do {
261         int retval;
262         retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
263         error = retval < 0 ? errno : 0;
264     } while (error == EINTR);
265     log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
266     if (!error) {
267         COVERAGE_INC(netlink_sent);
268     }
269     return error;
270 }
271
272 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
273  * 'sock'.  nlmsg_len in 'msg' will be finalized to match msg->size, and
274  * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
275  *
276  * Returns 0 if successful, otherwise a positive errno value.  If
277  * 'wait' is true, then the send will wait until buffer space is ready;
278  * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
279 int
280 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
281 {
282     int error = nl_sock_cow__(sock);
283     if (error) {
284         return error;
285     }
286     return nl_sock_send__(sock, msg, wait);
287 }
288
289 /* This stress option is useful for testing that OVS properly tolerates
290  * -ENOBUFS on NetLink sockets.  Such errors are unavoidable because they can
291  * occur if the kernel cannot temporarily allocate enough GFP_ATOMIC memory to
292  * reply to a request.  They can also occur if messages arrive on a multicast
293  * channel faster than OVS can process them. */
294 STRESS_OPTION(
295     netlink_overflow, "simulate netlink socket receive buffer overflow",
296     5, 1, -1, 100);
297
298 static int
299 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
300 {
301     /* We can't accurately predict the size of the data to be received.  Most
302      * received data will fit in a 2 kB buffer, so we allocate that much space.
303      * In case the data is actually bigger than that, we make available enough
304      * additional space to allow Netlink messages to be up to 64 kB long (a
305      * reasonable figure since that's the maximum length of a Netlink
306      * attribute). */
307     enum { MAX_SIZE = 65536 };
308     enum { HEAD_SIZE = 2048 };
309     enum { TAIL_SIZE = MAX_SIZE - HEAD_SIZE };
310
311     struct nlmsghdr *nlmsghdr;
312     uint8_t tail[TAIL_SIZE];
313     struct iovec iov[2];
314     struct ofpbuf *buf;
315     struct msghdr msg;
316     ssize_t retval;
317
318     *bufp = NULL;
319
320     buf = ofpbuf_new(HEAD_SIZE);
321     iov[0].iov_base = buf->data;
322     iov[0].iov_len = HEAD_SIZE;
323     iov[1].iov_base = tail;
324     iov[1].iov_len = TAIL_SIZE;
325
326     memset(&msg, 0, sizeof msg);
327     msg.msg_iov = iov;
328     msg.msg_iovlen = 2;
329
330     do {
331         retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
332     } while (retval < 0 && errno == EINTR);
333
334     if (retval < 0) {
335         int error = errno;
336         if (error == ENOBUFS) {
337             /* Socket receive buffer overflow dropped one or more messages that
338              * the kernel tried to send to us. */
339             COVERAGE_INC(netlink_overflow);
340         }
341         ofpbuf_delete(buf);
342         return error;
343     }
344
345     if (msg.msg_flags & MSG_TRUNC) {
346         VLOG_ERR_RL(&rl, "truncated message (longer than %d bytes)", MAX_SIZE);
347         ofpbuf_delete(buf);
348         return E2BIG;
349     }
350
351     ofpbuf_put_uninit(buf, MIN(retval, HEAD_SIZE));
352     if (retval > HEAD_SIZE) {
353         COVERAGE_INC(netlink_recv_jumbo);
354         ofpbuf_put(buf, tail, retval - HEAD_SIZE);
355     }
356
357     nlmsghdr = buf->data;
358     if (retval < sizeof *nlmsghdr
359         || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
360         || nlmsghdr->nlmsg_len > retval) {
361         VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
362                     retval, NLMSG_HDRLEN);
363         ofpbuf_delete(buf);
364         return EPROTO;
365     }
366
367     if (STRESS(netlink_overflow)) {
368         ofpbuf_delete(buf);
369         return ENOBUFS;
370     }
371
372     *bufp = buf;
373     log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
374     COVERAGE_INC(netlink_received);
375
376     return 0;
377 }
378
379 /* Tries to receive a netlink message from the kernel on 'sock'.  If
380  * successful, stores the received message into '*bufp' and returns 0.  The
381  * caller is responsible for destroying the message with ofpbuf_delete().  On
382  * failure, returns a positive errno value and stores a null pointer into
383  * '*bufp'.
384  *
385  * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
386  * returns EAGAIN if the 'sock' receive buffer is empty. */
387 int
388 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
389 {
390     int error = nl_sock_cow__(sock);
391     if (error) {
392         return error;
393     }
394     return nl_sock_recv__(sock, bufp, wait);
395 }
396
397 static int
398 find_nl_transaction_by_seq(struct nl_transaction **transactions, size_t n,
399                            uint32_t seq)
400 {
401     int i;
402
403     for (i = 0; i < n; i++) {
404         struct nl_transaction *t = transactions[i];
405
406         if (seq == nl_msg_nlmsghdr(t->request)->nlmsg_seq) {
407             return i;
408         }
409     }
410
411     return -1;
412 }
413
414 static void
415 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
416                         int error)
417 {
418     size_t i;
419
420     for (i = 0; i < n; i++) {
421         transactions[i]->error = error;
422         transactions[i]->reply = NULL;
423     }
424 }
425
426 static int
427 nl_sock_transact_multiple__(struct nl_sock *sock,
428                             struct nl_transaction **transactions, size_t n,
429                             size_t *done)
430 {
431     struct iovec iovs[MAX_IOVS];
432     struct msghdr msg;
433     int error;
434     int i;
435
436     *done = 0;
437     for (i = 0; i < n; i++) {
438         struct ofpbuf *request = transactions[i]->request;
439         struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(request);
440
441         nlmsg->nlmsg_len = request->size;
442         nlmsg->nlmsg_pid = sock->pid;
443
444         iovs[i].iov_base = request->data;
445         iovs[i].iov_len = request->size;
446     }
447
448     memset(&msg, 0, sizeof msg);
449     msg.msg_iov = iovs;
450     msg.msg_iovlen = n;
451     do {
452         error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
453     } while (error == EINTR);
454
455     for (i = 0; i < n; i++) {
456         struct ofpbuf *request = transactions[i]->request;
457
458         log_nlmsg(__func__, error, request->data, request->size,
459                   sock->protocol);
460     }
461     if (!error) {
462         COVERAGE_ADD(netlink_sent, n);
463     }
464
465     if (error) {
466         return error;
467     }
468
469     while (n > 0) {
470         struct ofpbuf *reply;
471
472         error = nl_sock_recv__(sock, &reply, false);
473         if (error == EAGAIN) {
474             nl_sock_record_errors__(transactions, n, 0);
475             *done += n;
476             return 0;
477         } else if (error) {
478             return error;
479         }
480
481         i = find_nl_transaction_by_seq(transactions, n,
482                                        nl_msg_nlmsghdr(reply)->nlmsg_seq);
483         if (i < 0) {
484             VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32,
485                         nl_msg_nlmsghdr(reply)->nlmsg_seq);
486             ofpbuf_delete(reply);
487             continue;
488         }
489
490         nl_sock_record_errors__(transactions, i, 0);
491         if (nl_msg_nlmsgerr(reply, &error)) {
492             transactions[i]->reply = NULL;
493             transactions[i]->error = error;
494             if (error) {
495                 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
496                             error, strerror(error));
497             }
498             ofpbuf_delete(reply);
499         } else {
500             transactions[i]->reply = reply;
501             transactions[i]->error = 0;
502         }
503
504         *done += i + 1;
505         transactions += i + 1;
506         n -= i + 1;
507     }
508
509     return 0;
510 }
511
512 /* Sends the 'request' member of the 'n' transactions in 'transactions' to the
513  * kernel, in order, and waits for responses to all of them.  Fills in the
514  * 'error' member of each transaction with 0 if it was successful, otherwise
515  * with a positive errno value.  'reply' will be NULL on error or if the
516  * transaction was successful but had no reply beyond an indication of success.
517  * For a successful transaction that did have a more detailed reply, 'reply'
518  * will be set to the reply message.
519  *
520  * The caller is responsible for destroying each request and reply, and the
521  * transactions array itself.
522  *
523  * Before sending each message, this function will finalize nlmsg_len in each
524  * 'request' to match the ofpbuf's size, and set nlmsg_pid to 'sock''s pid.
525  * NLM_F_ACK will be added to some requests' nlmsg_flags.
526  *
527  * Bare Netlink is an unreliable transport protocol.  This function layers
528  * reliable delivery and reply semantics on top of bare Netlink.  See
529  * nl_sock_transact() for some caveats.
530  */
531 void
532 nl_sock_transact_multiple(struct nl_sock *sock,
533                           struct nl_transaction **transactions, size_t n)
534 {
535     int max_batch_count;
536     int error;
537
538     if (!n) {
539         return;
540     }
541
542     error = nl_sock_cow__(sock);
543     if (error) {
544         nl_sock_record_errors__(transactions, n, error);
545         return;
546     }
547
548     /* In theory, every request could have a 64 kB reply.  But the default and
549      * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
550      * be a bit below 128 kB, so that would only allow a single message in a
551      * "batch".  So we assume that replies average (at most) 4 kB, which allows
552      * a good deal of batching.
553      *
554      * In practice, most of the requests that we batch either have no reply at
555      * all or a brief reply. */
556     max_batch_count = MAX(sock->rcvbuf / 4096, 1);
557     max_batch_count = MIN(max_batch_count, max_iovs);
558
559     while (n > 0) {
560         size_t count, bytes;
561         size_t done;
562
563         /* Batch up to 'max_batch_count' transactions.  But cap it at about a
564          * page of requests total because big skbuffs are expensive to
565          * allocate in the kernel.  */
566 #if defined(PAGESIZE)
567         enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
568 #else
569         enum { MAX_BATCH_BYTES = 4096 - 512 };
570 #endif
571         bytes = transactions[0]->request->size;
572         for (count = 1; count < n && count < max_batch_count; count++) {
573             if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
574                 break;
575             }
576             bytes += transactions[count]->request->size;
577         }
578
579         error = nl_sock_transact_multiple__(sock, transactions, count, &done);
580         transactions += done;
581         n -= done;
582
583         if (error == ENOBUFS) {
584             VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
585         } else if (error) {
586             VLOG_ERR_RL(&rl, "transaction error (%s)", strerror(error));
587             nl_sock_record_errors__(transactions, n, error);
588         }
589     }
590 }
591
592 /* Sends 'request' to the kernel via 'sock' and waits for a response.  If
593  * successful, returns 0.  On failure, returns a positive errno value.
594  *
595  * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
596  * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
597  * on failure '*replyp' is set to NULL.  If 'replyp' is null, then the kernel's
598  * reply, if any, is discarded.
599  *
600  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
601  * be set to 'sock''s pid, before the message is sent.  NLM_F_ACK will be set
602  * in nlmsg_flags.
603  *
604  * The caller is responsible for destroying 'request'.
605  *
606  * Bare Netlink is an unreliable transport protocol.  This function layers
607  * reliable delivery and reply semantics on top of bare Netlink.
608  *
609  * In Netlink, sending a request to the kernel is reliable enough, because the
610  * kernel will tell us if the message cannot be queued (and we will in that
611  * case put it on the transmit queue and wait until it can be delivered).
612  *
613  * Receiving the reply is the real problem: if the socket buffer is full when
614  * the kernel tries to send the reply, the reply will be dropped.  However, the
615  * kernel sets a flag that a reply has been dropped.  The next call to recv
616  * then returns ENOBUFS.  We can then re-send the request.
617  *
618  * Caveats:
619  *
620  *      1. Netlink depends on sequence numbers to match up requests and
621  *         replies.  The sender of a request supplies a sequence number, and
622  *         the reply echos back that sequence number.
623  *
624  *         This is fine, but (1) some kernel netlink implementations are
625  *         broken, in that they fail to echo sequence numbers and (2) this
626  *         function will drop packets with non-matching sequence numbers, so
627  *         that only a single request can be usefully transacted at a time.
628  *
629  *      2. Resending the request causes it to be re-executed, so the request
630  *         needs to be idempotent.
631  */
632 int
633 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
634                  struct ofpbuf **replyp)
635 {
636     struct nl_transaction *transactionp;
637     struct nl_transaction transaction;
638
639     transaction.request = (struct ofpbuf *) request;
640     transactionp = &transaction;
641     nl_sock_transact_multiple(sock, &transactionp, 1);
642     if (replyp) {
643         *replyp = transaction.reply;
644     } else {
645         ofpbuf_delete(transaction.reply);
646     }
647     return transaction.error;
648 }
649
650 /* Drain all the messages currently in 'sock''s receive queue. */
651 int
652 nl_sock_drain(struct nl_sock *sock)
653 {
654     int error = nl_sock_cow__(sock);
655     if (error) {
656         return error;
657     }
658     return drain_rcvbuf(sock->fd);
659 }
660
661 /* The client is attempting some operation on 'sock'.  If 'sock' has an ongoing
662  * dump operation, then replace 'sock''s fd with a new socket and hand 'sock''s
663  * old fd over to the dump. */
664 static int
665 nl_sock_cow__(struct nl_sock *sock)
666 {
667     struct nl_sock *copy;
668     uint32_t tmp_pid;
669     int tmp_fd;
670     int error;
671
672     if (!sock->dump) {
673         return 0;
674     }
675
676     error = nl_sock_clone(sock, &copy);
677     if (error) {
678         return error;
679     }
680
681     tmp_fd = sock->fd;
682     sock->fd = copy->fd;
683     copy->fd = tmp_fd;
684
685     tmp_pid = sock->pid;
686     sock->pid = copy->pid;
687     copy->pid = tmp_pid;
688
689     sock->dump->sock = copy;
690     sock->dump = NULL;
691
692     return 0;
693 }
694
695 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel via
696  * 'sock', and initializes 'dump' to reflect the state of the operation.
697  *
698  * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
699  * be set to 'sock''s pid, before the message is sent.  NLM_F_DUMP and
700  * NLM_F_ACK will be set in nlmsg_flags.
701  *
702  * This Netlink socket library is designed to ensure that the dump is reliable
703  * and that it will not interfere with other operations on 'sock', including
704  * destroying or sending and receiving messages on 'sock'.  One corner case is
705  * not handled:
706  *
707  *   - If 'sock' has been used to send a request (e.g. with nl_sock_send())
708  *     whose response has not yet been received (e.g. with nl_sock_recv()).
709  *     This is unusual: usually nl_sock_transact() is used to send a message
710  *     and receive its reply all in one go.
711  *
712  * This function provides no status indication.  An error status for the entire
713  * dump operation is provided when it is completed by calling nl_dump_done().
714  *
715  * The caller is responsible for destroying 'request'.
716  *
717  * The new 'dump' is independent of 'sock'.  'sock' and 'dump' may be destroyed
718  * in either order.
719  */
720 void
721 nl_dump_start(struct nl_dump *dump,
722               struct nl_sock *sock, const struct ofpbuf *request)
723 {
724     struct nlmsghdr *nlmsghdr = nl_msg_nlmsghdr(request);
725     nlmsghdr->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
726     dump->seq = nlmsghdr->nlmsg_seq;
727     dump->buffer = NULL;
728     if (sock->dump) {
729         /* 'sock' already has an ongoing dump.  Clone the socket because
730          * Netlink only allows one dump at a time. */
731         dump->status = nl_sock_clone(sock, &dump->sock);
732         if (dump->status) {
733             return;
734         }
735     } else {
736         sock->dump = dump;
737         dump->sock = sock;
738         dump->status = 0;
739     }
740     dump->status = nl_sock_send__(sock, request, true);
741 }
742
743 /* Helper function for nl_dump_next(). */
744 static int
745 nl_dump_recv(struct nl_dump *dump, struct ofpbuf **bufferp)
746 {
747     struct nlmsghdr *nlmsghdr;
748     struct ofpbuf *buffer;
749     int retval;
750
751     retval = nl_sock_recv__(dump->sock, bufferp, true);
752     if (retval) {
753         return retval == EINTR ? EAGAIN : retval;
754     }
755     buffer = *bufferp;
756
757     nlmsghdr = nl_msg_nlmsghdr(buffer);
758     if (dump->seq != nlmsghdr->nlmsg_seq) {
759         VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
760                     nlmsghdr->nlmsg_seq, dump->seq);
761         return EAGAIN;
762     }
763
764     if (nl_msg_nlmsgerr(buffer, &retval)) {
765         VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
766                      strerror(retval));
767         return retval && retval != EAGAIN ? retval : EPROTO;
768     }
769
770     return 0;
771 }
772
773 /* Attempts to retrieve another reply from 'dump', which must have been
774  * initialized with nl_dump_start().
775  *
776  * If successful, returns true and points 'reply->data' and 'reply->size' to
777  * the message that was retrieved.  The caller must not modify 'reply' (because
778  * it points into the middle of a larger buffer).
779  *
780  * On failure, returns false and sets 'reply->data' to NULL and 'reply->size'
781  * to 0.  Failure might indicate an actual error or merely the end of replies.
782  * An error status for the entire dump operation is provided when it is
783  * completed by calling nl_dump_done().
784  */
785 bool
786 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply)
787 {
788     struct nlmsghdr *nlmsghdr;
789
790     reply->data = NULL;
791     reply->size = 0;
792     if (dump->status) {
793         return false;
794     }
795
796     if (dump->buffer && !dump->buffer->size) {
797         ofpbuf_delete(dump->buffer);
798         dump->buffer = NULL;
799     }
800     while (!dump->buffer) {
801         int retval = nl_dump_recv(dump, &dump->buffer);
802         if (retval) {
803             ofpbuf_delete(dump->buffer);
804             dump->buffer = NULL;
805             if (retval != EAGAIN) {
806                 dump->status = retval;
807                 return false;
808             }
809         }
810     }
811
812     nlmsghdr = nl_msg_next(dump->buffer, reply);
813     if (!nlmsghdr) {
814         VLOG_WARN_RL(&rl, "netlink dump reply contains message fragment");
815         dump->status = EPROTO;
816         return false;
817     } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
818         dump->status = EOF;
819         return false;
820     }
821
822     return true;
823 }
824
825 /* Completes Netlink dump operation 'dump', which must have been initialized
826  * with nl_dump_start().  Returns 0 if the dump operation was error-free,
827  * otherwise a positive errno value describing the problem. */
828 int
829 nl_dump_done(struct nl_dump *dump)
830 {
831     /* Drain any remaining messages that the client didn't read.  Otherwise the
832      * kernel will continue to queue them up and waste buffer space. */
833     while (!dump->status) {
834         struct ofpbuf reply;
835         if (!nl_dump_next(dump, &reply)) {
836             assert(dump->status);
837         }
838     }
839
840     if (dump->sock) {
841         if (dump->sock->dump) {
842             dump->sock->dump = NULL;
843         } else {
844             nl_sock_destroy(dump->sock);
845         }
846     }
847     ofpbuf_delete(dump->buffer);
848     return dump->status == EOF ? 0 : dump->status;
849 }
850
851 /* Causes poll_block() to wake up when any of the specified 'events' (which is
852  * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
853 void
854 nl_sock_wait(const struct nl_sock *sock, short int events)
855 {
856     poll_fd_wait(sock->fd, events);
857 }
858
859 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
860  * that can't use nl_sock_wait().
861  *
862  * It's a little tricky to use the returned fd correctly, because nl_sock does
863  * "copy on write" to allow a single nl_sock to be used for notifications,
864  * transactions, and dumps.  If 'sock' is used only for notifications and
865  * transactions (and never for dump) then the usage is safe. */
866 int
867 nl_sock_fd(const struct nl_sock *sock)
868 {
869     return sock->fd;
870 }
871
872 /* Returns the PID associated with this socket. */
873 uint32_t
874 nl_sock_pid(const struct nl_sock *sock)
875 {
876     return sock->pid;
877 }
878 \f
879 /* Miscellaneous.  */
880
881 struct genl_family {
882     struct hmap_node hmap_node;
883     uint16_t id;
884     char *name;
885 };
886
887 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
888
889 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
890     [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
891     [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
892 };
893
894 static struct genl_family *
895 find_genl_family_by_id(uint16_t id)
896 {
897     struct genl_family *family;
898
899     HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
900                              &genl_families) {
901         if (family->id == id) {
902             return family;
903         }
904     }
905     return NULL;
906 }
907
908 static void
909 define_genl_family(uint16_t id, const char *name)
910 {
911     struct genl_family *family = find_genl_family_by_id(id);
912
913     if (family) {
914         if (!strcmp(family->name, name)) {
915             return;
916         }
917         free(family->name);
918     } else {
919         family = xmalloc(sizeof *family);
920         family->id = id;
921         hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
922     }
923     family->name = xstrdup(name);
924 }
925
926 static const char *
927 genl_family_to_name(uint16_t id)
928 {
929     if (id == GENL_ID_CTRL) {
930         return "control";
931     } else {
932         struct genl_family *family = find_genl_family_by_id(id);
933         return family ? family->name : "unknown";
934     }
935 }
936
937 static int
938 do_lookup_genl_family(const char *name, struct nlattr **attrs,
939                       struct ofpbuf **replyp)
940 {
941     struct nl_sock *sock;
942     struct ofpbuf request, *reply;
943     int error;
944
945     *replyp = NULL;
946     error = nl_sock_create(NETLINK_GENERIC, &sock);
947     if (error) {
948         return error;
949     }
950
951     ofpbuf_init(&request, 0);
952     nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
953                           CTRL_CMD_GETFAMILY, 1);
954     nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
955     error = nl_sock_transact(sock, &request, &reply);
956     ofpbuf_uninit(&request);
957     if (error) {
958         nl_sock_destroy(sock);
959         return error;
960     }
961
962     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
963                          family_policy, attrs, ARRAY_SIZE(family_policy))
964         || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
965         nl_sock_destroy(sock);
966         ofpbuf_delete(reply);
967         return EPROTO;
968     }
969
970     nl_sock_destroy(sock);
971     *replyp = reply;
972     return 0;
973 }
974
975 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
976  * When successful, writes its result to 'multicast_group' and returns 0.
977  * Otherwise, clears 'multicast_group' and returns a positive error code.
978  *
979  * Some kernels do not support looking up a multicast group with this function.
980  * In this case, 'multicast_group' will be populated with 'fallback'. */
981 int
982 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
983                        unsigned int *multicast_group, unsigned int fallback)
984 {
985     struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
986     const struct nlattr *mc;
987     struct ofpbuf *reply;
988     unsigned int left;
989     int error;
990
991     *multicast_group = 0;
992     error = do_lookup_genl_family(family_name, family_attrs, &reply);
993     if (error) {
994         return error;
995     }
996
997     if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
998         *multicast_group = fallback;
999         VLOG_WARN("%s-%s: has no multicast group, using fallback %d",
1000                   family_name, group_name, *multicast_group);
1001         error = 0;
1002         goto exit;
1003     }
1004
1005     NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1006         static const struct nl_policy mc_policy[] = {
1007             [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1008             [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1009         };
1010
1011         struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1012         const char *mc_name;
1013
1014         if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1015             error = EPROTO;
1016             goto exit;
1017         }
1018
1019         mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1020         if (!strcmp(group_name, mc_name)) {
1021             *multicast_group =
1022                 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1023             error = 0;
1024             goto exit;
1025         }
1026     }
1027     error = EPROTO;
1028
1029 exit:
1030     ofpbuf_delete(reply);
1031     return error;
1032 }
1033
1034 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1035  * number and stores it in '*number'.  If successful, returns 0 and the caller
1036  * may use '*number' as the family number.  On failure, returns a positive
1037  * errno value and '*number' caches the errno value. */
1038 int
1039 nl_lookup_genl_family(const char *name, int *number)
1040 {
1041     if (*number == 0) {
1042         struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1043         struct ofpbuf *reply;
1044         int error;
1045
1046         error = do_lookup_genl_family(name, attrs, &reply);
1047         if (!error) {
1048             *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1049             define_genl_family(*number, name);
1050         } else {
1051             *number = -error;
1052         }
1053         ofpbuf_delete(reply);
1054
1055         assert(*number != 0);
1056     }
1057     return *number > 0 ? 0 : -*number;
1058 }
1059 \f
1060 static void
1061 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1062 {
1063     struct nlmsg_flag {
1064         unsigned int bits;
1065         const char *name;
1066     };
1067     static const struct nlmsg_flag flags[] = {
1068         { NLM_F_REQUEST, "REQUEST" },
1069         { NLM_F_MULTI, "MULTI" },
1070         { NLM_F_ACK, "ACK" },
1071         { NLM_F_ECHO, "ECHO" },
1072         { NLM_F_DUMP, "DUMP" },
1073         { NLM_F_ROOT, "ROOT" },
1074         { NLM_F_MATCH, "MATCH" },
1075         { NLM_F_ATOMIC, "ATOMIC" },
1076     };
1077     const struct nlmsg_flag *flag;
1078     uint16_t flags_left;
1079
1080     ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1081                   h->nlmsg_len, h->nlmsg_type);
1082     if (h->nlmsg_type == NLMSG_NOOP) {
1083         ds_put_cstr(ds, "(no-op)");
1084     } else if (h->nlmsg_type == NLMSG_ERROR) {
1085         ds_put_cstr(ds, "(error)");
1086     } else if (h->nlmsg_type == NLMSG_DONE) {
1087         ds_put_cstr(ds, "(done)");
1088     } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1089         ds_put_cstr(ds, "(overrun)");
1090     } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1091         ds_put_cstr(ds, "(reserved)");
1092     } else if (protocol == NETLINK_GENERIC) {
1093         ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1094     } else {
1095         ds_put_cstr(ds, "(family-defined)");
1096     }
1097     ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1098     flags_left = h->nlmsg_flags;
1099     for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1100         if ((flags_left & flag->bits) == flag->bits) {
1101             ds_put_format(ds, "[%s]", flag->name);
1102             flags_left &= ~flag->bits;
1103         }
1104     }
1105     if (flags_left) {
1106         ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1107     }
1108     ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1109                   h->nlmsg_seq, h->nlmsg_pid);
1110 }
1111
1112 static char *
1113 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1114 {
1115     struct ds ds = DS_EMPTY_INITIALIZER;
1116     const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1117     if (h) {
1118         nlmsghdr_to_string(h, protocol, &ds);
1119         if (h->nlmsg_type == NLMSG_ERROR) {
1120             const struct nlmsgerr *e;
1121             e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1122                           NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1123             if (e) {
1124                 ds_put_format(&ds, " error(%d", e->error);
1125                 if (e->error < 0) {
1126                     ds_put_format(&ds, "(%s)", strerror(-e->error));
1127                 }
1128                 ds_put_cstr(&ds, ", in-reply-to(");
1129                 nlmsghdr_to_string(&e->msg, protocol, &ds);
1130                 ds_put_cstr(&ds, "))");
1131             } else {
1132                 ds_put_cstr(&ds, " error(truncated)");
1133             }
1134         } else if (h->nlmsg_type == NLMSG_DONE) {
1135             int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1136             if (error) {
1137                 ds_put_format(&ds, " done(%d", *error);
1138                 if (*error < 0) {
1139                     ds_put_format(&ds, "(%s)", strerror(-*error));
1140                 }
1141                 ds_put_cstr(&ds, ")");
1142             } else {
1143                 ds_put_cstr(&ds, " done(truncated)");
1144             }
1145         } else if (protocol == NETLINK_GENERIC) {
1146             struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1147             if (genl) {
1148                 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1149                               genl->cmd, genl->version);
1150             }
1151         }
1152     } else {
1153         ds_put_cstr(&ds, "nl(truncated)");
1154     }
1155     return ds.string;
1156 }
1157
1158 static void
1159 log_nlmsg(const char *function, int error,
1160           const void *message, size_t size, int protocol)
1161 {
1162     struct ofpbuf buffer;
1163     char *nlmsg;
1164
1165     if (!VLOG_IS_DBG_ENABLED()) {
1166         return;
1167     }
1168
1169     ofpbuf_use_const(&buffer, message, size);
1170     nlmsg = nlmsg_to_string(&buffer, protocol);
1171     VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
1172     free(nlmsg);
1173 }
1174
1175