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