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