]> git.proxmox.com Git - mirror_frr.git/blob - zebra/kernel_netlink.c
Merge pull request #6033 from rubenk/lib-do-not-use-aliased-inet-ntop-on-apple
[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", __func__,
701 nl_msg_type_to_str(err_nlh->nlmsg_type));
702 }
703 }
704
705 if (msg && *msg != '\0') {
706 bool is_err = !!err->error;
707
708 if (is_err)
709 zlog_err("Extended Error: %s", msg);
710 else
711 flog_warn(EC_ZEBRA_NETLINK_EXTENDED_WARNING,
712 "Extended Warning: %s", msg);
713 }
714 }
715
716 /*
717 * netlink_parse_info
718 *
719 * Receive message from netlink interface and pass those information
720 * to the given function.
721 *
722 * filter -> Function to call to read the results
723 * nl -> netlink socket information
724 * zns -> The zebra namespace data
725 * count -> How many we should read in, 0 means as much as possible
726 * startup -> Are we reading in under startup conditions? passed to
727 * the filter.
728 */
729 int netlink_parse_info(int (*filter)(struct nlmsghdr *, ns_id_t, int),
730 const struct nlsock *nl,
731 const struct zebra_dplane_info *zns,
732 int count, int startup)
733 {
734 int status;
735 int ret = 0;
736 int error;
737 int read_in = 0;
738
739 while (1) {
740 char buf[NL_RCV_PKT_BUF_SIZE];
741 struct iovec iov = {.iov_base = buf, .iov_len = sizeof(buf)};
742 struct sockaddr_nl snl;
743 struct msghdr msg = {.msg_name = (void *)&snl,
744 .msg_namelen = sizeof(snl),
745 .msg_iov = &iov,
746 .msg_iovlen = 1};
747 struct nlmsghdr *h;
748
749 if (count && read_in >= count)
750 return 0;
751
752 #if defined(HANDLE_NETLINK_FUZZING)
753 /* Check if reading and filename is set */
754 if (netlink_read && '\0' != netlink_fuzz_file[0]) {
755 zlog_debug("Reading netlink fuzz file");
756 status = netlink_read_file(buf, netlink_fuzz_file);
757 snl.nl_pid = 0;
758 } else {
759 status = recvmsg(nl->sock, &msg, 0);
760 }
761 #else
762 status = recvmsg(nl->sock, &msg, 0);
763 #endif /* HANDLE_NETLINK_FUZZING */
764 if (status < 0) {
765 if (errno == EINTR)
766 continue;
767 if (errno == EWOULDBLOCK || errno == EAGAIN)
768 break;
769 flog_err(EC_ZEBRA_RECVMSG_OVERRUN,
770 "%s recvmsg overrun: %s", nl->name,
771 safe_strerror(errno));
772 /*
773 * In this case we are screwed.
774 * There is no good way to
775 * recover zebra at this point.
776 */
777 exit(-1);
778 continue;
779 }
780
781 if (status == 0) {
782 flog_err_sys(EC_LIB_SOCKET, "%s EOF", nl->name);
783 return -1;
784 }
785
786 if (msg.msg_namelen != sizeof(snl)) {
787 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
788 "%s sender address length error: length %d",
789 nl->name, msg.msg_namelen);
790 return -1;
791 }
792
793 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_RECV) {
794 zlog_debug("%s: << netlink message dump [recv]",
795 __func__);
796 zlog_hexdump(buf, status);
797 }
798
799 #if defined(HANDLE_NETLINK_FUZZING)
800 if (!netlink_read) {
801 zlog_debug("Writing incoming netlink message");
802 netlink_write_incoming(buf, status,
803 netlink_file_counter++);
804 }
805 #endif /* HANDLE_NETLINK_FUZZING */
806
807 read_in++;
808 for (h = (struct nlmsghdr *)buf;
809 (status >= 0 && NLMSG_OK(h, (unsigned int)status));
810 h = NLMSG_NEXT(h, status)) {
811 /* Finish of reading. */
812 if (h->nlmsg_type == NLMSG_DONE)
813 return ret;
814
815 /* Error handling. */
816 if (h->nlmsg_type == NLMSG_ERROR) {
817 struct nlmsgerr *err =
818 (struct nlmsgerr *)NLMSG_DATA(h);
819 int errnum = err->error;
820 int msg_type = err->msg.nlmsg_type;
821
822 if (h->nlmsg_len
823 < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
824 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
825 "%s error: message truncated",
826 nl->name);
827 return -1;
828 }
829
830 /*
831 * Parse the extended information before
832 * we actually handle it.
833 * At this point in time we do not
834 * do anything other than report the
835 * issue.
836 */
837 if (h->nlmsg_flags & NLM_F_ACK_TLVS)
838 netlink_parse_extended_ack(h);
839
840 /* If the error field is zero, then this is an
841 * ACK */
842 if (err->error == 0) {
843 if (IS_ZEBRA_DEBUG_KERNEL) {
844 zlog_debug(
845 "%s: %s ACK: type=%s(%u), seq=%u, pid=%u",
846 __func__, nl->name,
847 nl_msg_type_to_str(
848 err->msg.nlmsg_type),
849 err->msg.nlmsg_type,
850 err->msg.nlmsg_seq,
851 err->msg.nlmsg_pid);
852 }
853
854 /* return if not a multipart message,
855 * otherwise continue */
856 if (!(h->nlmsg_flags & NLM_F_MULTI))
857 return 0;
858 continue;
859 }
860
861 /* Deal with errors that occur because of races
862 * in link handling */
863 if (zns->is_cmd
864 && ((msg_type == RTM_DELROUTE
865 && (-errnum == ENODEV
866 || -errnum == ESRCH))
867 || (msg_type == RTM_NEWROUTE
868 && (-errnum == ENETDOWN
869 || -errnum == EEXIST)))) {
870 if (IS_ZEBRA_DEBUG_KERNEL)
871 zlog_debug(
872 "%s: error: %s type=%s(%u), seq=%u, pid=%u",
873 nl->name,
874 safe_strerror(-errnum),
875 nl_msg_type_to_str(
876 msg_type),
877 msg_type,
878 err->msg.nlmsg_seq,
879 err->msg.nlmsg_pid);
880 return 0;
881 }
882
883 /* We see RTM_DELNEIGH when shutting down an
884 * interface with an IPv4
885 * link-local. The kernel should have already
886 * deleted the neighbor
887 * so do not log these as an error.
888 */
889 if (msg_type == RTM_DELNEIGH
890 || (zns->is_cmd && msg_type == RTM_NEWROUTE
891 && (-errnum == ESRCH
892 || -errnum == ENETUNREACH))) {
893 /* This is known to happen in some
894 * situations, don't log
895 * as error.
896 */
897 if (IS_ZEBRA_DEBUG_KERNEL)
898 zlog_debug(
899 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
900 nl->name,
901 safe_strerror(-errnum),
902 nl_msg_type_to_str(
903 msg_type),
904 msg_type,
905 err->msg.nlmsg_seq,
906 err->msg.nlmsg_pid);
907 } else {
908 if ((msg_type != RTM_GETNEXTHOP)
909 || !startup)
910 flog_err(
911 EC_ZEBRA_UNEXPECTED_MESSAGE,
912 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
913 nl->name,
914 safe_strerror(-errnum),
915 nl_msg_type_to_str(
916 msg_type),
917 msg_type,
918 err->msg.nlmsg_seq,
919 err->msg.nlmsg_pid);
920 }
921
922 return -1;
923 }
924
925 /* OK we got netlink message. */
926 if (IS_ZEBRA_DEBUG_KERNEL)
927 zlog_debug(
928 "netlink_parse_info: %s type %s(%u), len=%d, seq=%u, pid=%u",
929 nl->name,
930 nl_msg_type_to_str(h->nlmsg_type),
931 h->nlmsg_type, h->nlmsg_len,
932 h->nlmsg_seq, h->nlmsg_pid);
933
934
935 /*
936 * Ignore messages that maybe sent from
937 * other actors besides the kernel
938 */
939 if (snl.nl_pid != 0) {
940 zlog_debug("Ignoring message from pid %u",
941 snl.nl_pid);
942 continue;
943 }
944
945 error = (*filter)(h, zns->ns_id, startup);
946 if (error < 0) {
947 zlog_debug("%s filter function error",
948 nl->name);
949 ret = error;
950 }
951 }
952
953 /* After error care. */
954 if (msg.msg_flags & MSG_TRUNC) {
955 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
956 "%s error: message truncated", nl->name);
957 continue;
958 }
959 if (status) {
960 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
961 "%s error: data remnant size %d", nl->name,
962 status);
963 return -1;
964 }
965 }
966 return ret;
967 }
968
969 /*
970 * netlink_talk_info
971 *
972 * sendmsg() to netlink socket then recvmsg().
973 * Calls netlink_parse_info to parse returned data
974 *
975 * filter -> The filter to read final results from kernel
976 * nlmsghdr -> The data to send to the kernel
977 * dp_info -> The dataplane and netlink socket information
978 * startup -> Are we reading in under startup conditions
979 * This is passed through eventually to filter.
980 */
981 int netlink_talk_info(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
982 struct nlmsghdr *n,
983 const struct zebra_dplane_info *dp_info, int startup)
984 {
985 int status = 0;
986 struct sockaddr_nl snl;
987 struct iovec iov;
988 struct msghdr msg;
989 int save_errno = 0;
990 const struct nlsock *nl;
991
992 memset(&snl, 0, sizeof(snl));
993 memset(&iov, 0, sizeof(iov));
994 memset(&msg, 0, sizeof(msg));
995
996 iov.iov_base = n;
997 iov.iov_len = n->nlmsg_len;
998 msg.msg_name = (void *)&snl;
999 msg.msg_namelen = sizeof(snl);
1000 msg.msg_iov = &iov;
1001 msg.msg_iovlen = 1;
1002
1003 snl.nl_family = AF_NETLINK;
1004
1005 nl = &(dp_info->nls);
1006 n->nlmsg_seq = nl->seq;
1007 n->nlmsg_pid = nl->snl.nl_pid;
1008
1009 if (IS_ZEBRA_DEBUG_KERNEL)
1010 zlog_debug(
1011 "netlink_talk: %s type %s(%u), len=%d seq=%u flags 0x%x",
1012 nl->name, nl_msg_type_to_str(n->nlmsg_type),
1013 n->nlmsg_type, n->nlmsg_len, n->nlmsg_seq,
1014 n->nlmsg_flags);
1015
1016 /* Send message to netlink interface. */
1017 frr_with_privs(&zserv_privs) {
1018 status = sendmsg(nl->sock, &msg, 0);
1019 save_errno = errno;
1020 }
1021
1022 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_SEND) {
1023 zlog_debug("%s: >> netlink message dump [sent]", __func__);
1024 zlog_hexdump(n, n->nlmsg_len);
1025 }
1026
1027 if (status < 0) {
1028 flog_err_sys(EC_LIB_SOCKET, "netlink_talk sendmsg() error: %s",
1029 safe_strerror(save_errno));
1030 return -1;
1031 }
1032
1033 /*
1034 * Get reply from netlink socket.
1035 * The reply should either be an acknowlegement or an error.
1036 */
1037 return netlink_parse_info(filter, nl, dp_info, 0, startup);
1038 }
1039
1040 /*
1041 * Synchronous version of netlink_talk_info. Converts args to suit the
1042 * common version, which is suitable for both sync and async use.
1043 */
1044 int netlink_talk(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
1045 struct nlmsghdr *n, struct nlsock *nl, struct zebra_ns *zns,
1046 int startup)
1047 {
1048 struct zebra_dplane_info dp_info;
1049
1050 /* Increment sequence number before capturing snapshot of ns socket
1051 * info.
1052 */
1053 nl->seq++;
1054
1055 /* Capture info in intermediate info struct */
1056 zebra_dplane_info_from_zns(&dp_info, zns, (nl == &(zns->netlink_cmd)));
1057
1058 return netlink_talk_info(filter, n, &dp_info, startup);
1059 }
1060
1061 /* Issue request message to kernel via netlink socket. GET messages
1062 * are issued through this interface.
1063 */
1064 int netlink_request(struct nlsock *nl, struct nlmsghdr *n)
1065 {
1066 int ret;
1067 struct sockaddr_nl snl;
1068
1069 /* Check netlink socket. */
1070 if (nl->sock < 0) {
1071 flog_err_sys(EC_LIB_SOCKET, "%s socket isn't active.",
1072 nl->name);
1073 return -1;
1074 }
1075
1076 /* Fill common fields for all requests. */
1077 n->nlmsg_pid = nl->snl.nl_pid;
1078 n->nlmsg_seq = ++nl->seq;
1079
1080 memset(&snl, 0, sizeof(snl));
1081 snl.nl_family = AF_NETLINK;
1082
1083 /* Raise capabilities and send message, then lower capabilities. */
1084 frr_with_privs(&zserv_privs) {
1085 ret = sendto(nl->sock, (void *)n, n->nlmsg_len, 0,
1086 (struct sockaddr *)&snl, sizeof(snl));
1087 }
1088
1089 if (ret < 0) {
1090 zlog_err("%s sendto failed: %s", nl->name,
1091 safe_strerror(errno));
1092 return -1;
1093 }
1094
1095 return 0;
1096 }
1097
1098 /* Exported interface function. This function simply calls
1099 netlink_socket (). */
1100 void kernel_init(struct zebra_ns *zns)
1101 {
1102 uint32_t groups;
1103 #if defined SOL_NETLINK
1104 int one, ret;
1105 #endif
1106
1107 /*
1108 * Initialize netlink sockets
1109 *
1110 * If RTMGRP_XXX exists use that, but at some point
1111 * I think the kernel developers realized that
1112 * keeping track of all the different values would
1113 * lead to confusion, so we need to convert the
1114 * RTNLGRP_XXX to a bit position for ourself
1115 */
1116 groups = RTMGRP_LINK |
1117 RTMGRP_IPV4_ROUTE |
1118 RTMGRP_IPV4_IFADDR |
1119 RTMGRP_IPV6_ROUTE |
1120 RTMGRP_IPV6_IFADDR |
1121 RTMGRP_IPV4_MROUTE |
1122 RTMGRP_NEIGH |
1123 ((uint32_t) 1 << (RTNLGRP_IPV4_RULE - 1)) |
1124 ((uint32_t) 1 << (RTNLGRP_IPV6_RULE - 1)) |
1125 ((uint32_t) 1 << (RTNLGRP_NEXTHOP - 1));
1126
1127 snprintf(zns->netlink.name, sizeof(zns->netlink.name),
1128 "netlink-listen (NS %u)", zns->ns_id);
1129 zns->netlink.sock = -1;
1130 if (netlink_socket(&zns->netlink, groups, zns->ns_id) < 0) {
1131 zlog_err("Failure to create %s socket",
1132 zns->netlink.name);
1133 exit(-1);
1134 }
1135
1136 snprintf(zns->netlink_cmd.name, sizeof(zns->netlink_cmd.name),
1137 "netlink-cmd (NS %u)", zns->ns_id);
1138 zns->netlink_cmd.sock = -1;
1139 if (netlink_socket(&zns->netlink_cmd, 0, zns->ns_id) < 0) {
1140 zlog_err("Failure to create %s socket",
1141 zns->netlink_cmd.name);
1142 exit(-1);
1143 }
1144
1145 snprintf(zns->netlink_dplane.name, sizeof(zns->netlink_dplane.name),
1146 "netlink-dp (NS %u)", zns->ns_id);
1147 zns->netlink_dplane.sock = -1;
1148 if (netlink_socket(&zns->netlink_dplane, 0, zns->ns_id) < 0) {
1149 zlog_err("Failure to create %s socket",
1150 zns->netlink_dplane.name);
1151 exit(-1);
1152 }
1153
1154 /*
1155 * SOL_NETLINK is not available on all platforms yet
1156 * apparently. It's in bits/socket.h which I am not
1157 * sure that we want to pull into our build system.
1158 */
1159 #if defined SOL_NETLINK
1160 /*
1161 * Let's tell the kernel that we want to receive extended
1162 * ACKS over our command socket(s)
1163 */
1164 one = 1;
1165 ret = setsockopt(zns->netlink_cmd.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1166 &one, sizeof(one));
1167
1168 if (ret < 0)
1169 zlog_notice("Registration for extended cmd ACK failed : %d %s",
1170 errno, safe_strerror(errno));
1171
1172 one = 1;
1173 ret = setsockopt(zns->netlink_dplane.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1174 &one, sizeof(one));
1175
1176 if (ret < 0)
1177 zlog_notice("Registration for extended dp ACK failed : %d %s",
1178 errno, safe_strerror(errno));
1179 #endif
1180
1181 /* Register kernel socket. */
1182 if (fcntl(zns->netlink.sock, F_SETFL, O_NONBLOCK) < 0)
1183 flog_err_sys(EC_LIB_SOCKET, "Can't set %s socket flags: %s",
1184 zns->netlink.name, safe_strerror(errno));
1185
1186 if (fcntl(zns->netlink_cmd.sock, F_SETFL, O_NONBLOCK) < 0)
1187 zlog_err("Can't set %s socket error: %s(%d)",
1188 zns->netlink_cmd.name, safe_strerror(errno), errno);
1189
1190 if (fcntl(zns->netlink_dplane.sock, F_SETFL, O_NONBLOCK) < 0)
1191 zlog_err("Can't set %s socket error: %s(%d)",
1192 zns->netlink_dplane.name, safe_strerror(errno), errno);
1193
1194 /* Set receive buffer size if it's set from command line */
1195 if (nl_rcvbufsize)
1196 netlink_recvbuf(&zns->netlink, nl_rcvbufsize);
1197
1198 netlink_install_filter(zns->netlink.sock,
1199 zns->netlink_cmd.snl.nl_pid,
1200 zns->netlink_dplane.snl.nl_pid);
1201
1202 zns->t_netlink = NULL;
1203
1204 thread_add_read(zrouter.master, kernel_read, zns,
1205 zns->netlink.sock, &zns->t_netlink);
1206
1207 rt_netlink_init();
1208 }
1209
1210 void kernel_terminate(struct zebra_ns *zns, bool complete)
1211 {
1212 THREAD_READ_OFF(zns->t_netlink);
1213
1214 if (zns->netlink.sock >= 0) {
1215 close(zns->netlink.sock);
1216 zns->netlink.sock = -1;
1217 }
1218
1219 if (zns->netlink_cmd.sock >= 0) {
1220 close(zns->netlink_cmd.sock);
1221 zns->netlink_cmd.sock = -1;
1222 }
1223
1224 /* During zebra shutdown, we need to leave the dataplane socket
1225 * around until all work is done.
1226 */
1227 if (complete) {
1228 if (zns->netlink_dplane.sock >= 0) {
1229 close(zns->netlink_dplane.sock);
1230 zns->netlink_dplane.sock = -1;
1231 }
1232 }
1233 }
1234 #endif /* HAVE_NETLINK */