]> git.proxmox.com Git - mirror_frr.git/blob - zebra/kernel_netlink.c
zebra: add support for protodown reason code
[mirror_frr.git] / zebra / kernel_netlink.c
1 /* Kernel communication using netlink interface.
2 * Copyright (C) 1999 Kunihiro Ishiguro
3 *
4 * This file is part of GNU Zebra.
5 *
6 * GNU Zebra is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2, or (at your option) any
9 * later version.
10 *
11 * GNU Zebra is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; see the file COPYING; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21 #include <zebra.h>
22
23 #ifdef HAVE_NETLINK
24
25 #include "linklist.h"
26 #include "if.h"
27 #include "log.h"
28 #include "prefix.h"
29 #include "connected.h"
30 #include "table.h"
31 #include "memory.h"
32 #include "rib.h"
33 #include "thread.h"
34 #include "privs.h"
35 #include "nexthop.h"
36 #include "vrf.h"
37 #include "mpls.h"
38 #include "lib_errors.h"
39 #include "hash.h"
40
41 #include "zebra/zebra_router.h"
42 #include "zebra/zebra_ns.h"
43 #include "zebra/zebra_vrf.h"
44 #include "zebra/rt.h"
45 #include "zebra/debug.h"
46 #include "zebra/kernel_netlink.h"
47 #include "zebra/rt_netlink.h"
48 #include "zebra/if_netlink.h"
49 #include "zebra/rule_netlink.h"
50 #include "zebra/netconf_netlink.h"
51 #include "zebra/zebra_errors.h"
52
53 #ifndef SO_RCVBUFFORCE
54 #define SO_RCVBUFFORCE (33)
55 #endif
56
57 /* Hack for GNU libc version 2. */
58 #ifndef MSG_TRUNC
59 #define MSG_TRUNC 0x20
60 #endif /* MSG_TRUNC */
61
62 #ifndef NLMSG_TAIL
63 #define NLMSG_TAIL(nmsg) \
64 ((struct rtattr *)(((uint8_t *)(nmsg)) \
65 + NLMSG_ALIGN((nmsg)->nlmsg_len)))
66 #endif
67
68 #ifndef RTA_TAIL
69 #define RTA_TAIL(rta) \
70 ((struct rtattr *)(((uint8_t *)(rta)) + RTA_ALIGN((rta)->rta_len)))
71 #endif
72
73 #ifndef RTNL_FAMILY_IP6MR
74 #define RTNL_FAMILY_IP6MR 129
75 #endif
76
77 #ifndef RTPROT_MROUTED
78 #define RTPROT_MROUTED 17
79 #endif
80
81 #define NL_DEFAULT_BATCH_BUFSIZE (16 * NL_PKT_BUF_SIZE)
82
83 /*
84 * We limit the batch's size to a number smaller than the length of the
85 * underlying buffer since the last message that wouldn't fit the batch would go
86 * over the upper boundary and then it would have to be encoded again into a new
87 * buffer. If the difference between the limit and the length of the buffer is
88 * big enough (bigger than the biggest Netlink message) then this situation
89 * won't occur.
90 */
91 #define NL_DEFAULT_BATCH_SEND_THRESHOLD (15 * NL_PKT_BUF_SIZE)
92
93 static const struct message nlmsg_str[] = {{RTM_NEWROUTE, "RTM_NEWROUTE"},
94 {RTM_DELROUTE, "RTM_DELROUTE"},
95 {RTM_GETROUTE, "RTM_GETROUTE"},
96 {RTM_NEWLINK, "RTM_NEWLINK"},
97 {RTM_SETLINK, "RTM_SETLINK"},
98 {RTM_DELLINK, "RTM_DELLINK"},
99 {RTM_GETLINK, "RTM_GETLINK"},
100 {RTM_NEWADDR, "RTM_NEWADDR"},
101 {RTM_DELADDR, "RTM_DELADDR"},
102 {RTM_GETADDR, "RTM_GETADDR"},
103 {RTM_NEWNEIGH, "RTM_NEWNEIGH"},
104 {RTM_DELNEIGH, "RTM_DELNEIGH"},
105 {RTM_GETNEIGH, "RTM_GETNEIGH"},
106 {RTM_NEWRULE, "RTM_NEWRULE"},
107 {RTM_DELRULE, "RTM_DELRULE"},
108 {RTM_GETRULE, "RTM_GETRULE"},
109 {RTM_NEWNEXTHOP, "RTM_NEWNEXTHOP"},
110 {RTM_DELNEXTHOP, "RTM_DELNEXTHOP"},
111 {RTM_GETNEXTHOP, "RTM_GETNEXTHOP"},
112 {RTM_NEWNETCONF, "RTM_NEWNETCONF"},
113 {RTM_DELNETCONF, "RTM_DELNETCONF"},
114 {0}};
115
116 static const struct message rtproto_str[] = {
117 {RTPROT_REDIRECT, "redirect"},
118 {RTPROT_KERNEL, "kernel"},
119 {RTPROT_BOOT, "boot"},
120 {RTPROT_STATIC, "static"},
121 {RTPROT_GATED, "GateD"},
122 {RTPROT_RA, "router advertisement"},
123 {RTPROT_MRT, "MRT"},
124 {RTPROT_ZEBRA, "Zebra"},
125 #ifdef RTPROT_BIRD
126 {RTPROT_BIRD, "BIRD"},
127 #endif /* RTPROT_BIRD */
128 {RTPROT_MROUTED, "mroute"},
129 {RTPROT_BGP, "BGP"},
130 {RTPROT_OSPF, "OSPF"},
131 {RTPROT_ISIS, "IS-IS"},
132 {RTPROT_RIP, "RIP"},
133 {RTPROT_RIPNG, "RIPNG"},
134 {RTPROT_ZSTATIC, "static"},
135 {0}};
136
137 static const struct message family_str[] = {{AF_INET, "ipv4"},
138 {AF_INET6, "ipv6"},
139 {AF_BRIDGE, "bridge"},
140 {RTNL_FAMILY_IPMR, "ipv4MR"},
141 {RTNL_FAMILY_IP6MR, "ipv6MR"},
142 {0}};
143
144 static const struct message rttype_str[] = {{RTN_UNSPEC, "none"},
145 {RTN_UNICAST, "unicast"},
146 {RTN_LOCAL, "local"},
147 {RTN_BROADCAST, "broadcast"},
148 {RTN_ANYCAST, "anycast"},
149 {RTN_MULTICAST, "multicast"},
150 {RTN_BLACKHOLE, "blackhole"},
151 {RTN_UNREACHABLE, "unreachable"},
152 {RTN_PROHIBIT, "prohibited"},
153 {RTN_THROW, "throw"},
154 {RTN_NAT, "nat"},
155 {RTN_XRESOLVE, "resolver"},
156 {0}};
157
158 extern struct thread_master *master;
159
160 extern struct zebra_privs_t zserv_privs;
161
162 DEFINE_MTYPE_STATIC(ZEBRA, NL_BUF, "Zebra Netlink buffers");
163
164 /* Hashtable and mutex to allow lookup of nlsock structs by socket/fd value.
165 * We have both the main and dplane pthreads using these structs, so we have
166 * to protect the hash with a lock.
167 */
168 static struct hash *nlsock_hash;
169 pthread_mutex_t nlsock_mutex;
170
171 /* Lock and unlock wrappers for nlsock hash */
172 #define NLSOCK_LOCK() pthread_mutex_lock(&nlsock_mutex)
173 #define NLSOCK_UNLOCK() pthread_mutex_unlock(&nlsock_mutex)
174
175 size_t nl_batch_tx_bufsize;
176 char *nl_batch_tx_buf;
177
178 _Atomic uint32_t nl_batch_bufsize = NL_DEFAULT_BATCH_BUFSIZE;
179 _Atomic uint32_t nl_batch_send_threshold = NL_DEFAULT_BATCH_SEND_THRESHOLD;
180
181 struct nl_batch {
182 void *buf;
183 size_t bufsiz;
184 size_t limit;
185
186 void *buf_head;
187 size_t curlen;
188 size_t msgcnt;
189
190 const struct zebra_dplane_info *zns;
191
192 struct dplane_ctx_q ctx_list;
193
194 /*
195 * Pointer to the queue of completed contexts outbound back
196 * towards the dataplane module.
197 */
198 struct dplane_ctx_q *ctx_out_q;
199 };
200
201 int netlink_config_write_helper(struct vty *vty)
202 {
203 uint32_t size =
204 atomic_load_explicit(&nl_batch_bufsize, memory_order_relaxed);
205 uint32_t threshold = atomic_load_explicit(&nl_batch_send_threshold,
206 memory_order_relaxed);
207
208 if (size != NL_DEFAULT_BATCH_BUFSIZE
209 || threshold != NL_DEFAULT_BATCH_SEND_THRESHOLD)
210 vty_out(vty, "zebra kernel netlink batch-tx-buf %u %u\n", size,
211 threshold);
212
213 return 0;
214 }
215
216 void netlink_set_batch_buffer_size(uint32_t size, uint32_t threshold, bool set)
217 {
218 if (!set) {
219 size = NL_DEFAULT_BATCH_BUFSIZE;
220 threshold = NL_DEFAULT_BATCH_SEND_THRESHOLD;
221 }
222
223 atomic_store_explicit(&nl_batch_bufsize, size, memory_order_relaxed);
224 atomic_store_explicit(&nl_batch_send_threshold, threshold,
225 memory_order_relaxed);
226 }
227
228 int netlink_talk_filter(struct nlmsghdr *h, ns_id_t ns_id, int startup)
229 {
230 /*
231 * This is an error condition that must be handled during
232 * development.
233 *
234 * The netlink_talk_filter function is used for communication
235 * down the netlink_cmd pipe and we are expecting
236 * an ack being received. So if we get here
237 * then we did not receive the ack and instead
238 * received some other message in an unexpected
239 * way.
240 */
241 zlog_debug("%s: ignoring message type 0x%04x(%s) NS %u", __func__,
242 h->nlmsg_type, nl_msg_type_to_str(h->nlmsg_type), ns_id);
243 return 0;
244 }
245
246 static int netlink_recvbuf(struct nlsock *nl, uint32_t newsize)
247 {
248 uint32_t oldsize;
249 socklen_t newlen = sizeof(newsize);
250 socklen_t oldlen = sizeof(oldsize);
251 int ret;
252
253 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &oldsize, &oldlen);
254 if (ret < 0) {
255 flog_err_sys(EC_LIB_SOCKET,
256 "Can't get %s receive buffer size: %s", nl->name,
257 safe_strerror(errno));
258 return -1;
259 }
260
261 /* Try force option (linux >= 2.6.14) and fall back to normal set */
262 frr_with_privs(&zserv_privs) {
263 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUFFORCE,
264 &rcvbufsize, sizeof(rcvbufsize));
265 }
266 if (ret < 0)
267 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &rcvbufsize,
268 sizeof(rcvbufsize));
269 if (ret < 0) {
270 flog_err_sys(EC_LIB_SOCKET,
271 "Can't set %s receive buffer size: %s", nl->name,
272 safe_strerror(errno));
273 return -1;
274 }
275
276 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &newsize, &newlen);
277 if (ret < 0) {
278 flog_err_sys(EC_LIB_SOCKET,
279 "Can't get %s receive buffer size: %s", nl->name,
280 safe_strerror(errno));
281 return -1;
282 }
283 return 0;
284 }
285
286 /* Make socket for Linux netlink interface. */
287 static int netlink_socket(struct nlsock *nl, unsigned long groups,
288 ns_id_t ns_id)
289 {
290 int ret;
291 struct sockaddr_nl snl;
292 int sock;
293 int namelen;
294
295 frr_with_privs(&zserv_privs) {
296 sock = ns_socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, ns_id);
297 if (sock < 0) {
298 zlog_err("Can't open %s socket: %s", nl->name,
299 safe_strerror(errno));
300 return -1;
301 }
302
303 memset(&snl, 0, sizeof(snl));
304 snl.nl_family = AF_NETLINK;
305 snl.nl_groups = groups;
306
307 /* Bind the socket to the netlink structure for anything. */
308 ret = bind(sock, (struct sockaddr *)&snl, sizeof(snl));
309 }
310
311 if (ret < 0) {
312 zlog_err("Can't bind %s socket to group 0x%x: %s", nl->name,
313 snl.nl_groups, safe_strerror(errno));
314 close(sock);
315 return -1;
316 }
317
318 /* multiple netlink sockets will have different nl_pid */
319 namelen = sizeof(snl);
320 ret = getsockname(sock, (struct sockaddr *)&snl, (socklen_t *)&namelen);
321 if (ret < 0 || namelen != sizeof(snl)) {
322 flog_err_sys(EC_LIB_SOCKET, "Can't get %s socket name: %s",
323 nl->name, safe_strerror(errno));
324 close(sock);
325 return -1;
326 }
327
328 nl->snl = snl;
329 nl->sock = sock;
330 nl->buflen = NL_RCV_PKT_BUF_SIZE;
331 nl->buf = XMALLOC(MTYPE_NL_BUF, nl->buflen);
332
333 return ret;
334 }
335
336 /*
337 * Dispatch an incoming netlink message; used by the zebra main pthread's
338 * netlink event reader.
339 */
340 static int netlink_information_fetch(struct nlmsghdr *h, ns_id_t ns_id,
341 int startup)
342 {
343 /*
344 * When we handle new message types here
345 * because we are starting to install them
346 * then lets check the netlink_install_filter
347 * and see if we should add the corresponding
348 * allow through entry there.
349 * Probably not needed to do but please
350 * think about it.
351 */
352 switch (h->nlmsg_type) {
353 case RTM_NEWROUTE:
354 return netlink_route_change(h, ns_id, startup);
355 case RTM_DELROUTE:
356 return netlink_route_change(h, ns_id, startup);
357 case RTM_NEWLINK:
358 return netlink_link_change(h, ns_id, startup);
359 case RTM_DELLINK:
360 return netlink_link_change(h, ns_id, startup);
361 case RTM_NEWNEIGH:
362 case RTM_DELNEIGH:
363 case RTM_GETNEIGH:
364 return netlink_neigh_change(h, ns_id);
365 case RTM_NEWRULE:
366 return netlink_rule_change(h, ns_id, startup);
367 case RTM_DELRULE:
368 return netlink_rule_change(h, ns_id, startup);
369 case RTM_NEWNEXTHOP:
370 return netlink_nexthop_change(h, ns_id, startup);
371 case RTM_DELNEXTHOP:
372 return netlink_nexthop_change(h, ns_id, startup);
373
374 /* Messages handled in the dplane thread */
375 case RTM_NEWADDR:
376 case RTM_DELADDR:
377 case RTM_NEWNETCONF:
378 case RTM_DELNETCONF:
379 return 0;
380
381 default:
382 /*
383 * If we have received this message then
384 * we have made a mistake during development
385 * and we need to write some code to handle
386 * this message type or not ask for
387 * it to be sent up to us
388 */
389 flog_err(EC_ZEBRA_UNKNOWN_NLMSG,
390 "Unknown netlink nlmsg_type %s(%d) vrf %u",
391 nl_msg_type_to_str(h->nlmsg_type), h->nlmsg_type,
392 ns_id);
393 break;
394 }
395 return 0;
396 }
397
398 /*
399 * Dispatch an incoming netlink message; used by the dataplane pthread's
400 * netlink event reader code.
401 */
402 static int dplane_netlink_information_fetch(struct nlmsghdr *h, ns_id_t ns_id,
403 int startup)
404 {
405 /*
406 * Dispatch the incoming messages that the dplane pthread handles
407 */
408 switch (h->nlmsg_type) {
409 case RTM_NEWADDR:
410 case RTM_DELADDR:
411 return netlink_interface_addr_dplane(h, ns_id, startup);
412
413 case RTM_NEWNETCONF:
414 case RTM_DELNETCONF:
415 return netlink_netconf_change(h, ns_id, startup);
416
417 /* TODO -- other messages for the dplane socket and pthread */
418
419 case RTM_NEWLINK:
420 case RTM_DELLINK:
421
422 default:
423 break;
424 }
425
426 return 0;
427 }
428
429 static void kernel_read(struct thread *thread)
430 {
431 struct zebra_ns *zns = (struct zebra_ns *)THREAD_ARG(thread);
432 struct zebra_dplane_info dp_info;
433
434 /* Capture key info from ns struct */
435 zebra_dplane_info_from_zns(&dp_info, zns, false);
436
437 netlink_parse_info(netlink_information_fetch, &zns->netlink, &dp_info,
438 5, false);
439
440 thread_add_read(zrouter.master, kernel_read, zns, zns->netlink.sock,
441 &zns->t_netlink);
442 }
443
444 /*
445 * Called by the dplane pthread to read incoming OS messages and dispatch them.
446 */
447 int kernel_dplane_read(struct zebra_dplane_info *info)
448 {
449 struct nlsock *nl = kernel_netlink_nlsock_lookup(info->sock);
450
451 netlink_parse_info(dplane_netlink_information_fetch, nl, info, 5,
452 false);
453
454 return 0;
455 }
456
457 /*
458 * Filter out messages from self that occur on listener socket,
459 * caused by our actions on the command socket(s)
460 *
461 * When we add new Netlink message types we probably
462 * do not need to add them here as that we are filtering
463 * on the routes we actually care to receive( which is rarer
464 * then the normal course of operations). We are intentionally
465 * allowing some messages from ourselves through
466 * ( I'm looking at you Interface based netlink messages )
467 * so that we only have to write one way to handle incoming
468 * address add/delete and xxxNETCONF changes.
469 */
470 static void netlink_install_filter(int sock, uint32_t pid, uint32_t dplane_pid)
471 {
472 /*
473 * BPF_JUMP instructions and where you jump to are based upon
474 * 0 as being the next statement. So count from 0. Writing
475 * this down because every time I look at this I have to
476 * re-remember it.
477 */
478 struct sock_filter filter[] = {
479 /*
480 * Logic:
481 * if (nlmsg_pid == pid ||
482 * nlmsg_pid == dplane_pid) {
483 * if (the incoming nlmsg_type ==
484 * RTM_NEWADDR || RTM_DELADDR || RTM_NEWNETCONF ||
485 * RTM_DELNETCONF)
486 * keep this message
487 * else
488 * skip this message
489 * } else
490 * keep this netlink message
491 */
492 /*
493 * 0: Load the nlmsg_pid into the BPF register
494 */
495 BPF_STMT(BPF_LD | BPF_ABS | BPF_W,
496 offsetof(struct nlmsghdr, nlmsg_pid)),
497 /*
498 * 1: Compare to pid
499 */
500 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(pid), 1, 0),
501 /*
502 * 2: Compare to dplane pid
503 */
504 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(dplane_pid), 0, 6),
505 /*
506 * 3: Load the nlmsg_type into BPF register
507 */
508 BPF_STMT(BPF_LD | BPF_ABS | BPF_H,
509 offsetof(struct nlmsghdr, nlmsg_type)),
510 /*
511 * 4: Compare to RTM_NEWADDR
512 */
513 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_NEWADDR), 4, 0),
514 /*
515 * 5: Compare to RTM_DELADDR
516 */
517 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_DELADDR), 3, 0),
518 /*
519 * 6: Compare to RTM_NEWNETCONF
520 */
521 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_NEWNETCONF), 2,
522 0),
523 /*
524 * 7: Compare to RTM_DELNETCONF
525 */
526 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_DELNETCONF), 1,
527 0),
528 /*
529 * 8: This is the end state of we want to skip the
530 * message
531 */
532 BPF_STMT(BPF_RET | BPF_K, 0),
533 /* 9: This is the end state of we want to keep
534 * the message
535 */
536 BPF_STMT(BPF_RET | BPF_K, 0xffff),
537 };
538
539 struct sock_fprog prog = {
540 .len = array_size(filter), .filter = filter,
541 };
542
543 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog))
544 < 0)
545 flog_err_sys(EC_LIB_SOCKET, "Can't install socket filter: %s",
546 safe_strerror(errno));
547 }
548
549 void netlink_parse_rtattr_flags(struct rtattr **tb, int max, struct rtattr *rta,
550 int len, unsigned short flags)
551 {
552 unsigned short type;
553
554 memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
555 while (RTA_OK(rta, len)) {
556 type = rta->rta_type & ~flags;
557 if ((type <= max) && (!tb[type]))
558 tb[type] = rta;
559 rta = RTA_NEXT(rta, len);
560 }
561 }
562
563 void netlink_parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta,
564 int len)
565 {
566 memset(tb, 0, sizeof(struct rtattr *) * (max + 1));
567 while (RTA_OK(rta, len)) {
568 if (rta->rta_type <= max)
569 tb[rta->rta_type] = rta;
570 rta = RTA_NEXT(rta, len);
571 }
572 }
573
574 /**
575 * netlink_parse_rtattr_nested() - Parses a nested route attribute
576 * @tb: Pointer to array for storing rtattr in.
577 * @max: Max number to store.
578 * @rta: Pointer to rtattr to look for nested items in.
579 */
580 void netlink_parse_rtattr_nested(struct rtattr **tb, int max,
581 struct rtattr *rta)
582 {
583 netlink_parse_rtattr(tb, max, RTA_DATA(rta), RTA_PAYLOAD(rta));
584 }
585
586 bool nl_attr_put(struct nlmsghdr *n, unsigned int maxlen, int type,
587 const void *data, unsigned int alen)
588 {
589 int len;
590 struct rtattr *rta;
591
592 len = RTA_LENGTH(alen);
593
594 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen)
595 return false;
596
597 rta = (struct rtattr *)(((char *)n) + NLMSG_ALIGN(n->nlmsg_len));
598 rta->rta_type = type;
599 rta->rta_len = len;
600
601 if (data)
602 memcpy(RTA_DATA(rta), data, alen);
603 else
604 assert(alen == 0);
605
606 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
607
608 return true;
609 }
610
611 bool nl_attr_put8(struct nlmsghdr *n, unsigned int maxlen, int type,
612 uint8_t data)
613 {
614 return nl_attr_put(n, maxlen, type, &data, sizeof(uint8_t));
615 }
616
617 bool nl_attr_put16(struct nlmsghdr *n, unsigned int maxlen, int type,
618 uint16_t data)
619 {
620 return nl_attr_put(n, maxlen, type, &data, sizeof(uint16_t));
621 }
622
623 bool nl_attr_put32(struct nlmsghdr *n, unsigned int maxlen, int type,
624 uint32_t data)
625 {
626 return nl_attr_put(n, maxlen, type, &data, sizeof(uint32_t));
627 }
628
629 struct rtattr *nl_attr_nest(struct nlmsghdr *n, unsigned int maxlen, int type)
630 {
631 struct rtattr *nest = NLMSG_TAIL(n);
632
633 if (!nl_attr_put(n, maxlen, type, NULL, 0))
634 return NULL;
635
636 nest->rta_type |= NLA_F_NESTED;
637 return nest;
638 }
639
640 int nl_attr_nest_end(struct nlmsghdr *n, struct rtattr *nest)
641 {
642 nest->rta_len = (uint8_t *)NLMSG_TAIL(n) - (uint8_t *)nest;
643 return n->nlmsg_len;
644 }
645
646 struct rtnexthop *nl_attr_rtnh(struct nlmsghdr *n, unsigned int maxlen)
647 {
648 struct rtnexthop *rtnh = (struct rtnexthop *)NLMSG_TAIL(n);
649
650 if (NLMSG_ALIGN(n->nlmsg_len) + RTNH_ALIGN(sizeof(struct rtnexthop))
651 > maxlen)
652 return NULL;
653
654 memset(rtnh, 0, sizeof(struct rtnexthop));
655 n->nlmsg_len =
656 NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(sizeof(struct rtnexthop));
657
658 return rtnh;
659 }
660
661 void nl_attr_rtnh_end(struct nlmsghdr *n, struct rtnexthop *rtnh)
662 {
663 rtnh->rtnh_len = (uint8_t *)NLMSG_TAIL(n) - (uint8_t *)rtnh;
664 }
665
666 const char *nl_msg_type_to_str(uint16_t msg_type)
667 {
668 return lookup_msg(nlmsg_str, msg_type, "");
669 }
670
671 const char *nl_rtproto_to_str(uint8_t rtproto)
672 {
673 return lookup_msg(rtproto_str, rtproto, "");
674 }
675
676 const char *nl_family_to_str(uint8_t family)
677 {
678 return lookup_msg(family_str, family, "");
679 }
680
681 const char *nl_rttype_to_str(uint8_t rttype)
682 {
683 return lookup_msg(rttype_str, rttype, "");
684 }
685
686 #define NLA_OK(nla, len) \
687 ((len) >= (int)sizeof(struct nlattr) \
688 && (nla)->nla_len >= sizeof(struct nlattr) \
689 && (nla)->nla_len <= (len))
690 #define NLA_NEXT(nla, attrlen) \
691 ((attrlen) -= NLA_ALIGN((nla)->nla_len), \
692 (struct nlattr *)(((char *)(nla)) + NLA_ALIGN((nla)->nla_len)))
693 #define NLA_LENGTH(len) (NLA_ALIGN(sizeof(struct nlattr)) + (len))
694 #define NLA_DATA(nla) ((struct nlattr *)(((char *)(nla)) + NLA_LENGTH(0)))
695
696 #define ERR_NLA(err, inner_len) \
697 ((struct nlattr *)(((char *)(err)) \
698 + NLMSG_ALIGN(sizeof(struct nlmsgerr)) \
699 + NLMSG_ALIGN((inner_len))))
700
701 static void netlink_parse_nlattr(struct nlattr **tb, int max,
702 struct nlattr *nla, int len)
703 {
704 while (NLA_OK(nla, len)) {
705 if (nla->nla_type <= max)
706 tb[nla->nla_type] = nla;
707 nla = NLA_NEXT(nla, len);
708 }
709 }
710
711 static void netlink_parse_extended_ack(struct nlmsghdr *h)
712 {
713 struct nlattr *tb[NLMSGERR_ATTR_MAX + 1] = {};
714 const struct nlmsgerr *err = (const struct nlmsgerr *)NLMSG_DATA(h);
715 const struct nlmsghdr *err_nlh = NULL;
716 /* Length not including nlmsghdr */
717 uint32_t len = 0;
718 /* Inner error netlink message length */
719 uint32_t inner_len = 0;
720 const char *msg = NULL;
721 uint32_t off = 0;
722
723 if (!(h->nlmsg_flags & NLM_F_CAPPED))
724 inner_len = (uint32_t)NLMSG_PAYLOAD(&err->msg, 0);
725
726 len = (uint32_t)(NLMSG_PAYLOAD(h, sizeof(struct nlmsgerr)) - inner_len);
727
728 netlink_parse_nlattr(tb, NLMSGERR_ATTR_MAX, ERR_NLA(err, inner_len),
729 len);
730
731 if (tb[NLMSGERR_ATTR_MSG])
732 msg = (const char *)NLA_DATA(tb[NLMSGERR_ATTR_MSG]);
733
734 if (tb[NLMSGERR_ATTR_OFFS]) {
735 off = *(uint32_t *)NLA_DATA(tb[NLMSGERR_ATTR_OFFS]);
736
737 if (off > h->nlmsg_len) {
738 zlog_err("Invalid offset for NLMSGERR_ATTR_OFFS");
739 } else if (!(h->nlmsg_flags & NLM_F_CAPPED)) {
740 /*
741 * Header of failed message
742 * we are not doing anything currently with it
743 * but noticing it for later.
744 */
745 err_nlh = &err->msg;
746 zlog_debug("%s: Received %s extended Ack", __func__,
747 nl_msg_type_to_str(err_nlh->nlmsg_type));
748 }
749 }
750
751 if (msg && *msg != '\0') {
752 bool is_err = !!err->error;
753
754 if (is_err)
755 zlog_err("Extended Error: %s", msg);
756 else
757 flog_warn(EC_ZEBRA_NETLINK_EXTENDED_WARNING,
758 "Extended Warning: %s", msg);
759 }
760 }
761
762 /*
763 * netlink_send_msg - send a netlink message of a certain size.
764 *
765 * Returns -1 on error. Otherwise, it returns the number of bytes sent.
766 */
767 static ssize_t netlink_send_msg(const struct nlsock *nl, void *buf,
768 size_t buflen)
769 {
770 struct sockaddr_nl snl = {};
771 struct iovec iov = {};
772 struct msghdr msg = {};
773 ssize_t status;
774 int save_errno = 0;
775
776 iov.iov_base = buf;
777 iov.iov_len = buflen;
778 msg.msg_name = &snl;
779 msg.msg_namelen = sizeof(snl);
780 msg.msg_iov = &iov;
781 msg.msg_iovlen = 1;
782
783 snl.nl_family = AF_NETLINK;
784
785 /* Send message to netlink interface. */
786 frr_with_privs(&zserv_privs) {
787 status = sendmsg(nl->sock, &msg, 0);
788 save_errno = errno;
789 }
790
791 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_SEND) {
792 zlog_debug("%s: >> netlink message dump [sent]", __func__);
793 #ifdef NETLINK_DEBUG
794 nl_dump(buf, buflen);
795 #else
796 zlog_hexdump(buf, buflen);
797 #endif /* NETLINK_DEBUG */
798 }
799
800 if (status == -1) {
801 flog_err_sys(EC_LIB_SOCKET, "%s error: %s", __func__,
802 safe_strerror(save_errno));
803 return -1;
804 }
805
806 return status;
807 }
808
809 /*
810 * netlink_recv_msg - receive a netlink message.
811 *
812 * Returns -1 on error, 0 if read would block or the number of bytes received.
813 */
814 static int netlink_recv_msg(struct nlsock *nl, struct msghdr *msg)
815 {
816 struct iovec iov;
817 int status;
818
819 iov.iov_base = nl->buf;
820 iov.iov_len = nl->buflen;
821 msg->msg_iov = &iov;
822 msg->msg_iovlen = 1;
823
824 do {
825 int bytes;
826
827 bytes = recv(nl->sock, NULL, 0, MSG_PEEK | MSG_TRUNC);
828
829 if (bytes >= 0 && (size_t)bytes > nl->buflen) {
830 nl->buf = XREALLOC(MTYPE_NL_BUF, nl->buf, bytes);
831 nl->buflen = bytes;
832 iov.iov_base = nl->buf;
833 iov.iov_len = nl->buflen;
834 }
835
836 status = recvmsg(nl->sock, msg, 0);
837 } while (status == -1 && errno == EINTR);
838
839 if (status == -1) {
840 if (errno == EWOULDBLOCK || errno == EAGAIN)
841 return 0;
842 flog_err(EC_ZEBRA_RECVMSG_OVERRUN, "%s recvmsg overrun: %s",
843 nl->name, safe_strerror(errno));
844 /*
845 * In this case we are screwed. There is no good way to recover
846 * zebra at this point.
847 */
848 exit(-1);
849 }
850
851 if (status == 0) {
852 flog_err_sys(EC_LIB_SOCKET, "%s EOF", nl->name);
853 return -1;
854 }
855
856 if (msg->msg_namelen != sizeof(struct sockaddr_nl)) {
857 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
858 "%s sender address length error: length %d", nl->name,
859 msg->msg_namelen);
860 return -1;
861 }
862
863 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_RECV) {
864 zlog_debug("%s: << netlink message dump [recv]", __func__);
865 #ifdef NETLINK_DEBUG
866 nl_dump(nl->buf, status);
867 #else
868 zlog_hexdump(nl->buf, status);
869 #endif /* NETLINK_DEBUG */
870 }
871
872 return status;
873 }
874
875 /*
876 * netlink_parse_error - parse a netlink error message
877 *
878 * Returns 1 if this message is acknowledgement, 0 if this error should be
879 * ignored, -1 otherwise.
880 */
881 static int netlink_parse_error(const struct nlsock *nl, struct nlmsghdr *h,
882 bool is_cmd, bool startup)
883 {
884 struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(h);
885 int errnum = err->error;
886 int msg_type = err->msg.nlmsg_type;
887
888 if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
889 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
890 "%s error: message truncated", nl->name);
891 return -1;
892 }
893
894 /*
895 * Parse the extended information before we actually handle it. At this
896 * point in time we do not do anything other than report the issue.
897 */
898 if (h->nlmsg_flags & NLM_F_ACK_TLVS)
899 netlink_parse_extended_ack(h);
900
901 /* If the error field is zero, then this is an ACK. */
902 if (err->error == 0) {
903 if (IS_ZEBRA_DEBUG_KERNEL) {
904 zlog_debug("%s: %s ACK: type=%s(%u), seq=%u, pid=%u",
905 __func__, nl->name,
906 nl_msg_type_to_str(err->msg.nlmsg_type),
907 err->msg.nlmsg_type, err->msg.nlmsg_seq,
908 err->msg.nlmsg_pid);
909 }
910
911 return 1;
912 }
913
914 /* Deal with errors that occur because of races in link handling. */
915 if (is_cmd
916 && ((msg_type == RTM_DELROUTE
917 && (-errnum == ENODEV || -errnum == ESRCH))
918 || (msg_type == RTM_NEWROUTE
919 && (-errnum == ENETDOWN || -errnum == EEXIST)))) {
920 if (IS_ZEBRA_DEBUG_KERNEL)
921 zlog_debug("%s: error: %s type=%s(%u), seq=%u, pid=%u",
922 nl->name, safe_strerror(-errnum),
923 nl_msg_type_to_str(msg_type), msg_type,
924 err->msg.nlmsg_seq, err->msg.nlmsg_pid);
925 return 0;
926 }
927
928 /*
929 * We see RTM_DELNEIGH when shutting down an interface with an IPv4
930 * link-local. The kernel should have already deleted the neighbor so
931 * do not log these as an error.
932 */
933 if (msg_type == RTM_DELNEIGH
934 || (is_cmd && msg_type == RTM_NEWROUTE
935 && (-errnum == ESRCH || -errnum == ENETUNREACH))) {
936 /*
937 * This is known to happen in some situations, don't log as
938 * error.
939 */
940 if (IS_ZEBRA_DEBUG_KERNEL)
941 zlog_debug("%s error: %s, type=%s(%u), seq=%u, pid=%u",
942 nl->name, safe_strerror(-errnum),
943 nl_msg_type_to_str(msg_type), msg_type,
944 err->msg.nlmsg_seq, err->msg.nlmsg_pid);
945 } else {
946 if ((msg_type != RTM_GETNEXTHOP) || !startup)
947 flog_err(EC_ZEBRA_UNEXPECTED_MESSAGE,
948 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
949 nl->name, safe_strerror(-errnum),
950 nl_msg_type_to_str(msg_type), msg_type,
951 err->msg.nlmsg_seq, err->msg.nlmsg_pid);
952 }
953
954 return -1;
955 }
956
957 /*
958 * netlink_parse_info
959 *
960 * Receive message from netlink interface and pass those information
961 * to the given function.
962 *
963 * filter -> Function to call to read the results
964 * nl -> netlink socket information
965 * zns -> The zebra namespace data
966 * count -> How many we should read in, 0 means as much as possible
967 * startup -> Are we reading in under startup conditions? passed to
968 * the filter.
969 */
970 int netlink_parse_info(int (*filter)(struct nlmsghdr *, ns_id_t, int),
971 struct nlsock *nl, const struct zebra_dplane_info *zns,
972 int count, bool startup)
973 {
974 int status;
975 int ret = 0;
976 int error;
977 int read_in = 0;
978
979 while (1) {
980 struct sockaddr_nl snl;
981 struct msghdr msg = {.msg_name = (void *)&snl,
982 .msg_namelen = sizeof(snl)};
983 struct nlmsghdr *h;
984
985 if (count && read_in >= count)
986 return 0;
987
988 status = netlink_recv_msg(nl, &msg);
989 if (status == -1)
990 return -1;
991 else if (status == 0)
992 break;
993
994 read_in++;
995 for (h = (struct nlmsghdr *)nl->buf;
996 (status >= 0 && NLMSG_OK(h, (unsigned int)status));
997 h = NLMSG_NEXT(h, status)) {
998 /* Finish of reading. */
999 if (h->nlmsg_type == NLMSG_DONE)
1000 return ret;
1001
1002 /* Error handling. */
1003 if (h->nlmsg_type == NLMSG_ERROR) {
1004 int err = netlink_parse_error(
1005 nl, h, zns->is_cmd, startup);
1006
1007 if (err == 1) {
1008 if (!(h->nlmsg_flags & NLM_F_MULTI))
1009 return 0;
1010 continue;
1011 } else
1012 return err;
1013 }
1014
1015 /* OK we got netlink message. */
1016 if (IS_ZEBRA_DEBUG_KERNEL)
1017 zlog_debug(
1018 "%s: %s type %s(%u), len=%d, seq=%u, pid=%u",
1019 __func__, nl->name,
1020 nl_msg_type_to_str(h->nlmsg_type),
1021 h->nlmsg_type, h->nlmsg_len,
1022 h->nlmsg_seq, h->nlmsg_pid);
1023
1024
1025 /*
1026 * Ignore messages that maybe sent from
1027 * other actors besides the kernel
1028 */
1029 if (snl.nl_pid != 0) {
1030 zlog_debug("Ignoring message from pid %u",
1031 snl.nl_pid);
1032 continue;
1033 }
1034
1035 error = (*filter)(h, zns->ns_id, startup);
1036 if (error < 0) {
1037 zlog_debug("%s filter function error",
1038 nl->name);
1039 ret = error;
1040 }
1041 }
1042
1043 /* After error care. */
1044 if (msg.msg_flags & MSG_TRUNC) {
1045 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
1046 "%s error: message truncated", nl->name);
1047 continue;
1048 }
1049 if (status) {
1050 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
1051 "%s error: data remnant size %d", nl->name,
1052 status);
1053 return -1;
1054 }
1055 }
1056 return ret;
1057 }
1058
1059 /*
1060 * netlink_talk_info
1061 *
1062 * sendmsg() to netlink socket then recvmsg().
1063 * Calls netlink_parse_info to parse returned data
1064 *
1065 * filter -> The filter to read final results from kernel
1066 * nlmsghdr -> The data to send to the kernel
1067 * dp_info -> The dataplane and netlink socket information
1068 * startup -> Are we reading in under startup conditions
1069 * This is passed through eventually to filter.
1070 */
1071 static int netlink_talk_info(int (*filter)(struct nlmsghdr *, ns_id_t,
1072 int startup),
1073 struct nlmsghdr *n,
1074 struct zebra_dplane_info *dp_info, bool startup)
1075 {
1076 struct nlsock *nl;
1077
1078 nl = kernel_netlink_nlsock_lookup(dp_info->sock);
1079 n->nlmsg_seq = dp_info->seq;
1080 n->nlmsg_pid = nl->snl.nl_pid;
1081
1082 if (IS_ZEBRA_DEBUG_KERNEL)
1083 zlog_debug(
1084 "netlink_talk: %s type %s(%u), len=%d seq=%u flags 0x%x",
1085 nl->name, nl_msg_type_to_str(n->nlmsg_type),
1086 n->nlmsg_type, n->nlmsg_len, n->nlmsg_seq,
1087 n->nlmsg_flags);
1088
1089 if (netlink_send_msg(nl, n, n->nlmsg_len) == -1)
1090 return -1;
1091
1092 /*
1093 * Get reply from netlink socket.
1094 * The reply should either be an acknowlegement or an error.
1095 */
1096 return netlink_parse_info(filter, nl, dp_info, 0, startup);
1097 }
1098
1099 /*
1100 * Synchronous version of netlink_talk_info. Converts args to suit the
1101 * common version, which is suitable for both sync and async use.
1102 */
1103 int netlink_talk(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
1104 struct nlmsghdr *n, struct nlsock *nl, struct zebra_ns *zns,
1105 bool startup)
1106 {
1107 struct zebra_dplane_info dp_info;
1108
1109 /* Increment sequence number before capturing snapshot of ns socket
1110 * info.
1111 */
1112 nl->seq++;
1113
1114 /* Capture info in intermediate info struct */
1115 zebra_dplane_info_from_zns(&dp_info, zns, (nl == &(zns->netlink_cmd)));
1116
1117 return netlink_talk_info(filter, n, &dp_info, startup);
1118 }
1119
1120 /* Issue request message to kernel via netlink socket. GET messages
1121 * are issued through this interface.
1122 */
1123 int netlink_request(struct nlsock *nl, void *req)
1124 {
1125 struct nlmsghdr *n = (struct nlmsghdr *)req;
1126
1127 /* Check netlink socket. */
1128 if (nl->sock < 0) {
1129 flog_err_sys(EC_LIB_SOCKET, "%s socket isn't active.",
1130 nl->name);
1131 return -1;
1132 }
1133
1134 /* Fill common fields for all requests. */
1135 n->nlmsg_pid = nl->snl.nl_pid;
1136 n->nlmsg_seq = ++nl->seq;
1137
1138 if (netlink_send_msg(nl, req, n->nlmsg_len) == -1)
1139 return -1;
1140
1141 return 0;
1142 }
1143
1144 static int nl_batch_read_resp(struct nl_batch *bth)
1145 {
1146 struct nlmsghdr *h;
1147 struct sockaddr_nl snl;
1148 struct msghdr msg = {};
1149 int status, seq;
1150 struct nlsock *nl;
1151 struct zebra_dplane_ctx *ctx;
1152 bool ignore_msg;
1153
1154 nl = kernel_netlink_nlsock_lookup(bth->zns->sock);
1155
1156 msg.msg_name = (void *)&snl;
1157 msg.msg_namelen = sizeof(snl);
1158
1159 /*
1160 * The responses are not batched, so we need to read and process one
1161 * message at a time.
1162 */
1163 while (true) {
1164 status = netlink_recv_msg(nl, &msg);
1165 /*
1166 * status == -1 is a full on failure somewhere
1167 * since we don't know where the problem happened
1168 * we must mark all as failed
1169 *
1170 * Else we mark everything as worked
1171 *
1172 */
1173 if (status == -1 || status == 0) {
1174 while ((ctx = dplane_ctx_dequeue(&(bth->ctx_list))) !=
1175 NULL) {
1176 if (status == -1)
1177 dplane_ctx_set_status(
1178 ctx,
1179 ZEBRA_DPLANE_REQUEST_FAILURE);
1180 dplane_ctx_enqueue_tail(bth->ctx_out_q, ctx);
1181 }
1182 return status;
1183 }
1184
1185 h = (struct nlmsghdr *)nl->buf;
1186 ignore_msg = false;
1187 seq = h->nlmsg_seq;
1188 /*
1189 * Find the corresponding context object. Received responses are
1190 * in the same order as requests we sent, so we can simply
1191 * iterate over the context list and match responses with
1192 * requests at same time.
1193 */
1194 while (true) {
1195 ctx = dplane_ctx_get_head(&(bth->ctx_list));
1196 if (ctx == NULL) {
1197 /*
1198 * This is a situation where we have gotten
1199 * into a bad spot. We need to know that
1200 * this happens( does it? )
1201 */
1202 zlog_err(
1203 "%s:WARNING Received netlink Response for an error and no Contexts to associate with it",
1204 __func__);
1205 break;
1206 }
1207
1208 /*
1209 * 'update' context objects take two consecutive
1210 * sequence numbers.
1211 */
1212 if (dplane_ctx_is_update(ctx) &&
1213 dplane_ctx_get_ns(ctx)->seq + 1 == seq) {
1214 /*
1215 * This is the situation where we get a response
1216 * to a message that should be ignored.
1217 */
1218 ignore_msg = true;
1219 break;
1220 }
1221
1222 ctx = dplane_ctx_dequeue(&(bth->ctx_list));
1223 dplane_ctx_enqueue_tail(bth->ctx_out_q, ctx);
1224
1225 /* We have found corresponding context object. */
1226 if (dplane_ctx_get_ns(ctx)->seq == seq)
1227 break;
1228
1229 if (dplane_ctx_get_ns(ctx)->seq > seq)
1230 zlog_warn(
1231 "%s:WARNING Received %u is less than any context on the queue ctx->seq %u",
1232 __func__, seq,
1233 dplane_ctx_get_ns(ctx)->seq);
1234 }
1235
1236 if (ignore_msg) {
1237 /*
1238 * If we ignore the message due to an update
1239 * above we should still fricking decode the
1240 * message for our operator to understand
1241 * what is going on
1242 */
1243 int err = netlink_parse_error(nl, h, bth->zns->is_cmd,
1244 false);
1245
1246 zlog_debug("%s: netlink error message seq=%d %d",
1247 __func__, h->nlmsg_seq, err);
1248 continue;
1249 }
1250
1251 /*
1252 * We received a message with the sequence number that isn't
1253 * associated with any dplane context object.
1254 */
1255 if (ctx == NULL) {
1256 if (IS_ZEBRA_DEBUG_KERNEL)
1257 zlog_debug(
1258 "%s: skipping unassociated response, seq number %d NS %u",
1259 __func__, h->nlmsg_seq,
1260 bth->zns->ns_id);
1261 continue;
1262 }
1263
1264 if (h->nlmsg_type == NLMSG_ERROR) {
1265 int err = netlink_parse_error(nl, h, bth->zns->is_cmd,
1266 false);
1267
1268 if (err == -1)
1269 dplane_ctx_set_status(
1270 ctx, ZEBRA_DPLANE_REQUEST_FAILURE);
1271
1272 if (IS_ZEBRA_DEBUG_KERNEL)
1273 zlog_debug("%s: netlink error message seq=%d ",
1274 __func__, h->nlmsg_seq);
1275 continue;
1276 }
1277
1278 /*
1279 * If we get here then we did not receive neither the ack nor
1280 * the error and instead received some other message in an
1281 * unexpected way.
1282 */
1283 if (IS_ZEBRA_DEBUG_KERNEL)
1284 zlog_debug("%s: ignoring message type 0x%04x(%s) NS %u",
1285 __func__, h->nlmsg_type,
1286 nl_msg_type_to_str(h->nlmsg_type),
1287 bth->zns->ns_id);
1288 }
1289
1290 return 0;
1291 }
1292
1293 static void nl_batch_reset(struct nl_batch *bth)
1294 {
1295 bth->buf_head = bth->buf;
1296 bth->curlen = 0;
1297 bth->msgcnt = 0;
1298 bth->zns = NULL;
1299
1300 TAILQ_INIT(&(bth->ctx_list));
1301 }
1302
1303 static void nl_batch_init(struct nl_batch *bth, struct dplane_ctx_q *ctx_out_q)
1304 {
1305 /*
1306 * If the size of the buffer has changed, free and then allocate a new
1307 * one.
1308 */
1309 size_t bufsize =
1310 atomic_load_explicit(&nl_batch_bufsize, memory_order_relaxed);
1311 if (bufsize != nl_batch_tx_bufsize) {
1312 if (nl_batch_tx_buf)
1313 XFREE(MTYPE_NL_BUF, nl_batch_tx_buf);
1314
1315 nl_batch_tx_buf = XCALLOC(MTYPE_NL_BUF, bufsize);
1316 nl_batch_tx_bufsize = bufsize;
1317 }
1318
1319 bth->buf = nl_batch_tx_buf;
1320 bth->bufsiz = bufsize;
1321 bth->limit = atomic_load_explicit(&nl_batch_send_threshold,
1322 memory_order_relaxed);
1323
1324 bth->ctx_out_q = ctx_out_q;
1325
1326 nl_batch_reset(bth);
1327 }
1328
1329 static void nl_batch_send(struct nl_batch *bth)
1330 {
1331 struct zebra_dplane_ctx *ctx;
1332 bool err = false;
1333
1334 if (bth->curlen != 0 && bth->zns != NULL) {
1335 struct nlsock *nl =
1336 kernel_netlink_nlsock_lookup(bth->zns->sock);
1337
1338 if (IS_ZEBRA_DEBUG_KERNEL)
1339 zlog_debug("%s: %s, batch size=%zu, msg cnt=%zu",
1340 __func__, nl->name, bth->curlen,
1341 bth->msgcnt);
1342
1343 if (netlink_send_msg(nl, bth->buf, bth->curlen) == -1)
1344 err = true;
1345
1346 if (!err) {
1347 if (nl_batch_read_resp(bth) == -1)
1348 err = true;
1349 }
1350 }
1351
1352 /* Move remaining contexts to the outbound queue. */
1353 while (true) {
1354 ctx = dplane_ctx_dequeue(&(bth->ctx_list));
1355 if (ctx == NULL)
1356 break;
1357
1358 if (err)
1359 dplane_ctx_set_status(ctx,
1360 ZEBRA_DPLANE_REQUEST_FAILURE);
1361
1362 dplane_ctx_enqueue_tail(bth->ctx_out_q, ctx);
1363 }
1364
1365 nl_batch_reset(bth);
1366 }
1367
1368 enum netlink_msg_status netlink_batch_add_msg(
1369 struct nl_batch *bth, struct zebra_dplane_ctx *ctx,
1370 ssize_t (*msg_encoder)(struct zebra_dplane_ctx *, void *, size_t),
1371 bool ignore_res)
1372 {
1373 int seq;
1374 ssize_t size;
1375 struct nlmsghdr *msgh;
1376 struct nlsock *nl;
1377
1378 size = (*msg_encoder)(ctx, bth->buf_head, bth->bufsiz - bth->curlen);
1379
1380 /*
1381 * If there was an error while encoding the message (other than buffer
1382 * overflow) then return an error.
1383 */
1384 if (size < 0)
1385 return FRR_NETLINK_ERROR;
1386
1387 /*
1388 * If the message doesn't fit entirely in the buffer then send the batch
1389 * and retry.
1390 */
1391 if (size == 0) {
1392 nl_batch_send(bth);
1393 size = (*msg_encoder)(ctx, bth->buf_head,
1394 bth->bufsiz - bth->curlen);
1395 /*
1396 * If the message doesn't fit in the empty buffer then just
1397 * return an error.
1398 */
1399 if (size <= 0)
1400 return FRR_NETLINK_ERROR;
1401 }
1402
1403 seq = dplane_ctx_get_ns(ctx)->seq;
1404 nl = kernel_netlink_nlsock_lookup(dplane_ctx_get_ns_sock(ctx));
1405
1406 if (ignore_res)
1407 seq++;
1408
1409 msgh = (struct nlmsghdr *)bth->buf_head;
1410 msgh->nlmsg_seq = seq;
1411 msgh->nlmsg_pid = nl->snl.nl_pid;
1412
1413 bth->zns = dplane_ctx_get_ns(ctx);
1414 bth->buf_head = ((char *)bth->buf_head) + size;
1415 bth->curlen += size;
1416 bth->msgcnt++;
1417
1418 return FRR_NETLINK_QUEUED;
1419 }
1420
1421 static enum netlink_msg_status nl_put_msg(struct nl_batch *bth,
1422 struct zebra_dplane_ctx *ctx)
1423 {
1424 if (dplane_ctx_is_skip_kernel(ctx))
1425 return FRR_NETLINK_SUCCESS;
1426
1427 switch (dplane_ctx_get_op(ctx)) {
1428
1429 case DPLANE_OP_ROUTE_INSTALL:
1430 case DPLANE_OP_ROUTE_UPDATE:
1431 case DPLANE_OP_ROUTE_DELETE:
1432 return netlink_put_route_update_msg(bth, ctx);
1433
1434 case DPLANE_OP_NH_INSTALL:
1435 case DPLANE_OP_NH_UPDATE:
1436 case DPLANE_OP_NH_DELETE:
1437 return netlink_put_nexthop_update_msg(bth, ctx);
1438
1439 case DPLANE_OP_LSP_INSTALL:
1440 case DPLANE_OP_LSP_UPDATE:
1441 case DPLANE_OP_LSP_DELETE:
1442 return netlink_put_lsp_update_msg(bth, ctx);
1443
1444 case DPLANE_OP_PW_INSTALL:
1445 case DPLANE_OP_PW_UNINSTALL:
1446 return netlink_put_pw_update_msg(bth, ctx);
1447
1448 case DPLANE_OP_ADDR_INSTALL:
1449 case DPLANE_OP_ADDR_UNINSTALL:
1450 return netlink_put_address_update_msg(bth, ctx);
1451
1452 case DPLANE_OP_MAC_INSTALL:
1453 case DPLANE_OP_MAC_DELETE:
1454 return netlink_put_mac_update_msg(bth, ctx);
1455
1456 case DPLANE_OP_NEIGH_INSTALL:
1457 case DPLANE_OP_NEIGH_UPDATE:
1458 case DPLANE_OP_NEIGH_DELETE:
1459 case DPLANE_OP_VTEP_ADD:
1460 case DPLANE_OP_VTEP_DELETE:
1461 case DPLANE_OP_NEIGH_DISCOVER:
1462 case DPLANE_OP_NEIGH_IP_INSTALL:
1463 case DPLANE_OP_NEIGH_IP_DELETE:
1464 case DPLANE_OP_NEIGH_TABLE_UPDATE:
1465 return netlink_put_neigh_update_msg(bth, ctx);
1466
1467 case DPLANE_OP_RULE_ADD:
1468 case DPLANE_OP_RULE_DELETE:
1469 case DPLANE_OP_RULE_UPDATE:
1470 return netlink_put_rule_update_msg(bth, ctx);
1471
1472 case DPLANE_OP_SYS_ROUTE_ADD:
1473 case DPLANE_OP_SYS_ROUTE_DELETE:
1474 case DPLANE_OP_ROUTE_NOTIFY:
1475 case DPLANE_OP_LSP_NOTIFY:
1476 case DPLANE_OP_BR_PORT_UPDATE:
1477 return FRR_NETLINK_SUCCESS;
1478
1479 case DPLANE_OP_IPTABLE_ADD:
1480 case DPLANE_OP_IPTABLE_DELETE:
1481 case DPLANE_OP_IPSET_ADD:
1482 case DPLANE_OP_IPSET_DELETE:
1483 case DPLANE_OP_IPSET_ENTRY_ADD:
1484 case DPLANE_OP_IPSET_ENTRY_DELETE:
1485 return FRR_NETLINK_ERROR;
1486
1487 case DPLANE_OP_GRE_SET:
1488 return netlink_put_gre_set_msg(bth, ctx);
1489
1490 case DPLANE_OP_INTF_ADDR_ADD:
1491 case DPLANE_OP_INTF_ADDR_DEL:
1492 case DPLANE_OP_INTF_NETCONFIG:
1493 case DPLANE_OP_NONE:
1494 return FRR_NETLINK_ERROR;
1495
1496 case DPLANE_OP_INTF_INSTALL:
1497 case DPLANE_OP_INTF_UPDATE:
1498 case DPLANE_OP_INTF_DELETE:
1499 return netlink_put_intf_update_msg(bth, ctx);
1500 }
1501
1502 return FRR_NETLINK_ERROR;
1503 }
1504
1505 void kernel_update_multi(struct dplane_ctx_q *ctx_list)
1506 {
1507 struct nl_batch batch;
1508 struct zebra_dplane_ctx *ctx;
1509 struct dplane_ctx_q handled_list;
1510 enum netlink_msg_status res;
1511
1512 TAILQ_INIT(&handled_list);
1513 nl_batch_init(&batch, &handled_list);
1514
1515 while (true) {
1516 ctx = dplane_ctx_dequeue(ctx_list);
1517 if (ctx == NULL)
1518 break;
1519
1520 if (batch.zns != NULL
1521 && batch.zns->ns_id != dplane_ctx_get_ns(ctx)->ns_id)
1522 nl_batch_send(&batch);
1523
1524 /*
1525 * Assume all messages will succeed and then mark only the ones
1526 * that failed.
1527 */
1528 dplane_ctx_set_status(ctx, ZEBRA_DPLANE_REQUEST_SUCCESS);
1529
1530 res = nl_put_msg(&batch, ctx);
1531
1532 dplane_ctx_enqueue_tail(&(batch.ctx_list), ctx);
1533 if (res == FRR_NETLINK_ERROR)
1534 dplane_ctx_set_status(ctx,
1535 ZEBRA_DPLANE_REQUEST_FAILURE);
1536
1537 if (batch.curlen > batch.limit)
1538 nl_batch_send(&batch);
1539 }
1540
1541 nl_batch_send(&batch);
1542
1543 TAILQ_INIT(ctx_list);
1544 dplane_ctx_list_append(ctx_list, &handled_list);
1545 }
1546
1547 struct nlsock *kernel_netlink_nlsock_lookup(int sock)
1548 {
1549 struct nlsock lookup, *retval;
1550
1551 lookup.sock = sock;
1552
1553 NLSOCK_LOCK();
1554 retval = hash_lookup(nlsock_hash, &lookup);
1555 NLSOCK_UNLOCK();
1556
1557 return retval;
1558 }
1559
1560 /* Insert nlsock entry into hash */
1561 static void kernel_netlink_nlsock_insert(struct nlsock *nls)
1562 {
1563 NLSOCK_LOCK();
1564 (void)hash_get(nlsock_hash, nls, hash_alloc_intern);
1565 NLSOCK_UNLOCK();
1566 }
1567
1568 /* Remove nlsock entry from hash */
1569 static void kernel_netlink_nlsock_remove(struct nlsock *nls)
1570 {
1571 NLSOCK_LOCK();
1572 (void)hash_release(nlsock_hash, nls);
1573 NLSOCK_UNLOCK();
1574 }
1575
1576 static uint32_t kernel_netlink_nlsock_key(const void *arg)
1577 {
1578 const struct nlsock *nl = arg;
1579
1580 return nl->sock;
1581 }
1582
1583 static bool kernel_netlink_nlsock_hash_equal(const void *arg1, const void *arg2)
1584 {
1585 const struct nlsock *nl1 = arg1;
1586 const struct nlsock *nl2 = arg2;
1587
1588 if (nl1->sock == nl2->sock)
1589 return true;
1590
1591 return false;
1592 }
1593
1594 /* Exported interface function. This function simply calls
1595 netlink_socket (). */
1596 void kernel_init(struct zebra_ns *zns)
1597 {
1598 uint32_t groups, dplane_groups;
1599 #if defined SOL_NETLINK
1600 int one, ret;
1601 #endif
1602
1603 /*
1604 * Initialize netlink sockets
1605 *
1606 * If RTMGRP_XXX exists use that, but at some point
1607 * I think the kernel developers realized that
1608 * keeping track of all the different values would
1609 * lead to confusion, so we need to convert the
1610 * RTNLGRP_XXX to a bit position for ourself
1611 */
1612 groups = RTMGRP_LINK |
1613 RTMGRP_IPV4_ROUTE |
1614 RTMGRP_IPV4_IFADDR |
1615 RTMGRP_IPV6_ROUTE |
1616 RTMGRP_IPV6_IFADDR |
1617 RTMGRP_IPV4_MROUTE |
1618 RTMGRP_NEIGH |
1619 ((uint32_t) 1 << (RTNLGRP_IPV4_RULE - 1)) |
1620 ((uint32_t) 1 << (RTNLGRP_IPV6_RULE - 1)) |
1621 ((uint32_t) 1 << (RTNLGRP_NEXTHOP - 1));
1622
1623 dplane_groups = (RTMGRP_LINK |
1624 RTMGRP_IPV4_IFADDR |
1625 RTMGRP_IPV6_IFADDR |
1626 ((uint32_t) 1 << (RTNLGRP_IPV4_NETCONF - 1)) |
1627 ((uint32_t) 1 << (RTNLGRP_IPV6_NETCONF - 1)) |
1628 ((uint32_t) 1 << (RTNLGRP_MPLS_NETCONF - 1)));
1629
1630
1631 snprintf(zns->netlink.name, sizeof(zns->netlink.name),
1632 "netlink-listen (NS %u)", zns->ns_id);
1633 zns->netlink.sock = -1;
1634 if (netlink_socket(&zns->netlink, groups, zns->ns_id) < 0) {
1635 zlog_err("Failure to create %s socket",
1636 zns->netlink.name);
1637 exit(-1);
1638 }
1639
1640 kernel_netlink_nlsock_insert(&zns->netlink);
1641
1642 snprintf(zns->netlink_cmd.name, sizeof(zns->netlink_cmd.name),
1643 "netlink-cmd (NS %u)", zns->ns_id);
1644 zns->netlink_cmd.sock = -1;
1645 if (netlink_socket(&zns->netlink_cmd, 0, zns->ns_id) < 0) {
1646 zlog_err("Failure to create %s socket",
1647 zns->netlink_cmd.name);
1648 exit(-1);
1649 }
1650
1651 kernel_netlink_nlsock_insert(&zns->netlink_cmd);
1652
1653 /* Outbound socket for dplane programming of the host OS. */
1654 snprintf(zns->netlink_dplane_out.name,
1655 sizeof(zns->netlink_dplane_out.name), "netlink-dp (NS %u)",
1656 zns->ns_id);
1657 zns->netlink_dplane_out.sock = -1;
1658 if (netlink_socket(&zns->netlink_dplane_out, 0, zns->ns_id) < 0) {
1659 zlog_err("Failure to create %s socket",
1660 zns->netlink_dplane_out.name);
1661 exit(-1);
1662 }
1663
1664 kernel_netlink_nlsock_insert(&zns->netlink_dplane_out);
1665
1666 /* Inbound socket for OS events coming to the dplane. */
1667 snprintf(zns->netlink_dplane_in.name,
1668 sizeof(zns->netlink_dplane_in.name), "netlink-dp-in (NS %u)",
1669 zns->ns_id);
1670 zns->netlink_dplane_in.sock = -1;
1671 if (netlink_socket(&zns->netlink_dplane_in, dplane_groups,
1672 zns->ns_id) < 0) {
1673 zlog_err("Failure to create %s socket",
1674 zns->netlink_dplane_in.name);
1675 exit(-1);
1676 }
1677
1678 kernel_netlink_nlsock_insert(&zns->netlink_dplane_in);
1679
1680 /*
1681 * SOL_NETLINK is not available on all platforms yet
1682 * apparently. It's in bits/socket.h which I am not
1683 * sure that we want to pull into our build system.
1684 */
1685 #if defined SOL_NETLINK
1686 /*
1687 * Let's tell the kernel that we want to receive extended
1688 * ACKS over our command socket(s)
1689 */
1690 one = 1;
1691 ret = setsockopt(zns->netlink_cmd.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1692 &one, sizeof(one));
1693
1694 if (ret < 0)
1695 zlog_notice("Registration for extended cmd ACK failed : %d %s",
1696 errno, safe_strerror(errno));
1697
1698 one = 1;
1699 ret = setsockopt(zns->netlink_dplane_out.sock, SOL_NETLINK,
1700 NETLINK_EXT_ACK, &one, sizeof(one));
1701
1702 if (ret < 0)
1703 zlog_notice("Registration for extended dp ACK failed : %d %s",
1704 errno, safe_strerror(errno));
1705
1706 /*
1707 * Trim off the payload of the original netlink message in the
1708 * acknowledgment. This option is available since Linux 4.2, so if
1709 * setsockopt fails, ignore the error.
1710 */
1711 one = 1;
1712 ret = setsockopt(zns->netlink_dplane_out.sock, SOL_NETLINK,
1713 NETLINK_CAP_ACK, &one, sizeof(one));
1714 if (ret < 0)
1715 zlog_notice(
1716 "Registration for reduced ACK packet size failed, probably running an early kernel");
1717 #endif
1718
1719 /* Register kernel socket. */
1720 if (fcntl(zns->netlink.sock, F_SETFL, O_NONBLOCK) < 0)
1721 flog_err_sys(EC_LIB_SOCKET, "Can't set %s socket flags: %s",
1722 zns->netlink.name, safe_strerror(errno));
1723
1724 if (fcntl(zns->netlink_cmd.sock, F_SETFL, O_NONBLOCK) < 0)
1725 zlog_err("Can't set %s socket error: %s(%d)",
1726 zns->netlink_cmd.name, safe_strerror(errno), errno);
1727
1728 if (fcntl(zns->netlink_dplane_out.sock, F_SETFL, O_NONBLOCK) < 0)
1729 zlog_err("Can't set %s socket error: %s(%d)",
1730 zns->netlink_dplane_out.name, safe_strerror(errno),
1731 errno);
1732
1733 if (fcntl(zns->netlink_dplane_in.sock, F_SETFL, O_NONBLOCK) < 0)
1734 zlog_err("Can't set %s socket error: %s(%d)",
1735 zns->netlink_dplane_in.name, safe_strerror(errno),
1736 errno);
1737
1738 /* Set receive buffer size if it's set from command line */
1739 if (rcvbufsize) {
1740 netlink_recvbuf(&zns->netlink, rcvbufsize);
1741 netlink_recvbuf(&zns->netlink_cmd, rcvbufsize);
1742 netlink_recvbuf(&zns->netlink_dplane_out, rcvbufsize);
1743 netlink_recvbuf(&zns->netlink_dplane_in, rcvbufsize);
1744 }
1745
1746 /* Set filter for inbound sockets, to exclude events we've generated
1747 * ourselves.
1748 */
1749 netlink_install_filter(zns->netlink.sock, zns->netlink_cmd.snl.nl_pid,
1750 zns->netlink_dplane_out.snl.nl_pid);
1751
1752 netlink_install_filter(zns->netlink_dplane_in.sock,
1753 zns->netlink_cmd.snl.nl_pid,
1754 zns->netlink_dplane_out.snl.nl_pid);
1755
1756 zns->t_netlink = NULL;
1757
1758 thread_add_read(zrouter.master, kernel_read, zns,
1759 zns->netlink.sock, &zns->t_netlink);
1760
1761 rt_netlink_init();
1762 }
1763
1764 /* Helper to clean up an nlsock */
1765 static void kernel_nlsock_fini(struct nlsock *nls)
1766 {
1767 if (nls && nls->sock >= 0) {
1768 kernel_netlink_nlsock_remove(nls);
1769 close(nls->sock);
1770 nls->sock = -1;
1771 XFREE(MTYPE_NL_BUF, nls->buf);
1772 nls->buflen = 0;
1773 }
1774 }
1775
1776 void kernel_terminate(struct zebra_ns *zns, bool complete)
1777 {
1778 thread_cancel(&zns->t_netlink);
1779
1780 kernel_nlsock_fini(&zns->netlink);
1781
1782 kernel_nlsock_fini(&zns->netlink_cmd);
1783
1784 kernel_nlsock_fini(&zns->netlink_dplane_in);
1785
1786 /* During zebra shutdown, we need to leave the dataplane socket
1787 * around until all work is done.
1788 */
1789 if (complete)
1790 kernel_nlsock_fini(&zns->netlink_dplane_out);
1791 }
1792
1793 /*
1794 * Global init for platform-/OS-specific things
1795 */
1796 void kernel_router_init(void)
1797 {
1798 /* Init nlsock hash and lock */
1799 pthread_mutex_init(&nlsock_mutex, NULL);
1800 nlsock_hash = hash_create_size(8, kernel_netlink_nlsock_key,
1801 kernel_netlink_nlsock_hash_equal,
1802 "Netlink Socket Hash");
1803 }
1804
1805 /*
1806 * Global deinit for platform-/OS-specific things
1807 */
1808 void kernel_router_terminate(void)
1809 {
1810 pthread_mutex_destroy(&nlsock_mutex);
1811
1812 hash_free(nlsock_hash);
1813 nlsock_hash = NULL;
1814 }
1815
1816 #endif /* HAVE_NETLINK */