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