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