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