2 * Copyright (c) 2008, 2009, 2010 Nicira Networks.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
28 #include "dynamic-string.h"
29 #include "netlink-protocol.h"
31 #include "poll-loop.h"
36 #define THIS_MODULE VLM_netlink
38 /* Linux header file confusion causes this to be undefined. */
40 #define SOL_NETLINK 270
43 /* A single (bad) Netlink message can in theory dump out many, many log
44 * messages, so the burst size is set quite high here to avoid missing useful
45 * information. Also, at high logging levels we log *all* Netlink messages. */
46 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
48 static void log_nlmsg(const char *function, int error,
49 const void *message, size_t size);
51 /* Netlink sockets. */
59 /* Next nlmsghdr sequence number.
61 * This implementation uses sequence numbers that are unique process-wide, to
62 * avoid a hypothetical race: send request, close socket, open new socket that
63 * reuses the old socket's PID value, send request on new socket, receive reply
64 * from kernel to old socket but with same PID and sequence number. (This race
65 * could be avoided other ways, e.g. by preventing PIDs from being quickly
67 static uint32_t next_seq;
69 static int alloc_pid(uint32_t *);
70 static void free_pid(uint32_t);
72 /* Creates a new netlink socket for the given netlink 'protocol'
73 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
74 * new socket if successful, otherwise returns a positive errno value.
76 * If 'multicast_group' is nonzero, the new socket subscribes to the specified
77 * netlink multicast group. (A netlink socket may listen to an arbitrary
78 * number of multicast groups, but so far we only need one at a time.)
80 * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
81 * receive buffer size, respectively.
84 nl_sock_create(int protocol, int multicast_group,
85 size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
88 struct sockaddr_nl local, remote;
92 /* Pick initial sequence number. */
93 next_seq = getpid() ^ time_wall();
97 sock = malloc(sizeof *sock);
102 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
104 VLOG_ERR("fcntl: %s", strerror(errno));
108 retval = alloc_pid(&sock->pid);
114 && setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
115 &so_sndbuf, sizeof so_sndbuf) < 0) {
116 VLOG_ERR("setsockopt(SO_SNDBUF,%zu): %s", so_sndbuf, strerror(errno));
121 && setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
122 &so_rcvbuf, sizeof so_rcvbuf) < 0) {
123 VLOG_ERR("setsockopt(SO_RCVBUF,%zu): %s", so_rcvbuf, strerror(errno));
127 /* Bind local address as our selected pid. */
128 memset(&local, 0, sizeof local);
129 local.nl_family = AF_NETLINK;
130 local.nl_pid = sock->pid;
131 if (multicast_group > 0 && multicast_group <= 32) {
132 /* This method of joining multicast groups is supported by old kernels,
133 * but it only allows 32 multicast groups per protocol. */
134 local.nl_groups |= 1ul << (multicast_group - 1);
136 if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
137 VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
141 /* Bind remote address as the kernel (pid 0). */
142 memset(&remote, 0, sizeof remote);
143 remote.nl_family = AF_NETLINK;
145 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
146 VLOG_ERR("connect(0): %s", strerror(errno));
150 /* Older kernel headers failed to define this macro. We want our programs
151 * to support the newer kernel features even if compiled with older
152 * headers, so define it ourselves in such a case. */
153 #ifndef NETLINK_ADD_MEMBERSHIP
154 #define NETLINK_ADD_MEMBERSHIP 1
157 /* This method of joining multicast groups is only supported by newish
158 * kernels, but it allows for an arbitrary number of multicast groups. */
159 if (multicast_group > 32
160 && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
161 &multicast_group, sizeof multicast_group) < 0) {
162 VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
163 multicast_group, strerror(errno));
186 /* Destroys netlink socket 'sock'. */
188 nl_sock_destroy(struct nl_sock *sock)
197 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
198 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, and
199 * nlmsg_pid will be set to 'sock''s pid, before the message is sent.
201 * Returns 0 if successful, otherwise a positive errno value. If
202 * 'wait' is true, then the send will wait until buffer space is ready;
203 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
205 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
207 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
210 nlmsg->nlmsg_len = msg->size;
211 nlmsg->nlmsg_pid = sock->pid;
214 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
215 error = retval < 0 ? errno : 0;
216 } while (error == EINTR);
217 log_nlmsg(__func__, error, msg->data, msg->size);
219 COVERAGE_INC(netlink_sent);
224 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
225 * a single Netlink message. (The message must be fully formed and not require
226 * finalization of its nlmsg_len or nlmsg_pid fields.)
228 * Returns 0 if successful, otherwise a positive errno value. If 'wait' is
229 * true, then the send will wait until buffer space is ready; otherwise,
230 * returns EAGAIN if the 'sock' send buffer is full. */
232 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
238 COVERAGE_INC(netlink_send);
239 memset(&msg, 0, sizeof msg);
240 msg.msg_iov = (struct iovec *) iov;
241 msg.msg_iovlen = n_iov;
244 retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
245 error = retval < 0 ? errno : 0;
246 } while (error == EINTR);
247 if (error != EAGAIN) {
248 log_nlmsg(__func__, error, iov[0].iov_base, iov[0].iov_len);
250 COVERAGE_INC(netlink_sent);
256 /* Tries to receive a netlink message from the kernel on 'sock'. If
257 * successful, stores the received message into '*bufp' and returns 0. The
258 * caller is responsible for destroying the message with ofpbuf_delete(). On
259 * failure, returns a positive errno value and stores a null pointer into
262 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
263 * returns EAGAIN if the 'sock' receive buffer is empty. */
265 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
268 ssize_t bufsize = 2048;
269 ssize_t nbytes, nbytes2;
271 struct nlmsghdr *nlmsghdr;
273 struct msghdr msg = {
283 buf = ofpbuf_new(bufsize);
287 /* Attempt to read the message. We don't know the size of the data
288 * yet, so we take a guess at 2048. If we're wrong, we keep trying
289 * and doubling the buffer size each time.
291 nlmsghdr = ofpbuf_put_uninit(buf, bufsize);
292 iov.iov_base = nlmsghdr;
293 iov.iov_len = bufsize;
295 nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
296 } while (nbytes < 0 && errno == EINTR);
301 if (msg.msg_flags & MSG_TRUNC) {
302 COVERAGE_INC(netlink_recv_retry);
304 ofpbuf_reinit(buf, bufsize);
309 /* We successfully read the message, so recv again to clear the queue */
313 nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
314 } while (nbytes2 < 0 && errno == EINTR);
316 if (errno == ENOBUFS) {
317 /* The kernel is notifying us that a message it tried to send to us
318 * was dropped. We have to pass this along to the caller in case
319 * it wants to retry a request. So kill the buffer, which we can
320 * re-read next time. */
321 COVERAGE_INC(netlink_overflow);
325 VLOG_ERR_RL(&rl, "failed to remove nlmsg from socket: %s\n",
329 if (nbytes < sizeof *nlmsghdr
330 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
331 || nlmsghdr->nlmsg_len > nbytes) {
332 VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
333 bufsize, NLMSG_HDRLEN);
338 log_nlmsg(__func__, 0, buf->data, buf->size);
339 COVERAGE_INC(netlink_received);
343 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
344 * successful, returns 0. On failure, returns a positive errno value.
346 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
347 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
348 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
349 * reply, if any, is discarded.
351 * nlmsg_len in 'msg' will be finalized to match msg->size, and nlmsg_pid will
352 * be set to 'sock''s pid, before the message is sent. NLM_F_ACK will be set
355 * The caller is responsible for destroying 'request'.
357 * Bare Netlink is an unreliable transport protocol. This function layers
358 * reliable delivery and reply semantics on top of bare Netlink.
360 * In Netlink, sending a request to the kernel is reliable enough, because the
361 * kernel will tell us if the message cannot be queued (and we will in that
362 * case put it on the transmit queue and wait until it can be delivered).
364 * Receiving the reply is the real problem: if the socket buffer is full when
365 * the kernel tries to send the reply, the reply will be dropped. However, the
366 * kernel sets a flag that a reply has been dropped. The next call to recv
367 * then returns ENOBUFS. We can then re-send the request.
371 * 1. Netlink depends on sequence numbers to match up requests and
372 * replies. The sender of a request supplies a sequence number, and
373 * the reply echos back that sequence number.
375 * This is fine, but (1) some kernel netlink implementations are
376 * broken, in that they fail to echo sequence numbers and (2) this
377 * function will drop packets with non-matching sequence numbers, so
378 * that only a single request can be usefully transacted at a time.
380 * 2. Resending the request causes it to be re-executed, so the request
381 * needs to be idempotent.
384 nl_sock_transact(struct nl_sock *sock,
385 const struct ofpbuf *request, struct ofpbuf **replyp)
387 uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
388 struct nlmsghdr *nlmsghdr;
389 struct ofpbuf *reply;
396 /* Ensure that we get a reply even if this message doesn't ordinarily call
398 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
401 retval = nl_sock_send(sock, request, true);
407 retval = nl_sock_recv(sock, &reply, true);
409 if (retval == ENOBUFS) {
410 COVERAGE_INC(netlink_overflow);
411 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
417 nlmsghdr = nl_msg_nlmsghdr(reply);
418 if (seq != nlmsghdr->nlmsg_seq) {
419 VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
420 nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
421 ofpbuf_delete(reply);
424 if (nl_msg_nlmsgerr(reply, &retval)) {
425 ofpbuf_delete(reply);
427 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
428 retval, strerror(retval));
430 return retval != EAGAIN ? retval : EPROTO;
436 ofpbuf_delete(reply);
441 /* Causes poll_block() to wake up when any of the specified 'events' (which is
442 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
444 nl_sock_wait(const struct nl_sock *sock, short int events)
446 poll_fd_wait(sock->fd, events);
449 /* Netlink messages. */
451 /* Returns the nlmsghdr at the head of 'msg'.
453 * 'msg' must be at least as large as a nlmsghdr. */
455 nl_msg_nlmsghdr(const struct ofpbuf *msg)
457 return ofpbuf_at_assert(msg, 0, NLMSG_HDRLEN);
460 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
462 * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
463 * and a genlmsghdr. */
465 nl_msg_genlmsghdr(const struct ofpbuf *msg)
467 return ofpbuf_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
470 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
471 * message, otherwise a positive errno value, and returns true. If 'buffer' is
472 * not an NLMSG_ERROR message, returns false.
474 * 'msg' must be at least as large as a nlmsghdr. */
476 nl_msg_nlmsgerr(const struct ofpbuf *msg, int *errorp)
478 if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
479 struct nlmsgerr *err = ofpbuf_at(msg, NLMSG_HDRLEN, sizeof *err);
482 VLOG_ERR_RL(&rl, "received invalid nlmsgerr (%zd bytes < %zd)",
483 msg->size, NLMSG_HDRLEN + sizeof *err);
484 } else if (err->error <= 0 && err->error > INT_MIN) {
496 /* Ensures that 'b' has room for at least 'size' bytes plus netlink padding at
497 * its tail end, reallocating and copying its data if necessary. */
499 nl_msg_reserve(struct ofpbuf *msg, size_t size)
501 ofpbuf_prealloc_tailroom(msg, NLMSG_ALIGN(size));
504 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
505 * Uses the given 'type' and 'flags'. 'expected_payload' should be
506 * an estimate of the number of payload bytes to be supplied; if the size of
507 * the payload is unknown a value of 0 is acceptable.
509 * 'type' is ordinarily an enumerated value specific to the Netlink protocol
510 * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol). For Generic Netlink, 'type'
511 * is the family number obtained via nl_lookup_genl_family().
513 * 'flags' is a bit-mask that indicates what kind of request is being made. It
514 * is often NLM_F_REQUEST indicating that a request is being made, commonly
515 * or'd with NLM_F_ACK to request an acknowledgement.
517 * Sets the new nlmsghdr's nlmsg_pid field to 0 for now. nl_sock_send() will
518 * fill it in just before sending the message.
520 * nl_msg_put_genlmsghdr() is more convenient for composing a Generic Netlink
523 nl_msg_put_nlmsghdr(struct ofpbuf *msg,
524 size_t expected_payload, uint32_t type, uint32_t flags)
526 struct nlmsghdr *nlmsghdr;
528 assert(msg->size == 0);
530 nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
531 nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
532 nlmsghdr->nlmsg_len = 0;
533 nlmsghdr->nlmsg_type = type;
534 nlmsghdr->nlmsg_flags = flags;
535 nlmsghdr->nlmsg_seq = ++next_seq;
536 nlmsghdr->nlmsg_pid = 0;
539 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
540 * initially empty. 'expected_payload' should be an estimate of the number of
541 * payload bytes to be supplied; if the size of the payload is unknown a value
542 * of 0 is acceptable.
544 * 'family' is the family number obtained via nl_lookup_genl_family().
546 * 'flags' is a bit-mask that indicates what kind of request is being made. It
547 * is often NLM_F_REQUEST indicating that a request is being made, commonly
548 * or'd with NLM_F_ACK to request an acknowledgement.
550 * 'cmd' is an enumerated value specific to the Generic Netlink family
551 * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
553 * 'version' is a version number specific to the family and command (often 1).
555 * Sets the new nlmsghdr's nlmsg_pid field to 0 for now. nl_sock_send() will
556 * fill it in just before sending the message.
558 * nl_msg_put_nlmsghdr() should be used to compose Netlink messages that are
559 * not Generic Netlink messages. */
561 nl_msg_put_genlmsghdr(struct ofpbuf *msg, size_t expected_payload,
562 int family, uint32_t flags, uint8_t cmd, uint8_t version)
564 struct genlmsghdr *genlmsghdr;
566 nl_msg_put_nlmsghdr(msg, GENL_HDRLEN + expected_payload, family, flags);
567 assert(msg->size == NLMSG_HDRLEN);
568 genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
569 genlmsghdr->cmd = cmd;
570 genlmsghdr->version = version;
571 genlmsghdr->reserved = 0;
574 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
575 * the tail end of 'msg'. Data in 'msg' is reallocated and copied if
578 nl_msg_put(struct ofpbuf *msg, const void *data, size_t size)
580 memcpy(nl_msg_put_uninit(msg, size), data, size);
583 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
584 * end of 'msg', reallocating and copying its data if necessary. Returns a
585 * pointer to the first byte of the new data, which is left uninitialized. */
587 nl_msg_put_uninit(struct ofpbuf *msg, size_t size)
589 size_t pad = NLMSG_ALIGN(size) - size;
590 char *p = ofpbuf_put_uninit(msg, size + pad);
592 memset(p + size, 0, pad);
597 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
598 * data as its payload, plus Netlink padding if needed, to the tail end of
599 * 'msg', reallocating and copying its data if necessary. Returns a pointer to
600 * the first byte of data in the attribute, which is left uninitialized. */
602 nl_msg_put_unspec_uninit(struct ofpbuf *msg, uint16_t type, size_t size)
604 size_t total_size = NLA_HDRLEN + size;
605 struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
606 assert(NLA_ALIGN(total_size) <= UINT16_MAX);
607 nla->nla_len = total_size;
608 nla->nla_type = type;
612 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
613 * 'data' as its payload, to the tail end of 'msg', reallocating and copying
614 * its data if necessary. Returns a pointer to the first byte of data in the
615 * attribute, which is left uninitialized. */
617 nl_msg_put_unspec(struct ofpbuf *msg, uint16_t type,
618 const void *data, size_t size)
620 memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
623 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
624 * (Some Netlink protocols use the presence or absence of an attribute as a
627 nl_msg_put_flag(struct ofpbuf *msg, uint16_t type)
629 nl_msg_put_unspec(msg, type, NULL, 0);
632 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
635 nl_msg_put_u8(struct ofpbuf *msg, uint16_t type, uint8_t value)
637 nl_msg_put_unspec(msg, type, &value, sizeof value);
640 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
643 nl_msg_put_u16(struct ofpbuf *msg, uint16_t type, uint16_t value)
645 nl_msg_put_unspec(msg, type, &value, sizeof value);
648 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
651 nl_msg_put_u32(struct ofpbuf *msg, uint16_t type, uint32_t value)
653 nl_msg_put_unspec(msg, type, &value, sizeof value);
656 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
659 nl_msg_put_u64(struct ofpbuf *msg, uint16_t type, uint64_t value)
661 nl_msg_put_unspec(msg, type, &value, sizeof value);
664 /* Appends a Netlink attribute of the given 'type' and the given
665 * null-terminated string 'value' to 'msg'. */
667 nl_msg_put_string(struct ofpbuf *msg, uint16_t type, const char *value)
669 nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
672 /* Appends a Netlink attribute of the given 'type' and the given buffered
673 * netlink message in 'nested_msg' to 'msg'. The nlmsg_len field in
674 * 'nested_msg' is finalized to match 'nested_msg->size'. */
676 nl_msg_put_nested(struct ofpbuf *msg,
677 uint16_t type, struct ofpbuf *nested_msg)
679 nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
680 nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
683 /* Returns the first byte in the payload of attribute 'nla'. */
685 nl_attr_get(const struct nlattr *nla)
687 assert(nla->nla_len >= NLA_HDRLEN);
691 /* Returns the number of bytes in the payload of attribute 'nla'. */
693 nl_attr_get_size(const struct nlattr *nla)
695 assert(nla->nla_len >= NLA_HDRLEN);
696 return nla->nla_len - NLA_HDRLEN;
699 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
700 * first byte of the payload. */
702 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
704 assert(nla->nla_len >= NLA_HDRLEN + size);
708 /* Returns true if 'nla' is nonnull. (Some Netlink protocols use the presence
709 * or absence of an attribute as a Boolean flag.) */
711 nl_attr_get_flag(const struct nlattr *nla)
716 #define NL_ATTR_GET_AS(NLA, TYPE) \
717 (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
719 /* Returns the 8-bit value in 'nla''s payload.
721 * Asserts that 'nla''s payload is at least 1 byte long. */
723 nl_attr_get_u8(const struct nlattr *nla)
725 return NL_ATTR_GET_AS(nla, uint8_t);
728 /* Returns the 16-bit value in 'nla''s payload.
730 * Asserts that 'nla''s payload is at least 2 bytes long. */
732 nl_attr_get_u16(const struct nlattr *nla)
734 return NL_ATTR_GET_AS(nla, uint16_t);
737 /* Returns the 32-bit value in 'nla''s payload.
739 * Asserts that 'nla''s payload is at least 4 bytes long. */
741 nl_attr_get_u32(const struct nlattr *nla)
743 return NL_ATTR_GET_AS(nla, uint32_t);
746 /* Returns the 64-bit value in 'nla''s payload.
748 * Asserts that 'nla''s payload is at least 8 bytes long. */
750 nl_attr_get_u64(const struct nlattr *nla)
752 return NL_ATTR_GET_AS(nla, uint64_t);
755 /* Returns the null-terminated string value in 'nla''s payload.
757 * Asserts that 'nla''s payload contains a null-terminated string. */
759 nl_attr_get_string(const struct nlattr *nla)
761 assert(nla->nla_len > NLA_HDRLEN);
762 assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
763 return nl_attr_get(nla);
766 /* Default minimum and maximum payload sizes for each type of attribute. */
767 static const size_t attr_len_range[][2] = {
768 [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
769 [NL_A_U8] = { 1, 1 },
770 [NL_A_U16] = { 2, 2 },
771 [NL_A_U32] = { 4, 4 },
772 [NL_A_U64] = { 8, 8 },
773 [NL_A_STRING] = { 1, SIZE_MAX },
774 [NL_A_FLAG] = { 0, SIZE_MAX },
775 [NL_A_NESTED] = { 0, SIZE_MAX },
778 /* Parses the 'msg' starting at the given 'nla_offset' as a sequence of Netlink
779 * attributes. 'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
780 * with nla_type == i is parsed; a pointer to attribute i is stored in
781 * attrs[i]. Returns true if successful, false on failure.
783 * If the Netlink attributes in 'msg' follow a Netlink header and a Generic
784 * Netlink header, then 'nla_offset' should be NLMSG_HDRLEN + GENL_HDRLEN. */
786 nl_policy_parse(const struct ofpbuf *msg, size_t nla_offset,
787 const struct nl_policy policy[],
788 struct nlattr *attrs[], size_t n_attrs)
795 for (i = 0; i < n_attrs; i++) {
798 assert(policy[i].type < N_NL_ATTR_TYPES);
799 if (policy[i].type != NL_A_NO_ATTR
800 && policy[i].type != NL_A_FLAG
801 && !policy[i].optional) {
806 p = ofpbuf_at(msg, nla_offset, 0);
808 VLOG_DBG_RL(&rl, "missing headers in nl_policy_parse");
811 tail = ofpbuf_tail(msg);
814 size_t offset = (char*)p - (char*)msg->data;
815 struct nlattr *nla = p;
816 size_t len, aligned_len;
819 /* Make sure its claimed length is plausible. */
820 if (nla->nla_len < NLA_HDRLEN) {
821 VLOG_DBG_RL(&rl, "%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
822 offset, nla->nla_len);
825 len = nla->nla_len - NLA_HDRLEN;
826 aligned_len = NLA_ALIGN(len);
827 if (aligned_len > (char*)tail - (char*)p) {
828 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" aligned data len (%zu) "
829 "> bytes left (%tu)",
830 offset, nla->nla_type, aligned_len,
831 (char*)tail - (char*)p);
835 type = nla->nla_type;
836 if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
837 const struct nl_policy *p = &policy[type];
838 size_t min_len, max_len;
840 /* Validate length and content. */
841 min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
842 max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
843 if (len < min_len || len > max_len) {
844 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" length %zu not in "
845 "allowed range %zu...%zu",
846 offset, type, len, min_len, max_len);
849 if (p->type == NL_A_STRING) {
850 if (((char *) nla)[nla->nla_len - 1]) {
851 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" lacks null at end",
855 if (memchr(nla + 1, '\0', len - 1) != NULL) {
856 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" has bad length",
861 if (!p->optional && attrs[type] == NULL) {
862 assert(n_required > 0);
867 /* Skip attribute type that we don't care about. */
869 p = (char*)p + NLA_ALIGN(nla->nla_len);
872 VLOG_DBG_RL(&rl, "%zu required attrs missing", n_required);
880 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
881 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
884 static int do_lookup_genl_family(const char *name)
886 struct nl_sock *sock;
887 struct ofpbuf request, *reply;
888 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
891 retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
896 ofpbuf_init(&request, 0);
897 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
898 CTRL_CMD_GETFAMILY, 1);
899 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
900 retval = nl_sock_transact(sock, &request, &reply);
901 ofpbuf_uninit(&request);
903 nl_sock_destroy(sock);
907 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
908 family_policy, attrs, ARRAY_SIZE(family_policy))) {
909 nl_sock_destroy(sock);
910 ofpbuf_delete(reply);
914 retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
918 nl_sock_destroy(sock);
919 ofpbuf_delete(reply);
923 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
924 * number and stores it in '*number'. If successful, returns 0 and the caller
925 * may use '*number' as the family number. On failure, returns a positive
926 * errno value and '*number' caches the errno value. */
928 nl_lookup_genl_family(const char *name, int *number)
931 *number = do_lookup_genl_family(name);
932 assert(*number != 0);
934 return *number > 0 ? 0 : -*number;
939 * Every Netlink socket must be bound to a unique 32-bit PID. By convention,
940 * programs that have a single Netlink socket use their Unix process ID as PID,
941 * and programs with multiple Netlink sockets add a unique per-socket
942 * identifier in the bits above the Unix process ID.
944 * The kernel has Netlink PID 0.
947 /* Parameters for how many bits in the PID should come from the Unix process ID
948 * and how many unique per-socket. */
949 #define SOCKET_BITS 10
950 #define MAX_SOCKETS (1u << SOCKET_BITS)
952 #define PROCESS_BITS (32 - SOCKET_BITS)
953 #define MAX_PROCESSES (1u << PROCESS_BITS)
954 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
956 /* Bit vector of unused socket identifiers. */
957 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
959 /* Allocates and returns a new Netlink PID. */
961 alloc_pid(uint32_t *pid)
965 for (i = 0; i < MAX_SOCKETS; i++) {
966 if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
967 avail_sockets[i / 32] |= 1u << (i % 32);
968 *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
972 VLOG_ERR("netlink pid space exhausted");
976 /* Makes the specified 'pid' available for reuse. */
978 free_pid(uint32_t pid)
980 int sock = pid >> PROCESS_BITS;
981 assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
982 avail_sockets[sock / 32] &= ~(1u << (sock % 32));
986 nlmsghdr_to_string(const struct nlmsghdr *h, struct ds *ds)
992 static const struct nlmsg_flag flags[] = {
993 { NLM_F_REQUEST, "REQUEST" },
994 { NLM_F_MULTI, "MULTI" },
995 { NLM_F_ACK, "ACK" },
996 { NLM_F_ECHO, "ECHO" },
997 { NLM_F_DUMP, "DUMP" },
998 { NLM_F_ROOT, "ROOT" },
999 { NLM_F_MATCH, "MATCH" },
1000 { NLM_F_ATOMIC, "ATOMIC" },
1002 const struct nlmsg_flag *flag;
1003 uint16_t flags_left;
1005 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1006 h->nlmsg_len, h->nlmsg_type);
1007 if (h->nlmsg_type == NLMSG_NOOP) {
1008 ds_put_cstr(ds, "(no-op)");
1009 } else if (h->nlmsg_type == NLMSG_ERROR) {
1010 ds_put_cstr(ds, "(error)");
1011 } else if (h->nlmsg_type == NLMSG_DONE) {
1012 ds_put_cstr(ds, "(done)");
1013 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1014 ds_put_cstr(ds, "(overrun)");
1015 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1016 ds_put_cstr(ds, "(reserved)");
1018 ds_put_cstr(ds, "(family-defined)");
1020 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1021 flags_left = h->nlmsg_flags;
1022 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1023 if ((flags_left & flag->bits) == flag->bits) {
1024 ds_put_format(ds, "[%s]", flag->name);
1025 flags_left &= ~flag->bits;
1029 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1031 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
1032 h->nlmsg_seq, h->nlmsg_pid,
1033 (int) (h->nlmsg_pid & PROCESS_MASK),
1034 (int) (h->nlmsg_pid >> PROCESS_BITS));
1038 nlmsg_to_string(const struct ofpbuf *buffer)
1040 struct ds ds = DS_EMPTY_INITIALIZER;
1041 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1043 nlmsghdr_to_string(h, &ds);
1044 if (h->nlmsg_type == NLMSG_ERROR) {
1045 const struct nlmsgerr *e;
1046 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1047 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1049 ds_put_format(&ds, " error(%d", e->error);
1051 ds_put_format(&ds, "(%s)", strerror(-e->error));
1053 ds_put_cstr(&ds, ", in-reply-to(");
1054 nlmsghdr_to_string(&e->msg, &ds);
1055 ds_put_cstr(&ds, "))");
1057 ds_put_cstr(&ds, " error(truncated)");
1059 } else if (h->nlmsg_type == NLMSG_DONE) {
1060 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1062 ds_put_format(&ds, " done(%d", *error);
1064 ds_put_format(&ds, "(%s)", strerror(-*error));
1066 ds_put_cstr(&ds, ")");
1068 ds_put_cstr(&ds, " done(truncated)");
1072 ds_put_cstr(&ds, "nl(truncated)");
1078 log_nlmsg(const char *function, int error,
1079 const void *message, size_t size)
1081 struct ofpbuf buffer;
1084 if (!VLOG_IS_DBG_ENABLED()) {
1088 buffer.data = (void *) message;
1090 nlmsg = nlmsg_to_string(&buffer);
1091 VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);