]> git.proxmox.com Git - mirror_ovs.git/blob - lib/netlink.c
ofproto: Only zero stats for non exact-match sub-rules.
[mirror_ovs.git] / lib / netlink.c
1 /*
2 * Copyright (c) 2008, 2009 Nicira Networks.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <config.h>
18 #include "netlink.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <time.h>
26 #include <unistd.h>
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "netlink-protocol.h"
30 #include "ofpbuf.h"
31 #include "poll-loop.h"
32 #include "timeval.h"
33 #include "util.h"
34
35 #include "vlog.h"
36 #define THIS_MODULE VLM_netlink
37
38 /* Linux header file confusion causes this to be undefined. */
39 #ifndef SOL_NETLINK
40 #define SOL_NETLINK 270
41 #endif
42
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);
47
48 static void log_nlmsg(const char *function, int error,
49 const void *message, size_t size);
50 \f
51 /* Netlink sockets. */
52
53 struct nl_sock
54 {
55 int fd;
56 uint32_t pid;
57 };
58
59 /* Next nlmsghdr sequence number.
60 *
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
66 * reused). */
67 static uint32_t next_seq;
68
69 static int alloc_pid(uint32_t *);
70 static void free_pid(uint32_t);
71
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.
75 *
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.)
79 *
80 * Nonzero 'so_sndbuf' or 'so_rcvbuf' override the kernel default send or
81 * receive buffer size, respectively.
82 */
83 int
84 nl_sock_create(int protocol, int multicast_group,
85 size_t so_sndbuf, size_t so_rcvbuf, struct nl_sock **sockp)
86 {
87 struct nl_sock *sock;
88 struct sockaddr_nl local, remote;
89 int retval = 0;
90
91 if (next_seq == 0) {
92 /* Pick initial sequence number. */
93 next_seq = getpid() ^ time_now();
94 }
95
96 *sockp = NULL;
97 sock = malloc(sizeof *sock);
98 if (sock == NULL) {
99 return ENOMEM;
100 }
101
102 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
103 if (sock->fd < 0) {
104 VLOG_ERR("fcntl: %s", strerror(errno));
105 goto error;
106 }
107
108 retval = alloc_pid(&sock->pid);
109 if (retval) {
110 goto error;
111 }
112
113 if (so_sndbuf != 0
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));
117 goto error_free_pid;
118 }
119
120 if (so_rcvbuf != 0
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));
124 goto error_free_pid;
125 }
126
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);
135 }
136 if (bind(sock->fd, (struct sockaddr *) &local, sizeof local) < 0) {
137 VLOG_ERR("bind(%"PRIu32"): %s", sock->pid, strerror(errno));
138 goto error_free_pid;
139 }
140
141 /* Bind remote address as the kernel (pid 0). */
142 memset(&remote, 0, sizeof remote);
143 remote.nl_family = AF_NETLINK;
144 remote.nl_pid = 0;
145 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
146 VLOG_ERR("connect(0): %s", strerror(errno));
147 goto error_free_pid;
148 }
149
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
155 #endif
156
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));
164 goto error_free_pid;
165 }
166
167 *sockp = sock;
168 return 0;
169
170 error_free_pid:
171 free_pid(sock->pid);
172 error:
173 if (retval == 0) {
174 retval = errno;
175 if (retval == 0) {
176 retval = EINVAL;
177 }
178 }
179 if (sock->fd >= 0) {
180 close(sock->fd);
181 }
182 free(sock);
183 return retval;
184 }
185
186 /* Destroys netlink socket 'sock'. */
187 void
188 nl_sock_destroy(struct nl_sock *sock)
189 {
190 if (sock) {
191 close(sock->fd);
192 free_pid(sock->pid);
193 free(sock);
194 }
195 }
196
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 before the
199 * message is sent.
200 *
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. */
204 int
205 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
206 {
207 int error;
208
209 nl_msg_nlmsghdr(msg)->nlmsg_len = msg->size;
210 do {
211 int retval;
212 retval = send(sock->fd, msg->data, msg->size, wait ? 0 : MSG_DONTWAIT);
213 error = retval < 0 ? errno : 0;
214 } while (error == EINTR);
215 log_nlmsg(__func__, error, msg->data, msg->size);
216 if (!error) {
217 COVERAGE_INC(netlink_sent);
218 }
219 return error;
220 }
221
222 /* Tries to send the 'n_iov' chunks of data in 'iov' to the kernel on 'sock' as
223 * a single Netlink message. (The message must be fully formed and not require
224 * finalization of its nlmsg_len field.)
225 *
226 * Returns 0 if successful, otherwise a positive errno value. If 'wait' is
227 * true, then the send will wait until buffer space is ready; otherwise,
228 * returns EAGAIN if the 'sock' send buffer is full. */
229 int
230 nl_sock_sendv(struct nl_sock *sock, const struct iovec iov[], size_t n_iov,
231 bool wait)
232 {
233 struct msghdr msg;
234 int error;
235
236 COVERAGE_INC(netlink_send);
237 memset(&msg, 0, sizeof msg);
238 msg.msg_iov = (struct iovec *) iov;
239 msg.msg_iovlen = n_iov;
240 do {
241 int retval;
242 retval = sendmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
243 error = retval < 0 ? errno : 0;
244 } while (error == EINTR);
245 if (error != EAGAIN) {
246 log_nlmsg(__func__, error, iov[0].iov_base, iov[0].iov_len);
247 if (!error) {
248 COVERAGE_INC(netlink_sent);
249 }
250 }
251 return error;
252 }
253
254 /* Tries to receive a netlink message from the kernel on 'sock'. If
255 * successful, stores the received message into '*bufp' and returns 0. The
256 * caller is responsible for destroying the message with ofpbuf_delete(). On
257 * failure, returns a positive errno value and stores a null pointer into
258 * '*bufp'.
259 *
260 * If 'wait' is true, nl_sock_recv waits for a message to be ready; otherwise,
261 * returns EAGAIN if the 'sock' receive buffer is empty. */
262 int
263 nl_sock_recv(struct nl_sock *sock, struct ofpbuf **bufp, bool wait)
264 {
265 uint8_t tmp;
266 ssize_t bufsize = 2048;
267 ssize_t nbytes, nbytes2;
268 struct ofpbuf *buf;
269 struct nlmsghdr *nlmsghdr;
270 struct iovec iov;
271 struct msghdr msg = {
272 .msg_name = NULL,
273 .msg_namelen = 0,
274 .msg_iov = &iov,
275 .msg_iovlen = 1,
276 .msg_control = NULL,
277 .msg_controllen = 0,
278 .msg_flags = 0
279 };
280
281 buf = ofpbuf_new(bufsize);
282 *bufp = NULL;
283
284 try_again:
285 /* Attempt to read the message. We don't know the size of the data
286 * yet, so we take a guess at 2048. If we're wrong, we keep trying
287 * and doubling the buffer size each time.
288 */
289 nlmsghdr = ofpbuf_put_uninit(buf, bufsize);
290 iov.iov_base = nlmsghdr;
291 iov.iov_len = bufsize;
292 do {
293 nbytes = recvmsg(sock->fd, &msg, (wait ? 0 : MSG_DONTWAIT) | MSG_PEEK);
294 } while (nbytes < 0 && errno == EINTR);
295 if (nbytes < 0) {
296 ofpbuf_delete(buf);
297 return errno;
298 }
299 if (msg.msg_flags & MSG_TRUNC) {
300 COVERAGE_INC(netlink_recv_retry);
301 bufsize *= 2;
302 ofpbuf_reinit(buf, bufsize);
303 goto try_again;
304 }
305 buf->size = nbytes;
306
307 /* We successfully read the message, so recv again to clear the queue */
308 iov.iov_base = &tmp;
309 iov.iov_len = 1;
310 do {
311 nbytes2 = recvmsg(sock->fd, &msg, MSG_DONTWAIT);
312 } while (nbytes2 < 0 && errno == EINTR);
313 if (nbytes2 < 0) {
314 if (errno == ENOBUFS) {
315 /* The kernel is notifying us that a message it tried to send to us
316 * was dropped. We have to pass this along to the caller in case
317 * it wants to retry a request. So kill the buffer, which we can
318 * re-read next time. */
319 COVERAGE_INC(netlink_overflow);
320 ofpbuf_delete(buf);
321 return ENOBUFS;
322 } else {
323 VLOG_ERR_RL(&rl, "failed to remove nlmsg from socket: %s\n",
324 strerror(errno));
325 }
326 }
327 if (nbytes < sizeof *nlmsghdr
328 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
329 || nlmsghdr->nlmsg_len > nbytes) {
330 VLOG_ERR_RL(&rl, "received invalid nlmsg (%zd bytes < %d)",
331 bufsize, NLMSG_HDRLEN);
332 ofpbuf_delete(buf);
333 return EPROTO;
334 }
335 *bufp = buf;
336 log_nlmsg(__func__, 0, buf->data, buf->size);
337 COVERAGE_INC(netlink_received);
338 return 0;
339 }
340
341 /* Sends 'request' to the kernel via 'sock' and waits for a response. If
342 * successful, stores the reply into '*replyp' and returns 0. The caller is
343 * responsible for destroying the reply with ofpbuf_delete(). On failure,
344 * returns a positive errno value and stores a null pointer into '*replyp'.
345 *
346 * The caller is responsible for destroying 'request'.
347 *
348 * Bare Netlink is an unreliable transport protocol. This function layers
349 * reliable delivery and reply semantics on top of bare Netlink.
350 *
351 * In Netlink, sending a request to the kernel is reliable enough, because the
352 * kernel will tell us if the message cannot be queued (and we will in that
353 * case put it on the transmit queue and wait until it can be delivered).
354 *
355 * Receiving the reply is the real problem: if the socket buffer is full when
356 * the kernel tries to send the reply, the reply will be dropped. However, the
357 * kernel sets a flag that a reply has been dropped. The next call to recv
358 * then returns ENOBUFS. We can then re-send the request.
359 *
360 * Caveats:
361 *
362 * 1. Netlink depends on sequence numbers to match up requests and
363 * replies. The sender of a request supplies a sequence number, and
364 * the reply echos back that sequence number.
365 *
366 * This is fine, but (1) some kernel netlink implementations are
367 * broken, in that they fail to echo sequence numbers and (2) this
368 * function will drop packets with non-matching sequence numbers, so
369 * that only a single request can be usefully transacted at a time.
370 *
371 * 2. Resending the request causes it to be re-executed, so the request
372 * needs to be idempotent.
373 */
374 int
375 nl_sock_transact(struct nl_sock *sock,
376 const struct ofpbuf *request, struct ofpbuf **replyp)
377 {
378 uint32_t seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
379 struct nlmsghdr *nlmsghdr;
380 struct ofpbuf *reply;
381 int retval;
382
383 *replyp = NULL;
384
385 /* Ensure that we get a reply even if this message doesn't ordinarily call
386 * for one. */
387 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_ACK;
388
389 send:
390 retval = nl_sock_send(sock, request, true);
391 if (retval) {
392 return retval;
393 }
394
395 recv:
396 retval = nl_sock_recv(sock, &reply, true);
397 if (retval) {
398 if (retval == ENOBUFS) {
399 COVERAGE_INC(netlink_overflow);
400 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
401 goto send;
402 } else {
403 return retval;
404 }
405 }
406 nlmsghdr = nl_msg_nlmsghdr(reply);
407 if (seq != nlmsghdr->nlmsg_seq) {
408 VLOG_DBG_RL(&rl, "ignoring seq %"PRIu32" != expected %"PRIu32,
409 nl_msg_nlmsghdr(reply)->nlmsg_seq, seq);
410 ofpbuf_delete(reply);
411 goto recv;
412 }
413 if (nl_msg_nlmsgerr(reply, &retval)) {
414 ofpbuf_delete(reply);
415 if (retval) {
416 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
417 retval, strerror(retval));
418 }
419 return retval != EAGAIN ? retval : EPROTO;
420 }
421
422 *replyp = reply;
423 return 0;
424 }
425
426 /* Causes poll_block() to wake up when any of the specified 'events' (which is
427 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'. */
428 void
429 nl_sock_wait(const struct nl_sock *sock, short int events)
430 {
431 poll_fd_wait(sock->fd, events);
432 }
433 \f
434 /* Netlink messages. */
435
436 /* Returns the nlmsghdr at the head of 'msg'.
437 *
438 * 'msg' must be at least as large as a nlmsghdr. */
439 struct nlmsghdr *
440 nl_msg_nlmsghdr(const struct ofpbuf *msg)
441 {
442 return ofpbuf_at_assert(msg, 0, NLMSG_HDRLEN);
443 }
444
445 /* Returns the genlmsghdr just past 'msg''s nlmsghdr.
446 *
447 * Returns a null pointer if 'msg' is not large enough to contain an nlmsghdr
448 * and a genlmsghdr. */
449 struct genlmsghdr *
450 nl_msg_genlmsghdr(const struct ofpbuf *msg)
451 {
452 return ofpbuf_at(msg, NLMSG_HDRLEN, GENL_HDRLEN);
453 }
454
455 /* If 'buffer' is a NLMSG_ERROR message, stores 0 in '*errorp' if it is an ACK
456 * message, otherwise a positive errno value, and returns true. If 'buffer' is
457 * not an NLMSG_ERROR message, returns false.
458 *
459 * 'msg' must be at least as large as a nlmsghdr. */
460 bool
461 nl_msg_nlmsgerr(const struct ofpbuf *msg, int *errorp)
462 {
463 if (nl_msg_nlmsghdr(msg)->nlmsg_type == NLMSG_ERROR) {
464 struct nlmsgerr *err = ofpbuf_at(msg, NLMSG_HDRLEN, sizeof *err);
465 int code = EPROTO;
466 if (!err) {
467 VLOG_ERR_RL(&rl, "received invalid nlmsgerr (%zd bytes < %zd)",
468 msg->size, NLMSG_HDRLEN + sizeof *err);
469 } else if (err->error <= 0 && err->error > INT_MIN) {
470 code = -err->error;
471 }
472 if (errorp) {
473 *errorp = code;
474 }
475 return true;
476 } else {
477 return false;
478 }
479 }
480
481 /* Ensures that 'b' has room for at least 'size' bytes plus netlink padding at
482 * its tail end, reallocating and copying its data if necessary. */
483 void
484 nl_msg_reserve(struct ofpbuf *msg, size_t size)
485 {
486 ofpbuf_prealloc_tailroom(msg, NLMSG_ALIGN(size));
487 }
488
489 /* Puts a nlmsghdr at the beginning of 'msg', which must be initially empty.
490 * Uses the given 'type' and 'flags'. 'sock' is used to obtain a PID and
491 * sequence number for proper routing of replies. 'expected_payload' should be
492 * an estimate of the number of payload bytes to be supplied; if the size of
493 * the payload is unknown a value of 0 is acceptable.
494 *
495 * 'type' is ordinarily an enumerated value specific to the Netlink protocol
496 * (e.g. RTM_NEWLINK, for NETLINK_ROUTE protocol). For Generic Netlink, 'type'
497 * is the family number obtained via nl_lookup_genl_family().
498 *
499 * 'flags' is a bit-mask that indicates what kind of request is being made. It
500 * is often NLM_F_REQUEST indicating that a request is being made, commonly
501 * or'd with NLM_F_ACK to request an acknowledgement.
502 *
503 * nl_msg_put_genlmsghdr is more convenient for composing a Generic Netlink
504 * message. */
505 void
506 nl_msg_put_nlmsghdr(struct ofpbuf *msg, struct nl_sock *sock,
507 size_t expected_payload, uint32_t type, uint32_t flags)
508 {
509 struct nlmsghdr *nlmsghdr;
510
511 assert(msg->size == 0);
512
513 nl_msg_reserve(msg, NLMSG_HDRLEN + expected_payload);
514 nlmsghdr = nl_msg_put_uninit(msg, NLMSG_HDRLEN);
515 nlmsghdr->nlmsg_len = 0;
516 nlmsghdr->nlmsg_type = type;
517 nlmsghdr->nlmsg_flags = flags;
518 nlmsghdr->nlmsg_seq = ++next_seq;
519 nlmsghdr->nlmsg_pid = sock->pid;
520 }
521
522 /* Puts a nlmsghdr and genlmsghdr at the beginning of 'msg', which must be
523 * initially empty. 'sock' is used to obtain a PID and sequence number for
524 * proper routing of replies. 'expected_payload' should be an estimate of the
525 * number of payload bytes to be supplied; if the size of the payload is
526 * unknown a value of 0 is acceptable.
527 *
528 * 'family' is the family number obtained via nl_lookup_genl_family().
529 *
530 * 'flags' is a bit-mask that indicates what kind of request is being made. It
531 * is often NLM_F_REQUEST indicating that a request is being made, commonly
532 * or'd with NLM_F_ACK to request an acknowledgement.
533 *
534 * 'cmd' is an enumerated value specific to the Generic Netlink family
535 * (e.g. CTRL_CMD_NEWFAMILY for the GENL_ID_CTRL family).
536 *
537 * 'version' is a version number specific to the family and command (often 1).
538 *
539 * nl_msg_put_nlmsghdr should be used to compose Netlink messages that are not
540 * Generic Netlink messages. */
541 void
542 nl_msg_put_genlmsghdr(struct ofpbuf *msg, struct nl_sock *sock,
543 size_t expected_payload, int family, uint32_t flags,
544 uint8_t cmd, uint8_t version)
545 {
546 struct genlmsghdr *genlmsghdr;
547
548 nl_msg_put_nlmsghdr(msg, sock, GENL_HDRLEN + expected_payload,
549 family, flags);
550 assert(msg->size == NLMSG_HDRLEN);
551 genlmsghdr = nl_msg_put_uninit(msg, GENL_HDRLEN);
552 genlmsghdr->cmd = cmd;
553 genlmsghdr->version = version;
554 genlmsghdr->reserved = 0;
555 }
556
557 /* Appends the 'size' bytes of data in 'p', plus Netlink padding if needed, to
558 * the tail end of 'msg'. Data in 'msg' is reallocated and copied if
559 * necessary. */
560 void
561 nl_msg_put(struct ofpbuf *msg, const void *data, size_t size)
562 {
563 memcpy(nl_msg_put_uninit(msg, size), data, size);
564 }
565
566 /* Appends 'size' bytes of data, plus Netlink padding if needed, to the tail
567 * end of 'msg', reallocating and copying its data if necessary. Returns a
568 * pointer to the first byte of the new data, which is left uninitialized. */
569 void *
570 nl_msg_put_uninit(struct ofpbuf *msg, size_t size)
571 {
572 size_t pad = NLMSG_ALIGN(size) - size;
573 char *p = ofpbuf_put_uninit(msg, size + pad);
574 if (pad) {
575 memset(p + size, 0, pad);
576 }
577 return p;
578 }
579
580 /* Appends a Netlink attribute of the given 'type' and room for 'size' bytes of
581 * data as its payload, plus Netlink padding if needed, to the tail end of
582 * 'msg', reallocating and copying its data if necessary. Returns a pointer to
583 * the first byte of data in the attribute, which is left uninitialized. */
584 void *
585 nl_msg_put_unspec_uninit(struct ofpbuf *msg, uint16_t type, size_t size)
586 {
587 size_t total_size = NLA_HDRLEN + size;
588 struct nlattr* nla = nl_msg_put_uninit(msg, total_size);
589 assert(NLA_ALIGN(total_size) <= UINT16_MAX);
590 nla->nla_len = total_size;
591 nla->nla_type = type;
592 return nla + 1;
593 }
594
595 /* Appends a Netlink attribute of the given 'type' and the 'size' bytes of
596 * 'data' as its payload, to the tail end of 'msg', reallocating and copying
597 * its data if necessary. Returns a pointer to the first byte of data in the
598 * attribute, which is left uninitialized. */
599 void
600 nl_msg_put_unspec(struct ofpbuf *msg, uint16_t type,
601 const void *data, size_t size)
602 {
603 memcpy(nl_msg_put_unspec_uninit(msg, type, size), data, size);
604 }
605
606 /* Appends a Netlink attribute of the given 'type' and no payload to 'msg'.
607 * (Some Netlink protocols use the presence or absence of an attribute as a
608 * Boolean flag.) */
609 void
610 nl_msg_put_flag(struct ofpbuf *msg, uint16_t type)
611 {
612 nl_msg_put_unspec(msg, type, NULL, 0);
613 }
614
615 /* Appends a Netlink attribute of the given 'type' and the given 8-bit 'value'
616 * to 'msg'. */
617 void
618 nl_msg_put_u8(struct ofpbuf *msg, uint16_t type, uint8_t value)
619 {
620 nl_msg_put_unspec(msg, type, &value, sizeof value);
621 }
622
623 /* Appends a Netlink attribute of the given 'type' and the given 16-bit 'value'
624 * to 'msg'. */
625 void
626 nl_msg_put_u16(struct ofpbuf *msg, uint16_t type, uint16_t value)
627 {
628 nl_msg_put_unspec(msg, type, &value, sizeof value);
629 }
630
631 /* Appends a Netlink attribute of the given 'type' and the given 32-bit 'value'
632 * to 'msg'. */
633 void
634 nl_msg_put_u32(struct ofpbuf *msg, uint16_t type, uint32_t value)
635 {
636 nl_msg_put_unspec(msg, type, &value, sizeof value);
637 }
638
639 /* Appends a Netlink attribute of the given 'type' and the given 64-bit 'value'
640 * to 'msg'. */
641 void
642 nl_msg_put_u64(struct ofpbuf *msg, uint16_t type, uint64_t value)
643 {
644 nl_msg_put_unspec(msg, type, &value, sizeof value);
645 }
646
647 /* Appends a Netlink attribute of the given 'type' and the given
648 * null-terminated string 'value' to 'msg'. */
649 void
650 nl_msg_put_string(struct ofpbuf *msg, uint16_t type, const char *value)
651 {
652 nl_msg_put_unspec(msg, type, value, strlen(value) + 1);
653 }
654
655 /* Appends a Netlink attribute of the given 'type' and the given buffered
656 * netlink message in 'nested_msg' to 'msg'. The nlmsg_len field in
657 * 'nested_msg' is finalized to match 'nested_msg->size'. */
658 void
659 nl_msg_put_nested(struct ofpbuf *msg,
660 uint16_t type, struct ofpbuf *nested_msg)
661 {
662 nl_msg_nlmsghdr(nested_msg)->nlmsg_len = nested_msg->size;
663 nl_msg_put_unspec(msg, type, nested_msg->data, nested_msg->size);
664 }
665
666 /* Returns the first byte in the payload of attribute 'nla'. */
667 const void *
668 nl_attr_get(const struct nlattr *nla)
669 {
670 assert(nla->nla_len >= NLA_HDRLEN);
671 return nla + 1;
672 }
673
674 /* Returns the number of bytes in the payload of attribute 'nla'. */
675 size_t
676 nl_attr_get_size(const struct nlattr *nla)
677 {
678 assert(nla->nla_len >= NLA_HDRLEN);
679 return nla->nla_len - NLA_HDRLEN;
680 }
681
682 /* Asserts that 'nla''s payload is at least 'size' bytes long, and returns the
683 * first byte of the payload. */
684 const void *
685 nl_attr_get_unspec(const struct nlattr *nla, size_t size)
686 {
687 assert(nla->nla_len >= NLA_HDRLEN + size);
688 return nla + 1;
689 }
690
691 /* Returns true if 'nla' is nonnull. (Some Netlink protocols use the presence
692 * or absence of an attribute as a Boolean flag.) */
693 bool
694 nl_attr_get_flag(const struct nlattr *nla)
695 {
696 return nla != NULL;
697 }
698
699 #define NL_ATTR_GET_AS(NLA, TYPE) \
700 (*(TYPE*) nl_attr_get_unspec(nla, sizeof(TYPE)))
701
702 /* Returns the 8-bit value in 'nla''s payload.
703 *
704 * Asserts that 'nla''s payload is at least 1 byte long. */
705 uint8_t
706 nl_attr_get_u8(const struct nlattr *nla)
707 {
708 return NL_ATTR_GET_AS(nla, uint8_t);
709 }
710
711 /* Returns the 16-bit value in 'nla''s payload.
712 *
713 * Asserts that 'nla''s payload is at least 2 bytes long. */
714 uint16_t
715 nl_attr_get_u16(const struct nlattr *nla)
716 {
717 return NL_ATTR_GET_AS(nla, uint16_t);
718 }
719
720 /* Returns the 32-bit value in 'nla''s payload.
721 *
722 * Asserts that 'nla''s payload is at least 4 bytes long. */
723 uint32_t
724 nl_attr_get_u32(const struct nlattr *nla)
725 {
726 return NL_ATTR_GET_AS(nla, uint32_t);
727 }
728
729 /* Returns the 64-bit value in 'nla''s payload.
730 *
731 * Asserts that 'nla''s payload is at least 8 bytes long. */
732 uint64_t
733 nl_attr_get_u64(const struct nlattr *nla)
734 {
735 return NL_ATTR_GET_AS(nla, uint64_t);
736 }
737
738 /* Returns the null-terminated string value in 'nla''s payload.
739 *
740 * Asserts that 'nla''s payload contains a null-terminated string. */
741 const char *
742 nl_attr_get_string(const struct nlattr *nla)
743 {
744 assert(nla->nla_len > NLA_HDRLEN);
745 assert(memchr(nl_attr_get(nla), '\0', nla->nla_len - NLA_HDRLEN) != NULL);
746 return nl_attr_get(nla);
747 }
748
749 /* Default minimum and maximum payload sizes for each type of attribute. */
750 static const size_t attr_len_range[][2] = {
751 [0 ... N_NL_ATTR_TYPES - 1] = { 0, SIZE_MAX },
752 [NL_A_U8] = { 1, 1 },
753 [NL_A_U16] = { 2, 2 },
754 [NL_A_U32] = { 4, 4 },
755 [NL_A_U64] = { 8, 8 },
756 [NL_A_STRING] = { 1, SIZE_MAX },
757 [NL_A_FLAG] = { 0, SIZE_MAX },
758 [NL_A_NESTED] = { NLMSG_HDRLEN, SIZE_MAX },
759 };
760
761 /* Parses the 'msg' starting at the given 'nla_offset' as a sequence of Netlink
762 * attributes. 'policy[i]', for 0 <= i < n_attrs, specifies how the attribute
763 * with nla_type == i is parsed; a pointer to attribute i is stored in
764 * attrs[i]. Returns true if successful, false on failure.
765 *
766 * If the Netlink attributes in 'msg' follow a Netlink header and a Generic
767 * Netlink header, then 'nla_offset' should be NLMSG_HDRLEN + GENL_HDRLEN. */
768 bool
769 nl_policy_parse(const struct ofpbuf *msg, size_t nla_offset,
770 const struct nl_policy policy[],
771 struct nlattr *attrs[], size_t n_attrs)
772 {
773 void *p, *tail;
774 size_t n_required;
775 size_t i;
776
777 n_required = 0;
778 for (i = 0; i < n_attrs; i++) {
779 attrs[i] = NULL;
780
781 assert(policy[i].type < N_NL_ATTR_TYPES);
782 if (policy[i].type != NL_A_NO_ATTR
783 && policy[i].type != NL_A_FLAG
784 && !policy[i].optional) {
785 n_required++;
786 }
787 }
788
789 p = ofpbuf_at(msg, nla_offset, 0);
790 if (p == NULL) {
791 VLOG_DBG_RL(&rl, "missing headers in nl_policy_parse");
792 return false;
793 }
794 tail = ofpbuf_tail(msg);
795
796 while (p < tail) {
797 size_t offset = (char*)p - (char*)msg->data;
798 struct nlattr *nla = p;
799 size_t len, aligned_len;
800 uint16_t type;
801
802 /* Make sure its claimed length is plausible. */
803 if (nla->nla_len < NLA_HDRLEN) {
804 VLOG_DBG_RL(&rl, "%zu: attr shorter than NLA_HDRLEN (%"PRIu16")",
805 offset, nla->nla_len);
806 return false;
807 }
808 len = nla->nla_len - NLA_HDRLEN;
809 aligned_len = NLA_ALIGN(len);
810 if (aligned_len > (char*)tail - (char*)p) {
811 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" aligned data len (%zu) "
812 "> bytes left (%tu)",
813 offset, nla->nla_type, aligned_len,
814 (char*)tail - (char*)p);
815 return false;
816 }
817
818 type = nla->nla_type;
819 if (type < n_attrs && policy[type].type != NL_A_NO_ATTR) {
820 const struct nl_policy *p = &policy[type];
821 size_t min_len, max_len;
822
823 /* Validate length and content. */
824 min_len = p->min_len ? p->min_len : attr_len_range[p->type][0];
825 max_len = p->max_len ? p->max_len : attr_len_range[p->type][1];
826 if (len < min_len || len > max_len) {
827 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" length %zu not in "
828 "allowed range %zu...%zu",
829 offset, type, len, min_len, max_len);
830 return false;
831 }
832 if (p->type == NL_A_STRING) {
833 if (((char *) nla)[nla->nla_len - 1]) {
834 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" lacks null at end",
835 offset, type);
836 return false;
837 }
838 if (memchr(nla + 1, '\0', len - 1) != NULL) {
839 VLOG_DBG_RL(&rl, "%zu: attr %"PRIu16" has bad length",
840 offset, type);
841 return false;
842 }
843 }
844 if (!p->optional && attrs[type] == NULL) {
845 assert(n_required > 0);
846 --n_required;
847 }
848 attrs[type] = nla;
849 } else {
850 /* Skip attribute type that we don't care about. */
851 }
852 p = (char*)p + NLA_ALIGN(nla->nla_len);
853 }
854 if (n_required) {
855 VLOG_DBG_RL(&rl, "%zu required attrs missing", n_required);
856 return false;
857 }
858 return true;
859 }
860 \f
861 /* Miscellaneous. */
862
863 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
864 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
865 };
866
867 static int do_lookup_genl_family(const char *name)
868 {
869 struct nl_sock *sock;
870 struct ofpbuf request, *reply;
871 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
872 int retval;
873
874 retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
875 if (retval) {
876 return -retval;
877 }
878
879 ofpbuf_init(&request, 0);
880 nl_msg_put_genlmsghdr(&request, sock, 0, GENL_ID_CTRL, NLM_F_REQUEST,
881 CTRL_CMD_GETFAMILY, 1);
882 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
883 retval = nl_sock_transact(sock, &request, &reply);
884 ofpbuf_uninit(&request);
885 if (retval) {
886 nl_sock_destroy(sock);
887 return -retval;
888 }
889
890 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
891 family_policy, attrs, ARRAY_SIZE(family_policy))) {
892 nl_sock_destroy(sock);
893 ofpbuf_delete(reply);
894 return -EPROTO;
895 }
896
897 retval = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
898 if (retval == 0) {
899 retval = -EPROTO;
900 }
901 nl_sock_destroy(sock);
902 ofpbuf_delete(reply);
903 return retval;
904 }
905
906 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
907 * number and stores it in '*number'. If successful, returns 0 and the caller
908 * may use '*number' as the family number. On failure, returns a positive
909 * errno value and '*number' caches the errno value. */
910 int
911 nl_lookup_genl_family(const char *name, int *number)
912 {
913 if (*number == 0) {
914 *number = do_lookup_genl_family(name);
915 assert(*number != 0);
916 }
917 return *number > 0 ? 0 : -*number;
918 }
919 \f
920 /* Netlink PID.
921 *
922 * Every Netlink socket must be bound to a unique 32-bit PID. By convention,
923 * programs that have a single Netlink socket use their Unix process ID as PID,
924 * and programs with multiple Netlink sockets add a unique per-socket
925 * identifier in the bits above the Unix process ID.
926 *
927 * The kernel has Netlink PID 0.
928 */
929
930 /* Parameters for how many bits in the PID should come from the Unix process ID
931 * and how many unique per-socket. */
932 #define SOCKET_BITS 10
933 #define MAX_SOCKETS (1u << SOCKET_BITS)
934
935 #define PROCESS_BITS (32 - SOCKET_BITS)
936 #define MAX_PROCESSES (1u << PROCESS_BITS)
937 #define PROCESS_MASK ((uint32_t) (MAX_PROCESSES - 1))
938
939 /* Bit vector of unused socket identifiers. */
940 static uint32_t avail_sockets[ROUND_UP(MAX_SOCKETS, 32)];
941
942 /* Allocates and returns a new Netlink PID. */
943 static int
944 alloc_pid(uint32_t *pid)
945 {
946 int i;
947
948 for (i = 0; i < MAX_SOCKETS; i++) {
949 if ((avail_sockets[i / 32] & (1u << (i % 32))) == 0) {
950 avail_sockets[i / 32] |= 1u << (i % 32);
951 *pid = (getpid() & PROCESS_MASK) | (i << PROCESS_BITS);
952 return 0;
953 }
954 }
955 VLOG_ERR("netlink pid space exhausted");
956 return ENOBUFS;
957 }
958
959 /* Makes the specified 'pid' available for reuse. */
960 static void
961 free_pid(uint32_t pid)
962 {
963 int sock = pid >> PROCESS_BITS;
964 assert(avail_sockets[sock / 32] & (1u << (sock % 32)));
965 avail_sockets[sock / 32] &= ~(1u << (sock % 32));
966 }
967 \f
968 static void
969 nlmsghdr_to_string(const struct nlmsghdr *h, struct ds *ds)
970 {
971 struct nlmsg_flag {
972 unsigned int bits;
973 const char *name;
974 };
975 static const struct nlmsg_flag flags[] = {
976 { NLM_F_REQUEST, "REQUEST" },
977 { NLM_F_MULTI, "MULTI" },
978 { NLM_F_ACK, "ACK" },
979 { NLM_F_ECHO, "ECHO" },
980 { NLM_F_DUMP, "DUMP" },
981 { NLM_F_ROOT, "ROOT" },
982 { NLM_F_MATCH, "MATCH" },
983 { NLM_F_ATOMIC, "ATOMIC" },
984 };
985 const struct nlmsg_flag *flag;
986 uint16_t flags_left;
987
988 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
989 h->nlmsg_len, h->nlmsg_type);
990 if (h->nlmsg_type == NLMSG_NOOP) {
991 ds_put_cstr(ds, "(no-op)");
992 } else if (h->nlmsg_type == NLMSG_ERROR) {
993 ds_put_cstr(ds, "(error)");
994 } else if (h->nlmsg_type == NLMSG_DONE) {
995 ds_put_cstr(ds, "(done)");
996 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
997 ds_put_cstr(ds, "(overrun)");
998 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
999 ds_put_cstr(ds, "(reserved)");
1000 } else {
1001 ds_put_cstr(ds, "(family-defined)");
1002 }
1003 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1004 flags_left = h->nlmsg_flags;
1005 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1006 if ((flags_left & flag->bits) == flag->bits) {
1007 ds_put_format(ds, "[%s]", flag->name);
1008 flags_left &= ~flag->bits;
1009 }
1010 }
1011 if (flags_left) {
1012 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1013 }
1014 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32"(%d:%d))",
1015 h->nlmsg_seq, h->nlmsg_pid,
1016 (int) (h->nlmsg_pid & PROCESS_MASK),
1017 (int) (h->nlmsg_pid >> PROCESS_BITS));
1018 }
1019
1020 static char *
1021 nlmsg_to_string(const struct ofpbuf *buffer)
1022 {
1023 struct ds ds = DS_EMPTY_INITIALIZER;
1024 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1025 if (h) {
1026 nlmsghdr_to_string(h, &ds);
1027 if (h->nlmsg_type == NLMSG_ERROR) {
1028 const struct nlmsgerr *e;
1029 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1030 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1031 if (e) {
1032 ds_put_format(&ds, " error(%d", e->error);
1033 if (e->error < 0) {
1034 ds_put_format(&ds, "(%s)", strerror(-e->error));
1035 }
1036 ds_put_cstr(&ds, ", in-reply-to(");
1037 nlmsghdr_to_string(&e->msg, &ds);
1038 ds_put_cstr(&ds, "))");
1039 } else {
1040 ds_put_cstr(&ds, " error(truncated)");
1041 }
1042 } else if (h->nlmsg_type == NLMSG_DONE) {
1043 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1044 if (error) {
1045 ds_put_format(&ds, " done(%d", *error);
1046 if (*error < 0) {
1047 ds_put_format(&ds, "(%s)", strerror(-*error));
1048 }
1049 ds_put_cstr(&ds, ")");
1050 } else {
1051 ds_put_cstr(&ds, " done(truncated)");
1052 }
1053 }
1054 } else {
1055 ds_put_cstr(&ds, "nl(truncated)");
1056 }
1057 return ds.string;
1058 }
1059
1060 static void
1061 log_nlmsg(const char *function, int error,
1062 const void *message, size_t size)
1063 {
1064 struct ofpbuf buffer;
1065 char *nlmsg;
1066
1067 if (!VLOG_IS_DBG_ENABLED()) {
1068 return;
1069 }
1070
1071 buffer.data = (void *) message;
1072 buffer.size = size;
1073 nlmsg = nlmsg_to_string(&buffer);
1074 VLOG_DBG_RL(&rl, "%s (%s): %s", function, strerror(error), nlmsg);
1075 free(nlmsg);
1076 }
1077