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.
47 #define THIS_MODULE VLM_netlink
49 /* Linux header file confusion causes this to be undefined. */
51 #define SOL_NETLINK 270
54 /* Netlink sockets. */
62 /* Next nlmsghdr sequence number.
64 * This implementation uses sequence numbers that are unique process-wide, to
65 * avoid a hypothetical race: send request, close socket, open new socket that
66 * reuses the old socket's PID value, send request on new socket, receive reply
67 * from kernel to old socket but with same PID and sequence number. (This race
68 * could be avoided other ways, e.g. by preventing PIDs from being quickly
70 static uint32_t next_seq;
72 static int alloc_pid(uint32_t *);
73 static void free_pid(uint32_t);
75 /* Creates a new netlink socket for the given netlink 'protocol'
76 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
77 * new socket if successful, otherwise returns a positive errno value.
79 * If 'multicast_group' is nonzero, the new socket subscribes to the specified
80 * netlink multicast group. (A netlink socket may listen to an arbitrary
81 * number of multicast groups, but so far we only need one at a time.)
83 * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
84 * receive buffer size, respectively.
87 nl_sock_create(int protocol, int multicast_group,
88 size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
91 struct sockaddr_nl local, remote;
95 /* Pick initial sequence number. */
96 next_seq = getpid() ^ time(0);
100 sock = malloc(sizeof *sock);
105 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
107 VLOG_ERR("fcntl: %s", strerror(errno));
111 retval = alloc_pid(&sock->pid);
117 && setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
118 &so_sndbuf, sizeof so_sndbuf) < 0) {
119 VLOG_ERR("setsockopt(SO_SNDBUF,%zu): %s", so_sndbuf, strerror(errno));
124 && setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
125 &so_rcvbuf, sizeof so_rcvbuf) < 0) {
126 VLOG_ERR("setsockopt(SO_RCVBUF,%zu): %s", so_rcvbuf, strerror(errno));
130 /* Bind local address as our selected pid. */
131 memset(&local, 0, sizeof local);
132 local.nl_family = AF_NETLINK;
133 local.nl_pid = sock->pid;
134 if (multicast_group > 0 && multicast_group <= 32) {
135 /* This method of joining multicast groups is supported by old kernels,
136 * but it only allows 32 multicast groups per protocol. */
137 local.nl_groups |= 1ul << (multicast_group - 1);
139 if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
140 VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
144 /* Bind remote address as the kernel (pid 0). */
145 memset(&remote, 0, sizeof remote);
146 remote.nl_family = AF_NETLINK;
148 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
149 VLOG_ERR("connect(0): %s", strerror(errno));
153 /* Older kernel headers failed to define this macro. We want our programs
154 * to support the newer kernel features even if compiled with older
155 * headers, so define it ourselves in such a case. */
156 #ifndef NETLINK_ADD_MEMBERSHIP
157 #define NETLINK_ADD_MEMBERSHIP 1
160 /* This method of joining multicast groups is only supported by newish
161 * kernels, but it allows for an arbitrary number of multicast groups. */
162 if (multicast_group > 32
163 && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
164 &multicast_group, sizeof multicast_group) < 0) {
165 VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
166 multicast_group, strerror(errno));
189 /* Destroys netlink socket 'sock'. */
191 nl_sock_destroy(struct nl_sock *sock)
200 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
201 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size before the
204 * Returns 0 if successful, otherwise a positive errno value. If
205 * 'wait' is true, then the send will wait until buffer space is ready;
206 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
208 nl_sock_send(struct nl_sock *sock, const struct buffer *msg, bool wait)
212 nl_msg_nlmsghdr(msg)->nlmsg_len = msg->size;
214 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
215 } while (retval < 0 && errno == EINTR);
216 return retval < 0 ? errno : 0;
219 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
220 * a single Netlink message. (The message must be fully formed and not require
221 * finalization of its nlmsg_len field.)
223 * Returns 0 if successful, otherwise a positive errno value. If 'wait' is
224 * true, then the send will wait until buffer space is ready; otherwise,
225 * returns EAGAIN if the 'sock' send buffer is full. */
227 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
233 memset(&msg, 0, sizeof msg);
234 msg.msg_iov = (struct iovec *) iov;
235 msg.msg_iovlen = n_iov;
237 retval = sendmsg(sock->fd, &msg, MSG_DONTWAIT);
238 } while (retval < 0 && errno == EINTR);
239 return retval < 0 ? errno : 0;
242 /* Tries to receive a netlink message from the kernel on 'sock'. If
243 * successful, stores the received message into '*bufp' and returns 0. The
244 * caller is responsible for destroying the message with buffer_delete(). On
245 * failure, returns a positive errno value and stores a null pointer into
248 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
249 * returns EAGAIN if the 'sock' receive buffer is empty. */
251 nl_sock_recv(struct nl_sock *sock, struct buffer **bufp, bool wait)
254 ssize_t bufsize = 2048;
255 ssize_t nbytes, nbytes2;
257 struct nlmsghdr *nlmsghdr;
259 struct msghdr msg = {
269 buf = buffer_new(bufsize);
273 /* Attempt to read the message. We don't know the size of the data
274 * yet, so we take a guess at 2048. If we're wrong, we keep trying
275 * and doubling the buffer size each time.
277 nlmsghdr = buffer_put_uninit(buf, bufsize);
278 iov.iov_base = nlmsghdr;
279 iov.iov_len = bufsize;
281 nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
282 } while (nbytes < 0 && errno == EINTR);
287 if (msg.msg_flags & MSG_TRUNC) {
289 buffer_reinit(buf, bufsize);
294 /* We successfully read the message, so recv again to clear the queue */
298 nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
300 VLOG_ERR("failed to remove nlmsg from socket: %d\n", errno);
302 } while (nbytes2 < 0 && errno == EINTR);
304 if (!NLMSG_OK(nlmsghdr, nbytes)) {
305 VLOG_ERR("received invalid nlmsg (%zd bytes < %d)",
306 bufsize, NLMSG_HDRLEN);
314 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
315 * successful, stores the reply into '*replyp' and returns 0. The caller is
316 * responsible for destroying the reply with buffer_delete(). On failure,
317 * returns a positive errno value and stores a null pointer into '*replyp'.
319 * Bare Netlink is an unreliable transport protocol. This function layers
320 * reliable delivery and reply semantics on top of bare Netlink.
322 * In Netlink, sending a request to the kernel is reliable enough, because the
323 * kernel will tell us if the message cannot be queued (and we will in that
324 * case put it on the transmit queue and wait until it can be delivered).
326 * Receiving the reply is the real problem: if the socket buffer is full when
327 * the kernel tries to send the reply, the reply will be dropped. However, the
328 * kernel sets a flag that a reply has been dropped. The next call to recv
329 * then returns ENOBUFS. We can then re-send the request.
333 * 1. Netlink depends on sequence numbers to match up requests and
334 * replies. The sender of a request supplies a sequence number, and
335 * the reply echos back that sequence number.
337 * This is fine, but (1) some kernel netlink implementations are
338 * broken, in that they fail to echo sequence numbers and (2) this
339 * function will drop packets with non-matching sequence numbers, so
340 * that only a single request can be usefully transacted at a time.
342 * 2. Resending the request causes it to be re-executed, so the request
343 * needs to be idempotent.
346 nl_sock_transact(struct nl_sock *sock,
347 const struct buffer *request, struct buffer **replyp)
349 uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
350 struct nlmsghdr *nlmsghdr;
351 struct buffer *reply;
356 /* Ensure that we get a reply even if this message doesn't ordinarily call
358 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
361 retval = nl_sock_send(sock, request, true);
367 retval = nl_sock_recv(sock, &reply, true);
369 if (retval == ENOBUFS) {
370 VLOG_DBG("receive buffer overflow, resending request");
376 nlmsghdr = nl_msg_nlmsghdr(reply);
377 if (seq != nlmsghdr->nlmsg_seq) {
378 VLOG_DBG("ignoring seq %"PRIu32" != expected %"PRIu32,
379 nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
380 buffer_delete(reply);
383 if (nl_msg_nlmsgerr(reply, &retval)) {
385 VLOG_DBG("received NAK error=%d (%s)", retval, strerror(retval));
387 return retval != EAGAIN ? retval : EPROTO;
394 /* Returns 'sock''s underlying file descriptor. */
396 nl_sock_fd(const struct nl_sock *sock)
401 /* Netlink messages. */
403 /* Returns the nlmsghdr at the head of 'msg'.
405 * 'msg' must be at least as large as a nlmsghdr. */
407 nl_msg_nlmsghdr(const struct buffer *msg)
409 return buffer_at_assert(msg, 0, NLMSG_HDRLEN);
412 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
414 * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
415 * and a genlmsghdr. */
417 nl_msg_genlmsghdr(const struct buffer *msg)
419 return buffer_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
422 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
423 * message, otherwise a positive errno value, and returns true. If 'buffer' is
424 * not an NLMSG_ERROR message, returns false.
426 * 'msg' must be at least as large as a nlmsghdr. */
428 nl_msg_nlmsgerr(const struct buffer *msg, int *errorp)
430 if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
431 struct nlmsgerr *err = buffer_at(msg, NLMSG_HDRLEN, sizeof *err);
434 VLOG_ERR("received invalid nlmsgerr (%zd bytes < %zd)",
435 msg->size, NLMSG_HDRLEN + sizeof *err);
436 } else if (err->error <= 0 && err->error > INT_MIN) {
448 /* Ensures that 'b' has room for at least 'size' bytes plus netlink pading at
449 * its tail end, reallocating and copying its data if necessary. */
451 nl_msg_reserve(struct buffer *msg, size_t size)
453 buffer_reserve_tailroom(msg, NLMSG_ALIGN(size));
456 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
457 * Uses the given 'type' and 'flags'. 'sock' is used to obtain a PID and
458 * sequence number for proper routing of replies. 'expected_payload' should be
459 * an estimate of the number of payload bytes to be supplied; if the size of
460 * the payload is unknown a value of 0 is acceptable.
462 * 'type' is ordinarily an enumerated value specific to the Netlink protocol
463 * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol). For Generic Netlink, 'type'
464 * is the family number obtained via nl_lookup_genl_family().
466 * 'flags' is a bit-mask that indicates what kind of request is being made. It
467 * is often NLM_F_REQUEST indicating that a request is being made, commonly
468 * or'd with NLM_F_ACK to request an acknowledgement.
470 * nl_msg_put_genlmsghdr is more convenient for composing a Generic Netlink
473 nl_msg_put_nlmsghdr(struct buffer *msg, struct nl_sock *sock,
474 size_t expected_payload, uint32_t type, uint32_t flags)
476 struct nlmsghdr *nlmsghdr;
478 assert(msg->size == 0);
480 nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
481 nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
482 nlmsghdr->nlmsg_len = 0;
483 nlmsghdr->nlmsg_type = type;
484 nlmsghdr->nlmsg_flags = flags;
485 nlmsghdr->nlmsg_seq = ++next_seq;
486 nlmsghdr->nlmsg_pid = sock->pid;
489 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
490 * initially empty. 'sock' is used to obtain a PID and sequence number for
491 * proper routing of replies. 'expected_payload' should be an estimate of the
492 * number of payload bytes to be supplied; if the size of the payload is
493 * unknown a value of 0 is acceptable.
495 * 'family' is the family number obtained via nl_lookup_genl_family().
497 * 'flags' is a bit-mask that indicates what kind of request is being made. It
498 * is often NLM_F_REQUEST indicating that a request is being made, commonly
499 * or'd with NLM_F_ACK to request an acknowledgement.
501 * 'cmd' is an enumerated value specific to the Generic Netlink family
502 * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
504 * 'version' is a version number specific to the family and command (often 1).
506 * nl_msg_put_nlmsghdr should be used to compose Netlink messages that are not
507 * Generic Netlink messages. */
509 nl_msg_put_genlmsghdr(struct buffer *msg, struct nl_sock *sock,
510 size_t expected_payload, int family, uint32_t flags,
511 uint8_t cmd, uint8_t version)
513 struct genlmsghdr *genlmsghdr;
515 nl_msg_put_nlmsghdr(msg, sock, GENL_HDRLEN + expected_payload,
517 assert(msg->size == NLMSG_HDRLEN);
518 genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
519 genlmsghdr->cmd = cmd;
520 genlmsghdr->version = version;
521 genlmsghdr->reserved = 0;
524 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
525 * the tail end of 'msg'. Data in 'msg' is reallocated and copied if
528 nl_msg_put(struct buffer *msg, const void *data, size_t size)
530 memcpy(nl_msg_put_uninit(msg, size), data, size);
533 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
534 * end of 'msg', reallocating and copying its data if necessary. Returns a
535 * pointer to the first byte of the new data, which is left uninitialized. */
537 nl_msg_put_uninit(struct buffer *msg, size_t size)
539 size_t pad = NLMSG_ALIGN(size) - size;
540 char *p = buffer_put_uninit(msg, size + pad);
542 memset(p + size, 0, pad);
547 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
548 * data as its payload, plus Netlink padding if needed, to the tail end of
549 * 'msg', reallocating and copying its data if necessary. Returns a pointer to
550 * the first byte of data in the attribute, which is left uninitialized. */
552 nl_msg_put_unspec_uninit(struct buffer *msg, uint16_t type, size_t size)
554 size_t total_size = NLA_HDRLEN + size;
555 struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
556 assert(NLA_ALIGN(total_size) <= UINT16_MAX);
557 nla->nla_len = total_size;
558 nla->nla_type = type;
562 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
563 * 'data' as its payload, to the tail end of 'msg', reallocating and copying
564 * its data if necessary. Returns a pointer to the first byte of data in the
565 * attribute, which is left uninitialized. */
567 nl_msg_put_unspec(struct buffer *msg, uint16_t type,
568 const void *data, size_t size)
570 memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
573 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
574 * (Some Netlink protocols use the presence or absence of an attribute as a
577 nl_msg_put_flag(struct buffer *msg, uint16_t type)
579 nl_msg_put_unspec(msg, type, NULL, 0);
582 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
585 nl_msg_put_u8(struct buffer *msg, uint16_t type, uint8_t value)
587 nl_msg_put_unspec(msg, type, &value, sizeof value);
590 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
593 nl_msg_put_u16(struct buffer *msg, uint16_t type, uint16_t value)
595 nl_msg_put_unspec(msg, type, &value, sizeof value);
598 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
601 nl_msg_put_u32(struct buffer *msg, uint16_t type, uint32_t value)
603 nl_msg_put_unspec(msg, type, &value, sizeof value);
606 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
609 nl_msg_put_u64(struct buffer *msg, uint16_t type, uint64_t value)
611 nl_msg_put_unspec(msg, type, &value, sizeof value);
614 /* Appends a Netlink attribute of the given 'type' and the given
615 * null-terminated string 'value' to 'msg'. */
617 nl_msg_put_string(struct buffer *msg, uint16_t type, const char *value)
619 nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
622 /* Appends a Netlink attribute of the given 'type' and the given buffered
623 * netlink message in 'nested_msg' to 'msg'. The nlmsg_len field in
624 * 'nested_msg' is finalized to match 'nested_msg->size'. */
626 nl_msg_put_nested(struct buffer *msg,
627 uint16_t type, struct buffer *nested_msg)
629 nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
630 nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
633 /* Returns the first byte in the payload of attribute 'nla'. */
635 nl_attr_get(const struct nlattr *nla)
637 assert(nla->nla_len >= NLA_HDRLEN);
641 /* Returns the number of bytes in the payload of attribute 'nla'. */
643 nl_attr_get_size(const struct nlattr *nla)
645 assert(nla->nla_len >= NLA_HDRLEN);
646 return nla->nla_len - NLA_HDRLEN;
649 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
650 * first byte of the payload. */
652 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
654 assert(nla->nla_len >= NLA_HDRLEN + size);
658 /* Returns true if 'nla' is nonnull. (Some Netlink protocols use the presence
659 * or absence of an attribute as a Boolean flag.) */
661 nl_attr_get_flag(const struct nlattr *nla)
666 #define NL_ATTR_GET_AS(NLA, TYPE) \
667 (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
669 /* Returns the 8-bit value in 'nla''s payload.
671 * Asserts that 'nla''s payload is at least 1 byte long. */
673 nl_attr_get_u8(const struct nlattr *nla)
675 return NL_ATTR_GET_AS(nla, uint8_t);
678 /* Returns the 16-bit value in 'nla''s payload.
680 * Asserts that 'nla''s payload is at least 2 bytes long. */
682 nl_attr_get_u16(const struct nlattr *nla)
684 return NL_ATTR_GET_AS(nla, uint16_t);
687 /* Returns the 32-bit value in 'nla''s payload.
689 * Asserts that 'nla''s payload is at least 4 bytes long. */
691 nl_attr_get_u32(const struct nlattr *nla)
693 return NL_ATTR_GET_AS(nla, uint32_t);
696 /* Returns the 64-bit value in 'nla''s payload.
698 * Asserts that 'nla''s payload is at least 8 bytes long. */
700 nl_attr_get_u64(const struct nlattr *nla)
702 return NL_ATTR_GET_AS(nla, uint64_t);
705 /* Returns the null-terminated string value in 'nla''s payload.
707 * Asserts that 'nla''s payload contains a null-terminated string. */
709 nl_attr_get_string(const struct nlattr *nla)
711 assert(nla->nla_len > NLA_HDRLEN);
712 assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
713 return nl_attr_get(nla);
716 /* Default minimum and maximum payload sizes for each type of attribute. */
717 static const size_t attr_len_range[][2] = {
718 [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
719 [NL_A_U8] = { 1, 1 },
720 [NL_A_U16] = { 2, 2 },
721 [NL_A_U32] = { 4, 4 },
722 [NL_A_U64] = { 8, 8 },
723 [NL_A_STRING] = { 1, SIZE_MAX },
724 [NL_A_FLAG] = { 0, SIZE_MAX },
725 [NL_A_NESTED] = { NLMSG_HDRLEN, SIZE_MAX },
728 /* Parses the Generic Netlink payload of 'msg' as a sequence of Netlink
729 * attributes. 'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
730 * with nla_type == i is parsed; a pointer to attribute i is stored in
731 * attrs[i]. Returns true if successful, false on failure. */
733 nl_policy_parse(const struct buffer *msg, const struct nl_policy policy[],
734 struct nlattr *attrs[], size_t n_attrs)
741 for (i = 0; i < n_attrs; i++) {
744 assert(policy[i].type < N_NL_ATTR_TYPES);
745 if (policy[i].type != NL_A_NO_ATTR
746 && policy[i].type != NL_A_FLAG
747 && !policy[i].optional) {
752 p = buffer_at(msg, NLMSG_HDRLEN + GENL_HDRLEN, 0);
754 VLOG_DBG("missing headers in nl_policy_parse");
757 tail = buffer_tail(msg);
760 size_t offset = p - msg->data;
761 struct nlattr *nla = p;
762 size_t len, aligned_len;
765 /* Make sure its claimed length is plausible. */
766 if (nla->nla_len < NLA_HDRLEN) {
767 VLOG_DBG("%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
768 offset, nla->nla_len);
771 len = nla->nla_len - NLA_HDRLEN;
772 aligned_len = NLA_ALIGN(len);
773 if (aligned_len > tail - p) {
774 VLOG_DBG("%zu: attr %"PRIu16" aligned data len (%zu) "
775 "> bytes left (%tu)",
776 offset, nla->nla_type, aligned_len, tail - p);
780 type = nla->nla_type;
781 if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
782 const struct nl_policy *p = &policy[type];
783 size_t min_len, max_len;
785 /* Validate length and content. */
786 min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
787 max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
788 if (len < min_len || len > max_len) {
789 VLOG_DBG("%zu: attr %"PRIu16" length %zu not in allowed range "
790 "%zu...%zu", offset, type, len, min_len, max_len);
793 if (p->type == NL_A_STRING) {
794 if (((char *) nla)[nla->nla_len - 1]) {
795 VLOG_DBG("%zu: attr %"PRIu16" lacks null terminator",
799 if (memchr(nla + 1, '\0', len - 1) != NULL) {
800 VLOG_DBG("%zu: attr %"PRIu16" lies about string length",
805 if (!p->optional && attrs[type] == NULL) {
806 assert(n_required > 0);
811 /* Skip attribute type that we don't care about. */
813 p += NLA_ALIGN(nla->nla_len);
816 VLOG_DBG("%zu required attrs missing", n_required);
824 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
825 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
828 static int do_lookup_genl_family(const char *name)
830 struct nl_sock *sock;
831 struct buffer request, *reply;
832 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
835 retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
840 buffer_init(&request, 0);
841 nl_msg_put_genlmsghdr(&request, sock, 0, GENL_ID_CTRL, NLM_F_REQUEST,
842 CTRL_CMD_GETFAMILY, 1);
843 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
844 retval = nl_sock_transact(sock, &request, &reply);
845 buffer_uninit(&request);
847 nl_sock_destroy(sock);
851 if (!nl_policy_parse(reply, family_policy, attrs,
852 ARRAY_SIZE(family_policy))) {
853 nl_sock_destroy(sock);
854 buffer_delete(reply);
858 retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
862 nl_sock_destroy(sock);
863 buffer_delete(reply);
867 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
868 * number and stores it in '*number'. If successful, returns 0 and the caller
869 * may use '*number' as the family number. On failure, returns a positive
870 * errno value and '*number' caches the errno value. */
872 nl_lookup_genl_family(const char *name, int *number)
875 *number = do_lookup_genl_family(name);
876 assert(*number != 0);
878 return *number > 0 ? 0 : -*number;
883 * Every Netlink socket must be bound to a unique 32-bit PID. By convention,
884 * programs that have a single Netlink socket use their Unix process ID as PID,
885 * and programs with multiple Netlink sockets add a unique per-socket
886 * identifier in the bits above the Unix process ID.
888 * The kernel has Netlink PID 0.
891 /* Parameters for how many bits in the PID should come from the Unix process ID
892 * and how many unique per-socket. */
893 #define SOCKET_BITS 10
894 #define MAX_SOCKETS (1u << SOCKET_BITS)
896 #define PROCESS_BITS (32 - SOCKET_BITS)
897 #define MAX_PROCESSES (1u << PROCESS_BITS)
898 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
900 /* Bit vector of unused socket identifiers. */
901 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
903 /* Allocates and returns a new Netlink PID. */
905 alloc_pid(uint32_t *pid)
909 for (i = 0; i < MAX_SOCKETS; i++) {
910 if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
911 avail_sockets[i / 32] |= 1u << (i % 32);
912 *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
916 VLOG_ERR("netlink pid space exhausted");
920 /* Makes the specified 'pid' available for reuse. */
922 free_pid(uint32_t pid)
924 int sock = pid >> PROCESS_BITS;
925 assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
926 avail_sockets[sock / 32] &= ~(1u << (sock % 32));