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