1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
4 * We are making the OpenFlow specification and associated documentation
5 * (Software) available for public use and benefit with the expectation
6 * that others will use, modify and enhance the Software and contribute
7 * those enhancements back to the community. However, since we would
8 * like to make the Software available for broadest use, with as few
9 * restrictions as possible permission is hereby granted, free of
10 * charge, to any person obtaining a copy of this Software to deal in
11 * the Software under the copyrights without restriction, including
12 * without limitation the rights to use, copy, modify, merge, publish,
13 * distribute, sublicense, and/or sell copies of the Software, and to
14 * permit persons to whom the Software is furnished to do so, subject to
15 * the following conditions:
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 * The name and trademarks of copyright holder(s) may NOT be used in
30 * advertising or publicity pertaining to the Software or any
31 * derivatives without specific, written prior permission.
44 #include "netlink-protocol.h"
48 #define THIS_MODULE VLM_netlink
50 /* Linux header file confusion causes this to be undefined. */
52 #define SOL_NETLINK 270
55 /* Netlink sockets. */
63 /* Next nlmsghdr sequence number.
65 * This implementation uses sequence numbers that are unique process-wide, to
66 * avoid a hypothetical race: send request, close socket, open new socket that
67 * reuses the old socket's PID value, send request on new socket, receive reply
68 * from kernel to old socket but with same PID and sequence number. (This race
69 * could be avoided other ways, e.g. by preventing PIDs from being quickly
71 static uint32_t next_seq;
73 static int alloc_pid(uint32_t *);
74 static void free_pid(uint32_t);
76 /* Creates a new netlink socket for the given netlink 'protocol'
77 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
78 * new socket if successful, otherwise returns a positive errno value.
80 * If 'multicast_group' is nonzero, the new socket subscribes to the specified
81 * netlink multicast group. (A netlink socket may listen to an arbitrary
82 * number of multicast groups, but so far we only need one at a time.)
84 * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
85 * receive buffer size, respectively.
88 nl_sock_create(int protocol, int multicast_group,
89 size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
92 struct sockaddr_nl local, remote;
96 /* Pick initial sequence number. */
97 next_seq = getpid() ^ time(0);
101 sock = malloc(sizeof *sock);
106 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
108 VLOG_ERR("fcntl: %s", strerror(errno));
112 retval = alloc_pid(&sock->pid);
118 && setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
119 &so_sndbuf, sizeof so_sndbuf) < 0) {
120 VLOG_ERR("setsockopt(SO_SNDBUF,%zu): %s", so_sndbuf, strerror(errno));
125 && setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
126 &so_rcvbuf, sizeof so_rcvbuf) < 0) {
127 VLOG_ERR("setsockopt(SO_RCVBUF,%zu): %s", so_rcvbuf, strerror(errno));
131 /* Bind local address as our selected pid. */
132 memset(&local, 0, sizeof local);
133 local.nl_family = AF_NETLINK;
134 local.nl_pid = sock->pid;
135 if (multicast_group > 0 && multicast_group <= 32) {
136 /* This method of joining multicast groups is supported by old kernels,
137 * but it only allows 32 multicast groups per protocol. */
138 local.nl_groups |= 1ul << (multicast_group - 1);
140 if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
141 VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
145 /* Bind remote address as the kernel (pid 0). */
146 memset(&remote, 0, sizeof remote);
147 remote.nl_family = AF_NETLINK;
149 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
150 VLOG_ERR("connect(0): %s", strerror(errno));
154 /* Older kernel headers failed to define this macro. We want our programs
155 * to support the newer kernel features even if compiled with older
156 * headers, so define it ourselves in such a case. */
157 #ifndef NETLINK_ADD_MEMBERSHIP
158 #define NETLINK_ADD_MEMBERSHIP 1
161 /* This method of joining multicast groups is only supported by newish
162 * kernels, but it allows for an arbitrary number of multicast groups. */
163 if (multicast_group > 32
164 && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
165 &multicast_group, sizeof multicast_group) < 0) {
166 VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
167 multicast_group, strerror(errno));
190 /* Destroys netlink socket 'sock'. */
192 nl_sock_destroy(struct nl_sock *sock)
201 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
202 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size before the
205 * Returns 0 if successful, otherwise a positive errno value. If
206 * 'wait' is true, then the send will wait until buffer space is ready;
207 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
209 nl_sock_send(struct nl_sock *sock, const struct buffer *msg, bool wait)
213 nl_msg_nlmsghdr(msg)->nlmsg_len = msg->size;
215 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
216 } while (retval < 0 && errno == EINTR);
217 return retval < 0 ? errno : 0;
220 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
221 * a single Netlink message. (The message must be fully formed and not require
222 * finalization of its nlmsg_len field.)
224 * Returns 0 if successful, otherwise a positive errno value. If 'wait' is
225 * true, then the send will wait until buffer space is ready; otherwise,
226 * returns EAGAIN if the 'sock' send buffer is full. */
228 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
234 memset(&msg, 0, sizeof msg);
235 msg.msg_iov = (struct iovec *) iov;
236 msg.msg_iovlen = n_iov;
238 retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
239 } while (retval < 0 && errno == EINTR);
240 return retval < 0 ? errno : 0;
243 /* Tries to receive a netlink message from the kernel on 'sock'. If
244 * successful, stores the received message into '*bufp' and returns 0. The
245 * caller is responsible for destroying the message with buffer_delete(). On
246 * failure, returns a positive errno value and stores a null pointer into
249 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
250 * returns EAGAIN if the 'sock' receive buffer is empty. */
252 nl_sock_recv(struct nl_sock *sock, struct buffer **bufp, bool wait)
255 ssize_t bufsize = 2048;
256 ssize_t nbytes, nbytes2;
258 struct nlmsghdr *nlmsghdr;
260 struct msghdr msg = {
270 buf = buffer_new(bufsize);
274 /* Attempt to read the message. We don't know the size of the data
275 * yet, so we take a guess at 2048. If we're wrong, we keep trying
276 * and doubling the buffer size each time.
278 nlmsghdr = buffer_put_uninit(buf, bufsize);
279 iov.iov_base = nlmsghdr;
280 iov.iov_len = bufsize;
282 nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
283 } while (nbytes < 0 && errno == EINTR);
288 if (msg.msg_flags & MSG_TRUNC) {
290 buffer_reinit(buf, bufsize);
295 /* We successfully read the message, so recv again to clear the queue */
299 nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
300 } while (nbytes2 < 0 && errno == EINTR);
302 if (errno == ENOBUFS) {
303 /* The kernel is notifying us that a message it tried to send to us
304 * was dropped. We have to pass this along to the caller in case
305 * it wants to retry a request. So kill the buffer, which we can
306 * re-read next time. */
310 VLOG_ERR("failed to remove nlmsg from socket: %s\n",
314 if (nbytes < sizeof *nlmsghdr
315 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
316 || nlmsghdr->nlmsg_len > nbytes) {
317 VLOG_ERR("received invalid nlmsg (%zd bytes < %d)",
318 bufsize, NLMSG_HDRLEN);
326 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
327 * successful, stores the reply into '*replyp' and returns 0. The caller is
328 * responsible for destroying the reply with buffer_delete(). On failure,
329 * returns a positive errno value and stores a null pointer into '*replyp'.
331 * Bare Netlink is an unreliable transport protocol. This function layers
332 * reliable delivery and reply semantics on top of bare Netlink.
334 * In Netlink, sending a request to the kernel is reliable enough, because the
335 * kernel will tell us if the message cannot be queued (and we will in that
336 * case put it on the transmit queue and wait until it can be delivered).
338 * Receiving the reply is the real problem: if the socket buffer is full when
339 * the kernel tries to send the reply, the reply will be dropped. However, the
340 * kernel sets a flag that a reply has been dropped. The next call to recv
341 * then returns ENOBUFS. We can then re-send the request.
345 * 1. Netlink depends on sequence numbers to match up requests and
346 * replies. The sender of a request supplies a sequence number, and
347 * the reply echos back that sequence number.
349 * This is fine, but (1) some kernel netlink implementations are
350 * broken, in that they fail to echo sequence numbers and (2) this
351 * function will drop packets with non-matching sequence numbers, so
352 * that only a single request can be usefully transacted at a time.
354 * 2. Resending the request causes it to be re-executed, so the request
355 * needs to be idempotent.
358 nl_sock_transact(struct nl_sock *sock,
359 const struct buffer *request, struct buffer **replyp)
361 uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
362 struct nlmsghdr *nlmsghdr;
363 struct buffer *reply;
368 /* Ensure that we get a reply even if this message doesn't ordinarily call
370 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
373 retval = nl_sock_send(sock, request, true);
379 retval = nl_sock_recv(sock, &reply, true);
381 if (retval == ENOBUFS) {
382 VLOG_DBG("receive buffer overflow, resending request");
388 nlmsghdr = nl_msg_nlmsghdr(reply);
389 if (seq != nlmsghdr->nlmsg_seq) {
390 VLOG_DBG("ignoring seq %"PRIu32" != expected %"PRIu32,
391 nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
392 buffer_delete(reply);
395 if (nl_msg_nlmsgerr(reply, &retval)) {
397 VLOG_DBG("received NAK error=%d (%s)", retval, strerror(retval));
399 return retval != EAGAIN ? retval : EPROTO;
406 /* Returns 'sock''s underlying file descriptor. */
408 nl_sock_fd(const struct nl_sock *sock)
413 /* Netlink messages. */
415 /* Returns the nlmsghdr at the head of 'msg'.
417 * 'msg' must be at least as large as a nlmsghdr. */
419 nl_msg_nlmsghdr(const struct buffer *msg)
421 return buffer_at_assert(msg, 0, NLMSG_HDRLEN);
424 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
426 * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
427 * and a genlmsghdr. */
429 nl_msg_genlmsghdr(const struct buffer *msg)
431 return buffer_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
434 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
435 * message, otherwise a positive errno value, and returns true. If 'buffer' is
436 * not an NLMSG_ERROR message, returns false.
438 * 'msg' must be at least as large as a nlmsghdr. */
440 nl_msg_nlmsgerr(const struct buffer *msg, int *errorp)
442 if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
443 struct nlmsgerr *err = buffer_at(msg, NLMSG_HDRLEN, sizeof *err);
446 VLOG_ERR("received invalid nlmsgerr (%zd bytes < %zd)",
447 msg->size, NLMSG_HDRLEN + sizeof *err);
448 } else if (err->error <= 0 && err->error > INT_MIN) {
460 /* Ensures that 'b' has room for at least 'size' bytes plus netlink pading at
461 * its tail end, reallocating and copying its data if necessary. */
463 nl_msg_reserve(struct buffer *msg, size_t size)
465 buffer_reserve_tailroom(msg, NLMSG_ALIGN(size));
468 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
469 * Uses the given 'type' and 'flags'. 'sock' is used to obtain a PID and
470 * sequence number for proper routing of replies. 'expected_payload' should be
471 * an estimate of the number of payload bytes to be supplied; if the size of
472 * the payload is unknown a value of 0 is acceptable.
474 * 'type' is ordinarily an enumerated value specific to the Netlink protocol
475 * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol). For Generic Netlink, 'type'
476 * is the family number obtained via nl_lookup_genl_family().
478 * 'flags' is a bit-mask that indicates what kind of request is being made. It
479 * is often NLM_F_REQUEST indicating that a request is being made, commonly
480 * or'd with NLM_F_ACK to request an acknowledgement.
482 * nl_msg_put_genlmsghdr is more convenient for composing a Generic Netlink
485 nl_msg_put_nlmsghdr(struct buffer *msg, struct nl_sock *sock,
486 size_t expected_payload, uint32_t type, uint32_t flags)
488 struct nlmsghdr *nlmsghdr;
490 assert(msg->size == 0);
492 nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
493 nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
494 nlmsghdr->nlmsg_len = 0;
495 nlmsghdr->nlmsg_type = type;
496 nlmsghdr->nlmsg_flags = flags;
497 nlmsghdr->nlmsg_seq = ++next_seq;
498 nlmsghdr->nlmsg_pid = sock->pid;
501 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
502 * initially empty. 'sock' is used to obtain a PID and sequence number for
503 * proper routing of replies. 'expected_payload' should be an estimate of the
504 * number of payload bytes to be supplied; if the size of the payload is
505 * unknown a value of 0 is acceptable.
507 * 'family' is the family number obtained via nl_lookup_genl_family().
509 * 'flags' is a bit-mask that indicates what kind of request is being made. It
510 * is often NLM_F_REQUEST indicating that a request is being made, commonly
511 * or'd with NLM_F_ACK to request an acknowledgement.
513 * 'cmd' is an enumerated value specific to the Generic Netlink family
514 * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
516 * 'version' is a version number specific to the family and command (often 1).
518 * nl_msg_put_nlmsghdr should be used to compose Netlink messages that are not
519 * Generic Netlink messages. */
521 nl_msg_put_genlmsghdr(struct buffer *msg, struct nl_sock *sock,
522 size_t expected_payload, int family, uint32_t flags,
523 uint8_t cmd, uint8_t version)
525 struct genlmsghdr *genlmsghdr;
527 nl_msg_put_nlmsghdr(msg, sock, GENL_HDRLEN + expected_payload,
529 assert(msg->size == NLMSG_HDRLEN);
530 genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
531 genlmsghdr->cmd = cmd;
532 genlmsghdr->version = version;
533 genlmsghdr->reserved = 0;
536 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
537 * the tail end of 'msg'. Data in 'msg' is reallocated and copied if
540 nl_msg_put(struct buffer *msg, const void *data, size_t size)
542 memcpy(nl_msg_put_uninit(msg, size), data, size);
545 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
546 * end of 'msg', reallocating and copying its data if necessary. Returns a
547 * pointer to the first byte of the new data, which is left uninitialized. */
549 nl_msg_put_uninit(struct buffer *msg, size_t size)
551 size_t pad = NLMSG_ALIGN(size) - size;
552 char *p = buffer_put_uninit(msg, size + pad);
554 memset(p + size, 0, pad);
559 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
560 * data as its payload, plus Netlink padding if needed, to the tail end of
561 * 'msg', reallocating and copying its data if necessary. Returns a pointer to
562 * the first byte of data in the attribute, which is left uninitialized. */
564 nl_msg_put_unspec_uninit(struct buffer *msg, uint16_t type, size_t size)
566 size_t total_size = NLA_HDRLEN + size;
567 struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
568 assert(NLA_ALIGN(total_size) <= UINT16_MAX);
569 nla->nla_len = total_size;
570 nla->nla_type = type;
574 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
575 * 'data' as its payload, to the tail end of 'msg', reallocating and copying
576 * its data if necessary. Returns a pointer to the first byte of data in the
577 * attribute, which is left uninitialized. */
579 nl_msg_put_unspec(struct buffer *msg, uint16_t type,
580 const void *data, size_t size)
582 memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
585 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
586 * (Some Netlink protocols use the presence or absence of an attribute as a
589 nl_msg_put_flag(struct buffer *msg, uint16_t type)
591 nl_msg_put_unspec(msg, type, NULL, 0);
594 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
597 nl_msg_put_u8(struct buffer *msg, uint16_t type, uint8_t value)
599 nl_msg_put_unspec(msg, type, &value, sizeof value);
602 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
605 nl_msg_put_u16(struct buffer *msg, uint16_t type, uint16_t value)
607 nl_msg_put_unspec(msg, type, &value, sizeof value);
610 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
613 nl_msg_put_u32(struct buffer *msg, uint16_t type, uint32_t value)
615 nl_msg_put_unspec(msg, type, &value, sizeof value);
618 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
621 nl_msg_put_u64(struct buffer *msg, uint16_t type, uint64_t value)
623 nl_msg_put_unspec(msg, type, &value, sizeof value);
626 /* Appends a Netlink attribute of the given 'type' and the given
627 * null-terminated string 'value' to 'msg'. */
629 nl_msg_put_string(struct buffer *msg, uint16_t type, const char *value)
631 nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
634 /* Appends a Netlink attribute of the given 'type' and the given buffered
635 * netlink message in 'nested_msg' to 'msg'. The nlmsg_len field in
636 * 'nested_msg' is finalized to match 'nested_msg->size'. */
638 nl_msg_put_nested(struct buffer *msg,
639 uint16_t type, struct buffer *nested_msg)
641 nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
642 nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
645 /* Returns the first byte in the payload of attribute 'nla'. */
647 nl_attr_get(const struct nlattr *nla)
649 assert(nla->nla_len >= NLA_HDRLEN);
653 /* Returns the number of bytes in the payload of attribute 'nla'. */
655 nl_attr_get_size(const struct nlattr *nla)
657 assert(nla->nla_len >= NLA_HDRLEN);
658 return nla->nla_len - NLA_HDRLEN;
661 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
662 * first byte of the payload. */
664 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
666 assert(nla->nla_len >= NLA_HDRLEN + size);
670 /* Returns true if 'nla' is nonnull. (Some Netlink protocols use the presence
671 * or absence of an attribute as a Boolean flag.) */
673 nl_attr_get_flag(const struct nlattr *nla)
678 #define NL_ATTR_GET_AS(NLA, TYPE) \
679 (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
681 /* Returns the 8-bit value in 'nla''s payload.
683 * Asserts that 'nla''s payload is at least 1 byte long. */
685 nl_attr_get_u8(const struct nlattr *nla)
687 return NL_ATTR_GET_AS(nla, uint8_t);
690 /* Returns the 16-bit value in 'nla''s payload.
692 * Asserts that 'nla''s payload is at least 2 bytes long. */
694 nl_attr_get_u16(const struct nlattr *nla)
696 return NL_ATTR_GET_AS(nla, uint16_t);
699 /* Returns the 32-bit value in 'nla''s payload.
701 * Asserts that 'nla''s payload is at least 4 bytes long. */
703 nl_attr_get_u32(const struct nlattr *nla)
705 return NL_ATTR_GET_AS(nla, uint32_t);
708 /* Returns the 64-bit value in 'nla''s payload.
710 * Asserts that 'nla''s payload is at least 8 bytes long. */
712 nl_attr_get_u64(const struct nlattr *nla)
714 return NL_ATTR_GET_AS(nla, uint64_t);
717 /* Returns the null-terminated string value in 'nla''s payload.
719 * Asserts that 'nla''s payload contains a null-terminated string. */
721 nl_attr_get_string(const struct nlattr *nla)
723 assert(nla->nla_len > NLA_HDRLEN);
724 assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
725 return nl_attr_get(nla);
728 /* Default minimum and maximum payload sizes for each type of attribute. */
729 static const size_t attr_len_range[][2] = {
730 [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
731 [NL_A_U8] = { 1, 1 },
732 [NL_A_U16] = { 2, 2 },
733 [NL_A_U32] = { 4, 4 },
734 [NL_A_U64] = { 8, 8 },
735 [NL_A_STRING] = { 1, SIZE_MAX },
736 [NL_A_FLAG] = { 0, SIZE_MAX },
737 [NL_A_NESTED] = { NLMSG_HDRLEN, SIZE_MAX },
740 /* Parses the Generic Netlink payload of 'msg' as a sequence of Netlink
741 * attributes. 'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
742 * with nla_type == i is parsed; a pointer to attribute i is stored in
743 * attrs[i]. Returns true if successful, false on failure. */
745 nl_policy_parse(const struct buffer *msg, const struct nl_policy policy[],
746 struct nlattr *attrs[], size_t n_attrs)
753 for (i = 0; i < n_attrs; i++) {
756 assert(policy[i].type < N_NL_ATTR_TYPES);
757 if (policy[i].type != NL_A_NO_ATTR
758 && policy[i].type != NL_A_FLAG
759 && !policy[i].optional) {
764 p = buffer_at(msg, NLMSG_HDRLEN + GENL_HDRLEN, 0);
766 VLOG_DBG("missing headers in nl_policy_parse");
769 tail = buffer_tail(msg);
772 size_t offset = p - msg->data;
773 struct nlattr *nla = p;
774 size_t len, aligned_len;
777 /* Make sure its claimed length is plausible. */
778 if (nla->nla_len < NLA_HDRLEN) {
779 VLOG_DBG("%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
780 offset, nla->nla_len);
783 len = nla->nla_len - NLA_HDRLEN;
784 aligned_len = NLA_ALIGN(len);
785 if (aligned_len > tail - p) {
786 VLOG_DBG("%zu: attr %"PRIu16" aligned data len (%zu) "
787 "> bytes left (%tu)",
788 offset, nla->nla_type, aligned_len, tail - p);
792 type = nla->nla_type;
793 if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
794 const struct nl_policy *p = &policy[type];
795 size_t min_len, max_len;
797 /* Validate length and content. */
798 min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
799 max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
800 if (len < min_len || len > max_len) {
801 VLOG_DBG("%zu: attr %"PRIu16" length %zu not in allowed range "
802 "%zu...%zu", offset, type, len, min_len, max_len);
805 if (p->type == NL_A_STRING) {
806 if (((char *) nla)[nla->nla_len - 1]) {
807 VLOG_DBG("%zu: attr %"PRIu16" lacks null terminator",
811 if (memchr(nla + 1, '\0', len - 1) != NULL) {
812 VLOG_DBG("%zu: attr %"PRIu16" lies about string length",
817 if (!p->optional && attrs[type] == NULL) {
818 assert(n_required > 0);
823 /* Skip attribute type that we don't care about. */
825 p += NLA_ALIGN(nla->nla_len);
828 VLOG_DBG("%zu required attrs missing", n_required);
836 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
837 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
840 static int do_lookup_genl_family(const char *name)
842 struct nl_sock *sock;
843 struct buffer request, *reply;
844 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
847 retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
852 buffer_init(&request, 0);
853 nl_msg_put_genlmsghdr(&request, sock, 0, GENL_ID_CTRL, NLM_F_REQUEST,
854 CTRL_CMD_GETFAMILY, 1);
855 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
856 retval = nl_sock_transact(sock, &request, &reply);
857 buffer_uninit(&request);
859 nl_sock_destroy(sock);
863 if (!nl_policy_parse(reply, family_policy, attrs,
864 ARRAY_SIZE(family_policy))) {
865 nl_sock_destroy(sock);
866 buffer_delete(reply);
870 retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
874 nl_sock_destroy(sock);
875 buffer_delete(reply);
879 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
880 * number and stores it in '*number'. If successful, returns 0 and the caller
881 * may use '*number' as the family number. On failure, returns a positive
882 * errno value and '*number' caches the errno value. */
884 nl_lookup_genl_family(const char *name, int *number)
887 *number = do_lookup_genl_family(name);
888 assert(*number != 0);
890 return *number > 0 ? 0 : -*number;
895 * Every Netlink socket must be bound to a unique 32-bit PID. By convention,
896 * programs that have a single Netlink socket use their Unix process ID as PID,
897 * and programs with multiple Netlink sockets add a unique per-socket
898 * identifier in the bits above the Unix process ID.
900 * The kernel has Netlink PID 0.
903 /* Parameters for how many bits in the PID should come from the Unix process ID
904 * and how many unique per-socket. */
905 #define SOCKET_BITS 10
906 #define MAX_SOCKETS (1u << SOCKET_BITS)
908 #define PROCESS_BITS (32 - SOCKET_BITS)
909 #define MAX_PROCESSES (1u << PROCESS_BITS)
910 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
912 /* Bit vector of unused socket identifiers. */
913 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
915 /* Allocates and returns a new Netlink PID. */
917 alloc_pid(uint32_t *pid)
921 for (i = 0; i < MAX_SOCKETS; i++) {
922 if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
923 avail_sockets[i / 32] |= 1u << (i % 32);
924 *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
928 VLOG_ERR("netlink pid space exhausted");
932 /* Makes the specified 'pid' available for reuse. */
934 free_pid(uint32_t pid)
936 int sock = pid >> PROCESS_BITS;
937 assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
938 avail_sockets[sock / 32] &= ~(1u << (sock % 32));