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