]> git.proxmox.com Git - mirror_frr.git/blob - zebra/kernel_netlink.c
*: style for EC replacements
[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(EC_LIB_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(EC_LIB_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(EC_LIB_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(EC_LIB_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(EC_ZEBRA_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(EC_LIB_SOCKET, "Can't install socket filter: %s\n",
457 safe_strerror(errno));
458 }
459
460 void netlink_parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta,
461 int len)
462 {
463 while (RTA_OK(rta, len)) {
464 if (rta->rta_type <= max)
465 tb[rta->rta_type] = rta;
466 rta = RTA_NEXT(rta, len);
467 }
468 }
469
470 /**
471 * netlink_parse_rtattr_nested() - Parses a nested route attribute
472 * @tb: Pointer to array for storing rtattr in.
473 * @max: Max number to store.
474 * @rta: Pointer to rtattr to look for nested items in.
475 */
476 void netlink_parse_rtattr_nested(struct rtattr **tb, int max,
477 struct rtattr *rta)
478 {
479 netlink_parse_rtattr(tb, max, RTA_DATA(rta), RTA_PAYLOAD(rta));
480 }
481
482 int addattr_l(struct nlmsghdr *n, unsigned int maxlen, int type,
483 const void *data, unsigned int alen)
484 {
485 int len;
486 struct rtattr *rta;
487
488 len = RTA_LENGTH(alen);
489
490 if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen)
491 return -1;
492
493 rta = (struct rtattr *)(((char *)n) + NLMSG_ALIGN(n->nlmsg_len));
494 rta->rta_type = type;
495 rta->rta_len = len;
496
497 if (data)
498 memcpy(RTA_DATA(rta), data, alen);
499 else
500 assert(alen == 0);
501
502 n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len);
503
504 return 0;
505 }
506
507 int rta_addattr_l(struct rtattr *rta, unsigned int maxlen, int type,
508 const void *data, unsigned int alen)
509 {
510 unsigned int len;
511 struct rtattr *subrta;
512
513 len = RTA_LENGTH(alen);
514
515 if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen)
516 return -1;
517
518 subrta = (struct rtattr *)(((char *)rta) + RTA_ALIGN(rta->rta_len));
519 subrta->rta_type = type;
520 subrta->rta_len = len;
521
522 if (data)
523 memcpy(RTA_DATA(subrta), data, alen);
524 else
525 assert(alen == 0);
526
527 rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len);
528
529 return 0;
530 }
531
532 int addattr16(struct nlmsghdr *n, unsigned int maxlen, int type, uint16_t data)
533 {
534 return addattr_l(n, maxlen, type, &data, sizeof(uint16_t));
535 }
536
537 int addattr32(struct nlmsghdr *n, unsigned int maxlen, int type, int data)
538 {
539 return addattr_l(n, maxlen, type, &data, sizeof(uint32_t));
540 }
541
542 struct rtattr *addattr_nest(struct nlmsghdr *n, int maxlen, int type)
543 {
544 struct rtattr *nest = NLMSG_TAIL(n);
545
546 addattr_l(n, maxlen, type, NULL, 0);
547 return nest;
548 }
549
550 int addattr_nest_end(struct nlmsghdr *n, struct rtattr *nest)
551 {
552 nest->rta_len = (uint8_t *)NLMSG_TAIL(n) - (uint8_t *)nest;
553 return n->nlmsg_len;
554 }
555
556 struct rtattr *rta_nest(struct rtattr *rta, int maxlen, int type)
557 {
558 struct rtattr *nest = RTA_TAIL(rta);
559
560 rta_addattr_l(rta, maxlen, type, NULL, 0);
561 return nest;
562 }
563
564 int rta_nest_end(struct rtattr *rta, struct rtattr *nest)
565 {
566 nest->rta_len = (uint8_t *)RTA_TAIL(rta) - (uint8_t *)nest;
567 return rta->rta_len;
568 }
569
570 const char *nl_msg_type_to_str(uint16_t msg_type)
571 {
572 return lookup_msg(nlmsg_str, msg_type, "");
573 }
574
575 const char *nl_rtproto_to_str(uint8_t rtproto)
576 {
577 return lookup_msg(rtproto_str, rtproto, "");
578 }
579
580 const char *nl_family_to_str(uint8_t family)
581 {
582 return lookup_msg(family_str, family, "");
583 }
584
585 const char *nl_rttype_to_str(uint8_t rttype)
586 {
587 return lookup_msg(rttype_str, rttype, "");
588 }
589
590 #define NL_OK(nla, len) \
591 ((len) >= (int)sizeof(struct nlattr) \
592 && (nla)->nla_len >= sizeof(struct nlattr) \
593 && (nla)->nla_len <= (len))
594 #define NL_NEXT(nla, attrlen) \
595 ((attrlen) -= RTA_ALIGN((nla)->nla_len), \
596 (struct nlattr *)(((char *)(nla)) + RTA_ALIGN((nla)->nla_len)))
597 #define NL_RTA(r) \
598 ((struct nlattr *)(((char *)(r)) \
599 + NLMSG_ALIGN(sizeof(struct nlmsgerr))))
600
601 static void netlink_parse_nlattr(struct nlattr **tb, int max,
602 struct nlattr *nla, int len)
603 {
604 while (NL_OK(nla, len)) {
605 if (nla->nla_type <= max)
606 tb[nla->nla_type] = nla;
607 nla = NL_NEXT(nla, len);
608 }
609 }
610
611 static void netlink_parse_extended_ack(struct nlmsghdr *h)
612 {
613 struct nlattr *tb[NLMSGERR_ATTR_MAX + 1];
614 const struct nlmsgerr *err =
615 (const struct nlmsgerr *)((uint8_t *)h
616 + NLMSG_ALIGN(
617 sizeof(struct nlmsghdr)));
618 const struct nlmsghdr *err_nlh = NULL;
619 uint32_t hlen = sizeof(*err);
620 const char *msg = NULL;
621 uint32_t off = 0;
622
623 if (!(h->nlmsg_flags & NLM_F_CAPPED))
624 hlen += h->nlmsg_len - NLMSG_ALIGN(sizeof(struct nlmsghdr));
625
626 memset(tb, 0, sizeof(tb));
627 netlink_parse_nlattr(tb, NLMSGERR_ATTR_MAX, NL_RTA(h), hlen);
628
629 if (tb[NLMSGERR_ATTR_MSG])
630 msg = (const char *)RTA_DATA(tb[NLMSGERR_ATTR_MSG]);
631
632 if (tb[NLMSGERR_ATTR_OFFS]) {
633 off = *(uint32_t *)RTA_DATA(tb[NLMSGERR_ATTR_OFFS]);
634
635 if (off > h->nlmsg_len) {
636 zlog_err("Invalid offset for NLMSGERR_ATTR_OFFS\n");
637 } else if (!(h->nlmsg_flags & NLM_F_CAPPED)) {
638 /*
639 * Header of failed message
640 * we are not doing anything currently with it
641 * but noticing it for later.
642 */
643 err_nlh = &err->msg;
644 zlog_debug("%s: Received %d extended Ack",
645 __PRETTY_FUNCTION__, err_nlh->nlmsg_type);
646 }
647 }
648
649 if (msg && *msg != '\0') {
650 bool is_err = !!err->error;
651
652 if (is_err)
653 zlog_err("Extended Error: %s", msg);
654 else
655 flog_warn(EC_ZEBRA_NETLINK_EXTENDED_WARNING,
656 "Extended Warning: %s", msg);
657 }
658 }
659
660 /*
661 * netlink_parse_info
662 *
663 * Receive message from netlink interface and pass those information
664 * to the given function.
665 *
666 * filter -> Function to call to read the results
667 * nl -> netlink socket information
668 * zns -> The zebra namespace data
669 * count -> How many we should read in, 0 means as much as possible
670 * startup -> Are we reading in under startup conditions? passed to
671 * the filter.
672 */
673 int netlink_parse_info(int (*filter)(struct nlmsghdr *, ns_id_t, int),
674 struct nlsock *nl, struct zebra_ns *zns, int count,
675 int startup)
676 {
677 int status;
678 int ret = 0;
679 int error;
680 int read_in = 0;
681
682 while (1) {
683 char buf[NL_RCV_PKT_BUF_SIZE];
684 struct iovec iov = {.iov_base = buf, .iov_len = sizeof buf};
685 struct sockaddr_nl snl;
686 struct msghdr msg = {.msg_name = (void *)&snl,
687 .msg_namelen = sizeof snl,
688 .msg_iov = &iov,
689 .msg_iovlen = 1};
690 struct nlmsghdr *h;
691
692 if (count && read_in >= count)
693 return 0;
694
695 #if defined(HANDLE_NETLINK_FUZZING)
696 /* Check if reading and filename is set */
697 if (netlink_read && '\0' != netlink_fuzz_file[0]) {
698 zlog_debug("Reading netlink fuzz file");
699 status = netlink_read_file(buf, netlink_fuzz_file);
700 snl.nl_pid = 0;
701 } else {
702 status = recvmsg(nl->sock, &msg, 0);
703 }
704 #else
705 status = recvmsg(nl->sock, &msg, 0);
706 #endif /* HANDLE_NETLINK_FUZZING */
707 if (status < 0) {
708 if (errno == EINTR)
709 continue;
710 if (errno == EWOULDBLOCK || errno == EAGAIN)
711 break;
712 flog_err(EC_ZEBRA_RECVMSG_OVERRUN,
713 "%s recvmsg overrun: %s", nl->name,
714 safe_strerror(errno));
715 /*
716 * In this case we are screwed.
717 * There is no good way to
718 * recover zebra at this point.
719 */
720 exit(-1);
721 continue;
722 }
723
724 if (status == 0) {
725 flog_err_sys(EC_LIB_SOCKET, "%s EOF", nl->name);
726 return -1;
727 }
728
729 if (msg.msg_namelen != sizeof snl) {
730 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
731 "%s sender address length error: length %d",
732 nl->name, msg.msg_namelen);
733 return -1;
734 }
735
736 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_RECV) {
737 zlog_debug("%s: << netlink message dump [recv]",
738 __func__);
739 zlog_hexdump(buf, status);
740 }
741
742 #if defined(HANDLE_NETLINK_FUZZING)
743 if (!netlink_read) {
744 zlog_debug("Writing incoming netlink message");
745 netlink_write_incoming(buf, status,
746 netlink_file_counter++);
747 }
748 #endif /* HANDLE_NETLINK_FUZZING */
749
750 read_in++;
751 for (h = (struct nlmsghdr *)buf;
752 (status >= 0 && NLMSG_OK(h, (unsigned int)status));
753 h = NLMSG_NEXT(h, status)) {
754 /* Finish of reading. */
755 if (h->nlmsg_type == NLMSG_DONE)
756 return ret;
757
758 /* Error handling. */
759 if (h->nlmsg_type == NLMSG_ERROR) {
760 struct nlmsgerr *err =
761 (struct nlmsgerr *)NLMSG_DATA(h);
762 int errnum = err->error;
763 int msg_type = err->msg.nlmsg_type;
764
765 if (h->nlmsg_len
766 < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
767 zlog_err("%s error: message truncated",
768 nl->name);
769 return -1;
770 }
771
772 /*
773 * Parse the extended information before
774 * we actually handle it.
775 * At this point in time we do not
776 * do anything other than report the
777 * issue.
778 */
779 if (h->nlmsg_flags & NLM_F_ACK_TLVS)
780 netlink_parse_extended_ack(h);
781
782 /* If the error field is zero, then this is an
783 * ACK */
784 if (err->error == 0) {
785 if (IS_ZEBRA_DEBUG_KERNEL) {
786 zlog_debug(
787 "%s: %s ACK: type=%s(%u), seq=%u, pid=%u",
788 __FUNCTION__, nl->name,
789 nl_msg_type_to_str(
790 err->msg.nlmsg_type),
791 err->msg.nlmsg_type,
792 err->msg.nlmsg_seq,
793 err->msg.nlmsg_pid);
794 }
795
796 /* return if not a multipart message,
797 * otherwise continue */
798 if (!(h->nlmsg_flags & NLM_F_MULTI))
799 return 0;
800 continue;
801 }
802
803 if (h->nlmsg_len
804 < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
805 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
806 "%s error: message truncated",
807 nl->name);
808 return -1;
809 }
810
811 /* Deal with errors that occur because of races
812 * in link handling */
813 if (nl == &zns->netlink_cmd
814 && ((msg_type == RTM_DELROUTE
815 && (-errnum == ENODEV
816 || -errnum == ESRCH))
817 || (msg_type == RTM_NEWROUTE
818 && (-errnum == ENETDOWN
819 || -errnum == EEXIST)))) {
820 if (IS_ZEBRA_DEBUG_KERNEL)
821 zlog_debug(
822 "%s: error: %s type=%s(%u), seq=%u, pid=%u",
823 nl->name,
824 safe_strerror(-errnum),
825 nl_msg_type_to_str(
826 msg_type),
827 msg_type,
828 err->msg.nlmsg_seq,
829 err->msg.nlmsg_pid);
830 return 0;
831 }
832
833 /* We see RTM_DELNEIGH when shutting down an
834 * interface with an IPv4
835 * link-local. The kernel should have already
836 * deleted the neighbor
837 * so do not log these as an error.
838 */
839 if (msg_type == RTM_DELNEIGH
840 || (nl == &zns->netlink_cmd
841 && msg_type == RTM_NEWROUTE
842 && (-errnum == ESRCH
843 || -errnum == ENETUNREACH))) {
844 /* This is known to happen in some
845 * situations, don't log
846 * as error.
847 */
848 if (IS_ZEBRA_DEBUG_KERNEL)
849 zlog_debug(
850 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
851 nl->name,
852 safe_strerror(-errnum),
853 nl_msg_type_to_str(
854 msg_type),
855 msg_type,
856 err->msg.nlmsg_seq,
857 err->msg.nlmsg_pid);
858 } else
859 flog_err(
860 EC_ZEBRA_UNEXPECTED_MESSAGE,
861 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
862 nl->name,
863 safe_strerror(-errnum),
864 nl_msg_type_to_str(msg_type),
865 msg_type, err->msg.nlmsg_seq,
866 err->msg.nlmsg_pid);
867
868 return -1;
869 }
870
871 /* OK we got netlink message. */
872 if (IS_ZEBRA_DEBUG_KERNEL)
873 zlog_debug(
874 "netlink_parse_info: %s type %s(%u), len=%d, seq=%u, pid=%u",
875 nl->name,
876 nl_msg_type_to_str(h->nlmsg_type),
877 h->nlmsg_type, h->nlmsg_len,
878 h->nlmsg_seq, h->nlmsg_pid);
879
880
881 /*
882 * Ignore messages that maybe sent from
883 * other actors besides the kernel
884 */
885 if (snl.nl_pid != 0) {
886 zlog_debug("Ignoring message from pid %u",
887 snl.nl_pid);
888 continue;
889 }
890
891 error = (*filter)(h, zns->ns_id, startup);
892 if (error < 0) {
893 zlog_debug("%s filter function error",
894 nl->name);
895 ret = error;
896 }
897 }
898
899 /* After error care. */
900 if (msg.msg_flags & MSG_TRUNC) {
901 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
902 "%s error: message truncated", nl->name);
903 continue;
904 }
905 if (status) {
906 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
907 "%s error: data remnant size %d", nl->name,
908 status);
909 return -1;
910 }
911 }
912 return ret;
913 }
914
915 /*
916 * netlink_talk
917 *
918 * sendmsg() to netlink socket then recvmsg().
919 * Calls netlink_parse_info to parse returned data
920 *
921 * filter -> The filter to read final results from kernel
922 * nlmsghdr -> The data to send to the kernel
923 * nl -> The netlink socket information
924 * zns -> The zebra namespace information
925 * startup -> Are we reading in under startup conditions
926 * This is passed through eventually to filter.
927 */
928 int netlink_talk(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
929 struct nlmsghdr *n, struct nlsock *nl, struct zebra_ns *zns,
930 int startup)
931 {
932 int status = 0;
933 struct sockaddr_nl snl;
934 struct iovec iov;
935 struct msghdr msg;
936 int save_errno = 0;
937
938 memset(&snl, 0, sizeof snl);
939 memset(&iov, 0, sizeof iov);
940 memset(&msg, 0, sizeof msg);
941
942 iov.iov_base = n;
943 iov.iov_len = n->nlmsg_len;
944 msg.msg_name = (void *)&snl;
945 msg.msg_namelen = sizeof snl;
946 msg.msg_iov = &iov;
947 msg.msg_iovlen = 1;
948
949 snl.nl_family = AF_NETLINK;
950
951 n->nlmsg_seq = ++nl->seq;
952 n->nlmsg_pid = nl->snl.nl_pid;
953
954 if (IS_ZEBRA_DEBUG_KERNEL)
955 zlog_debug(
956 "netlink_talk: %s type %s(%u), len=%d seq=%u flags 0x%x",
957 nl->name, nl_msg_type_to_str(n->nlmsg_type),
958 n->nlmsg_type, n->nlmsg_len, n->nlmsg_seq,
959 n->nlmsg_flags);
960
961 /* Send message to netlink interface. */
962 frr_elevate_privs(&zserv_privs) {
963 status = sendmsg(nl->sock, &msg, 0);
964 save_errno = errno;
965 }
966
967 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_SEND) {
968 zlog_debug("%s: >> netlink message dump [sent]", __func__);
969 zlog_hexdump(n, n->nlmsg_len);
970 }
971
972 if (status < 0) {
973 flog_err_sys(EC_LIB_SOCKET, "netlink_talk sendmsg() error: %s",
974 safe_strerror(save_errno));
975 return -1;
976 }
977
978
979 /*
980 * Get reply from netlink socket.
981 * The reply should either be an acknowlegement or an error.
982 */
983 return netlink_parse_info(filter, nl, zns, 0, startup);
984 }
985
986 /* Issue request message to kernel via netlink socket. GET messages
987 * are issued through this interface.
988 */
989 int netlink_request(struct nlsock *nl, struct nlmsghdr *n)
990 {
991 int ret;
992 struct sockaddr_nl snl;
993
994 /* Check netlink socket. */
995 if (nl->sock < 0) {
996 flog_err_sys(EC_LIB_SOCKET, "%s socket isn't active.",
997 nl->name);
998 return -1;
999 }
1000
1001 /* Fill common fields for all requests. */
1002 n->nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST;
1003 n->nlmsg_pid = nl->snl.nl_pid;
1004 n->nlmsg_seq = ++nl->seq;
1005
1006 memset(&snl, 0, sizeof snl);
1007 snl.nl_family = AF_NETLINK;
1008
1009 /* Raise capabilities and send message, then lower capabilities. */
1010 frr_elevate_privs(&zserv_privs) {
1011 ret = sendto(nl->sock, (void *)n, n->nlmsg_len, 0,
1012 (struct sockaddr *)&snl, sizeof snl);
1013 }
1014
1015 if (ret < 0) {
1016 zlog_err("%s sendto failed: %s", nl->name,
1017 safe_strerror(errno));
1018 return -1;
1019 }
1020
1021 return 0;
1022 }
1023
1024 /* Exported interface function. This function simply calls
1025 netlink_socket (). */
1026 void kernel_init(struct zebra_ns *zns)
1027 {
1028 unsigned long groups;
1029 #if defined SOL_NETLINK
1030 int one, ret;
1031 #endif
1032
1033 /*
1034 * Initialize netlink sockets
1035 *
1036 * If RTMGRP_XXX exists use that, but at some point
1037 * I think the kernel developers realized that
1038 * keeping track of all the different values would
1039 * lead to confusion, so we need to convert the
1040 * RTNLGRP_XXX to a bit position for ourself
1041 */
1042 groups = RTMGRP_LINK |
1043 RTMGRP_IPV4_ROUTE |
1044 RTMGRP_IPV4_IFADDR |
1045 RTMGRP_IPV6_ROUTE |
1046 RTMGRP_IPV6_IFADDR |
1047 RTMGRP_IPV4_MROUTE |
1048 RTMGRP_NEIGH |
1049 (1 << (RTNLGRP_IPV4_RULE - 1)) |
1050 (1 << (RTNLGRP_IPV6_RULE - 1));
1051
1052 snprintf(zns->netlink.name, sizeof(zns->netlink.name),
1053 "netlink-listen (NS %u)", zns->ns_id);
1054 zns->netlink.sock = -1;
1055 if (netlink_socket(&zns->netlink, groups, zns->ns_id) < 0) {
1056 zlog_err("Failure to create %s socket",
1057 zns->netlink.name);
1058 exit(-1);
1059 }
1060
1061 snprintf(zns->netlink_cmd.name, sizeof(zns->netlink_cmd.name),
1062 "netlink-cmd (NS %u)", zns->ns_id);
1063 zns->netlink_cmd.sock = -1;
1064 if (netlink_socket(&zns->netlink_cmd, 0, zns->ns_id) < 0) {
1065 zlog_err("Failure to create %s socket",
1066 zns->netlink_cmd.name);
1067 exit(-1);
1068 }
1069
1070 /*
1071 * SOL_NETLINK is not available on all platforms yet
1072 * apparently. It's in bits/socket.h which I am not
1073 * sure that we want to pull into our build system.
1074 */
1075 #if defined SOL_NETLINK
1076 /*
1077 * Let's tell the kernel that we want to receive extended
1078 * ACKS over our command socket
1079 */
1080 one = 1;
1081 ret = setsockopt(zns->netlink_cmd.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1082 &one, sizeof(one));
1083
1084 if (ret < 0)
1085 zlog_notice("Registration for extended ACK failed : %d %s",
1086 errno, safe_strerror(errno));
1087 #endif
1088
1089 /* Register kernel socket. */
1090 if (fcntl(zns->netlink.sock, F_SETFL, O_NONBLOCK) < 0)
1091 flog_err_sys(EC_LIB_SOCKET, "Can't set %s socket flags: %s",
1092 zns->netlink.name, safe_strerror(errno));
1093
1094 if (fcntl(zns->netlink_cmd.sock, F_SETFL, O_NONBLOCK) < 0)
1095 zlog_err("Can't set %s socket error: %s(%d)",
1096 zns->netlink_cmd.name, safe_strerror(errno), errno);
1097
1098 /* Set receive buffer size if it's set from command line */
1099 if (nl_rcvbufsize)
1100 netlink_recvbuf(&zns->netlink, nl_rcvbufsize);
1101
1102 assert(zns->netlink.sock >= 0);
1103 netlink_install_filter(zns->netlink.sock,
1104 zns->netlink_cmd.snl.nl_pid);
1105 zns->t_netlink = NULL;
1106
1107 thread_add_read(zebrad.master, kernel_read, zns,
1108 zns->netlink.sock, &zns->t_netlink);
1109
1110 rt_netlink_init();
1111 }
1112
1113 void kernel_terminate(struct zebra_ns *zns)
1114 {
1115 THREAD_READ_OFF(zns->t_netlink);
1116
1117 if (zns->netlink.sock >= 0) {
1118 close(zns->netlink.sock);
1119 zns->netlink.sock = -1;
1120 }
1121
1122 if (zns->netlink_cmd.sock >= 0) {
1123 close(zns->netlink_cmd.sock);
1124 zns->netlink_cmd.sock = -1;
1125 }
1126 }
1127
1128 #endif /* HAVE_NETLINK */