]> git.proxmox.com Git - mirror_frr.git/blob - zebra/kernel_netlink.c
Merge pull request #5793 from ton31337/fix/formatting_show_bgp_summary_failed
[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 #if defined(HANDLE_NETLINK_FUZZING)
24 #include <stdio.h>
25 #include <string.h>
26 #include "libfrr.h"
27 #endif /* HANDLE_NETLINK_FUZZING */
28
29 #ifdef HAVE_NETLINK
30
31 #include "linklist.h"
32 #include "if.h"
33 #include "log.h"
34 #include "prefix.h"
35 #include "connected.h"
36 #include "table.h"
37 #include "memory.h"
38 #include "zebra_memory.h"
39 #include "rib.h"
40 #include "thread.h"
41 #include "privs.h"
42 #include "nexthop.h"
43 #include "vrf.h"
44 #include "mpls.h"
45 #include "lib_errors.h"
46
47 //#include "zebra/zserv.h"
48 #include "zebra/zebra_router.h"
49 #include "zebra/zebra_ns.h"
50 #include "zebra/zebra_vrf.h"
51 #include "zebra/rt.h"
52 #include "zebra/debug.h"
53 #include "zebra/kernel_netlink.h"
54 #include "zebra/rt_netlink.h"
55 #include "zebra/if_netlink.h"
56 #include "zebra/rule_netlink.h"
57 #include "zebra/zebra_errors.h"
58
59 #ifndef SO_RCVBUFFORCE
60 #define SO_RCVBUFFORCE (33)
61 #endif
62
63 /* Hack for GNU libc version 2. */
64 #ifndef MSG_TRUNC
65 #define MSG_TRUNC 0x20
66 #endif /* MSG_TRUNC */
67
68 #ifndef NLMSG_TAIL
69 #define NLMSG_TAIL(nmsg) \
70 ((struct rtattr *)(((uint8_t *)(nmsg)) \
71 + NLMSG_ALIGN((nmsg)->nlmsg_len)))
72 #endif
73
74 #ifndef RTA_TAIL
75 #define RTA_TAIL(rta) \
76 ((struct rtattr *)(((uint8_t *)(rta)) + RTA_ALIGN((rta)->rta_len)))
77 #endif
78
79 #ifndef RTNL_FAMILY_IP6MR
80 #define RTNL_FAMILY_IP6MR 129
81 #endif
82
83 #ifndef RTPROT_MROUTED
84 #define RTPROT_MROUTED 17
85 #endif
86
87 static const struct message nlmsg_str[] = {{RTM_NEWROUTE, "RTM_NEWROUTE"},
88 {RTM_DELROUTE, "RTM_DELROUTE"},
89 {RTM_GETROUTE, "RTM_GETROUTE"},
90 {RTM_NEWLINK, "RTM_NEWLINK"},
91 {RTM_DELLINK, "RTM_DELLINK"},
92 {RTM_GETLINK, "RTM_GETLINK"},
93 {RTM_NEWADDR, "RTM_NEWADDR"},
94 {RTM_DELADDR, "RTM_DELADDR"},
95 {RTM_GETADDR, "RTM_GETADDR"},
96 {RTM_NEWNEIGH, "RTM_NEWNEIGH"},
97 {RTM_DELNEIGH, "RTM_DELNEIGH"},
98 {RTM_GETNEIGH, "RTM_GETNEIGH"},
99 {RTM_NEWRULE, "RTM_NEWRULE"},
100 {RTM_DELRULE, "RTM_DELRULE"},
101 {RTM_GETRULE, "RTM_GETRULE"},
102 {RTM_NEWNEXTHOP, "RTM_NEWNEXTHOP"},
103 {RTM_DELNEXTHOP, "RTM_DELNEXTHOP"},
104 {RTM_GETNEXTHOP, "RTM_GETNEXTHOP"},
105 {0}};
106
107 static const struct message rtproto_str[] = {
108 {RTPROT_REDIRECT, "redirect"},
109 {RTPROT_KERNEL, "kernel"},
110 {RTPROT_BOOT, "boot"},
111 {RTPROT_STATIC, "static"},
112 {RTPROT_GATED, "GateD"},
113 {RTPROT_RA, "router advertisement"},
114 {RTPROT_MRT, "MRT"},
115 {RTPROT_ZEBRA, "Zebra"},
116 #ifdef RTPROT_BIRD
117 {RTPROT_BIRD, "BIRD"},
118 #endif /* RTPROT_BIRD */
119 {RTPROT_MROUTED, "mroute"},
120 {RTPROT_BGP, "BGP"},
121 {RTPROT_OSPF, "OSPF"},
122 {RTPROT_ISIS, "IS-IS"},
123 {RTPROT_RIP, "RIP"},
124 {RTPROT_RIPNG, "RIPNG"},
125 {RTPROT_ZSTATIC, "static"},
126 {0}};
127
128 static const struct message family_str[] = {{AF_INET, "ipv4"},
129 {AF_INET6, "ipv6"},
130 {AF_BRIDGE, "bridge"},
131 {RTNL_FAMILY_IPMR, "ipv4MR"},
132 {RTNL_FAMILY_IP6MR, "ipv6MR"},
133 {0}};
134
135 static const struct message rttype_str[] = {{RTN_UNSPEC, "none"},
136 {RTN_UNICAST, "unicast"},
137 {RTN_LOCAL, "local"},
138 {RTN_BROADCAST, "broadcast"},
139 {RTN_ANYCAST, "anycast"},
140 {RTN_MULTICAST, "multicast"},
141 {RTN_BLACKHOLE, "blackhole"},
142 {RTN_UNREACHABLE, "unreachable"},
143 {RTN_PROHIBIT, "prohibited"},
144 {RTN_THROW, "throw"},
145 {RTN_NAT, "nat"},
146 {RTN_XRESOLVE, "resolver"},
147 {0}};
148
149 extern struct thread_master *master;
150 extern uint32_t nl_rcvbufsize;
151
152 extern struct zebra_privs_t zserv_privs;
153
154
155 int netlink_talk_filter(struct nlmsghdr *h, ns_id_t ns_id, int startup)
156 {
157 /*
158 * This is an error condition that must be handled during
159 * development.
160 *
161 * The netlink_talk_filter function is used for communication
162 * down the netlink_cmd pipe and we are expecting
163 * an ack being received. So if we get here
164 * then we did not receive the ack and instead
165 * received some other message in an unexpected
166 * way.
167 */
168 zlog_debug("%s: ignoring message type 0x%04x(%s) NS %u", __func__,
169 h->nlmsg_type, nl_msg_type_to_str(h->nlmsg_type), ns_id);
170 return 0;
171 }
172
173 static int netlink_recvbuf(struct nlsock *nl, uint32_t newsize)
174 {
175 uint32_t oldsize;
176 socklen_t newlen = sizeof(newsize);
177 socklen_t oldlen = sizeof(oldsize);
178 int ret;
179
180 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &oldsize, &oldlen);
181 if (ret < 0) {
182 flog_err_sys(EC_LIB_SOCKET,
183 "Can't get %s receive buffer size: %s", nl->name,
184 safe_strerror(errno));
185 return -1;
186 }
187
188 /* Try force option (linux >= 2.6.14) and fall back to normal set */
189 frr_with_privs(&zserv_privs) {
190 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUFFORCE,
191 &nl_rcvbufsize,
192 sizeof(nl_rcvbufsize));
193 }
194 if (ret < 0)
195 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF,
196 &nl_rcvbufsize, sizeof(nl_rcvbufsize));
197 if (ret < 0) {
198 flog_err_sys(EC_LIB_SOCKET,
199 "Can't set %s receive buffer size: %s", nl->name,
200 safe_strerror(errno));
201 return -1;
202 }
203
204 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &newsize, &newlen);
205 if (ret < 0) {
206 flog_err_sys(EC_LIB_SOCKET,
207 "Can't get %s receive buffer size: %s", nl->name,
208 safe_strerror(errno));
209 return -1;
210 }
211
212 zlog_info("Setting netlink socket receive buffer size: %u -> %u",
213 oldsize, newsize);
214 return 0;
215 }
216
217 /* Make socket for Linux netlink interface. */
218 static int netlink_socket(struct nlsock *nl, unsigned long groups,
219 ns_id_t ns_id)
220 {
221 int ret;
222 struct sockaddr_nl snl;
223 int sock;
224 int namelen;
225
226 frr_with_privs(&zserv_privs) {
227 sock = ns_socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, ns_id);
228 if (sock < 0) {
229 zlog_err("Can't open %s socket: %s", nl->name,
230 safe_strerror(errno));
231 return -1;
232 }
233
234 memset(&snl, 0, sizeof snl);
235 snl.nl_family = AF_NETLINK;
236 snl.nl_groups = groups;
237
238 /* Bind the socket to the netlink structure for anything. */
239 ret = bind(sock, (struct sockaddr *)&snl, sizeof snl);
240 }
241
242 if (ret < 0) {
243 zlog_err("Can't bind %s socket to group 0x%x: %s", nl->name,
244 snl.nl_groups, safe_strerror(errno));
245 close(sock);
246 return -1;
247 }
248
249 /* multiple netlink sockets will have different nl_pid */
250 namelen = sizeof snl;
251 ret = getsockname(sock, (struct sockaddr *)&snl, (socklen_t *)&namelen);
252 if (ret < 0 || namelen != sizeof snl) {
253 flog_err_sys(EC_LIB_SOCKET, "Can't get %s socket name: %s",
254 nl->name, safe_strerror(errno));
255 close(sock);
256 return -1;
257 }
258
259 nl->snl = snl;
260 nl->sock = sock;
261 return ret;
262 }
263
264 static int netlink_information_fetch(struct nlmsghdr *h, ns_id_t ns_id,
265 int startup)
266 {
267 /*
268 * When we handle new message types here
269 * because we are starting to install them
270 * then lets check the netlink_install_filter
271 * and see if we should add the corresponding
272 * allow through entry there.
273 * Probably not needed to do but please
274 * think about it.
275 */
276 switch (h->nlmsg_type) {
277 case RTM_NEWROUTE:
278 return netlink_route_change(h, ns_id, startup);
279 case RTM_DELROUTE:
280 return netlink_route_change(h, ns_id, startup);
281 case RTM_NEWLINK:
282 return netlink_link_change(h, ns_id, startup);
283 case RTM_DELLINK:
284 return netlink_link_change(h, ns_id, startup);
285 case RTM_NEWADDR:
286 return netlink_interface_addr(h, ns_id, startup);
287 case RTM_DELADDR:
288 return netlink_interface_addr(h, ns_id, startup);
289 case RTM_NEWNEIGH:
290 return netlink_neigh_change(h, ns_id);
291 case RTM_DELNEIGH:
292 return netlink_neigh_change(h, ns_id);
293 case RTM_GETNEIGH:
294 /*
295 * Kernel in some situations when it expects
296 * user space to resolve arp entries, we will
297 * receive this notification. As we don't
298 * need this notification and as that
299 * we don't want to spam the log file with
300 * below messages, just ignore.
301 */
302 if (IS_ZEBRA_DEBUG_KERNEL)
303 zlog_debug("Received RTM_GETNEIGH, ignoring");
304 break;
305 case RTM_NEWRULE:
306 return netlink_rule_change(h, ns_id, startup);
307 case RTM_DELRULE:
308 return netlink_rule_change(h, ns_id, startup);
309 case RTM_NEWNEXTHOP:
310 return netlink_nexthop_change(h, ns_id, startup);
311 case RTM_DELNEXTHOP:
312 return netlink_nexthop_change(h, ns_id, startup);
313 default:
314 /*
315 * If we have received this message then
316 * we have made a mistake during development
317 * and we need to write some code to handle
318 * this message type or not ask for
319 * it to be sent up to us
320 */
321 flog_err(EC_ZEBRA_UNKNOWN_NLMSG,
322 "Unknown netlink nlmsg_type %s(%d) vrf %u\n",
323 nl_msg_type_to_str(h->nlmsg_type), h->nlmsg_type,
324 ns_id);
325 break;
326 }
327 return 0;
328 }
329
330 #if defined(HANDLE_NETLINK_FUZZING)
331 /* Using globals here to avoid adding function parameters */
332
333 /* Keep distinct filenames for netlink fuzzy collection */
334 static unsigned int netlink_file_counter = 1;
335
336 /* File name to read fuzzed netlink from */
337 static char netlink_fuzz_file[MAXPATHLEN] = "";
338
339 /* Flag for whether to read from file or not */
340 bool netlink_read;
341
342 /**
343 * netlink_read_init() - Starts the message parser
344 * @fname: Filename to read.
345 */
346 void netlink_read_init(const char *fname)
347 {
348 struct zebra_dplane_info dp_info;
349
350 snprintf(netlink_fuzz_file, MAXPATHLEN, "%s", fname);
351 /* Creating this fake socket for testing purposes */
352 struct zebra_ns *zns = zebra_ns_lookup(NS_DEFAULT);
353
354 /* Capture key info from zns struct */
355 zebra_dplane_info_from_zns(&dp_info, zns, false);
356
357 netlink_parse_info(netlink_information_fetch, &zns->netlink,
358 &dp_info, 1, 0);
359 }
360
361 /**
362 * netlink_write_incoming() - Writes all data received from netlink to a file
363 * @buf: Data from netlink.
364 * @size: Size of data.
365 * @counter: Counter for keeping filenames distinct.
366 */
367 static void netlink_write_incoming(const char *buf, const unsigned int size,
368 unsigned int counter)
369 {
370 char fname[MAXPATHLEN];
371 FILE *f;
372
373 snprintf(fname, MAXPATHLEN, "%s/%s_%u", frr_vtydir, "netlink", counter);
374 frr_with_privs(&zserv_privs) {
375 f = fopen(fname, "w");
376 }
377 if (f) {
378 fwrite(buf, 1, size, f);
379 fclose(f);
380 }
381 }
382
383 /**
384 * netlink_read_file() - Reads netlink data from file
385 * @buf: Netlink buffer being overwritten.
386 * @fname: File name to read from.
387 *
388 * Return: Size of file.
389 */
390 static long netlink_read_file(char *buf, const char *fname)
391 {
392 FILE *f;
393 long file_bytes = -1;
394
395 frr_with_privs(&zserv_privs) {
396 f = fopen(fname, "r");
397 }
398 if (f) {
399 fseek(f, 0, SEEK_END);
400 file_bytes = ftell(f);
401 rewind(f);
402 fread(buf, NL_RCV_PKT_BUF_SIZE, 1, f);
403 fclose(f);
404 }
405 return file_bytes;
406 }
407
408 #endif /* HANDLE_NETLINK_FUZZING */
409
410 static int kernel_read(struct thread *thread)
411 {
412 struct zebra_ns *zns = (struct zebra_ns *)THREAD_ARG(thread);
413 struct zebra_dplane_info dp_info;
414
415 /* Capture key info from ns struct */
416 zebra_dplane_info_from_zns(&dp_info, zns, false);
417
418 netlink_parse_info(netlink_information_fetch, &zns->netlink, &dp_info,
419 5, 0);
420 zns->t_netlink = NULL;
421 thread_add_read(zrouter.master, kernel_read, zns, zns->netlink.sock,
422 &zns->t_netlink);
423
424 return 0;
425 }
426
427 /*
428 * Filter out messages from self that occur on listener socket,
429 * caused by our actions on the command socket(s)
430 *
431 * When we add new Netlink message types we probably
432 * do not need to add them here as that we are filtering
433 * on the routes we actually care to receive( which is rarer
434 * then the normal course of operations). We are intentionally
435 * allowing some messages from ourselves through
436 * ( I'm looking at you Interface based netlink messages )
437 * so that we only had to write one way to handle incoming
438 * address add/delete changes.
439 */
440 static void netlink_install_filter(int sock, __u32 pid, __u32 dplane_pid)
441 {
442 /*
443 * BPF_JUMP instructions and where you jump to are based upon
444 * 0 as being the next statement. So count from 0. Writing
445 * this down because every time I look at this I have to
446 * re-remember it.
447 */
448 struct sock_filter filter[] = {
449 /*
450 * Logic:
451 * if (nlmsg_pid == pid ||
452 * nlmsg_pid == dplane_pid) {
453 * if (the incoming nlmsg_type ==
454 * RTM_NEWADDR | RTM_DELADDR)
455 * keep this message
456 * else
457 * skip this message
458 * } else
459 * keep this netlink message
460 */
461 /*
462 * 0: Load the nlmsg_pid into the BPF register
463 */
464 BPF_STMT(BPF_LD | BPF_ABS | BPF_W,
465 offsetof(struct nlmsghdr, nlmsg_pid)),
466 /*
467 * 1: Compare to pid
468 */
469 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(pid), 1, 0),
470 /*
471 * 2: Compare to dplane pid
472 */
473 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htonl(dplane_pid), 0, 4),
474 /*
475 * 3: Load the nlmsg_type into BPF register
476 */
477 BPF_STMT(BPF_LD | BPF_ABS | BPF_H,
478 offsetof(struct nlmsghdr, nlmsg_type)),
479 /*
480 * 4: Compare to RTM_NEWADDR
481 */
482 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_NEWADDR), 2, 0),
483 /*
484 * 5: Compare to RTM_DELADDR
485 */
486 BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, htons(RTM_DELADDR), 1, 0),
487 /*
488 * 6: This is the end state of we want to skip the
489 * message
490 */
491 BPF_STMT(BPF_RET | BPF_K, 0),
492 /* 7: This is the end state of we want to keep
493 * the message
494 */
495 BPF_STMT(BPF_RET | BPF_K, 0xffff),
496 };
497
498 struct sock_fprog prog = {
499 .len = array_size(filter), .filter = filter,
500 };
501
502 if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog))
503 < 0)
504 flog_err_sys(EC_LIB_SOCKET, "Can't install socket filter: %s\n",
505 safe_strerror(errno));
506 }
507
508 void netlink_parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta,
509 int len)
510 {
511 while (RTA_OK(rta, len)) {
512 if (rta->rta_type <= max)
513 tb[rta->rta_type] = rta;
514 rta = RTA_NEXT(rta, len);
515 }
516 }
517
518 /**
519 * netlink_parse_rtattr_nested() - Parses a nested route attribute
520 * @tb: Pointer to array for storing rtattr in.
521 * @max: Max number to store.
522 * @rta: Pointer to rtattr to look for nested items in.
523 */
524 void netlink_parse_rtattr_nested(struct rtattr **tb, int max,
525 struct rtattr *rta)
526 {
527 netlink_parse_rtattr(tb, max, RTA_DATA(rta), RTA_PAYLOAD(rta));
528 }
529
530 int addattr_l(struct nlmsghdr *n, unsigned int maxlen, int type,
531 const void *data, unsigned int alen)
532 {
533 int len;
534 struct rtattr *rta;
535
536 len = RTA_LENGTH(alen);
537
538 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen)
539 return -1;
540
541 rta = (struct rtattr *)(((char *)n) + NLMSG_ALIGN(n->nlmsg_len));
542 rta->rta_type = type;
543 rta->rta_len = len;
544
545 if (data)
546 memcpy(RTA_DATA(rta), data, alen);
547 else
548 assert(alen == 0);
549
550 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
551
552 return 0;
553 }
554
555 int rta_addattr_l(struct rtattr *rta, unsigned int maxlen, int type,
556 const void *data, unsigned int alen)
557 {
558 unsigned int len;
559 struct rtattr *subrta;
560
561 len = RTA_LENGTH(alen);
562
563 if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen)
564 return -1;
565
566 subrta = (struct rtattr *)(((char *)rta) + RTA_ALIGN(rta->rta_len));
567 subrta->rta_type = type;
568 subrta->rta_len = len;
569
570 if (data)
571 memcpy(RTA_DATA(subrta), data, alen);
572 else
573 assert(alen == 0);
574
575 rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len);
576
577 return 0;
578 }
579
580 int addattr16(struct nlmsghdr *n, unsigned int maxlen, int type, uint16_t data)
581 {
582 return addattr_l(n, maxlen, type, &data, sizeof(uint16_t));
583 }
584
585 int addattr32(struct nlmsghdr *n, unsigned int maxlen, int type, int data)
586 {
587 return addattr_l(n, maxlen, type, &data, sizeof(uint32_t));
588 }
589
590 struct rtattr *addattr_nest(struct nlmsghdr *n, int maxlen, int type)
591 {
592 struct rtattr *nest = NLMSG_TAIL(n);
593
594 addattr_l(n, maxlen, type, NULL, 0);
595 nest->rta_type |= NLA_F_NESTED;
596 return nest;
597 }
598
599 int addattr_nest_end(struct nlmsghdr *n, struct rtattr *nest)
600 {
601 nest->rta_len = (uint8_t *)NLMSG_TAIL(n) - (uint8_t *)nest;
602 return n->nlmsg_len;
603 }
604
605 struct rtattr *rta_nest(struct rtattr *rta, int maxlen, int type)
606 {
607 struct rtattr *nest = RTA_TAIL(rta);
608
609 rta_addattr_l(rta, maxlen, type, NULL, 0);
610 nest->rta_type |= NLA_F_NESTED;
611 return nest;
612 }
613
614 int rta_nest_end(struct rtattr *rta, struct rtattr *nest)
615 {
616 nest->rta_len = (uint8_t *)RTA_TAIL(rta) - (uint8_t *)nest;
617 return rta->rta_len;
618 }
619
620 const char *nl_msg_type_to_str(uint16_t msg_type)
621 {
622 return lookup_msg(nlmsg_str, msg_type, "");
623 }
624
625 const char *nl_rtproto_to_str(uint8_t rtproto)
626 {
627 return lookup_msg(rtproto_str, rtproto, "");
628 }
629
630 const char *nl_family_to_str(uint8_t family)
631 {
632 return lookup_msg(family_str, family, "");
633 }
634
635 const char *nl_rttype_to_str(uint8_t rttype)
636 {
637 return lookup_msg(rttype_str, rttype, "");
638 }
639
640 #define NLA_OK(nla, len) \
641 ((len) >= (int)sizeof(struct nlattr) \
642 && (nla)->nla_len >= sizeof(struct nlattr) \
643 && (nla)->nla_len <= (len))
644 #define NLA_NEXT(nla, attrlen) \
645 ((attrlen) -= NLA_ALIGN((nla)->nla_len), \
646 (struct nlattr *)(((char *)(nla)) + NLA_ALIGN((nla)->nla_len)))
647 #define NLA_LENGTH(len) (NLA_ALIGN(sizeof(struct nlattr)) + (len))
648 #define NLA_DATA(nla) ((struct nlattr *)(((char *)(nla)) + NLA_LENGTH(0)))
649
650 #define ERR_NLA(err, inner_len) \
651 ((struct nlattr *)(((char *)(err)) \
652 + NLMSG_ALIGN(sizeof(struct nlmsgerr)) \
653 + NLMSG_ALIGN((inner_len))))
654
655 static void netlink_parse_nlattr(struct nlattr **tb, int max,
656 struct nlattr *nla, int len)
657 {
658 while (NLA_OK(nla, len)) {
659 if (nla->nla_type <= max)
660 tb[nla->nla_type] = nla;
661 nla = NLA_NEXT(nla, len);
662 }
663 }
664
665 static void netlink_parse_extended_ack(struct nlmsghdr *h)
666 {
667 struct nlattr *tb[NLMSGERR_ATTR_MAX + 1] = {};
668 const struct nlmsgerr *err = (const struct nlmsgerr *)NLMSG_DATA(h);
669 const struct nlmsghdr *err_nlh = NULL;
670 /* Length not including nlmsghdr */
671 uint32_t len = 0;
672 /* Inner error netlink message length */
673 uint32_t inner_len = 0;
674 const char *msg = NULL;
675 uint32_t off = 0;
676
677 if (!(h->nlmsg_flags & NLM_F_CAPPED))
678 inner_len = (uint32_t)NLMSG_PAYLOAD(&err->msg, 0);
679
680 len = (uint32_t)(NLMSG_PAYLOAD(h, sizeof(struct nlmsgerr)) - inner_len);
681
682 netlink_parse_nlattr(tb, NLMSGERR_ATTR_MAX, ERR_NLA(err, inner_len),
683 len);
684
685 if (tb[NLMSGERR_ATTR_MSG])
686 msg = (const char *)NLA_DATA(tb[NLMSGERR_ATTR_MSG]);
687
688 if (tb[NLMSGERR_ATTR_OFFS]) {
689 off = *(uint32_t *)NLA_DATA(tb[NLMSGERR_ATTR_OFFS]);
690
691 if (off > h->nlmsg_len) {
692 zlog_err("Invalid offset for NLMSGERR_ATTR_OFFS");
693 } else if (!(h->nlmsg_flags & NLM_F_CAPPED)) {
694 /*
695 * Header of failed message
696 * we are not doing anything currently with it
697 * but noticing it for later.
698 */
699 err_nlh = &err->msg;
700 zlog_debug("%s: Received %s extended Ack",
701 __PRETTY_FUNCTION__,
702 nl_msg_type_to_str(err_nlh->nlmsg_type));
703 }
704 }
705
706 if (msg && *msg != '\0') {
707 bool is_err = !!err->error;
708
709 if (is_err)
710 zlog_err("Extended Error: %s", msg);
711 else
712 flog_warn(EC_ZEBRA_NETLINK_EXTENDED_WARNING,
713 "Extended Warning: %s", msg);
714 }
715 }
716
717 /*
718 * netlink_parse_info
719 *
720 * Receive message from netlink interface and pass those information
721 * to the given function.
722 *
723 * filter -> Function to call to read the results
724 * nl -> netlink socket information
725 * zns -> The zebra namespace data
726 * count -> How many we should read in, 0 means as much as possible
727 * startup -> Are we reading in under startup conditions? passed to
728 * the filter.
729 */
730 int netlink_parse_info(int (*filter)(struct nlmsghdr *, ns_id_t, int),
731 const struct nlsock *nl,
732 const struct zebra_dplane_info *zns,
733 int count, int startup)
734 {
735 int status;
736 int ret = 0;
737 int error;
738 int read_in = 0;
739
740 while (1) {
741 char buf[NL_RCV_PKT_BUF_SIZE];
742 struct iovec iov = {.iov_base = buf, .iov_len = sizeof buf};
743 struct sockaddr_nl snl;
744 struct msghdr msg = {.msg_name = (void *)&snl,
745 .msg_namelen = sizeof snl,
746 .msg_iov = &iov,
747 .msg_iovlen = 1};
748 struct nlmsghdr *h;
749
750 if (count && read_in >= count)
751 return 0;
752
753 #if defined(HANDLE_NETLINK_FUZZING)
754 /* Check if reading and filename is set */
755 if (netlink_read && '\0' != netlink_fuzz_file[0]) {
756 zlog_debug("Reading netlink fuzz file");
757 status = netlink_read_file(buf, netlink_fuzz_file);
758 snl.nl_pid = 0;
759 } else {
760 status = recvmsg(nl->sock, &msg, 0);
761 }
762 #else
763 status = recvmsg(nl->sock, &msg, 0);
764 #endif /* HANDLE_NETLINK_FUZZING */
765 if (status < 0) {
766 if (errno == EINTR)
767 continue;
768 if (errno == EWOULDBLOCK || errno == EAGAIN)
769 break;
770 flog_err(EC_ZEBRA_RECVMSG_OVERRUN,
771 "%s recvmsg overrun: %s", nl->name,
772 safe_strerror(errno));
773 /*
774 * In this case we are screwed.
775 * There is no good way to
776 * recover zebra at this point.
777 */
778 exit(-1);
779 continue;
780 }
781
782 if (status == 0) {
783 flog_err_sys(EC_LIB_SOCKET, "%s EOF", nl->name);
784 return -1;
785 }
786
787 if (msg.msg_namelen != sizeof snl) {
788 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
789 "%s sender address length error: length %d",
790 nl->name, msg.msg_namelen);
791 return -1;
792 }
793
794 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_RECV) {
795 zlog_debug("%s: << netlink message dump [recv]",
796 __func__);
797 zlog_hexdump(buf, status);
798 }
799
800 #if defined(HANDLE_NETLINK_FUZZING)
801 if (!netlink_read) {
802 zlog_debug("Writing incoming netlink message");
803 netlink_write_incoming(buf, status,
804 netlink_file_counter++);
805 }
806 #endif /* HANDLE_NETLINK_FUZZING */
807
808 read_in++;
809 for (h = (struct nlmsghdr *)buf;
810 (status >= 0 && NLMSG_OK(h, (unsigned int)status));
811 h = NLMSG_NEXT(h, status)) {
812 /* Finish of reading. */
813 if (h->nlmsg_type == NLMSG_DONE)
814 return ret;
815
816 /* Error handling. */
817 if (h->nlmsg_type == NLMSG_ERROR) {
818 struct nlmsgerr *err =
819 (struct nlmsgerr *)NLMSG_DATA(h);
820 int errnum = err->error;
821 int msg_type = err->msg.nlmsg_type;
822
823 if (h->nlmsg_len
824 < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
825 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
826 "%s error: message truncated",
827 nl->name);
828 return -1;
829 }
830
831 /*
832 * Parse the extended information before
833 * we actually handle it.
834 * At this point in time we do not
835 * do anything other than report the
836 * issue.
837 */
838 if (h->nlmsg_flags & NLM_F_ACK_TLVS)
839 netlink_parse_extended_ack(h);
840
841 /* If the error field is zero, then this is an
842 * ACK */
843 if (err->error == 0) {
844 if (IS_ZEBRA_DEBUG_KERNEL) {
845 zlog_debug(
846 "%s: %s ACK: type=%s(%u), seq=%u, pid=%u",
847 __FUNCTION__, nl->name,
848 nl_msg_type_to_str(
849 err->msg.nlmsg_type),
850 err->msg.nlmsg_type,
851 err->msg.nlmsg_seq,
852 err->msg.nlmsg_pid);
853 }
854
855 /* return if not a multipart message,
856 * otherwise continue */
857 if (!(h->nlmsg_flags & NLM_F_MULTI))
858 return 0;
859 continue;
860 }
861
862 /* Deal with errors that occur because of races
863 * in link handling */
864 if (zns->is_cmd
865 && ((msg_type == RTM_DELROUTE
866 && (-errnum == ENODEV
867 || -errnum == ESRCH))
868 || (msg_type == RTM_NEWROUTE
869 && (-errnum == ENETDOWN
870 || -errnum == EEXIST)))) {
871 if (IS_ZEBRA_DEBUG_KERNEL)
872 zlog_debug(
873 "%s: error: %s type=%s(%u), seq=%u, pid=%u",
874 nl->name,
875 safe_strerror(-errnum),
876 nl_msg_type_to_str(
877 msg_type),
878 msg_type,
879 err->msg.nlmsg_seq,
880 err->msg.nlmsg_pid);
881 return 0;
882 }
883
884 /* We see RTM_DELNEIGH when shutting down an
885 * interface with an IPv4
886 * link-local. The kernel should have already
887 * deleted the neighbor
888 * so do not log these as an error.
889 */
890 if (msg_type == RTM_DELNEIGH
891 || (zns->is_cmd && msg_type == RTM_NEWROUTE
892 && (-errnum == ESRCH
893 || -errnum == ENETUNREACH))) {
894 /* This is known to happen in some
895 * situations, don't log
896 * as error.
897 */
898 if (IS_ZEBRA_DEBUG_KERNEL)
899 zlog_debug(
900 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
901 nl->name,
902 safe_strerror(-errnum),
903 nl_msg_type_to_str(
904 msg_type),
905 msg_type,
906 err->msg.nlmsg_seq,
907 err->msg.nlmsg_pid);
908 } else {
909 if ((msg_type != RTM_GETNEXTHOP)
910 || !startup)
911 flog_err(
912 EC_ZEBRA_UNEXPECTED_MESSAGE,
913 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
914 nl->name,
915 safe_strerror(-errnum),
916 nl_msg_type_to_str(
917 msg_type),
918 msg_type,
919 err->msg.nlmsg_seq,
920 err->msg.nlmsg_pid);
921 }
922
923 return -1;
924 }
925
926 /* OK we got netlink message. */
927 if (IS_ZEBRA_DEBUG_KERNEL)
928 zlog_debug(
929 "netlink_parse_info: %s type %s(%u), len=%d, seq=%u, pid=%u",
930 nl->name,
931 nl_msg_type_to_str(h->nlmsg_type),
932 h->nlmsg_type, h->nlmsg_len,
933 h->nlmsg_seq, h->nlmsg_pid);
934
935
936 /*
937 * Ignore messages that maybe sent from
938 * other actors besides the kernel
939 */
940 if (snl.nl_pid != 0) {
941 zlog_debug("Ignoring message from pid %u",
942 snl.nl_pid);
943 continue;
944 }
945
946 error = (*filter)(h, zns->ns_id, startup);
947 if (error < 0) {
948 zlog_debug("%s filter function error",
949 nl->name);
950 ret = error;
951 }
952 }
953
954 /* After error care. */
955 if (msg.msg_flags & MSG_TRUNC) {
956 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
957 "%s error: message truncated", nl->name);
958 continue;
959 }
960 if (status) {
961 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
962 "%s error: data remnant size %d", nl->name,
963 status);
964 return -1;
965 }
966 }
967 return ret;
968 }
969
970 /*
971 * netlink_talk_info
972 *
973 * sendmsg() to netlink socket then recvmsg().
974 * Calls netlink_parse_info to parse returned data
975 *
976 * filter -> The filter to read final results from kernel
977 * nlmsghdr -> The data to send to the kernel
978 * dp_info -> The dataplane and netlink socket information
979 * startup -> Are we reading in under startup conditions
980 * This is passed through eventually to filter.
981 */
982 int netlink_talk_info(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
983 struct nlmsghdr *n,
984 const struct zebra_dplane_info *dp_info, int startup)
985 {
986 int status = 0;
987 struct sockaddr_nl snl;
988 struct iovec iov;
989 struct msghdr msg;
990 int save_errno = 0;
991 const struct nlsock *nl;
992
993 memset(&snl, 0, sizeof snl);
994 memset(&iov, 0, sizeof iov);
995 memset(&msg, 0, sizeof msg);
996
997 iov.iov_base = n;
998 iov.iov_len = n->nlmsg_len;
999 msg.msg_name = (void *)&snl;
1000 msg.msg_namelen = sizeof snl;
1001 msg.msg_iov = &iov;
1002 msg.msg_iovlen = 1;
1003
1004 snl.nl_family = AF_NETLINK;
1005
1006 nl = &(dp_info->nls);
1007 n->nlmsg_seq = nl->seq;
1008 n->nlmsg_pid = nl->snl.nl_pid;
1009
1010 if (IS_ZEBRA_DEBUG_KERNEL)
1011 zlog_debug(
1012 "netlink_talk: %s type %s(%u), len=%d seq=%u flags 0x%x",
1013 nl->name, nl_msg_type_to_str(n->nlmsg_type),
1014 n->nlmsg_type, n->nlmsg_len, n->nlmsg_seq,
1015 n->nlmsg_flags);
1016
1017 /* Send message to netlink interface. */
1018 frr_with_privs(&zserv_privs) {
1019 status = sendmsg(nl->sock, &msg, 0);
1020 save_errno = errno;
1021 }
1022
1023 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_SEND) {
1024 zlog_debug("%s: >> netlink message dump [sent]", __func__);
1025 zlog_hexdump(n, n->nlmsg_len);
1026 }
1027
1028 if (status < 0) {
1029 flog_err_sys(EC_LIB_SOCKET, "netlink_talk sendmsg() error: %s",
1030 safe_strerror(save_errno));
1031 return -1;
1032 }
1033
1034 /*
1035 * Get reply from netlink socket.
1036 * The reply should either be an acknowlegement or an error.
1037 */
1038 return netlink_parse_info(filter, nl, dp_info, 0, startup);
1039 }
1040
1041 /*
1042 * Synchronous version of netlink_talk_info. Converts args to suit the
1043 * common version, which is suitable for both sync and async use.
1044 */
1045 int netlink_talk(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
1046 struct nlmsghdr *n, struct nlsock *nl, struct zebra_ns *zns,
1047 int startup)
1048 {
1049 struct zebra_dplane_info dp_info;
1050
1051 /* Increment sequence number before capturing snapshot of ns socket
1052 * info.
1053 */
1054 nl->seq++;
1055
1056 /* Capture info in intermediate info struct */
1057 zebra_dplane_info_from_zns(&dp_info, zns, (nl == &(zns->netlink_cmd)));
1058
1059 return netlink_talk_info(filter, n, &dp_info, startup);
1060 }
1061
1062 /* Issue request message to kernel via netlink socket. GET messages
1063 * are issued through this interface.
1064 */
1065 int netlink_request(struct nlsock *nl, struct nlmsghdr *n)
1066 {
1067 int ret;
1068 struct sockaddr_nl snl;
1069
1070 /* Check netlink socket. */
1071 if (nl->sock < 0) {
1072 flog_err_sys(EC_LIB_SOCKET, "%s socket isn't active.",
1073 nl->name);
1074 return -1;
1075 }
1076
1077 /* Fill common fields for all requests. */
1078 n->nlmsg_pid = nl->snl.nl_pid;
1079 n->nlmsg_seq = ++nl->seq;
1080
1081 memset(&snl, 0, sizeof snl);
1082 snl.nl_family = AF_NETLINK;
1083
1084 /* Raise capabilities and send message, then lower capabilities. */
1085 frr_with_privs(&zserv_privs) {
1086 ret = sendto(nl->sock, (void *)n, n->nlmsg_len, 0,
1087 (struct sockaddr *)&snl, sizeof snl);
1088 }
1089
1090 if (ret < 0) {
1091 zlog_err("%s sendto failed: %s", nl->name,
1092 safe_strerror(errno));
1093 return -1;
1094 }
1095
1096 return 0;
1097 }
1098
1099 /* Exported interface function. This function simply calls
1100 netlink_socket (). */
1101 void kernel_init(struct zebra_ns *zns)
1102 {
1103 uint32_t groups;
1104 #if defined SOL_NETLINK
1105 int one, ret;
1106 #endif
1107
1108 /*
1109 * Initialize netlink sockets
1110 *
1111 * If RTMGRP_XXX exists use that, but at some point
1112 * I think the kernel developers realized that
1113 * keeping track of all the different values would
1114 * lead to confusion, so we need to convert the
1115 * RTNLGRP_XXX to a bit position for ourself
1116 */
1117 groups = RTMGRP_LINK |
1118 RTMGRP_IPV4_ROUTE |
1119 RTMGRP_IPV4_IFADDR |
1120 RTMGRP_IPV6_ROUTE |
1121 RTMGRP_IPV6_IFADDR |
1122 RTMGRP_IPV4_MROUTE |
1123 RTMGRP_NEIGH |
1124 ((uint32_t) 1 << (RTNLGRP_IPV4_RULE - 1)) |
1125 ((uint32_t) 1 << (RTNLGRP_IPV6_RULE - 1)) |
1126 ((uint32_t) 1 << (RTNLGRP_NEXTHOP - 1));
1127
1128 snprintf(zns->netlink.name, sizeof(zns->netlink.name),
1129 "netlink-listen (NS %u)", zns->ns_id);
1130 zns->netlink.sock = -1;
1131 if (netlink_socket(&zns->netlink, groups, zns->ns_id) < 0) {
1132 zlog_err("Failure to create %s socket",
1133 zns->netlink.name);
1134 exit(-1);
1135 }
1136
1137 snprintf(zns->netlink_cmd.name, sizeof(zns->netlink_cmd.name),
1138 "netlink-cmd (NS %u)", zns->ns_id);
1139 zns->netlink_cmd.sock = -1;
1140 if (netlink_socket(&zns->netlink_cmd, 0, zns->ns_id) < 0) {
1141 zlog_err("Failure to create %s socket",
1142 zns->netlink_cmd.name);
1143 exit(-1);
1144 }
1145
1146 snprintf(zns->netlink_dplane.name, sizeof(zns->netlink_dplane.name),
1147 "netlink-dp (NS %u)", zns->ns_id);
1148 zns->netlink_dplane.sock = -1;
1149 if (netlink_socket(&zns->netlink_dplane, 0, zns->ns_id) < 0) {
1150 zlog_err("Failure to create %s socket",
1151 zns->netlink_dplane.name);
1152 exit(-1);
1153 }
1154
1155 /*
1156 * SOL_NETLINK is not available on all platforms yet
1157 * apparently. It's in bits/socket.h which I am not
1158 * sure that we want to pull into our build system.
1159 */
1160 #if defined SOL_NETLINK
1161 /*
1162 * Let's tell the kernel that we want to receive extended
1163 * ACKS over our command socket(s)
1164 */
1165 one = 1;
1166 ret = setsockopt(zns->netlink_cmd.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1167 &one, sizeof(one));
1168
1169 if (ret < 0)
1170 zlog_notice("Registration for extended cmd ACK failed : %d %s",
1171 errno, safe_strerror(errno));
1172
1173 one = 1;
1174 ret = setsockopt(zns->netlink_dplane.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1175 &one, sizeof(one));
1176
1177 if (ret < 0)
1178 zlog_notice("Registration for extended dp ACK failed : %d %s",
1179 errno, safe_strerror(errno));
1180 #endif
1181
1182 /* Register kernel socket. */
1183 if (fcntl(zns->netlink.sock, F_SETFL, O_NONBLOCK) < 0)
1184 flog_err_sys(EC_LIB_SOCKET, "Can't set %s socket flags: %s",
1185 zns->netlink.name, safe_strerror(errno));
1186
1187 if (fcntl(zns->netlink_cmd.sock, F_SETFL, O_NONBLOCK) < 0)
1188 zlog_err("Can't set %s socket error: %s(%d)",
1189 zns->netlink_cmd.name, safe_strerror(errno), errno);
1190
1191 if (fcntl(zns->netlink_dplane.sock, F_SETFL, O_NONBLOCK) < 0)
1192 zlog_err("Can't set %s socket error: %s(%d)",
1193 zns->netlink_dplane.name, safe_strerror(errno), errno);
1194
1195 /* Set receive buffer size if it's set from command line */
1196 if (nl_rcvbufsize)
1197 netlink_recvbuf(&zns->netlink, nl_rcvbufsize);
1198
1199 netlink_install_filter(zns->netlink.sock,
1200 zns->netlink_cmd.snl.nl_pid,
1201 zns->netlink_dplane.snl.nl_pid);
1202
1203 zns->t_netlink = NULL;
1204
1205 thread_add_read(zrouter.master, kernel_read, zns,
1206 zns->netlink.sock, &zns->t_netlink);
1207
1208 rt_netlink_init();
1209 }
1210
1211 void kernel_terminate(struct zebra_ns *zns, bool complete)
1212 {
1213 THREAD_READ_OFF(zns->t_netlink);
1214
1215 if (zns->netlink.sock >= 0) {
1216 close(zns->netlink.sock);
1217 zns->netlink.sock = -1;
1218 }
1219
1220 if (zns->netlink_cmd.sock >= 0) {
1221 close(zns->netlink_cmd.sock);
1222 zns->netlink_cmd.sock = -1;
1223 }
1224
1225 /* During zebra shutdown, we need to leave the dataplane socket
1226 * around until all work is done.
1227 */
1228 if (complete) {
1229 if (zns->netlink_dplane.sock >= 0) {
1230 close(zns->netlink_dplane.sock);
1231 zns->netlink_dplane.sock = -1;
1232 }
1233 }
1234 }
1235 #endif /* HAVE_NETLINK */