1 /* Copyright (C) 2007 Board of Trustees, Leland Stanford Jr. University.
3 * Permission is hereby granted, free of charge, to any person obtaining a copy
4 * of this software and associated documentation files (the "Software"), to
5 * deal in the Software without restriction, including without limitation the
6 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 * sell copies of the Software, and to permit persons to whom the Software is
8 * furnished to do so, subject to the following conditions:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
35 #define THIS_MODULE VLM_netlink
37 /* Linux header file confusion causes this to be undefined. */
39 #define SOL_NETLINK 270
42 /* Netlink sockets. */
50 /* Next nlmsghdr sequence number.
52 * This implementation uses sequence numbers that are unique process-wide, to
53 * avoid a hypothetical race: send request, close socket, open new socket that
54 * reuses the old socket's PID value, send request on new socket, receive reply
55 * from kernel to old socket but with same PID and sequence number. (This race
56 * could be avoided other ways, e.g. by preventing PIDs from being quickly
58 static uint32_t next_seq;
60 static int alloc_pid(uint32_t *);
61 static void free_pid(uint32_t);
63 /* Creates a new netlink socket for the given netlink 'protocol'
64 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
65 * new socket if successful, otherwise returns a positive errno value.
67 * If 'multicast_group' is nonzero, the new socket subscribes to the specified
68 * netlink multicast group. (A netlink socket may listen to an arbitrary
69 * number of multicast groups, but so far we only need one at a time.)
71 * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
72 * receive buffer size, respectively.
75 nl_sock_create(int protocol, int multicast_group,
76 size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
79 struct sockaddr_nl local, remote;
83 /* Pick initial sequence number. */
84 next_seq = getpid() ^ time(0);
88 sock = malloc(sizeof *sock);
93 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
95 VLOG_ERR("fcntl: %s", strerror(errno));
99 retval = alloc_pid(&sock->pid);
105 && setsockopt(sock->fd, SOL_SOCKET, SO_SNDBUF,
106 &so_sndbuf, sizeof so_sndbuf) < 0) {
107 VLOG_ERR("setsockopt(SO_SNDBUF,%zu): %s", so_sndbuf, strerror(errno));
112 && setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUF,
113 &so_rcvbuf, sizeof so_rcvbuf) < 0) {
114 VLOG_ERR("setsockopt(SO_RCVBUF,%zu): %s", so_rcvbuf, strerror(errno));
118 /* Bind local address as our selected pid. */
119 memset(&local, 0, sizeof local);
120 local.nl_family = AF_NETLINK;
121 local.nl_pid = sock->pid;
122 if (multicast_group > 0 && multicast_group <= 32) {
123 /* This method of joining multicast groups is supported by old kernels,
124 * but it only allows 32 multicast groups per protocol. */
125 local.nl_groups |= 1ul << (multicast_group - 1);
127 if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
128 VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
132 /* Bind remote address as the kernel (pid 0). */
133 memset(&remote, 0, sizeof remote);
134 remote.nl_family = AF_NETLINK;
136 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
137 VLOG_ERR("connect(0): %s", strerror(errno));
141 /* This method of joining multicast groups is only supported by newish
142 * kernels, but it allows for an arbitrary number of multicast groups. */
143 if (multicast_group > 32
144 && setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
145 &multicast_group, sizeof multicast_group) < 0) {
146 VLOG_ERR("setsockopt(NETLINK_ADD_MEMBERSHIP,%d): %s",
147 multicast_group, strerror(errno));
170 /* Destroys netlink socket 'sock'. */
172 nl_sock_destroy(struct nl_sock *sock)
181 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
182 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size before the
185 * Returns 0 if successful, otherwise a positive errno value. If
186 * 'wait' is true, then the send will wait until buffer space is ready;
187 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
189 nl_sock_send(struct nl_sock *sock, const struct buffer *msg, bool wait)
193 nl_msg_nlmsghdr(msg)->nlmsg_len = msg->size;
195 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
196 } while (retval < 0 && errno == EINTR);
197 return retval < 0 ? errno : 0;
200 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
201 * a single Netlink message. (The message must be fully formed and not require
202 * finalization of its nlmsg_len field.)
204 * Returns 0 if successful, otherwise a positive errno value. If 'wait' is
205 * true, then the send will wait until buffer space is ready; otherwise,
206 * returns EAGAIN if the 'sock' send buffer is full. */
208 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
214 memset(&msg, 0, sizeof msg);
215 msg.msg_iov = (struct iovec *) iov;
216 msg.msg_iovlen = n_iov;
218 retval = sendmsg(sock->fd, &msg, MSG_DONTWAIT);
219 } while (retval < 0 && errno == EINTR);
220 return retval < 0 ? errno : 0;
223 /* Tries to receive a netlink message from the kernel on 'sock'. If
224 * successful, stores the received message into '*bufp' and returns 0. The
225 * caller is responsible for destroying the message with buffer_delete(). On
226 * failure, returns a positive errno value and stores a null pointer into
229 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
230 * returns EAGAIN if the 'sock' receive buffer is empty. */
232 nl_sock_recv(struct nl_sock *sock, struct buffer **bufp, bool wait)
235 ssize_t bufsize = 2048;
236 ssize_t nbytes, nbytes2;
238 struct nlmsghdr *nlmsghdr;
240 struct msghdr msg = {
250 buf = buffer_new(bufsize);
254 /* Attempt to read the message. We don't know the size of the data
255 * yet, so we take a guess at 2048. If we're wrong, we keep trying
256 * and doubling the buffer size each time.
258 nlmsghdr = buffer_put_uninit(buf, bufsize);
259 iov.iov_base = nlmsghdr;
260 iov.iov_len = bufsize;
262 nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
263 } while (nbytes < 0 && errno == EINTR);
268 if (msg.msg_flags & MSG_TRUNC) {
270 buffer_reinit(buf, bufsize);
275 /* We successfully read the message, so recv again to clear the queue */
279 nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
281 VLOG_ERR("failed to remove nlmsg from socket: %d\n", errno);
283 } while (nbytes2 < 0 && errno == EINTR);
285 if (!NLMSG_OK(nlmsghdr, nbytes)) {
286 VLOG_ERR("received invalid nlmsg (%zd bytes < %d)",
287 bufsize, NLMSG_HDRLEN);
295 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
296 * successful, stores the reply into '*replyp' and returns 0. The caller is
297 * responsible for destroying the reply with buffer_delete(). On failure,
298 * returns a positive errno value and stores a null pointer into '*replyp'.
300 * Bare Netlink is an unreliable transport protocol. This function layers
301 * reliable delivery and reply semantics on top of bare Netlink.
303 * In Netlink, sending a request to the kernel is reliable enough, because the
304 * kernel will tell us if the message cannot be queued (and we will in that
305 * case put it on the transmit queue and wait until it can be delivered).
307 * Receiving the reply is the real problem: if the socket buffer is full when
308 * the kernel tries to send the reply, the reply will be dropped. However, the
309 * kernel sets a flag that a reply has been dropped. The next call to recv
310 * then returns ENOBUFS. We can then re-send the request.
314 * 1. Netlink depends on sequence numbers to match up requests and
315 * replies. The sender of a request supplies a sequence number, and
316 * the reply echos back that sequence number.
318 * This is fine, but (1) some kernel netlink implementations are
319 * broken, in that they fail to echo sequence numbers and (2) this
320 * function will drop packets with non-matching sequence numbers, so
321 * that only a single request can be usefully transacted at a time.
323 * 2. Resending the request causes it to be re-executed, so the request
324 * needs to be idempotent.
327 nl_sock_transact(struct nl_sock *sock,
328 const struct buffer *request, struct buffer **replyp)
330 uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
331 struct nlmsghdr *nlmsghdr;
332 struct buffer *reply;
337 /* Ensure that we get a reply even if this message doesn't ordinarily call
339 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
342 retval = nl_sock_send(sock, request, true);
348 retval = nl_sock_recv(sock, &reply, true);
350 if (retval == ENOBUFS) {
351 VLOG_DBG("receive buffer overflow, resending request");
357 nlmsghdr = nl_msg_nlmsghdr(reply);
358 if (seq != nlmsghdr->nlmsg_seq) {
359 VLOG_DBG("ignoring seq %"PRIu32" != expected %"PRIu32,
360 nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
361 buffer_delete(reply);
364 if (nl_msg_nlmsgerr(reply, &retval)) {
366 VLOG_DBG("received NAK error=%d (%s)", retval, strerror(retval));
368 return retval != EAGAIN ? retval : EPROTO;
375 /* Returns 'sock''s underlying file descriptor. */
377 nl_sock_fd(const struct nl_sock *sock)
382 /* Netlink messages. */
384 /* Returns the nlmsghdr at the head of 'msg'.
386 * 'msg' must be at least as large as a nlmsghdr. */
388 nl_msg_nlmsghdr(const struct buffer *msg)
390 return buffer_at_assert(msg, 0, NLMSG_HDRLEN);
393 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
395 * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
396 * and a genlmsghdr. */
398 nl_msg_genlmsghdr(const struct buffer *msg)
400 return buffer_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
403 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
404 * message, otherwise a positive errno value, and returns true. If 'buffer' is
405 * not an NLMSG_ERROR message, returns false.
407 * 'msg' must be at least as large as a nlmsghdr. */
409 nl_msg_nlmsgerr(const struct buffer *msg, int *errorp)
411 if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
412 struct nlmsgerr *err = buffer_at(msg, NLMSG_HDRLEN, sizeof *err);
415 VLOG_ERR("received invalid nlmsgerr (%zd bytes < %zd)",
416 msg->size, NLMSG_HDRLEN + sizeof *err);
417 } else if (err->error <= 0 && err->error > INT_MIN) {
429 /* Ensures that 'b' has room for at least 'size' bytes plus netlink pading at
430 * its tail end, reallocating and copying its data if necessary. */
432 nl_msg_reserve(struct buffer *msg, size_t size)
434 buffer_reserve_tailroom(msg, NLMSG_ALIGN(size));
437 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
438 * Uses the given 'type' and 'flags'. 'sock' is used to obtain a PID and
439 * sequence number for proper routing of replies. 'expected_payload' should be
440 * an estimate of the number of payload bytes to be supplied; if the size of
441 * the payload is unknown a value of 0 is acceptable.
443 * 'type' is ordinarily an enumerated value specific to the Netlink protocol
444 * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol). For Generic Netlink, 'type'
445 * is the family number obtained via nl_lookup_genl_family().
447 * 'flags' is a bit-mask that indicates what kind of request is being made. It
448 * is often NLM_F_REQUEST indicating that a request is being made, commonly
449 * or'd with NLM_F_ACK to request an acknowledgement.
451 * nl_msg_put_genlmsghdr is more convenient for composing a Generic Netlink
454 nl_msg_put_nlmsghdr(struct buffer *msg, struct nl_sock *sock,
455 size_t expected_payload, uint32_t type, uint32_t flags)
457 struct nlmsghdr *nlmsghdr;
459 assert(msg->size == 0);
461 nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
462 nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
463 nlmsghdr->nlmsg_len = 0;
464 nlmsghdr->nlmsg_type = type;
465 nlmsghdr->nlmsg_flags = flags;
466 nlmsghdr->nlmsg_seq = ++next_seq;
467 nlmsghdr->nlmsg_pid = sock->pid;
470 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
471 * initially empty. 'sock' is used to obtain a PID and sequence number for
472 * proper routing of replies. 'expected_payload' should be an estimate of the
473 * number of payload bytes to be supplied; if the size of the payload is
474 * unknown a value of 0 is acceptable.
476 * 'family' 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 * 'cmd' is an enumerated value specific to the Generic Netlink family
483 * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
485 * 'version' is a version number specific to the family and command (often 1).
487 * nl_msg_put_nlmsghdr should be used to compose Netlink messages that are not
488 * Generic Netlink messages. */
490 nl_msg_put_genlmsghdr(struct buffer *msg, struct nl_sock *sock,
491 size_t expected_payload, int family, uint32_t flags,
492 uint8_t cmd, uint8_t version)
494 struct genlmsghdr *genlmsghdr;
496 nl_msg_put_nlmsghdr(msg, sock, GENL_HDRLEN + expected_payload,
498 assert(msg->size == NLMSG_HDRLEN);
499 genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
500 genlmsghdr->cmd = cmd;
501 genlmsghdr->version = version;
502 genlmsghdr->reserved = 0;
505 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
506 * the tail end of 'msg'. Data in 'msg' is reallocated and copied if
509 nl_msg_put(struct buffer *msg, const void *data, size_t size)
511 memcpy(nl_msg_put_uninit(msg, size), data, size);
514 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
515 * end of 'msg', reallocating and copying its data if necessary. Returns a
516 * pointer to the first byte of the new data, which is left uninitialized. */
518 nl_msg_put_uninit(struct buffer *msg, size_t size)
520 size_t pad = NLMSG_ALIGN(size) - size;
521 char *p = buffer_put_uninit(msg, size + pad);
523 memset(p + size, 0, pad);
528 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
529 * data as its payload, plus Netlink padding if needed, to the tail end of
530 * 'msg', reallocating and copying its data if necessary. Returns a pointer to
531 * the first byte of data in the attribute, which is left uninitialized. */
533 nl_msg_put_unspec_uninit(struct buffer *msg, uint16_t type, size_t size)
535 size_t total_size = NLA_HDRLEN + size;
536 struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
537 assert(NLA_ALIGN(total_size) <= UINT16_MAX);
538 nla->nla_len = total_size;
539 nla->nla_type = type;
543 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
544 * 'data' as its payload, to the tail end of 'msg', reallocating and copying
545 * its data if necessary. Returns a pointer to the first byte of data in the
546 * attribute, which is left uninitialized. */
548 nl_msg_put_unspec(struct buffer *msg, uint16_t type,
549 const void *data, size_t size)
551 memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
554 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
555 * (Some Netlink protocols use the presence or absence of an attribute as a
558 nl_msg_put_flag(struct buffer *msg, uint16_t type)
560 nl_msg_put_unspec(msg, type, NULL, 0);
563 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
566 nl_msg_put_u8(struct buffer *msg, uint16_t type, uint8_t value)
568 nl_msg_put_unspec(msg, type, &value, sizeof value);
571 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
574 nl_msg_put_u16(struct buffer *msg, uint16_t type, uint16_t value)
576 nl_msg_put_unspec(msg, type, &value, sizeof value);
579 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
582 nl_msg_put_u32(struct buffer *msg, uint16_t type, uint32_t value)
584 nl_msg_put_unspec(msg, type, &value, sizeof value);
587 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
590 nl_msg_put_u64(struct buffer *msg, uint16_t type, uint64_t value)
592 nl_msg_put_unspec(msg, type, &value, sizeof value);
595 /* Appends a Netlink attribute of the given 'type' and the given
596 * null-terminated string 'value' to 'msg'. */
598 nl_msg_put_string(struct buffer *msg, uint16_t type, const char *value)
600 nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
603 /* Appends a Netlink attribute of the given 'type' and the given buffered
604 * netlink message in 'nested_msg' to 'msg'. The nlmsg_len field in
605 * 'nested_msg' is finalized to match 'nested_msg->size'. */
607 nl_msg_put_nested(struct buffer *msg,
608 uint16_t type, struct buffer *nested_msg)
610 nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
611 nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
614 /* Returns the first byte in the payload of attribute 'nla'. */
616 nl_attr_get(const struct nlattr *nla)
618 assert(nla->nla_len >= NLA_HDRLEN);
622 /* Returns the number of bytes in the payload of attribute 'nla'. */
624 nl_attr_get_size(const struct nlattr *nla)
626 assert(nla->nla_len >= NLA_HDRLEN);
627 return nla->nla_len - NLA_HDRLEN;
630 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
631 * first byte of the payload. */
633 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
635 assert(nla->nla_len >= NLA_HDRLEN + size);
639 /* Returns true if 'nla' is nonnull. (Some Netlink protocols use the presence
640 * or absence of an attribute as a Boolean flag.) */
642 nl_attr_get_flag(const struct nlattr *nla)
647 #define NL_ATTR_GET_AS(NLA, TYPE) \
648 (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
650 /* Returns the 8-bit value in 'nla''s payload.
652 * Asserts that 'nla''s payload is at least 1 byte long. */
654 nl_attr_get_u8(const struct nlattr *nla)
656 return NL_ATTR_GET_AS(nla, uint8_t);
659 /* Returns the 16-bit value in 'nla''s payload.
661 * Asserts that 'nla''s payload is at least 2 bytes long. */
663 nl_attr_get_u16(const struct nlattr *nla)
665 return NL_ATTR_GET_AS(nla, uint16_t);
668 /* Returns the 32-bit value in 'nla''s payload.
670 * Asserts that 'nla''s payload is at least 4 bytes long. */
672 nl_attr_get_u32(const struct nlattr *nla)
674 return NL_ATTR_GET_AS(nla, uint32_t);
677 /* Returns the 64-bit value in 'nla''s payload.
679 * Asserts that 'nla''s payload is at least 8 bytes long. */
681 nl_attr_get_u64(const struct nlattr *nla)
683 return NL_ATTR_GET_AS(nla, uint64_t);
686 /* Returns the null-terminated string value in 'nla''s payload.
688 * Asserts that 'nla''s payload contains a null-terminated string. */
690 nl_attr_get_string(const struct nlattr *nla)
692 assert(nla->nla_len > NLA_HDRLEN);
693 assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
694 return nl_attr_get(nla);
697 /* Default minimum and maximum payload sizes for each type of attribute. */
698 static const size_t attr_len_range[][2] = {
699 [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
700 [NL_A_U8] = { 1, 1 },
701 [NL_A_U16] = { 2, 2 },
702 [NL_A_U32] = { 4, 4 },
703 [NL_A_U64] = { 8, 8 },
704 [NL_A_STRING] = { 1, SIZE_MAX },
705 [NL_A_FLAG] = { 0, SIZE_MAX },
706 [NL_A_NESTED] = { NLMSG_HDRLEN, SIZE_MAX },
709 /* Parses the Generic Netlink payload of 'msg' as a sequence of Netlink
710 * attributes. 'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
711 * with nla_type == i is parsed; a pointer to attribute i is stored in
712 * attrs[i]. Returns true if successful, false on failure. */
714 nl_policy_parse(const struct buffer *msg, const struct nl_policy policy[],
715 struct nlattr *attrs[], size_t n_attrs)
722 for (i = 0; i < n_attrs; i++) {
725 assert(policy[i].type < N_NL_ATTR_TYPES);
726 if (policy[i].type != NL_A_NO_ATTR
727 && policy[i].type != NL_A_FLAG
728 && !policy[i].optional) {
733 p = buffer_at(msg, NLMSG_HDRLEN + GENL_HDRLEN, 0);
735 VLOG_DBG("missing headers in nl_policy_parse");
738 tail = buffer_tail(msg);
741 size_t offset = p - msg->data;
742 struct nlattr *nla = p;
743 size_t len, aligned_len;
746 /* Make sure its claimed length is plausible. */
747 if (nla->nla_len < NLA_HDRLEN) {
748 VLOG_DBG("%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
749 offset, nla->nla_len);
752 len = nla->nla_len - NLA_HDRLEN;
753 aligned_len = NLA_ALIGN(len);
754 if (aligned_len > tail - p) {
755 VLOG_DBG("%zu: attr %"PRIu16" aligned data len (%zu) "
756 "> bytes left (%tu)",
757 offset, nla->nla_type, aligned_len, tail - p);
761 type = nla->nla_type;
762 if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
763 const struct nl_policy *p = &policy[type];
764 size_t min_len, max_len;
766 /* Validate length and content. */
767 min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
768 max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
769 if (len < min_len || len > max_len) {
770 VLOG_DBG("%zu: attr %"PRIu16" length %zu not in allowed range "
771 "%zu...%zu", offset, type, len, min_len, max_len);
774 if (p->type == NL_A_STRING) {
775 if (((char *) nla)[nla->nla_len - 1]) {
776 VLOG_DBG("%zu: attr %"PRIu16" lacks null terminator",
780 if (memchr(nla + 1, '\0', len - 1) != NULL) {
781 VLOG_DBG("%zu: attr %"PRIu16" lies about string length",
786 if (!p->optional && attrs[type] == NULL) {
787 assert(n_required > 0);
792 /* Skip attribute type that we don't care about. */
794 p += NLA_ALIGN(nla->nla_len);
797 VLOG_DBG("%zu required attrs missing", n_required);
805 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
806 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
809 static int do_lookup_genl_family(const char *name)
811 struct nl_sock *sock;
812 struct buffer request, *reply;
813 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
816 retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
821 buffer_init(&request, 0);
822 nl_msg_put_genlmsghdr(&request, sock, 0, GENL_ID_CTRL, NLM_F_REQUEST,
823 CTRL_CMD_GETFAMILY, 1);
824 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
825 retval = nl_sock_transact(sock, &request, &reply);
826 buffer_uninit(&request);
828 nl_sock_destroy(sock);
832 if (!nl_policy_parse(reply, family_policy, attrs,
833 ARRAY_SIZE(family_policy))) {
834 nl_sock_destroy(sock);
835 buffer_delete(reply);
839 retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
843 nl_sock_destroy(sock);
844 buffer_delete(reply);
848 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
849 * number and stores it in '*number'. If successful, returns 0 and the caller
850 * may use '*number' as the family number. On failure, returns a positive
851 * errno value and '*number' caches the errno value. */
853 nl_lookup_genl_family(const char *name, int *number)
856 *number = do_lookup_genl_family(name);
857 assert(*number != 0);
859 return *number > 0 ? 0 : -*number;
864 * Every Netlink socket must be bound to a unique 32-bit PID. By convention,
865 * programs that have a single Netlink socket use their Unix process ID as PID,
866 * and programs with multiple Netlink sockets add a unique per-socket
867 * identifier in the bits above the Unix process ID.
869 * The kernel has Netlink PID 0.
872 /* Parameters for how many bits in the PID should come from the Unix process ID
873 * and how many unique per-socket. */
874 #define SOCKET_BITS 10
875 #define MAX_SOCKETS (1u << SOCKET_BITS)
877 #define PROCESS_BITS (32 - SOCKET_BITS)
878 #define MAX_PROCESSES (1u << PROCESS_BITS)
879 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
881 /* Bit vector of unused socket identifiers. */
882 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
884 /* Allocates and returns a new Netlink PID. */
886 alloc_pid(uint32_t *pid)
890 for (i = 0; i < MAX_SOCKETS; i++) {
891 if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
892 avail_sockets[i / 32] |= 1u << (i % 32);
893 *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
897 VLOG_ERR("netlink pid space exhausted");
901 /* Makes the specified 'pid' available for reuse. */
903 free_pid(uint32_t pid)
905 int sock = pid >> PROCESS_BITS;
906 assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
907 avail_sockets[sock / 32] &= ~(1u << (sock % 32));