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