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