]> git.proxmox.com Git - mirror_ovs.git/blob - lib/netlink-socket.c
lldp: validate a bit more received LLDP frames
[mirror_ovs.git] / lib / netlink-socket.c
1 /*
2 * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Nicira, Inc.
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-socket.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdlib.h>
22 #include <sys/socket.h>
23 #include <sys/types.h>
24 #include <sys/uio.h>
25 #include <unistd.h>
26 #include "coverage.h"
27 #include "openvswitch/dynamic-string.h"
28 #include "hash.h"
29 #include "openvswitch/hmap.h"
30 #include "netlink.h"
31 #include "netlink-protocol.h"
32 #include "netnsid.h"
33 #include "odp-netlink.h"
34 #include "openvswitch/ofpbuf.h"
35 #include "ovs-thread.h"
36 #include "openvswitch/poll-loop.h"
37 #include "seq.h"
38 #include "socket-util.h"
39 #include "util.h"
40 #include "openvswitch/vlog.h"
41
42 VLOG_DEFINE_THIS_MODULE(netlink_socket);
43
44 COVERAGE_DEFINE(netlink_overflow);
45 COVERAGE_DEFINE(netlink_received);
46 COVERAGE_DEFINE(netlink_recv_jumbo);
47 COVERAGE_DEFINE(netlink_sent);
48
49 /* Linux header file confusion causes this to be undefined. */
50 #ifndef SOL_NETLINK
51 #define SOL_NETLINK 270
52 #endif
53
54 /* A single (bad) Netlink message can in theory dump out many, many log
55 * messages, so the burst size is set quite high here to avoid missing useful
56 * information. Also, at high logging levels we log *all* Netlink messages. */
57 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 600);
58
59 static uint32_t nl_sock_allocate_seq(struct nl_sock *, unsigned int n);
60 static void log_nlmsg(const char *function, int error,
61 const void *message, size_t size, int protocol);
62 #ifdef _WIN32
63 static int get_sock_pid_from_kernel(struct nl_sock *sock);
64 static int set_sock_property(struct nl_sock *sock);
65 static int nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
66 struct ofpbuf **replyp);
67
68 /* In the case DeviceIoControl failed and GetLastError returns with
69 * ERROR_NOT_FOUND means we lost communication with the kernel device.
70 * CloseHandle will fail because the handle in 'theory' does not exist.
71 * The only remaining option is to crash and allow the service to be restarted
72 * via service manager. This is the only way to close the handle from both
73 * userspace and kernel. */
74 void
75 lost_communication(DWORD last_err)
76 {
77 if (last_err == ERROR_NOT_FOUND) {
78 ovs_abort(0, "lost communication with the kernel device");
79 }
80 }
81 #endif
82 \f
83 /* Netlink sockets. */
84
85 struct nl_sock {
86 #ifdef _WIN32
87 HANDLE handle;
88 OVERLAPPED overlapped;
89 DWORD read_ioctl;
90 #else
91 int fd;
92 #endif
93 uint32_t next_seq;
94 uint32_t pid;
95 int protocol;
96 unsigned int rcvbuf; /* Receive buffer size (SO_RCVBUF). */
97 };
98
99 /* Compile-time limit on iovecs, so that we can allocate a maximum-size array
100 * of iovecs on the stack. */
101 #define MAX_IOVS 128
102
103 /* Maximum number of iovecs that may be passed to sendmsg, capped at a
104 * minimum of _XOPEN_IOV_MAX (16) and a maximum of MAX_IOVS.
105 *
106 * Initialized by nl_sock_create(). */
107 static int max_iovs;
108
109 static int nl_pool_alloc(int protocol, struct nl_sock **sockp);
110 static void nl_pool_release(struct nl_sock *);
111
112 /* Creates a new netlink socket for the given netlink 'protocol'
113 * (NETLINK_ROUTE, NETLINK_GENERIC, ...). Returns 0 and sets '*sockp' to the
114 * new socket if successful, otherwise returns a positive errno value. */
115 int
116 nl_sock_create(int protocol, struct nl_sock **sockp)
117 {
118 static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
119 struct nl_sock *sock;
120 #ifndef _WIN32
121 struct sockaddr_nl local, remote;
122 #endif
123 socklen_t local_size;
124 int rcvbuf;
125 int retval = 0;
126
127 if (ovsthread_once_start(&once)) {
128 int save_errno = errno;
129 errno = 0;
130
131 max_iovs = sysconf(_SC_UIO_MAXIOV);
132 if (max_iovs < _XOPEN_IOV_MAX) {
133 if (max_iovs == -1 && errno) {
134 VLOG_WARN("sysconf(_SC_UIO_MAXIOV): %s", ovs_strerror(errno));
135 }
136 max_iovs = _XOPEN_IOV_MAX;
137 } else if (max_iovs > MAX_IOVS) {
138 max_iovs = MAX_IOVS;
139 }
140
141 errno = save_errno;
142 ovsthread_once_done(&once);
143 }
144
145 *sockp = NULL;
146 sock = xmalloc(sizeof *sock);
147
148 #ifdef _WIN32
149 sock->overlapped.hEvent = NULL;
150 sock->handle = CreateFile(OVS_DEVICE_NAME_USER,
151 GENERIC_READ | GENERIC_WRITE,
152 FILE_SHARE_READ | FILE_SHARE_WRITE,
153 NULL, OPEN_EXISTING,
154 FILE_FLAG_OVERLAPPED, NULL);
155
156 if (sock->handle == INVALID_HANDLE_VALUE) {
157 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
158 goto error;
159 }
160
161 memset(&sock->overlapped, 0, sizeof sock->overlapped);
162 sock->overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
163 if (sock->overlapped.hEvent == NULL) {
164 VLOG_ERR("fcntl: %s", ovs_lasterror_to_string());
165 goto error;
166 }
167 /* Initialize the type/ioctl to Generic */
168 sock->read_ioctl = OVS_IOCTL_READ;
169 #else
170 sock->fd = socket(AF_NETLINK, SOCK_RAW, protocol);
171 if (sock->fd < 0) {
172 VLOG_ERR("fcntl: %s", ovs_strerror(errno));
173 goto error;
174 }
175 #endif
176
177 sock->protocol = protocol;
178 sock->next_seq = 1;
179
180 rcvbuf = 1024 * 1024;
181 #ifdef _WIN32
182 sock->rcvbuf = rcvbuf;
183 retval = get_sock_pid_from_kernel(sock);
184 if (retval != 0) {
185 goto error;
186 }
187 retval = set_sock_property(sock);
188 if (retval != 0) {
189 goto error;
190 }
191 #else
192 if (setsockopt(sock->fd, SOL_SOCKET, SO_RCVBUFFORCE,
193 &rcvbuf, sizeof rcvbuf)) {
194 /* Only root can use SO_RCVBUFFORCE. Everyone else gets EPERM.
195 * Warn only if the failure is therefore unexpected. */
196 if (errno != EPERM) {
197 VLOG_WARN_RL(&rl, "setting %d-byte socket receive buffer failed "
198 "(%s)", rcvbuf, ovs_strerror(errno));
199 }
200 }
201
202 retval = get_socket_rcvbuf(sock->fd);
203 if (retval < 0) {
204 retval = -retval;
205 goto error;
206 }
207 sock->rcvbuf = retval;
208 retval = 0;
209
210 /* Connect to kernel (pid 0) as remote address. */
211 memset(&remote, 0, sizeof remote);
212 remote.nl_family = AF_NETLINK;
213 remote.nl_pid = 0;
214 if (connect(sock->fd, (struct sockaddr *) &remote, sizeof remote) < 0) {
215 VLOG_ERR("connect(0): %s", ovs_strerror(errno));
216 goto error;
217 }
218
219 /* Obtain pid assigned by kernel. */
220 local_size = sizeof local;
221 if (getsockname(sock->fd, (struct sockaddr *) &local, &local_size) < 0) {
222 VLOG_ERR("getsockname: %s", ovs_strerror(errno));
223 goto error;
224 }
225 if (local_size < sizeof local || local.nl_family != AF_NETLINK) {
226 VLOG_ERR("getsockname returned bad Netlink name");
227 retval = EINVAL;
228 goto error;
229 }
230 sock->pid = local.nl_pid;
231 #endif
232
233 *sockp = sock;
234 return 0;
235
236 error:
237 if (retval == 0) {
238 retval = errno;
239 if (retval == 0) {
240 retval = EINVAL;
241 }
242 }
243 #ifdef _WIN32
244 if (sock->overlapped.hEvent) {
245 CloseHandle(sock->overlapped.hEvent);
246 }
247 if (sock->handle != INVALID_HANDLE_VALUE) {
248 CloseHandle(sock->handle);
249 }
250 #else
251 if (sock->fd >= 0) {
252 close(sock->fd);
253 }
254 #endif
255 free(sock);
256 return retval;
257 }
258
259 /* Creates a new netlink socket for the same protocol as 'src'. Returns 0 and
260 * sets '*sockp' to the new socket if successful, otherwise returns a positive
261 * errno value. */
262 int
263 nl_sock_clone(const struct nl_sock *src, struct nl_sock **sockp)
264 {
265 return nl_sock_create(src->protocol, sockp);
266 }
267
268 /* Destroys netlink socket 'sock'. */
269 void
270 nl_sock_destroy(struct nl_sock *sock)
271 {
272 if (sock) {
273 #ifdef _WIN32
274 if (sock->overlapped.hEvent) {
275 CloseHandle(sock->overlapped.hEvent);
276 }
277 CloseHandle(sock->handle);
278 #else
279 close(sock->fd);
280 #endif
281 free(sock);
282 }
283 }
284
285 #ifdef _WIN32
286 /* Reads the pid for 'sock' generated in the kernel datapath. The function
287 * uses a separate IOCTL instead of a transaction semantic to avoid unnecessary
288 * message overhead. */
289 static int
290 get_sock_pid_from_kernel(struct nl_sock *sock)
291 {
292 uint32_t pid = 0;
293 int retval = 0;
294 DWORD bytes = 0;
295
296 if (!DeviceIoControl(sock->handle, OVS_IOCTL_GET_PID,
297 NULL, 0, &pid, sizeof(pid),
298 &bytes, NULL)) {
299 lost_communication(GetLastError());
300 retval = EINVAL;
301 } else {
302 if (bytes < sizeof(pid)) {
303 retval = EINVAL;
304 } else {
305 sock->pid = pid;
306 }
307 }
308
309 return retval;
310 }
311
312 /* Used for setting and managing socket properties in userspace and kernel.
313 * Currently two attributes are tracked - pid and protocol
314 * protocol - supplied by userspace based on the netlink family. Windows uses
315 * this property to set the value in kernel datapath.
316 * eg: (NETLINK_GENERIC/ NETLINK_NETFILTER)
317 * pid - generated by windows kernel and set in userspace. The property
318 * is not modified.
319 * Also verify if Protocol and PID in Kernel reflects the values in userspace
320 * */
321 static int
322 set_sock_property(struct nl_sock *sock)
323 {
324 static const struct nl_policy ovs_socket_policy[] = {
325 [OVS_NL_ATTR_SOCK_PROTO] = { .type = NL_A_BE32, .optional = true },
326 [OVS_NL_ATTR_SOCK_PID] = { .type = NL_A_BE32, .optional = true }
327 };
328
329 struct ofpbuf request, *reply;
330 struct ovs_header *ovs_header;
331 struct nlattr *attrs[ARRAY_SIZE(ovs_socket_policy)];
332 int retval = 0;
333 int error;
334
335 ofpbuf_init(&request, 0);
336 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
337 OVS_CTRL_CMD_SOCK_PROP, OVS_WIN_CONTROL_VERSION);
338 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
339 ovs_header->dp_ifindex = 0;
340
341 nl_msg_put_be32(&request, OVS_NL_ATTR_SOCK_PROTO, sock->protocol);
342 /* pid is already set as part of get_sock_pid_from_kernel()
343 * This is added to maintain consistency
344 */
345 nl_msg_put_be32(&request, OVS_NL_ATTR_SOCK_PID, sock->pid);
346
347 error = nl_sock_transact(sock, &request, &reply);
348 ofpbuf_uninit(&request);
349 if (error) {
350 retval = EINVAL;
351 }
352
353 if (!nl_policy_parse(reply,
354 NLMSG_HDRLEN + GENL_HDRLEN + sizeof *ovs_header,
355 ovs_socket_policy, attrs,
356 ARRAY_SIZE(ovs_socket_policy))) {
357 ofpbuf_delete(reply);
358 retval = EINVAL;
359 }
360 /* Verify if the properties are setup properly */
361 if (attrs[OVS_NL_ATTR_SOCK_PROTO]) {
362 int protocol = nl_attr_get_be32(attrs[OVS_NL_ATTR_SOCK_PROTO]);
363 if (protocol != sock->protocol) {
364 VLOG_ERR("Invalid protocol returned:%d expected:%d",
365 protocol, sock->protocol);
366 retval = EINVAL;
367 }
368 }
369
370 if (attrs[OVS_NL_ATTR_SOCK_PID]) {
371 int pid = nl_attr_get_be32(attrs[OVS_NL_ATTR_SOCK_PID]);
372 if (pid != sock->pid) {
373 VLOG_ERR("Invalid pid returned:%d expected:%d",
374 pid, sock->pid);
375 retval = EINVAL;
376 }
377 }
378
379 return retval;
380 }
381 #endif /* _WIN32 */
382
383 #ifdef _WIN32
384 static int __inline
385 nl_sock_mcgroup(struct nl_sock *sock, unsigned int multicast_group, bool join)
386 {
387 struct ofpbuf request;
388 uint64_t request_stub[128];
389 struct ovs_header *ovs_header;
390 struct nlmsghdr *nlmsg;
391 int error;
392
393 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
394
395 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
396 OVS_CTRL_CMD_MC_SUBSCRIBE_REQ,
397 OVS_WIN_CONTROL_VERSION);
398
399 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
400 ovs_header->dp_ifindex = 0;
401
402 nl_msg_put_u32(&request, OVS_NL_ATTR_MCAST_GRP, multicast_group);
403 nl_msg_put_u8(&request, OVS_NL_ATTR_MCAST_JOIN, join ? 1 : 0);
404
405 error = nl_sock_send(sock, &request, true);
406 ofpbuf_uninit(&request);
407 return error;
408 }
409 #endif
410 /* Tries to add 'sock' as a listener for 'multicast_group'. Returns 0 if
411 * successful, otherwise a positive errno value.
412 *
413 * A socket that is subscribed to a multicast group that receives asynchronous
414 * notifications must not be used for Netlink transactions or dumps, because
415 * transactions and dumps can cause notifications to be lost.
416 *
417 * Multicast group numbers are always positive.
418 *
419 * It is not an error to attempt to join a multicast group to which a socket
420 * already belongs. */
421 int
422 nl_sock_join_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
423 {
424 #ifdef _WIN32
425 /* Set the socket type as a "multicast" socket */
426 sock->read_ioctl = OVS_IOCTL_READ_EVENT;
427 int error = nl_sock_mcgroup(sock, multicast_group, true);
428 if (error) {
429 sock->read_ioctl = OVS_IOCTL_READ;
430 VLOG_WARN("could not join multicast group %u (%s)",
431 multicast_group, ovs_strerror(error));
432 return error;
433 }
434 #else
435 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP,
436 &multicast_group, sizeof multicast_group) < 0) {
437 VLOG_WARN("could not join multicast group %u (%s)",
438 multicast_group, ovs_strerror(errno));
439 return errno;
440 }
441 #endif
442 return 0;
443 }
444
445 /* When 'enable' is true, it tries to enable 'sock' to receive netlink
446 * notifications form all network namespaces that have an nsid assigned
447 * into the network namespace where the socket has been opened. The
448 * running kernel needs to provide support for that. When 'enable' is
449 * false, it will receive netlink notifications only from the network
450 * namespace where the socket has been opened.
451 *
452 * Returns 0 if successful, otherwise a positive errno. */
453 int
454 nl_sock_listen_all_nsid(struct nl_sock *sock, bool enable)
455 {
456 int error;
457 int val = enable ? 1 : 0;
458
459 #ifndef _WIN32
460 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, &val,
461 sizeof val) < 0) {
462 error = errno;
463 VLOG_INFO("netlink: could not %s listening to all nsid (%s)",
464 enable ? "enable" : "disable", ovs_strerror(error));
465 return errno;
466 }
467 #endif
468
469 return 0;
470 }
471
472 #ifdef _WIN32
473 int
474 nl_sock_subscribe_packet__(struct nl_sock *sock, bool subscribe)
475 {
476 struct ofpbuf request;
477 uint64_t request_stub[128];
478 struct ovs_header *ovs_header;
479 struct nlmsghdr *nlmsg;
480 int error;
481
482 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
483 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
484 OVS_CTRL_CMD_PACKET_SUBSCRIBE_REQ,
485 OVS_WIN_CONTROL_VERSION);
486
487 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
488 ovs_header->dp_ifindex = 0;
489 nl_msg_put_u8(&request, OVS_NL_ATTR_PACKET_SUBSCRIBE, subscribe ? 1 : 0);
490 nl_msg_put_u32(&request, OVS_NL_ATTR_PACKET_PID, sock->pid);
491
492 error = nl_sock_send(sock, &request, true);
493 ofpbuf_uninit(&request);
494 return error;
495 }
496
497 int
498 nl_sock_subscribe_packets(struct nl_sock *sock)
499 {
500 int error;
501
502 if (sock->read_ioctl != OVS_IOCTL_READ) {
503 return EINVAL;
504 }
505
506 error = nl_sock_subscribe_packet__(sock, true);
507 if (error) {
508 VLOG_WARN("could not subscribe packets (%s)",
509 ovs_strerror(error));
510 return error;
511 }
512 sock->read_ioctl = OVS_IOCTL_READ_PACKET;
513
514 return 0;
515 }
516
517 int
518 nl_sock_unsubscribe_packets(struct nl_sock *sock)
519 {
520 ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET);
521
522 int error = nl_sock_subscribe_packet__(sock, false);
523 if (error) {
524 VLOG_WARN("could not unsubscribe to packets (%s)",
525 ovs_strerror(error));
526 return error;
527 }
528
529 sock->read_ioctl = OVS_IOCTL_READ;
530 return 0;
531 }
532 #endif
533
534 /* Tries to make 'sock' stop listening to 'multicast_group'. Returns 0 if
535 * successful, otherwise a positive errno value.
536 *
537 * Multicast group numbers are always positive.
538 *
539 * It is not an error to attempt to leave a multicast group to which a socket
540 * does not belong.
541 *
542 * On success, reading from 'sock' will still return any messages that were
543 * received on 'multicast_group' before the group was left. */
544 int
545 nl_sock_leave_mcgroup(struct nl_sock *sock, unsigned int multicast_group)
546 {
547 #ifdef _WIN32
548 int error = nl_sock_mcgroup(sock, multicast_group, false);
549 if (error) {
550 VLOG_WARN("could not leave multicast group %u (%s)",
551 multicast_group, ovs_strerror(error));
552 return error;
553 }
554 sock->read_ioctl = OVS_IOCTL_READ;
555 #else
556 if (setsockopt(sock->fd, SOL_NETLINK, NETLINK_DROP_MEMBERSHIP,
557 &multicast_group, sizeof multicast_group) < 0) {
558 VLOG_WARN("could not leave multicast group %u (%s)",
559 multicast_group, ovs_strerror(errno));
560 return errno;
561 }
562 #endif
563 return 0;
564 }
565
566 static int
567 nl_sock_send__(struct nl_sock *sock, const struct ofpbuf *msg,
568 uint32_t nlmsg_seq, bool wait)
569 {
570 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(msg);
571 int error;
572
573 nlmsg->nlmsg_len = msg->size;
574 nlmsg->nlmsg_seq = nlmsg_seq;
575 nlmsg->nlmsg_pid = sock->pid;
576 do {
577 int retval;
578 #ifdef _WIN32
579 DWORD bytes;
580
581 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
582 msg->data, msg->size, NULL, 0,
583 &bytes, NULL)) {
584 lost_communication(GetLastError());
585 retval = -1;
586 /* XXX: Map to a more appropriate error based on GetLastError(). */
587 errno = EINVAL;
588 VLOG_DBG_RL(&rl, "fatal driver failure in write: %s",
589 ovs_lasterror_to_string());
590 } else {
591 retval = msg->size;
592 }
593 #else
594 retval = send(sock->fd, msg->data, msg->size,
595 wait ? 0 : MSG_DONTWAIT);
596 #endif
597 error = retval < 0 ? errno : 0;
598 } while (error == EINTR);
599 log_nlmsg(__func__, error, msg->data, msg->size, sock->protocol);
600 if (!error) {
601 COVERAGE_INC(netlink_sent);
602 }
603 return error;
604 }
605
606 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
607 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
608 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to a fresh
609 * sequence number, before the message is sent.
610 *
611 * Returns 0 if successful, otherwise a positive errno value. If
612 * 'wait' is true, then the send will wait until buffer space is ready;
613 * otherwise, returns EAGAIN if the 'sock' send buffer is full. */
614 int
615 nl_sock_send(struct nl_sock *sock, const struct ofpbuf *msg, bool wait)
616 {
617 return nl_sock_send_seq(sock, msg, nl_sock_allocate_seq(sock, 1), wait);
618 }
619
620 /* Tries to send 'msg', which must contain a Netlink message, to the kernel on
621 * 'sock'. nlmsg_len in 'msg' will be finalized to match msg->size, nlmsg_pid
622 * will be set to 'sock''s pid, and nlmsg_seq will be initialized to
623 * 'nlmsg_seq', before the message is sent.
624 *
625 * Returns 0 if successful, otherwise a positive errno value. If
626 * 'wait' is true, then the send will wait until buffer space is ready;
627 * otherwise, returns EAGAIN if the 'sock' send buffer is full.
628 *
629 * This function is suitable for sending a reply to a request that was received
630 * with sequence number 'nlmsg_seq'. Otherwise, use nl_sock_send() instead. */
631 int
632 nl_sock_send_seq(struct nl_sock *sock, const struct ofpbuf *msg,
633 uint32_t nlmsg_seq, bool wait)
634 {
635 return nl_sock_send__(sock, msg, nlmsg_seq, wait);
636 }
637
638 static int
639 nl_sock_recv__(struct nl_sock *sock, struct ofpbuf *buf, int *nsid, bool wait)
640 {
641 /* We can't accurately predict the size of the data to be received. The
642 * caller is supposed to have allocated enough space in 'buf' to handle the
643 * "typical" case. To handle exceptions, we make available enough space in
644 * 'tail' to allow Netlink messages to be up to 64 kB long (a reasonable
645 * figure since that's the maximum length of a Netlink attribute). */
646 struct nlmsghdr *nlmsghdr;
647 uint8_t tail[65536];
648 struct iovec iov[2];
649 struct msghdr msg;
650 uint8_t msgctrl[64];
651 struct cmsghdr *cmsg;
652 ssize_t retval;
653 int *ptr;
654 int error;
655
656 ovs_assert(buf->allocated >= sizeof *nlmsghdr);
657 ofpbuf_clear(buf);
658
659 iov[0].iov_base = buf->base;
660 iov[0].iov_len = buf->allocated;
661 iov[1].iov_base = tail;
662 iov[1].iov_len = sizeof tail;
663
664 memset(&msg, 0, sizeof msg);
665 msg.msg_iov = iov;
666 msg.msg_iovlen = 2;
667 msg.msg_control = msgctrl;
668 msg.msg_controllen = sizeof msgctrl;
669
670 /* Receive a Netlink message from the kernel.
671 *
672 * This works around a kernel bug in which the kernel returns an error code
673 * as if it were the number of bytes read. It doesn't actually modify
674 * anything in the receive buffer in that case, so we can initialize the
675 * Netlink header with an impossible message length and then, upon success,
676 * check whether it changed. */
677 nlmsghdr = buf->base;
678 do {
679 nlmsghdr->nlmsg_len = UINT32_MAX;
680 #ifdef _WIN32
681 DWORD bytes;
682 if (!DeviceIoControl(sock->handle, sock->read_ioctl,
683 NULL, 0, tail, sizeof tail, &bytes, NULL)) {
684 lost_communication(GetLastError());
685 VLOG_DBG_RL(&rl, "fatal driver failure in transact: %s",
686 ovs_lasterror_to_string());
687 retval = -1;
688 /* XXX: Map to a more appropriate error. */
689 errno = EINVAL;
690 } else {
691 retval = bytes;
692 if (retval == 0) {
693 retval = -1;
694 errno = EAGAIN;
695 } else {
696 if (retval >= buf->allocated) {
697 ofpbuf_reinit(buf, retval);
698 nlmsghdr = buf->base;
699 nlmsghdr->nlmsg_len = UINT32_MAX;
700 }
701 memcpy(buf->data, tail, retval);
702 buf->size = retval;
703 }
704 }
705 #else
706 retval = recvmsg(sock->fd, &msg, wait ? 0 : MSG_DONTWAIT);
707 #endif
708 error = (retval < 0 ? errno
709 : retval == 0 ? ECONNRESET /* not possible? */
710 : nlmsghdr->nlmsg_len != UINT32_MAX ? 0
711 : retval);
712 } while (error == EINTR);
713 if (error) {
714 if (error == ENOBUFS) {
715 /* Socket receive buffer overflow dropped one or more messages that
716 * the kernel tried to send to us. */
717 COVERAGE_INC(netlink_overflow);
718 }
719 return error;
720 }
721
722 if (msg.msg_flags & MSG_TRUNC) {
723 VLOG_ERR_RL(&rl, "truncated message (longer than %"PRIuSIZE" bytes)",
724 sizeof tail);
725 return E2BIG;
726 }
727
728 if (retval < sizeof *nlmsghdr
729 || nlmsghdr->nlmsg_len < sizeof *nlmsghdr
730 || nlmsghdr->nlmsg_len > retval) {
731 VLOG_ERR_RL(&rl, "received invalid nlmsg (%"PRIuSIZE" bytes < %"PRIuSIZE")",
732 retval, sizeof *nlmsghdr);
733 return EPROTO;
734 }
735 #ifndef _WIN32
736 buf->size = MIN(retval, buf->allocated);
737 if (retval > buf->allocated) {
738 COVERAGE_INC(netlink_recv_jumbo);
739 ofpbuf_put(buf, tail, retval - buf->allocated);
740 }
741 #endif
742
743 if (nsid) {
744 /* The network namespace id from which the message was sent comes
745 * as ancillary data. For older kernels, this data is either not
746 * available or it might be -1, so it falls back to local network
747 * namespace (no id). Latest kernels return a valid ID only if
748 * available or nothing. */
749 netnsid_set_local(nsid);
750 #ifndef _WIN32
751 cmsg = CMSG_FIRSTHDR(&msg);
752 while (cmsg != NULL) {
753 if (cmsg->cmsg_level == SOL_NETLINK
754 && cmsg->cmsg_type == NETLINK_LISTEN_ALL_NSID) {
755 ptr = ALIGNED_CAST(int *, CMSG_DATA(cmsg));
756 netnsid_set(nsid, *ptr);
757 }
758 if (cmsg->cmsg_level == SOL_SOCKET
759 && cmsg->cmsg_type == SCM_RIGHTS) {
760 /* This is unexpected and unwanted, close all fds */
761 int nfds;
762 int i;
763 nfds = (cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)))
764 / sizeof(int);
765 ptr = ALIGNED_CAST(int *, CMSG_DATA(cmsg));
766 for (i = 0; i < nfds; i++) {
767 VLOG_ERR_RL(&rl, "closing unexpected received fd (%d).",
768 ptr[i]);
769 close(ptr[i]);
770 }
771 }
772
773 cmsg = CMSG_NXTHDR(&msg, cmsg);
774 }
775 #endif
776 }
777
778 log_nlmsg(__func__, 0, buf->data, buf->size, sock->protocol);
779 COVERAGE_INC(netlink_received);
780
781 return 0;
782 }
783
784 /* Tries to receive a Netlink message from the kernel on 'sock' into 'buf'. If
785 * 'wait' is true, waits for a message to be ready. Otherwise, fails with
786 * EAGAIN if the 'sock' receive buffer is empty. If 'nsid' is provided, the
787 * network namespace id from which the message was sent will be provided.
788 *
789 * The caller must have initialized 'buf' with an allocation of at least
790 * NLMSG_HDRLEN bytes. For best performance, the caller should allocate enough
791 * space for a "typical" message.
792 *
793 * On success, returns 0 and replaces 'buf''s previous content by the received
794 * message. This function expands 'buf''s allocated memory, as necessary, to
795 * hold the actual size of the received message.
796 *
797 * On failure, returns a positive errno value and clears 'buf' to zero length.
798 * 'buf' retains its previous memory allocation.
799 *
800 * Regardless of success or failure, this function resets 'buf''s headroom to
801 * 0. */
802 int
803 nl_sock_recv(struct nl_sock *sock, struct ofpbuf *buf, int *nsid, bool wait)
804 {
805 return nl_sock_recv__(sock, buf, nsid, wait);
806 }
807
808 static void
809 nl_sock_record_errors__(struct nl_transaction **transactions, size_t n,
810 int error)
811 {
812 size_t i;
813
814 for (i = 0; i < n; i++) {
815 struct nl_transaction *txn = transactions[i];
816
817 txn->error = error;
818 if (txn->reply) {
819 ofpbuf_clear(txn->reply);
820 }
821 }
822 }
823
824 static int
825 nl_sock_transact_multiple__(struct nl_sock *sock,
826 struct nl_transaction **transactions, size_t n,
827 size_t *done)
828 {
829 uint64_t tmp_reply_stub[1024 / 8];
830 struct nl_transaction tmp_txn;
831 struct ofpbuf tmp_reply;
832
833 uint32_t base_seq;
834 struct iovec iovs[MAX_IOVS];
835 struct msghdr msg;
836 int error;
837 int i;
838
839 base_seq = nl_sock_allocate_seq(sock, n);
840 *done = 0;
841 for (i = 0; i < n; i++) {
842 struct nl_transaction *txn = transactions[i];
843 struct nlmsghdr *nlmsg = nl_msg_nlmsghdr(txn->request);
844
845 nlmsg->nlmsg_len = txn->request->size;
846 nlmsg->nlmsg_seq = base_seq + i;
847 nlmsg->nlmsg_pid = sock->pid;
848
849 iovs[i].iov_base = txn->request->data;
850 iovs[i].iov_len = txn->request->size;
851 }
852
853 #ifndef _WIN32
854 memset(&msg, 0, sizeof msg);
855 msg.msg_iov = iovs;
856 msg.msg_iovlen = n;
857 do {
858 error = sendmsg(sock->fd, &msg, 0) < 0 ? errno : 0;
859 } while (error == EINTR);
860
861 for (i = 0; i < n; i++) {
862 struct nl_transaction *txn = transactions[i];
863
864 log_nlmsg(__func__, error, txn->request->data,
865 txn->request->size, sock->protocol);
866 }
867 if (!error) {
868 COVERAGE_ADD(netlink_sent, n);
869 }
870
871 if (error) {
872 return error;
873 }
874
875 ofpbuf_use_stub(&tmp_reply, tmp_reply_stub, sizeof tmp_reply_stub);
876 tmp_txn.request = NULL;
877 tmp_txn.reply = &tmp_reply;
878 tmp_txn.error = 0;
879 while (n > 0) {
880 struct nl_transaction *buf_txn, *txn;
881 uint32_t seq;
882
883 /* Find a transaction whose buffer we can use for receiving a reply.
884 * If no such transaction is left, use tmp_txn. */
885 buf_txn = &tmp_txn;
886 for (i = 0; i < n; i++) {
887 if (transactions[i]->reply) {
888 buf_txn = transactions[i];
889 break;
890 }
891 }
892
893 /* Receive a reply. */
894 error = nl_sock_recv__(sock, buf_txn->reply, NULL, false);
895 if (error) {
896 if (error == EAGAIN) {
897 nl_sock_record_errors__(transactions, n, 0);
898 *done += n;
899 error = 0;
900 }
901 break;
902 }
903
904 /* Match the reply up with a transaction. */
905 seq = nl_msg_nlmsghdr(buf_txn->reply)->nlmsg_seq;
906 if (seq < base_seq || seq >= base_seq + n) {
907 VLOG_DBG_RL(&rl, "ignoring unexpected seq %#"PRIx32, seq);
908 continue;
909 }
910 i = seq - base_seq;
911 txn = transactions[i];
912
913 /* Fill in the results for 'txn'. */
914 if (nl_msg_nlmsgerr(buf_txn->reply, &txn->error)) {
915 if (txn->reply) {
916 ofpbuf_clear(txn->reply);
917 }
918 if (txn->error) {
919 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
920 error, ovs_strerror(txn->error));
921 }
922 } else {
923 txn->error = 0;
924 if (txn->reply && txn != buf_txn) {
925 /* Swap buffers. */
926 struct ofpbuf *reply = buf_txn->reply;
927 buf_txn->reply = txn->reply;
928 txn->reply = reply;
929 }
930 }
931
932 /* Fill in the results for transactions before 'txn'. (We have to do
933 * this after the results for 'txn' itself because of the buffer swap
934 * above.) */
935 nl_sock_record_errors__(transactions, i, 0);
936
937 /* Advance. */
938 *done += i + 1;
939 transactions += i + 1;
940 n -= i + 1;
941 base_seq += i + 1;
942 }
943 ofpbuf_uninit(&tmp_reply);
944 #else
945 error = 0;
946 uint8_t reply_buf[65536];
947 for (i = 0; i < n; i++) {
948 DWORD reply_len;
949 bool ret;
950 struct nl_transaction *txn = transactions[i];
951 struct nlmsghdr *request_nlmsg, *reply_nlmsg;
952
953 ret = DeviceIoControl(sock->handle, OVS_IOCTL_TRANSACT,
954 txn->request->data,
955 txn->request->size,
956 reply_buf, sizeof reply_buf,
957 &reply_len, NULL);
958
959 if (ret && reply_len == 0) {
960 /*
961 * The current transaction did not produce any data to read and that
962 * is not an error as such. Continue with the remainder of the
963 * transactions.
964 */
965 txn->error = 0;
966 if (txn->reply) {
967 ofpbuf_clear(txn->reply);
968 }
969 } else if (!ret) {
970 /* XXX: Map to a more appropriate error. */
971 lost_communication(GetLastError());
972 error = EINVAL;
973 VLOG_DBG_RL(&rl, "fatal driver failure: %s",
974 ovs_lasterror_to_string());
975 break;
976 }
977
978 if (reply_len != 0) {
979 request_nlmsg = nl_msg_nlmsghdr(txn->request);
980
981 if (reply_len < sizeof *reply_nlmsg) {
982 nl_sock_record_errors__(transactions, n, 0);
983 VLOG_DBG_RL(&rl, "insufficient length of reply %#"PRIu32
984 " for seq: %#"PRIx32, reply_len, request_nlmsg->nlmsg_seq);
985 break;
986 }
987
988 /* Validate the sequence number in the reply. */
989 reply_nlmsg = (struct nlmsghdr *)reply_buf;
990
991 if (request_nlmsg->nlmsg_seq != reply_nlmsg->nlmsg_seq) {
992 ovs_assert(request_nlmsg->nlmsg_seq == reply_nlmsg->nlmsg_seq);
993 VLOG_DBG_RL(&rl, "mismatched seq request %#"PRIx32
994 ", reply %#"PRIx32, request_nlmsg->nlmsg_seq,
995 reply_nlmsg->nlmsg_seq);
996 break;
997 }
998
999 /* Handle errors embedded within the netlink message. */
1000 ofpbuf_use_stub(&tmp_reply, reply_buf, sizeof reply_buf);
1001 tmp_reply.size = sizeof reply_buf;
1002 if (nl_msg_nlmsgerr(&tmp_reply, &txn->error)) {
1003 if (txn->reply) {
1004 ofpbuf_clear(txn->reply);
1005 }
1006 if (txn->error) {
1007 VLOG_DBG_RL(&rl, "received NAK error=%d (%s)",
1008 error, ovs_strerror(txn->error));
1009 }
1010 } else {
1011 txn->error = 0;
1012 if (txn->reply) {
1013 /* Copy the reply to the buffer specified by the caller. */
1014 if (reply_len > txn->reply->allocated) {
1015 ofpbuf_reinit(txn->reply, reply_len);
1016 }
1017 memcpy(txn->reply->data, reply_buf, reply_len);
1018 txn->reply->size = reply_len;
1019 }
1020 }
1021 ofpbuf_uninit(&tmp_reply);
1022 }
1023
1024 /* Count the number of successful transactions. */
1025 (*done)++;
1026
1027 }
1028
1029 if (!error) {
1030 COVERAGE_ADD(netlink_sent, n);
1031 }
1032 #endif
1033
1034 return error;
1035 }
1036
1037 static void
1038 nl_sock_transact_multiple(struct nl_sock *sock,
1039 struct nl_transaction **transactions, size_t n)
1040 {
1041 int max_batch_count;
1042 int error;
1043
1044 if (!n) {
1045 return;
1046 }
1047
1048 /* In theory, every request could have a 64 kB reply. But the default and
1049 * maximum socket rcvbuf size with typical Dom0 memory sizes both tend to
1050 * be a bit below 128 kB, so that would only allow a single message in a
1051 * "batch". So we assume that replies average (at most) 4 kB, which allows
1052 * a good deal of batching.
1053 *
1054 * In practice, most of the requests that we batch either have no reply at
1055 * all or a brief reply. */
1056 max_batch_count = MAX(sock->rcvbuf / 4096, 1);
1057 max_batch_count = MIN(max_batch_count, max_iovs);
1058
1059 while (n > 0) {
1060 size_t count, bytes;
1061 size_t done;
1062
1063 /* Batch up to 'max_batch_count' transactions. But cap it at about a
1064 * page of requests total because big skbuffs are expensive to
1065 * allocate in the kernel. */
1066 #if defined(PAGESIZE)
1067 enum { MAX_BATCH_BYTES = MAX(1, PAGESIZE - 512) };
1068 #else
1069 enum { MAX_BATCH_BYTES = 4096 - 512 };
1070 #endif
1071 bytes = transactions[0]->request->size;
1072 for (count = 1; count < n && count < max_batch_count; count++) {
1073 if (bytes + transactions[count]->request->size > MAX_BATCH_BYTES) {
1074 break;
1075 }
1076 bytes += transactions[count]->request->size;
1077 }
1078
1079 error = nl_sock_transact_multiple__(sock, transactions, count, &done);
1080 transactions += done;
1081 n -= done;
1082
1083 if (error == ENOBUFS) {
1084 VLOG_DBG_RL(&rl, "receive buffer overflow, resending request");
1085 } else if (error) {
1086 VLOG_ERR_RL(&rl, "transaction error (%s)", ovs_strerror(error));
1087 nl_sock_record_errors__(transactions, n, error);
1088 if (error != EAGAIN) {
1089 /* A fatal error has occurred. Abort the rest of
1090 * transactions. */
1091 break;
1092 }
1093 }
1094 }
1095 }
1096
1097 static int
1098 nl_sock_transact(struct nl_sock *sock, const struct ofpbuf *request,
1099 struct ofpbuf **replyp)
1100 {
1101 struct nl_transaction *transactionp;
1102 struct nl_transaction transaction;
1103
1104 transaction.request = CONST_CAST(struct ofpbuf *, request);
1105 transaction.reply = replyp ? ofpbuf_new(1024) : NULL;
1106 transactionp = &transaction;
1107
1108 nl_sock_transact_multiple(sock, &transactionp, 1);
1109
1110 if (replyp) {
1111 if (transaction.error) {
1112 ofpbuf_delete(transaction.reply);
1113 *replyp = NULL;
1114 } else {
1115 *replyp = transaction.reply;
1116 }
1117 }
1118
1119 return transaction.error;
1120 }
1121
1122 /* Drain all the messages currently in 'sock''s receive queue. */
1123 int
1124 nl_sock_drain(struct nl_sock *sock)
1125 {
1126 #ifdef _WIN32
1127 return 0;
1128 #else
1129 return drain_rcvbuf(sock->fd);
1130 #endif
1131 }
1132
1133 /* Starts a Netlink "dump" operation, by sending 'request' to the kernel on a
1134 * Netlink socket created with the given 'protocol', and initializes 'dump' to
1135 * reflect the state of the operation.
1136 *
1137 * 'request' must contain a Netlink message. Before sending the message,
1138 * nlmsg_len will be finalized to match request->size, and nlmsg_pid will be
1139 * set to the Netlink socket's pid. NLM_F_DUMP and NLM_F_ACK will be set in
1140 * nlmsg_flags.
1141 *
1142 * The design of this Netlink socket library ensures that the dump is reliable.
1143 *
1144 * This function provides no status indication. nl_dump_done() provides an
1145 * error status for the entire dump operation.
1146 *
1147 * The caller must eventually destroy 'request'.
1148 */
1149 void
1150 nl_dump_start(struct nl_dump *dump, int protocol, const struct ofpbuf *request)
1151 {
1152 nl_msg_nlmsghdr(request)->nlmsg_flags |= NLM_F_DUMP | NLM_F_ACK;
1153
1154 ovs_mutex_init(&dump->mutex);
1155 ovs_mutex_lock(&dump->mutex);
1156 dump->status = nl_pool_alloc(protocol, &dump->sock);
1157 if (!dump->status) {
1158 dump->status = nl_sock_send__(dump->sock, request,
1159 nl_sock_allocate_seq(dump->sock, 1),
1160 true);
1161 }
1162 dump->nl_seq = nl_msg_nlmsghdr(request)->nlmsg_seq;
1163 ovs_mutex_unlock(&dump->mutex);
1164 }
1165
1166 static int
1167 nl_dump_refill(struct nl_dump *dump, struct ofpbuf *buffer)
1168 OVS_REQUIRES(dump->mutex)
1169 {
1170 struct nlmsghdr *nlmsghdr;
1171 int error;
1172
1173 while (!buffer->size) {
1174 error = nl_sock_recv__(dump->sock, buffer, NULL, false);
1175 if (error) {
1176 /* The kernel never blocks providing the results of a dump, so
1177 * error == EAGAIN means that we've read the whole thing, and
1178 * therefore transform it into EOF. (The kernel always provides
1179 * NLMSG_DONE as a sentinel. Some other thread must have received
1180 * that already but not yet signaled it in 'status'.)
1181 *
1182 * Any other error is just an error. */
1183 return error == EAGAIN ? EOF : error;
1184 }
1185
1186 nlmsghdr = nl_msg_nlmsghdr(buffer);
1187 if (dump->nl_seq != nlmsghdr->nlmsg_seq) {
1188 VLOG_DBG_RL(&rl, "ignoring seq %#"PRIx32" != expected %#"PRIx32,
1189 nlmsghdr->nlmsg_seq, dump->nl_seq);
1190 ofpbuf_clear(buffer);
1191 }
1192 }
1193
1194 if (nl_msg_nlmsgerr(buffer, &error) && error) {
1195 VLOG_INFO_RL(&rl, "netlink dump request error (%s)",
1196 ovs_strerror(error));
1197 ofpbuf_clear(buffer);
1198 return error;
1199 }
1200
1201 return 0;
1202 }
1203
1204 static int
1205 nl_dump_next__(struct ofpbuf *reply, struct ofpbuf *buffer)
1206 {
1207 struct nlmsghdr *nlmsghdr = nl_msg_next(buffer, reply);
1208 if (!nlmsghdr) {
1209 VLOG_WARN_RL(&rl, "netlink dump contains message fragment");
1210 return EPROTO;
1211 } else if (nlmsghdr->nlmsg_type == NLMSG_DONE) {
1212 return EOF;
1213 } else {
1214 return 0;
1215 }
1216 }
1217
1218 /* Attempts to retrieve another reply from 'dump' into 'buffer'. 'dump' must
1219 * have been initialized with nl_dump_start(), and 'buffer' must have been
1220 * initialized. 'buffer' should be at least NL_DUMP_BUFSIZE bytes long.
1221 *
1222 * If successful, returns true and points 'reply->data' and
1223 * 'reply->size' to the message that was retrieved. The caller must not
1224 * modify 'reply' (because it points within 'buffer', which will be used by
1225 * future calls to this function).
1226 *
1227 * On failure, returns false and sets 'reply->data' to NULL and
1228 * 'reply->size' to 0. Failure might indicate an actual error or merely
1229 * the end of replies. An error status for the entire dump operation is
1230 * provided when it is completed by calling nl_dump_done().
1231 *
1232 * Multiple threads may call this function, passing the same nl_dump, however
1233 * each must provide independent buffers. This function may cache multiple
1234 * replies in the buffer, and these will be processed before more replies are
1235 * fetched. When this function returns false, other threads may continue to
1236 * process replies in their buffers, but they will not fetch more replies.
1237 */
1238 bool
1239 nl_dump_next(struct nl_dump *dump, struct ofpbuf *reply, struct ofpbuf *buffer)
1240 {
1241 int retval = 0;
1242
1243 /* If the buffer is empty, refill it.
1244 *
1245 * If the buffer is not empty, we don't check the dump's status.
1246 * Otherwise, we could end up skipping some of the dump results if thread A
1247 * hits EOF while thread B is in the midst of processing a batch. */
1248 if (!buffer->size) {
1249 ovs_mutex_lock(&dump->mutex);
1250 if (!dump->status) {
1251 /* Take the mutex here to avoid an in-kernel race. If two threads
1252 * try to read from a Netlink dump socket at once, then the socket
1253 * error can be set to EINVAL, which will be encountered on the
1254 * next recv on that socket, which could be anywhere due to the way
1255 * that we pool Netlink sockets. Serializing the recv calls avoids
1256 * the issue. */
1257 dump->status = nl_dump_refill(dump, buffer);
1258 }
1259 retval = dump->status;
1260 ovs_mutex_unlock(&dump->mutex);
1261 }
1262
1263 /* Fetch the next message from the buffer. */
1264 if (!retval) {
1265 retval = nl_dump_next__(reply, buffer);
1266 if (retval) {
1267 /* Record 'retval' as the dump status, but don't overwrite an error
1268 * with EOF. */
1269 ovs_mutex_lock(&dump->mutex);
1270 if (dump->status <= 0) {
1271 dump->status = retval;
1272 }
1273 ovs_mutex_unlock(&dump->mutex);
1274 }
1275 }
1276
1277 if (retval) {
1278 reply->data = NULL;
1279 reply->size = 0;
1280 }
1281 return !retval;
1282 }
1283
1284 /* Completes Netlink dump operation 'dump', which must have been initialized
1285 * with nl_dump_start(). Returns 0 if the dump operation was error-free,
1286 * otherwise a positive errno value describing the problem. */
1287 int
1288 nl_dump_done(struct nl_dump *dump)
1289 {
1290 int status;
1291
1292 ovs_mutex_lock(&dump->mutex);
1293 status = dump->status;
1294 ovs_mutex_unlock(&dump->mutex);
1295
1296 /* Drain any remaining messages that the client didn't read. Otherwise the
1297 * kernel will continue to queue them up and waste buffer space.
1298 *
1299 * XXX We could just destroy and discard the socket in this case. */
1300 if (!status) {
1301 uint64_t tmp_reply_stub[NL_DUMP_BUFSIZE / 8];
1302 struct ofpbuf reply, buf;
1303
1304 ofpbuf_use_stub(&buf, tmp_reply_stub, sizeof tmp_reply_stub);
1305 while (nl_dump_next(dump, &reply, &buf)) {
1306 /* Nothing to do. */
1307 }
1308 ofpbuf_uninit(&buf);
1309
1310 ovs_mutex_lock(&dump->mutex);
1311 status = dump->status;
1312 ovs_mutex_unlock(&dump->mutex);
1313 ovs_assert(status);
1314 }
1315
1316 nl_pool_release(dump->sock);
1317 ovs_mutex_destroy(&dump->mutex);
1318
1319 return status == EOF ? 0 : status;
1320 }
1321
1322 #ifdef _WIN32
1323 /* Pend an I/O request in the driver. The driver completes the I/O whenever
1324 * an event or a packet is ready to be read. Once the I/O is completed
1325 * the overlapped structure event associated with the pending I/O will be set
1326 */
1327 static int
1328 pend_io_request(struct nl_sock *sock)
1329 {
1330 struct ofpbuf request;
1331 uint64_t request_stub[128];
1332 struct ovs_header *ovs_header;
1333 struct nlmsghdr *nlmsg;
1334 uint32_t seq;
1335 int retval = 0;
1336 int error;
1337 DWORD bytes;
1338 OVERLAPPED *overlapped = CONST_CAST(OVERLAPPED *, &sock->overlapped);
1339 uint16_t cmd = OVS_CTRL_CMD_WIN_PEND_PACKET_REQ;
1340
1341 ovs_assert(sock->read_ioctl == OVS_IOCTL_READ_PACKET ||
1342 sock->read_ioctl == OVS_IOCTL_READ_EVENT);
1343 if (sock->read_ioctl == OVS_IOCTL_READ_EVENT) {
1344 cmd = OVS_CTRL_CMD_WIN_PEND_REQ;
1345 }
1346
1347 int ovs_msg_size = sizeof (struct nlmsghdr) + sizeof (struct genlmsghdr) +
1348 sizeof (struct ovs_header);
1349
1350 ofpbuf_use_stub(&request, request_stub, sizeof request_stub);
1351
1352 seq = nl_sock_allocate_seq(sock, 1);
1353 nl_msg_put_genlmsghdr(&request, 0, OVS_WIN_NL_CTRL_FAMILY_ID, 0,
1354 cmd, OVS_WIN_CONTROL_VERSION);
1355 nlmsg = nl_msg_nlmsghdr(&request);
1356 nlmsg->nlmsg_seq = seq;
1357 nlmsg->nlmsg_pid = sock->pid;
1358
1359 ovs_header = ofpbuf_put_uninit(&request, sizeof *ovs_header);
1360 ovs_header->dp_ifindex = 0;
1361 nlmsg->nlmsg_len = request.size;
1362
1363 if (!DeviceIoControl(sock->handle, OVS_IOCTL_WRITE,
1364 request.data, request.size,
1365 NULL, 0, &bytes, overlapped)) {
1366 error = GetLastError();
1367 /* Check if the I/O got pended */
1368 if (error != ERROR_IO_INCOMPLETE && error != ERROR_IO_PENDING) {
1369 lost_communication(error);
1370 VLOG_ERR("nl_sock_wait failed - %s\n", ovs_format_message(error));
1371 retval = EINVAL;
1372 }
1373 } else {
1374 retval = EAGAIN;
1375 }
1376
1377 done:
1378 ofpbuf_uninit(&request);
1379 return retval;
1380 }
1381 #endif /* _WIN32 */
1382
1383 /* Causes poll_block() to wake up when any of the specified 'events' (which is
1384 * a OR'd combination of POLLIN, POLLOUT, etc.) occur on 'sock'.
1385 * On Windows, 'sock' is not treated as const, and may be modified. */
1386 void
1387 nl_sock_wait(const struct nl_sock *sock, short int events)
1388 {
1389 #ifdef _WIN32
1390 if (sock->overlapped.Internal != STATUS_PENDING) {
1391 int ret = pend_io_request(CONST_CAST(struct nl_sock *, sock));
1392 if (ret == 0) {
1393 poll_wevent_wait(sock->overlapped.hEvent);
1394 } else {
1395 poll_immediate_wake();
1396 }
1397 } else {
1398 poll_wevent_wait(sock->overlapped.hEvent);
1399 }
1400 #else
1401 poll_fd_wait(sock->fd, events);
1402 #endif
1403 }
1404
1405 #ifndef _WIN32
1406 /* Returns the underlying fd for 'sock', for use in "poll()"-like operations
1407 * that can't use nl_sock_wait().
1408 *
1409 * It's a little tricky to use the returned fd correctly, because nl_sock does
1410 * "copy on write" to allow a single nl_sock to be used for notifications,
1411 * transactions, and dumps. If 'sock' is used only for notifications and
1412 * transactions (and never for dump) then the usage is safe. */
1413 int
1414 nl_sock_fd(const struct nl_sock *sock)
1415 {
1416 return sock->fd;
1417 }
1418 #endif
1419
1420 /* Returns the PID associated with this socket. */
1421 uint32_t
1422 nl_sock_pid(const struct nl_sock *sock)
1423 {
1424 return sock->pid;
1425 }
1426 \f
1427 /* Miscellaneous. */
1428
1429 struct genl_family {
1430 struct hmap_node hmap_node;
1431 uint16_t id;
1432 char *name;
1433 };
1434
1435 static struct hmap genl_families = HMAP_INITIALIZER(&genl_families);
1436
1437 static const struct nl_policy family_policy[CTRL_ATTR_MAX + 1] = {
1438 [CTRL_ATTR_FAMILY_ID] = {.type = NL_A_U16},
1439 [CTRL_ATTR_MCAST_GROUPS] = {.type = NL_A_NESTED, .optional = true},
1440 };
1441
1442 static struct genl_family *
1443 find_genl_family_by_id(uint16_t id)
1444 {
1445 struct genl_family *family;
1446
1447 HMAP_FOR_EACH_IN_BUCKET (family, hmap_node, hash_int(id, 0),
1448 &genl_families) {
1449 if (family->id == id) {
1450 return family;
1451 }
1452 }
1453 return NULL;
1454 }
1455
1456 static void
1457 define_genl_family(uint16_t id, const char *name)
1458 {
1459 struct genl_family *family = find_genl_family_by_id(id);
1460
1461 if (family) {
1462 if (!strcmp(family->name, name)) {
1463 return;
1464 }
1465 free(family->name);
1466 } else {
1467 family = xmalloc(sizeof *family);
1468 family->id = id;
1469 hmap_insert(&genl_families, &family->hmap_node, hash_int(id, 0));
1470 }
1471 family->name = xstrdup(name);
1472 }
1473
1474 static const char *
1475 genl_family_to_name(uint16_t id)
1476 {
1477 if (id == GENL_ID_CTRL) {
1478 return "control";
1479 } else {
1480 struct genl_family *family = find_genl_family_by_id(id);
1481 return family ? family->name : "unknown";
1482 }
1483 }
1484
1485 #ifndef _WIN32
1486 static int
1487 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1488 struct ofpbuf **replyp)
1489 {
1490 struct nl_sock *sock;
1491 struct ofpbuf request, *reply;
1492 int error;
1493
1494 *replyp = NULL;
1495 error = nl_sock_create(NETLINK_GENERIC, &sock);
1496 if (error) {
1497 return error;
1498 }
1499
1500 ofpbuf_init(&request, 0);
1501 nl_msg_put_genlmsghdr(&request, 0, GENL_ID_CTRL, NLM_F_REQUEST,
1502 CTRL_CMD_GETFAMILY, 1);
1503 nl_msg_put_string(&request, CTRL_ATTR_FAMILY_NAME, name);
1504 error = nl_sock_transact(sock, &request, &reply);
1505 ofpbuf_uninit(&request);
1506 if (error) {
1507 nl_sock_destroy(sock);
1508 return error;
1509 }
1510
1511 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1512 family_policy, attrs, ARRAY_SIZE(family_policy))
1513 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1514 nl_sock_destroy(sock);
1515 ofpbuf_delete(reply);
1516 return EPROTO;
1517 }
1518
1519 nl_sock_destroy(sock);
1520 *replyp = reply;
1521 return 0;
1522 }
1523 #else
1524 static int
1525 do_lookup_genl_family(const char *name, struct nlattr **attrs,
1526 struct ofpbuf **replyp)
1527 {
1528 struct nlmsghdr *nlmsg;
1529 struct ofpbuf *reply;
1530 int error;
1531 uint16_t family_id;
1532 const char *family_name;
1533 uint32_t family_version;
1534 uint32_t family_attrmax;
1535 uint32_t mcgrp_id = OVS_WIN_NL_INVALID_MCGRP_ID;
1536 const char *mcgrp_name = NULL;
1537
1538 *replyp = NULL;
1539 reply = ofpbuf_new(1024);
1540
1541 /* CTRL_ATTR_MCAST_GROUPS is supported only for VPORT family. */
1542 if (!strcmp(name, OVS_WIN_CONTROL_FAMILY)) {
1543 family_id = OVS_WIN_NL_CTRL_FAMILY_ID;
1544 family_name = OVS_WIN_CONTROL_FAMILY;
1545 family_version = OVS_WIN_CONTROL_VERSION;
1546 family_attrmax = OVS_WIN_CONTROL_ATTR_MAX;
1547 } else if (!strcmp(name, OVS_DATAPATH_FAMILY)) {
1548 family_id = OVS_WIN_NL_DATAPATH_FAMILY_ID;
1549 family_name = OVS_DATAPATH_FAMILY;
1550 family_version = OVS_DATAPATH_VERSION;
1551 family_attrmax = OVS_DP_ATTR_MAX;
1552 } else if (!strcmp(name, OVS_PACKET_FAMILY)) {
1553 family_id = OVS_WIN_NL_PACKET_FAMILY_ID;
1554 family_name = OVS_PACKET_FAMILY;
1555 family_version = OVS_PACKET_VERSION;
1556 family_attrmax = OVS_PACKET_ATTR_MAX;
1557 } else if (!strcmp(name, OVS_VPORT_FAMILY)) {
1558 family_id = OVS_WIN_NL_VPORT_FAMILY_ID;
1559 family_name = OVS_VPORT_FAMILY;
1560 family_version = OVS_VPORT_VERSION;
1561 family_attrmax = OVS_VPORT_ATTR_MAX;
1562 mcgrp_id = OVS_WIN_NL_VPORT_MCGRP_ID;
1563 mcgrp_name = OVS_VPORT_MCGROUP;
1564 } else if (!strcmp(name, OVS_FLOW_FAMILY)) {
1565 family_id = OVS_WIN_NL_FLOW_FAMILY_ID;
1566 family_name = OVS_FLOW_FAMILY;
1567 family_version = OVS_FLOW_VERSION;
1568 family_attrmax = OVS_FLOW_ATTR_MAX;
1569 } else if (!strcmp(name, OVS_WIN_NETDEV_FAMILY)) {
1570 family_id = OVS_WIN_NL_NETDEV_FAMILY_ID;
1571 family_name = OVS_WIN_NETDEV_FAMILY;
1572 family_version = OVS_WIN_NETDEV_VERSION;
1573 family_attrmax = OVS_WIN_NETDEV_ATTR_MAX;
1574 } else if (!strcmp(name, OVS_CT_LIMIT_FAMILY)) {
1575 family_id = OVS_WIN_NL_CTLIMIT_FAMILY_ID;
1576 family_name = OVS_CT_LIMIT_FAMILY;
1577 family_version = OVS_CT_LIMIT_VERSION;
1578 family_attrmax = OVS_CT_LIMIT_ATTR_MAX;
1579 } else {
1580 ofpbuf_delete(reply);
1581 return EINVAL;
1582 }
1583
1584 nl_msg_put_genlmsghdr(reply, 0, GENL_ID_CTRL, 0,
1585 CTRL_CMD_NEWFAMILY, family_version);
1586 /* CTRL_ATTR_HDRSIZE and CTRL_ATTR_OPS are not populated, but the
1587 * callers do not seem to need them. */
1588 nl_msg_put_u16(reply, CTRL_ATTR_FAMILY_ID, family_id);
1589 nl_msg_put_string(reply, CTRL_ATTR_FAMILY_NAME, family_name);
1590 nl_msg_put_u32(reply, CTRL_ATTR_VERSION, family_version);
1591 nl_msg_put_u32(reply, CTRL_ATTR_MAXATTR, family_attrmax);
1592
1593 if (mcgrp_id != OVS_WIN_NL_INVALID_MCGRP_ID) {
1594 size_t mcgrp_ofs1 = nl_msg_start_nested(reply, CTRL_ATTR_MCAST_GROUPS);
1595 size_t mcgrp_ofs2= nl_msg_start_nested(reply,
1596 OVS_WIN_NL_VPORT_MCGRP_ID - OVS_WIN_NL_MCGRP_START_ID);
1597 nl_msg_put_u32(reply, CTRL_ATTR_MCAST_GRP_ID, mcgrp_id);
1598 ovs_assert(mcgrp_name != NULL);
1599 nl_msg_put_string(reply, CTRL_ATTR_MCAST_GRP_NAME, mcgrp_name);
1600 nl_msg_end_nested(reply, mcgrp_ofs2);
1601 nl_msg_end_nested(reply, mcgrp_ofs1);
1602 }
1603
1604 /* Set the total length of the netlink message. */
1605 nlmsg = nl_msg_nlmsghdr(reply);
1606 nlmsg->nlmsg_len = reply->size;
1607
1608 if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
1609 family_policy, attrs, ARRAY_SIZE(family_policy))
1610 || nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]) == 0) {
1611 ofpbuf_delete(reply);
1612 return EPROTO;
1613 }
1614
1615 *replyp = reply;
1616 return 0;
1617 }
1618 #endif
1619
1620 /* Finds the multicast group called 'group_name' in genl family 'family_name'.
1621 * When successful, writes its result to 'multicast_group' and returns 0.
1622 * Otherwise, clears 'multicast_group' and returns a positive error code.
1623 */
1624 int
1625 nl_lookup_genl_mcgroup(const char *family_name, const char *group_name,
1626 unsigned int *multicast_group)
1627 {
1628 struct nlattr *family_attrs[ARRAY_SIZE(family_policy)];
1629 const struct nlattr *mc;
1630 struct ofpbuf *reply;
1631 unsigned int left;
1632 int error;
1633
1634 *multicast_group = 0;
1635 error = do_lookup_genl_family(family_name, family_attrs, &reply);
1636 if (error) {
1637 return error;
1638 }
1639
1640 if (!family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1641 error = EPROTO;
1642 goto exit;
1643 }
1644
1645 NL_NESTED_FOR_EACH (mc, left, family_attrs[CTRL_ATTR_MCAST_GROUPS]) {
1646 static const struct nl_policy mc_policy[] = {
1647 [CTRL_ATTR_MCAST_GRP_ID] = {.type = NL_A_U32},
1648 [CTRL_ATTR_MCAST_GRP_NAME] = {.type = NL_A_STRING},
1649 };
1650
1651 struct nlattr *mc_attrs[ARRAY_SIZE(mc_policy)];
1652 const char *mc_name;
1653
1654 if (!nl_parse_nested(mc, mc_policy, mc_attrs, ARRAY_SIZE(mc_policy))) {
1655 error = EPROTO;
1656 goto exit;
1657 }
1658
1659 mc_name = nl_attr_get_string(mc_attrs[CTRL_ATTR_MCAST_GRP_NAME]);
1660 if (!strcmp(group_name, mc_name)) {
1661 *multicast_group =
1662 nl_attr_get_u32(mc_attrs[CTRL_ATTR_MCAST_GRP_ID]);
1663 error = 0;
1664 goto exit;
1665 }
1666 }
1667 error = EPROTO;
1668
1669 exit:
1670 ofpbuf_delete(reply);
1671 return error;
1672 }
1673
1674 /* If '*number' is 0, translates the given Generic Netlink family 'name' to a
1675 * number and stores it in '*number'. If successful, returns 0 and the caller
1676 * may use '*number' as the family number. On failure, returns a positive
1677 * errno value and '*number' caches the errno value. */
1678 int
1679 nl_lookup_genl_family(const char *name, int *number)
1680 {
1681 if (*number == 0) {
1682 struct nlattr *attrs[ARRAY_SIZE(family_policy)];
1683 struct ofpbuf *reply;
1684 int error;
1685
1686 error = do_lookup_genl_family(name, attrs, &reply);
1687 if (!error) {
1688 *number = nl_attr_get_u16(attrs[CTRL_ATTR_FAMILY_ID]);
1689 define_genl_family(*number, name);
1690 } else {
1691 *number = -error;
1692 }
1693 ofpbuf_delete(reply);
1694
1695 ovs_assert(*number != 0);
1696 }
1697 return *number > 0 ? 0 : -*number;
1698 }
1699 \f
1700 struct nl_pool {
1701 struct nl_sock *socks[16];
1702 int n;
1703 };
1704
1705 static struct ovs_mutex pool_mutex = OVS_MUTEX_INITIALIZER;
1706 static struct nl_pool pools[MAX_LINKS] OVS_GUARDED_BY(pool_mutex);
1707
1708 static int
1709 nl_pool_alloc(int protocol, struct nl_sock **sockp)
1710 {
1711 struct nl_sock *sock = NULL;
1712 struct nl_pool *pool;
1713
1714 ovs_assert(protocol >= 0 && protocol < ARRAY_SIZE(pools));
1715
1716 ovs_mutex_lock(&pool_mutex);
1717 pool = &pools[protocol];
1718 if (pool->n > 0) {
1719 sock = pool->socks[--pool->n];
1720 }
1721 ovs_mutex_unlock(&pool_mutex);
1722
1723 if (sock) {
1724 *sockp = sock;
1725 return 0;
1726 } else {
1727 return nl_sock_create(protocol, sockp);
1728 }
1729 }
1730
1731 static void
1732 nl_pool_release(struct nl_sock *sock)
1733 {
1734 if (sock) {
1735 struct nl_pool *pool = &pools[sock->protocol];
1736
1737 ovs_mutex_lock(&pool_mutex);
1738 if (pool->n < ARRAY_SIZE(pool->socks)) {
1739 pool->socks[pool->n++] = sock;
1740 sock = NULL;
1741 }
1742 ovs_mutex_unlock(&pool_mutex);
1743
1744 nl_sock_destroy(sock);
1745 }
1746 }
1747
1748 /* Sends 'request' to the kernel on a Netlink socket for the given 'protocol'
1749 * (e.g. NETLINK_ROUTE or NETLINK_GENERIC) and waits for a response. If
1750 * successful, returns 0. On failure, returns a positive errno value.
1751 *
1752 * If 'replyp' is nonnull, then on success '*replyp' is set to the kernel's
1753 * reply, which the caller is responsible for freeing with ofpbuf_delete(), and
1754 * on failure '*replyp' is set to NULL. If 'replyp' is null, then the kernel's
1755 * reply, if any, is discarded.
1756 *
1757 * Before the message is sent, nlmsg_len in 'request' will be finalized to
1758 * match msg->size, nlmsg_pid will be set to the pid of the socket used
1759 * for sending the request, and nlmsg_seq will be initialized.
1760 *
1761 * The caller is responsible for destroying 'request'.
1762 *
1763 * Bare Netlink is an unreliable transport protocol. This function layers
1764 * reliable delivery and reply semantics on top of bare Netlink.
1765 *
1766 * In Netlink, sending a request to the kernel is reliable enough, because the
1767 * kernel will tell us if the message cannot be queued (and we will in that
1768 * case put it on the transmit queue and wait until it can be delivered).
1769 *
1770 * Receiving the reply is the real problem: if the socket buffer is full when
1771 * the kernel tries to send the reply, the reply will be dropped. However, the
1772 * kernel sets a flag that a reply has been dropped. The next call to recv
1773 * then returns ENOBUFS. We can then re-send the request.
1774 *
1775 * Caveats:
1776 *
1777 * 1. Netlink depends on sequence numbers to match up requests and
1778 * replies. The sender of a request supplies a sequence number, and
1779 * the reply echos back that sequence number.
1780 *
1781 * This is fine, but (1) some kernel netlink implementations are
1782 * broken, in that they fail to echo sequence numbers and (2) this
1783 * function will drop packets with non-matching sequence numbers, so
1784 * that only a single request can be usefully transacted at a time.
1785 *
1786 * 2. Resending the request causes it to be re-executed, so the request
1787 * needs to be idempotent.
1788 */
1789 int
1790 nl_transact(int protocol, const struct ofpbuf *request,
1791 struct ofpbuf **replyp)
1792 {
1793 struct nl_sock *sock;
1794 int error;
1795
1796 error = nl_pool_alloc(protocol, &sock);
1797 if (error) {
1798 if (replyp) {
1799 *replyp = NULL;
1800 }
1801 return error;
1802 }
1803
1804 error = nl_sock_transact(sock, request, replyp);
1805
1806 nl_pool_release(sock);
1807 return error;
1808 }
1809
1810 /* Sends the 'request' member of the 'n' transactions in 'transactions' on a
1811 * Netlink socket for the given 'protocol' (e.g. NETLINK_ROUTE or
1812 * NETLINK_GENERIC), in order, and receives responses to all of them. Fills in
1813 * the 'error' member of each transaction with 0 if it was successful,
1814 * otherwise with a positive errno value. If 'reply' is nonnull, then it will
1815 * be filled with the reply if the message receives a detailed reply. In other
1816 * cases, i.e. where the request failed or had no reply beyond an indication of
1817 * success, 'reply' will be cleared if it is nonnull.
1818 *
1819 * The caller is responsible for destroying each request and reply, and the
1820 * transactions array itself.
1821 *
1822 * Before sending each message, this function will finalize nlmsg_len in each
1823 * 'request' to match the ofpbuf's size, set nlmsg_pid to the pid of the socket
1824 * used for the transaction, and initialize nlmsg_seq.
1825 *
1826 * Bare Netlink is an unreliable transport protocol. This function layers
1827 * reliable delivery and reply semantics on top of bare Netlink. See
1828 * nl_transact() for some caveats.
1829 */
1830 void
1831 nl_transact_multiple(int protocol,
1832 struct nl_transaction **transactions, size_t n)
1833 {
1834 struct nl_sock *sock;
1835 int error;
1836
1837 error = nl_pool_alloc(protocol, &sock);
1838 if (!error) {
1839 nl_sock_transact_multiple(sock, transactions, n);
1840 nl_pool_release(sock);
1841 } else {
1842 nl_sock_record_errors__(transactions, n, error);
1843 }
1844 }
1845
1846 \f
1847 static uint32_t
1848 nl_sock_allocate_seq(struct nl_sock *sock, unsigned int n)
1849 {
1850 uint32_t seq = sock->next_seq;
1851
1852 sock->next_seq += n;
1853
1854 /* Make it impossible for the next request for sequence numbers to wrap
1855 * around to 0. Start over with 1 to avoid ever using a sequence number of
1856 * 0, because the kernel uses sequence number 0 for notifications. */
1857 if (sock->next_seq >= UINT32_MAX / 2) {
1858 sock->next_seq = 1;
1859 }
1860
1861 return seq;
1862 }
1863
1864 static void
1865 nlmsghdr_to_string(const struct nlmsghdr *h, int protocol, struct ds *ds)
1866 {
1867 struct nlmsg_flag {
1868 unsigned int bits;
1869 const char *name;
1870 };
1871 static const struct nlmsg_flag flags[] = {
1872 { NLM_F_REQUEST, "REQUEST" },
1873 { NLM_F_MULTI, "MULTI" },
1874 { NLM_F_ACK, "ACK" },
1875 { NLM_F_ECHO, "ECHO" },
1876 { NLM_F_DUMP, "DUMP" },
1877 { NLM_F_ROOT, "ROOT" },
1878 { NLM_F_MATCH, "MATCH" },
1879 { NLM_F_ATOMIC, "ATOMIC" },
1880 };
1881 const struct nlmsg_flag *flag;
1882 uint16_t flags_left;
1883
1884 ds_put_format(ds, "nl(len:%"PRIu32", type=%"PRIu16,
1885 h->nlmsg_len, h->nlmsg_type);
1886 if (h->nlmsg_type == NLMSG_NOOP) {
1887 ds_put_cstr(ds, "(no-op)");
1888 } else if (h->nlmsg_type == NLMSG_ERROR) {
1889 ds_put_cstr(ds, "(error)");
1890 } else if (h->nlmsg_type == NLMSG_DONE) {
1891 ds_put_cstr(ds, "(done)");
1892 } else if (h->nlmsg_type == NLMSG_OVERRUN) {
1893 ds_put_cstr(ds, "(overrun)");
1894 } else if (h->nlmsg_type < NLMSG_MIN_TYPE) {
1895 ds_put_cstr(ds, "(reserved)");
1896 } else if (protocol == NETLINK_GENERIC) {
1897 ds_put_format(ds, "(%s)", genl_family_to_name(h->nlmsg_type));
1898 } else {
1899 ds_put_cstr(ds, "(family-defined)");
1900 }
1901 ds_put_format(ds, ", flags=%"PRIx16, h->nlmsg_flags);
1902 flags_left = h->nlmsg_flags;
1903 for (flag = flags; flag < &flags[ARRAY_SIZE(flags)]; flag++) {
1904 if ((flags_left & flag->bits) == flag->bits) {
1905 ds_put_format(ds, "[%s]", flag->name);
1906 flags_left &= ~flag->bits;
1907 }
1908 }
1909 if (flags_left) {
1910 ds_put_format(ds, "[OTHER:%"PRIx16"]", flags_left);
1911 }
1912 ds_put_format(ds, ", seq=%"PRIx32", pid=%"PRIu32,
1913 h->nlmsg_seq, h->nlmsg_pid);
1914 }
1915
1916 static char *
1917 nlmsg_to_string(const struct ofpbuf *buffer, int protocol)
1918 {
1919 struct ds ds = DS_EMPTY_INITIALIZER;
1920 const struct nlmsghdr *h = ofpbuf_at(buffer, 0, NLMSG_HDRLEN);
1921 if (h) {
1922 nlmsghdr_to_string(h, protocol, &ds);
1923 if (h->nlmsg_type == NLMSG_ERROR) {
1924 const struct nlmsgerr *e;
1925 e = ofpbuf_at(buffer, NLMSG_HDRLEN,
1926 NLMSG_ALIGN(sizeof(struct nlmsgerr)));
1927 if (e) {
1928 ds_put_format(&ds, " error(%d", e->error);
1929 if (e->error < 0) {
1930 ds_put_format(&ds, "(%s)", ovs_strerror(-e->error));
1931 }
1932 ds_put_cstr(&ds, ", in-reply-to(");
1933 nlmsghdr_to_string(&e->msg, protocol, &ds);
1934 ds_put_cstr(&ds, "))");
1935 } else {
1936 ds_put_cstr(&ds, " error(truncated)");
1937 }
1938 } else if (h->nlmsg_type == NLMSG_DONE) {
1939 int *error = ofpbuf_at(buffer, NLMSG_HDRLEN, sizeof *error);
1940 if (error) {
1941 ds_put_format(&ds, " done(%d", *error);
1942 if (*error < 0) {
1943 ds_put_format(&ds, "(%s)", ovs_strerror(-*error));
1944 }
1945 ds_put_cstr(&ds, ")");
1946 } else {
1947 ds_put_cstr(&ds, " done(truncated)");
1948 }
1949 } else if (protocol == NETLINK_GENERIC) {
1950 struct genlmsghdr *genl = nl_msg_genlmsghdr(buffer);
1951 if (genl) {
1952 ds_put_format(&ds, ",genl(cmd=%"PRIu8",version=%"PRIu8")",
1953 genl->cmd, genl->version);
1954 }
1955 }
1956 } else {
1957 ds_put_cstr(&ds, "nl(truncated)");
1958 }
1959 return ds.string;
1960 }
1961
1962 static void
1963 log_nlmsg(const char *function, int error,
1964 const void *message, size_t size, int protocol)
1965 {
1966 if (!VLOG_IS_DBG_ENABLED()) {
1967 return;
1968 }
1969
1970 struct ofpbuf buffer = ofpbuf_const_initializer(message, size);
1971 char *nlmsg = nlmsg_to_string(&buffer, protocol);
1972 VLOG_DBG_RL(&rl, "%s (%s): %s", function, ovs_strerror(error), nlmsg);
1973 free(nlmsg);
1974 }