]> git.proxmox.com Git - mirror_frr.git/blob - zebra/kernel_netlink.c
Merge pull request #4514 from opensourcerouting/warnings-20190612
[mirror_frr.git] / zebra / kernel_netlink.c
1 /* Kernel communication using netlink interface.
2 * Copyright (C) 1999 Kunihiro Ishiguro
3 *
4 * This file is part of GNU Zebra.
5 *
6 * GNU Zebra is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2, or (at your option) any
9 * later version.
10 *
11 * GNU Zebra is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; see the file COPYING; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21 #include <zebra.h>
22
23 #if defined(HANDLE_NETLINK_FUZZING)
24 #include <stdio.h>
25 #include <string.h>
26 #include "libfrr.h"
27 #endif /* HANDLE_NETLINK_FUZZING */
28
29 #ifdef HAVE_NETLINK
30
31 #include "linklist.h"
32 #include "if.h"
33 #include "log.h"
34 #include "prefix.h"
35 #include "connected.h"
36 #include "table.h"
37 #include "memory.h"
38 #include "zebra_memory.h"
39 #include "rib.h"
40 #include "thread.h"
41 #include "privs.h"
42 #include "nexthop.h"
43 #include "vrf.h"
44 #include "mpls.h"
45 #include "lib_errors.h"
46
47 //#include "zebra/zserv.h"
48 #include "zebra/zebra_router.h"
49 #include "zebra/zebra_ns.h"
50 #include "zebra/zebra_vrf.h"
51 #include "zebra/rt.h"
52 #include "zebra/debug.h"
53 #include "zebra/kernel_netlink.h"
54 #include "zebra/rt_netlink.h"
55 #include "zebra/if_netlink.h"
56 #include "zebra/rule_netlink.h"
57 #include "zebra/zebra_errors.h"
58
59 #ifndef SO_RCVBUFFORCE
60 #define SO_RCVBUFFORCE (33)
61 #endif
62
63 /* Hack for GNU libc version 2. */
64 #ifndef MSG_TRUNC
65 #define MSG_TRUNC 0x20
66 #endif /* MSG_TRUNC */
67
68 #ifndef NLMSG_TAIL
69 #define NLMSG_TAIL(nmsg) \
70 ((struct rtattr *)(((uint8_t *)(nmsg)) \
71 + NLMSG_ALIGN((nmsg)->nlmsg_len)))
72 #endif
73
74 #ifndef RTA_TAIL
75 #define RTA_TAIL(rta) \
76 ((struct rtattr *)(((uint8_t *)(rta)) + RTA_ALIGN((rta)->rta_len)))
77 #endif
78
79 #ifndef RTNL_FAMILY_IP6MR
80 #define RTNL_FAMILY_IP6MR 129
81 #endif
82
83 #ifndef RTPROT_MROUTED
84 #define RTPROT_MROUTED 17
85 #endif
86
87 static const struct message nlmsg_str[] = {{RTM_NEWROUTE, "RTM_NEWROUTE"},
88 {RTM_DELROUTE, "RTM_DELROUTE"},
89 {RTM_GETROUTE, "RTM_GETROUTE"},
90 {RTM_NEWLINK, "RTM_NEWLINK"},
91 {RTM_DELLINK, "RTM_DELLINK"},
92 {RTM_GETLINK, "RTM_GETLINK"},
93 {RTM_NEWADDR, "RTM_NEWADDR"},
94 {RTM_DELADDR, "RTM_DELADDR"},
95 {RTM_GETADDR, "RTM_GETADDR"},
96 {RTM_NEWNEIGH, "RTM_NEWNEIGH"},
97 {RTM_DELNEIGH, "RTM_DELNEIGH"},
98 {RTM_GETNEIGH, "RTM_GETNEIGH"},
99 {RTM_NEWRULE, "RTM_NEWRULE"},
100 {RTM_DELRULE, "RTM_DELRULE"},
101 {RTM_GETRULE, "RTM_GETRULE"},
102 {0}};
103
104 static const struct message rtproto_str[] = {
105 {RTPROT_REDIRECT, "redirect"},
106 {RTPROT_KERNEL, "kernel"},
107 {RTPROT_BOOT, "boot"},
108 {RTPROT_STATIC, "static"},
109 {RTPROT_GATED, "GateD"},
110 {RTPROT_RA, "router advertisement"},
111 {RTPROT_MRT, "MRT"},
112 {RTPROT_ZEBRA, "Zebra"},
113 #ifdef RTPROT_BIRD
114 {RTPROT_BIRD, "BIRD"},
115 #endif /* RTPROT_BIRD */
116 {RTPROT_MROUTED, "mroute"},
117 {RTPROT_BGP, "BGP"},
118 {RTPROT_OSPF, "OSPF"},
119 {RTPROT_ISIS, "IS-IS"},
120 {RTPROT_RIP, "RIP"},
121 {RTPROT_RIPNG, "RIPNG"},
122 {RTPROT_ZSTATIC, "static"},
123 {0}};
124
125 static const struct message family_str[] = {{AF_INET, "ipv4"},
126 {AF_INET6, "ipv6"},
127 {AF_BRIDGE, "bridge"},
128 {RTNL_FAMILY_IPMR, "ipv4MR"},
129 {RTNL_FAMILY_IP6MR, "ipv6MR"},
130 {0}};
131
132 static const struct message rttype_str[] = {{RTN_UNICAST, "unicast"},
133 {RTN_MULTICAST, "multicast"},
134 {0}};
135
136 extern struct thread_master *master;
137 extern uint32_t nl_rcvbufsize;
138
139 extern struct zebra_privs_t zserv_privs;
140
141
142 int netlink_talk_filter(struct nlmsghdr *h, ns_id_t ns_id, int startup)
143 {
144 /*
145 * This is an error condition that must be handled during
146 * development.
147 *
148 * The netlink_talk_filter function is used for communication
149 * down the netlink_cmd pipe and we are expecting
150 * an ack being received. So if we get here
151 * then we did not receive the ack and instead
152 * received some other message in an unexpected
153 * way.
154 */
155 zlog_debug("%s: ignoring message type 0x%04x(%s) NS %u", __func__,
156 h->nlmsg_type, nl_msg_type_to_str(h->nlmsg_type), ns_id);
157 return 0;
158 }
159
160 static int netlink_recvbuf(struct nlsock *nl, uint32_t newsize)
161 {
162 uint32_t oldsize;
163 socklen_t newlen = sizeof(newsize);
164 socklen_t oldlen = sizeof(oldsize);
165 int ret;
166
167 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &oldsize, &oldlen);
168 if (ret < 0) {
169 flog_err_sys(EC_LIB_SOCKET,
170 "Can't get %s receive buffer size: %s", nl->name,
171 safe_strerror(errno));
172 return -1;
173 }
174
175 /* Try force option (linux >= 2.6.14) and fall back to normal set */
176 frr_elevate_privs(&zserv_privs) {
177 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUFFORCE,
178 &nl_rcvbufsize,
179 sizeof(nl_rcvbufsize));
180 }
181 if (ret < 0)
182 ret = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF,
183 &nl_rcvbufsize, sizeof(nl_rcvbufsize));
184 if (ret < 0) {
185 flog_err_sys(EC_LIB_SOCKET,
186 "Can't set %s receive buffer size: %s", nl->name,
187 safe_strerror(errno));
188 return -1;
189 }
190
191 ret = getsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF, &newsize, &newlen);
192 if (ret < 0) {
193 flog_err_sys(EC_LIB_SOCKET,
194 "Can't get %s receive buffer size: %s", nl->name,
195 safe_strerror(errno));
196 return -1;
197 }
198
199 zlog_info("Setting netlink socket receive buffer size: %u -> %u",
200 oldsize, newsize);
201 return 0;
202 }
203
204 /* Make socket for Linux netlink interface. */
205 static int netlink_socket(struct nlsock *nl, unsigned long groups,
206 ns_id_t ns_id)
207 {
208 int ret;
209 struct sockaddr_nl snl;
210 int sock;
211 int namelen;
212
213 frr_elevate_privs(&zserv_privs) {
214 sock = ns_socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE, ns_id);
215 if (sock < 0) {
216 zlog_err("Can't open %s socket: %s", nl->name,
217 safe_strerror(errno));
218 return -1;
219 }
220
221 memset(&snl, 0, sizeof snl);
222 snl.nl_family = AF_NETLINK;
223 snl.nl_groups = groups;
224
225 /* Bind the socket to the netlink structure for anything. */
226 ret = bind(sock, (struct sockaddr *)&snl, sizeof snl);
227 }
228
229 if (ret < 0) {
230 zlog_err("Can't bind %s socket to group 0x%x: %s", nl->name,
231 snl.nl_groups, safe_strerror(errno));
232 close(sock);
233 return -1;
234 }
235
236 /* multiple netlink sockets will have different nl_pid */
237 namelen = sizeof snl;
238 ret = getsockname(sock, (struct sockaddr *)&snl, (socklen_t *)&namelen);
239 if (ret < 0 || namelen != sizeof snl) {
240 flog_err_sys(EC_LIB_SOCKET, "Can't get %s socket name: %s",
241 nl->name, safe_strerror(errno));
242 close(sock);
243 return -1;
244 }
245
246 nl->snl = snl;
247 nl->sock = sock;
248 return ret;
249 }
250
251 static int netlink_information_fetch(struct nlmsghdr *h, ns_id_t ns_id,
252 int startup)
253 {
254 /*
255 * When we handle new message types here
256 * because we are starting to install them
257 * then lets check the netlink_install_filter
258 * and see if we should add the corresponding
259 * allow through entry there.
260 * Probably not needed to do but please
261 * think about it.
262 */
263 switch (h->nlmsg_type) {
264 case RTM_NEWROUTE:
265 return netlink_route_change(h, ns_id, startup);
266 case RTM_DELROUTE:
267 return netlink_route_change(h, ns_id, startup);
268 case RTM_NEWLINK:
269 return netlink_link_change(h, ns_id, startup);
270 case RTM_DELLINK:
271 return netlink_link_change(h, ns_id, startup);
272 case RTM_NEWADDR:
273 return netlink_interface_addr(h, ns_id, startup);
274 case RTM_DELADDR:
275 return netlink_interface_addr(h, ns_id, startup);
276 case RTM_NEWNEIGH:
277 return netlink_neigh_change(h, ns_id);
278 case RTM_DELNEIGH:
279 return netlink_neigh_change(h, ns_id);
280 case RTM_NEWRULE:
281 return netlink_rule_change(h, ns_id, startup);
282 case RTM_DELRULE:
283 return netlink_rule_change(h, ns_id, startup);
284 default:
285 /*
286 * If we have received this message then
287 * we have made a mistake during development
288 * and we need to write some code to handle
289 * this message type or not ask for
290 * it to be sent up to us
291 */
292 flog_err(EC_ZEBRA_UNKNOWN_NLMSG,
293 "Unknown netlink nlmsg_type %s(%d) vrf %u\n",
294 nl_msg_type_to_str(h->nlmsg_type), h->nlmsg_type,
295 ns_id);
296 break;
297 }
298 return 0;
299 }
300
301 #if defined(HANDLE_NETLINK_FUZZING)
302 /* Using globals here to avoid adding function parameters */
303
304 /* Keep distinct filenames for netlink fuzzy collection */
305 static unsigned int netlink_file_counter = 1;
306
307 /* File name to read fuzzed netlink from */
308 static char netlink_fuzz_file[MAXPATHLEN] = "";
309
310 /* Flag for whether to read from file or not */
311 bool netlink_read;
312
313 /**
314 * netlink_read_init() - Starts the message parser
315 * @fname: Filename to read.
316 */
317 void netlink_read_init(const char *fname)
318 {
319 struct zebra_dplane_info dp_info;
320
321 snprintf(netlink_fuzz_file, MAXPATHLEN, "%s", fname);
322 /* Creating this fake socket for testing purposes */
323 struct zebra_ns *zns = zebra_ns_lookup(NS_DEFAULT);
324
325 /* Capture key info from zns struct */
326 zebra_dplane_info_from_zns(&dp_info, zns, false);
327
328 netlink_parse_info(netlink_information_fetch, &zns->netlink,
329 &dp_info, 1, 0);
330 }
331
332 /**
333 * netlink_write_incoming() - Writes all data received from netlink to a file
334 * @buf: Data from netlink.
335 * @size: Size of data.
336 * @counter: Counter for keeping filenames distinct.
337 */
338 static void netlink_write_incoming(const char *buf, const unsigned int size,
339 unsigned int counter)
340 {
341 char fname[MAXPATHLEN];
342 FILE *f;
343
344 snprintf(fname, MAXPATHLEN, "%s/%s_%u", frr_vtydir, "netlink", 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 NLA_OK(nla, len) \
610 ((len) >= (int)sizeof(struct nlattr) \
611 && (nla)->nla_len >= sizeof(struct nlattr) \
612 && (nla)->nla_len <= (len))
613 #define NLA_NEXT(nla, attrlen) \
614 ((attrlen) -= NLA_ALIGN((nla)->nla_len), \
615 (struct nlattr *)(((char *)(nla)) + NLA_ALIGN((nla)->nla_len)))
616 #define NLA_LENGTH(len) (NLA_ALIGN(sizeof(struct nlattr)) + (len))
617 #define NLA_DATA(nla) ((struct nlattr *)(((char *)(nla)) + NLA_LENGTH(0)))
618
619 #define ERR_NLA(err, inner_len) \
620 ((struct nlattr *)(((char *)(err)) \
621 + NLMSG_ALIGN(sizeof(struct nlmsgerr)) \
622 + NLMSG_ALIGN((inner_len))))
623
624 static void netlink_parse_nlattr(struct nlattr **tb, int max,
625 struct nlattr *nla, int len)
626 {
627 while (NLA_OK(nla, len)) {
628 if (nla->nla_type <= max)
629 tb[nla->nla_type] = nla;
630 nla = NLA_NEXT(nla, len);
631 }
632 }
633
634 static void netlink_parse_extended_ack(struct nlmsghdr *h)
635 {
636 struct nlattr *tb[NLMSGERR_ATTR_MAX + 1] = {};
637 const struct nlmsgerr *err = (const struct nlmsgerr *)NLMSG_DATA(h);
638 const struct nlmsghdr *err_nlh = NULL;
639 /* Length not including nlmsghdr */
640 uint32_t len = 0;
641 /* Inner error netlink message length */
642 uint32_t inner_len = 0;
643 const char *msg = NULL;
644 uint32_t off = 0;
645
646 if (!(h->nlmsg_flags & NLM_F_CAPPED))
647 inner_len = (uint32_t)NLMSG_PAYLOAD(&err->msg, 0);
648
649 len = (uint32_t)(NLMSG_PAYLOAD(h, sizeof(struct nlmsgerr)) - inner_len);
650
651 netlink_parse_nlattr(tb, NLMSGERR_ATTR_MAX, ERR_NLA(err, inner_len),
652 len);
653
654 if (tb[NLMSGERR_ATTR_MSG])
655 msg = (const char *)NLA_DATA(tb[NLMSGERR_ATTR_MSG]);
656
657 if (tb[NLMSGERR_ATTR_OFFS]) {
658 off = *(uint32_t *)NLA_DATA(tb[NLMSGERR_ATTR_OFFS]);
659
660 if (off > h->nlmsg_len) {
661 zlog_err("Invalid offset for NLMSGERR_ATTR_OFFS");
662 } else if (!(h->nlmsg_flags & NLM_F_CAPPED)) {
663 /*
664 * Header of failed message
665 * we are not doing anything currently with it
666 * but noticing it for later.
667 */
668 err_nlh = &err->msg;
669 zlog_debug("%s: Received %s extended Ack",
670 __PRETTY_FUNCTION__,
671 nl_msg_type_to_str(err_nlh->nlmsg_type));
672 }
673 }
674
675 if (msg && *msg != '\0') {
676 bool is_err = !!err->error;
677
678 if (is_err)
679 zlog_err("Extended Error: %s", msg);
680 else
681 flog_warn(EC_ZEBRA_NETLINK_EXTENDED_WARNING,
682 "Extended Warning: %s", msg);
683 }
684 }
685
686 /*
687 * netlink_parse_info
688 *
689 * Receive message from netlink interface and pass those information
690 * to the given function.
691 *
692 * filter -> Function to call to read the results
693 * nl -> netlink socket information
694 * zns -> The zebra namespace data
695 * count -> How many we should read in, 0 means as much as possible
696 * startup -> Are we reading in under startup conditions? passed to
697 * the filter.
698 */
699 int netlink_parse_info(int (*filter)(struct nlmsghdr *, ns_id_t, int),
700 const struct nlsock *nl,
701 const struct zebra_dplane_info *zns,
702 int count, int startup)
703 {
704 int status;
705 int ret = 0;
706 int error;
707 int read_in = 0;
708
709 while (1) {
710 char buf[NL_RCV_PKT_BUF_SIZE];
711 struct iovec iov = {.iov_base = buf, .iov_len = sizeof buf};
712 struct sockaddr_nl snl;
713 struct msghdr msg = {.msg_name = (void *)&snl,
714 .msg_namelen = sizeof snl,
715 .msg_iov = &iov,
716 .msg_iovlen = 1};
717 struct nlmsghdr *h;
718
719 if (count && read_in >= count)
720 return 0;
721
722 #if defined(HANDLE_NETLINK_FUZZING)
723 /* Check if reading and filename is set */
724 if (netlink_read && '\0' != netlink_fuzz_file[0]) {
725 zlog_debug("Reading netlink fuzz file");
726 status = netlink_read_file(buf, netlink_fuzz_file);
727 snl.nl_pid = 0;
728 } else {
729 status = recvmsg(nl->sock, &msg, 0);
730 }
731 #else
732 status = recvmsg(nl->sock, &msg, 0);
733 #endif /* HANDLE_NETLINK_FUZZING */
734 if (status < 0) {
735 if (errno == EINTR)
736 continue;
737 if (errno == EWOULDBLOCK || errno == EAGAIN)
738 break;
739 flog_err(EC_ZEBRA_RECVMSG_OVERRUN,
740 "%s recvmsg overrun: %s", nl->name,
741 safe_strerror(errno));
742 /*
743 * In this case we are screwed.
744 * There is no good way to
745 * recover zebra at this point.
746 */
747 exit(-1);
748 continue;
749 }
750
751 if (status == 0) {
752 flog_err_sys(EC_LIB_SOCKET, "%s EOF", nl->name);
753 return -1;
754 }
755
756 if (msg.msg_namelen != sizeof snl) {
757 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
758 "%s sender address length error: length %d",
759 nl->name, msg.msg_namelen);
760 return -1;
761 }
762
763 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_RECV) {
764 zlog_debug("%s: << netlink message dump [recv]",
765 __func__);
766 zlog_hexdump(buf, status);
767 }
768
769 #if defined(HANDLE_NETLINK_FUZZING)
770 if (!netlink_read) {
771 zlog_debug("Writing incoming netlink message");
772 netlink_write_incoming(buf, status,
773 netlink_file_counter++);
774 }
775 #endif /* HANDLE_NETLINK_FUZZING */
776
777 read_in++;
778 for (h = (struct nlmsghdr *)buf;
779 (status >= 0 && NLMSG_OK(h, (unsigned int)status));
780 h = NLMSG_NEXT(h, status)) {
781 /* Finish of reading. */
782 if (h->nlmsg_type == NLMSG_DONE)
783 return ret;
784
785 /* Error handling. */
786 if (h->nlmsg_type == NLMSG_ERROR) {
787 struct nlmsgerr *err =
788 (struct nlmsgerr *)NLMSG_DATA(h);
789 int errnum = err->error;
790 int msg_type = err->msg.nlmsg_type;
791
792 if (h->nlmsg_len
793 < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
794 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
795 "%s error: message truncated",
796 nl->name);
797 return -1;
798 }
799
800 /*
801 * Parse the extended information before
802 * we actually handle it.
803 * At this point in time we do not
804 * do anything other than report the
805 * issue.
806 */
807 if (h->nlmsg_flags & NLM_F_ACK_TLVS)
808 netlink_parse_extended_ack(h);
809
810 /* If the error field is zero, then this is an
811 * ACK */
812 if (err->error == 0) {
813 if (IS_ZEBRA_DEBUG_KERNEL) {
814 zlog_debug(
815 "%s: %s ACK: type=%s(%u), seq=%u, pid=%u",
816 __FUNCTION__, nl->name,
817 nl_msg_type_to_str(
818 err->msg.nlmsg_type),
819 err->msg.nlmsg_type,
820 err->msg.nlmsg_seq,
821 err->msg.nlmsg_pid);
822 }
823
824 /* return if not a multipart message,
825 * otherwise continue */
826 if (!(h->nlmsg_flags & NLM_F_MULTI))
827 return 0;
828 continue;
829 }
830
831 /* Deal with errors that occur because of races
832 * in link handling */
833 if (zns->is_cmd
834 && ((msg_type == RTM_DELROUTE
835 && (-errnum == ENODEV
836 || -errnum == ESRCH))
837 || (msg_type == RTM_NEWROUTE
838 && (-errnum == ENETDOWN
839 || -errnum == EEXIST)))) {
840 if (IS_ZEBRA_DEBUG_KERNEL)
841 zlog_debug(
842 "%s: error: %s type=%s(%u), seq=%u, pid=%u",
843 nl->name,
844 safe_strerror(-errnum),
845 nl_msg_type_to_str(
846 msg_type),
847 msg_type,
848 err->msg.nlmsg_seq,
849 err->msg.nlmsg_pid);
850 return 0;
851 }
852
853 /* We see RTM_DELNEIGH when shutting down an
854 * interface with an IPv4
855 * link-local. The kernel should have already
856 * deleted the neighbor
857 * so do not log these as an error.
858 */
859 if (msg_type == RTM_DELNEIGH
860 || (zns->is_cmd && msg_type == RTM_NEWROUTE
861 && (-errnum == ESRCH
862 || -errnum == ENETUNREACH))) {
863 /* This is known to happen in some
864 * situations, don't log
865 * as error.
866 */
867 if (IS_ZEBRA_DEBUG_KERNEL)
868 zlog_debug(
869 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
870 nl->name,
871 safe_strerror(-errnum),
872 nl_msg_type_to_str(
873 msg_type),
874 msg_type,
875 err->msg.nlmsg_seq,
876 err->msg.nlmsg_pid);
877 } else
878 flog_err(
879 EC_ZEBRA_UNEXPECTED_MESSAGE,
880 "%s error: %s, type=%s(%u), seq=%u, pid=%u",
881 nl->name,
882 safe_strerror(-errnum),
883 nl_msg_type_to_str(msg_type),
884 msg_type, err->msg.nlmsg_seq,
885 err->msg.nlmsg_pid);
886
887 return -1;
888 }
889
890 /* OK we got netlink message. */
891 if (IS_ZEBRA_DEBUG_KERNEL)
892 zlog_debug(
893 "netlink_parse_info: %s type %s(%u), len=%d, seq=%u, pid=%u",
894 nl->name,
895 nl_msg_type_to_str(h->nlmsg_type),
896 h->nlmsg_type, h->nlmsg_len,
897 h->nlmsg_seq, h->nlmsg_pid);
898
899
900 /*
901 * Ignore messages that maybe sent from
902 * other actors besides the kernel
903 */
904 if (snl.nl_pid != 0) {
905 zlog_debug("Ignoring message from pid %u",
906 snl.nl_pid);
907 continue;
908 }
909
910 error = (*filter)(h, zns->ns_id, startup);
911 if (error < 0) {
912 zlog_debug("%s filter function error",
913 nl->name);
914 ret = error;
915 }
916 }
917
918 /* After error care. */
919 if (msg.msg_flags & MSG_TRUNC) {
920 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
921 "%s error: message truncated", nl->name);
922 continue;
923 }
924 if (status) {
925 flog_err(EC_ZEBRA_NETLINK_LENGTH_ERROR,
926 "%s error: data remnant size %d", nl->name,
927 status);
928 return -1;
929 }
930 }
931 return ret;
932 }
933
934 /*
935 * netlink_talk_info
936 *
937 * sendmsg() to netlink socket then recvmsg().
938 * Calls netlink_parse_info to parse returned data
939 *
940 * filter -> The filter to read final results from kernel
941 * nlmsghdr -> The data to send to the kernel
942 * dp_info -> The dataplane and netlink socket information
943 * startup -> Are we reading in under startup conditions
944 * This is passed through eventually to filter.
945 */
946 int netlink_talk_info(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
947 struct nlmsghdr *n,
948 const struct zebra_dplane_info *dp_info, int startup)
949 {
950 int status = 0;
951 struct sockaddr_nl snl;
952 struct iovec iov;
953 struct msghdr msg;
954 int save_errno = 0;
955 const struct nlsock *nl;
956
957 memset(&snl, 0, sizeof snl);
958 memset(&iov, 0, sizeof iov);
959 memset(&msg, 0, sizeof msg);
960
961 iov.iov_base = n;
962 iov.iov_len = n->nlmsg_len;
963 msg.msg_name = (void *)&snl;
964 msg.msg_namelen = sizeof snl;
965 msg.msg_iov = &iov;
966 msg.msg_iovlen = 1;
967
968 snl.nl_family = AF_NETLINK;
969
970 nl = &(dp_info->nls);
971 n->nlmsg_seq = nl->seq;
972 n->nlmsg_pid = nl->snl.nl_pid;
973
974 if (IS_ZEBRA_DEBUG_KERNEL)
975 zlog_debug(
976 "netlink_talk: %s type %s(%u), len=%d seq=%u flags 0x%x",
977 nl->name, nl_msg_type_to_str(n->nlmsg_type),
978 n->nlmsg_type, n->nlmsg_len, n->nlmsg_seq,
979 n->nlmsg_flags);
980
981 /* Send message to netlink interface. */
982 frr_elevate_privs(&zserv_privs) {
983 status = sendmsg(nl->sock, &msg, 0);
984 save_errno = errno;
985 }
986
987 if (IS_ZEBRA_DEBUG_KERNEL_MSGDUMP_SEND) {
988 zlog_debug("%s: >> netlink message dump [sent]", __func__);
989 zlog_hexdump(n, n->nlmsg_len);
990 }
991
992 if (status < 0) {
993 flog_err_sys(EC_LIB_SOCKET, "netlink_talk sendmsg() error: %s",
994 safe_strerror(save_errno));
995 return -1;
996 }
997
998 /*
999 * Get reply from netlink socket.
1000 * The reply should either be an acknowlegement or an error.
1001 */
1002 return netlink_parse_info(filter, nl, dp_info, 0, startup);
1003 }
1004
1005 /*
1006 * Synchronous version of netlink_talk_info. Converts args to suit the
1007 * common version, which is suitable for both sync and async use.
1008 */
1009 int netlink_talk(int (*filter)(struct nlmsghdr *, ns_id_t, int startup),
1010 struct nlmsghdr *n, struct nlsock *nl, struct zebra_ns *zns,
1011 int startup)
1012 {
1013 struct zebra_dplane_info dp_info;
1014
1015 /* Increment sequence number before capturing snapshot of ns socket
1016 * info.
1017 */
1018 nl->seq++;
1019
1020 /* Capture info in intermediate info struct */
1021 zebra_dplane_info_from_zns(&dp_info, zns, (nl == &(zns->netlink_cmd)));
1022
1023 return netlink_talk_info(filter, n, &dp_info, startup);
1024 }
1025
1026 /* Issue request message to kernel via netlink socket. GET messages
1027 * are issued through this interface.
1028 */
1029 int netlink_request(struct nlsock *nl, struct nlmsghdr *n)
1030 {
1031 int ret;
1032 struct sockaddr_nl snl;
1033
1034 /* Check netlink socket. */
1035 if (nl->sock < 0) {
1036 flog_err_sys(EC_LIB_SOCKET, "%s socket isn't active.",
1037 nl->name);
1038 return -1;
1039 }
1040
1041 /* Fill common fields for all requests. */
1042 n->nlmsg_pid = nl->snl.nl_pid;
1043 n->nlmsg_seq = ++nl->seq;
1044
1045 memset(&snl, 0, sizeof snl);
1046 snl.nl_family = AF_NETLINK;
1047
1048 /* Raise capabilities and send message, then lower capabilities. */
1049 frr_elevate_privs(&zserv_privs) {
1050 ret = sendto(nl->sock, (void *)n, n->nlmsg_len, 0,
1051 (struct sockaddr *)&snl, sizeof snl);
1052 }
1053
1054 if (ret < 0) {
1055 zlog_err("%s sendto failed: %s", nl->name,
1056 safe_strerror(errno));
1057 return -1;
1058 }
1059
1060 return 0;
1061 }
1062
1063 /* Exported interface function. This function simply calls
1064 netlink_socket (). */
1065 void kernel_init(struct zebra_ns *zns)
1066 {
1067 unsigned long groups;
1068 #if defined SOL_NETLINK
1069 int one, ret;
1070 #endif
1071
1072 /*
1073 * Initialize netlink sockets
1074 *
1075 * If RTMGRP_XXX exists use that, but at some point
1076 * I think the kernel developers realized that
1077 * keeping track of all the different values would
1078 * lead to confusion, so we need to convert the
1079 * RTNLGRP_XXX to a bit position for ourself
1080 */
1081 groups = RTMGRP_LINK |
1082 RTMGRP_IPV4_ROUTE |
1083 RTMGRP_IPV4_IFADDR |
1084 RTMGRP_IPV6_ROUTE |
1085 RTMGRP_IPV6_IFADDR |
1086 RTMGRP_IPV4_MROUTE |
1087 RTMGRP_NEIGH |
1088 (1 << (RTNLGRP_IPV4_RULE - 1)) |
1089 (1 << (RTNLGRP_IPV6_RULE - 1));
1090
1091 snprintf(zns->netlink.name, sizeof(zns->netlink.name),
1092 "netlink-listen (NS %u)", zns->ns_id);
1093 zns->netlink.sock = -1;
1094 if (netlink_socket(&zns->netlink, groups, zns->ns_id) < 0) {
1095 zlog_err("Failure to create %s socket",
1096 zns->netlink.name);
1097 exit(-1);
1098 }
1099
1100 snprintf(zns->netlink_cmd.name, sizeof(zns->netlink_cmd.name),
1101 "netlink-cmd (NS %u)", zns->ns_id);
1102 zns->netlink_cmd.sock = -1;
1103 if (netlink_socket(&zns->netlink_cmd, 0, zns->ns_id) < 0) {
1104 zlog_err("Failure to create %s socket",
1105 zns->netlink_cmd.name);
1106 exit(-1);
1107 }
1108
1109 snprintf(zns->netlink_dplane.name, sizeof(zns->netlink_dplane.name),
1110 "netlink-dp (NS %u)", zns->ns_id);
1111 zns->netlink_dplane.sock = -1;
1112 if (netlink_socket(&zns->netlink_dplane, 0, zns->ns_id) < 0) {
1113 zlog_err("Failure to create %s socket",
1114 zns->netlink_dplane.name);
1115 exit(-1);
1116 }
1117
1118 /*
1119 * SOL_NETLINK is not available on all platforms yet
1120 * apparently. It's in bits/socket.h which I am not
1121 * sure that we want to pull into our build system.
1122 */
1123 #if defined SOL_NETLINK
1124 /*
1125 * Let's tell the kernel that we want to receive extended
1126 * ACKS over our command socket(s)
1127 */
1128 one = 1;
1129 ret = setsockopt(zns->netlink_cmd.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1130 &one, sizeof(one));
1131
1132 if (ret < 0)
1133 zlog_notice("Registration for extended cmd ACK failed : %d %s",
1134 errno, safe_strerror(errno));
1135
1136 one = 1;
1137 ret = setsockopt(zns->netlink_dplane.sock, SOL_NETLINK, NETLINK_EXT_ACK,
1138 &one, sizeof(one));
1139
1140 if (ret < 0)
1141 zlog_notice("Registration for extended dp ACK failed : %d %s",
1142 errno, safe_strerror(errno));
1143 #endif
1144
1145 /* Register kernel socket. */
1146 if (fcntl(zns->netlink.sock, F_SETFL, O_NONBLOCK) < 0)
1147 flog_err_sys(EC_LIB_SOCKET, "Can't set %s socket flags: %s",
1148 zns->netlink.name, safe_strerror(errno));
1149
1150 if (fcntl(zns->netlink_cmd.sock, F_SETFL, O_NONBLOCK) < 0)
1151 zlog_err("Can't set %s socket error: %s(%d)",
1152 zns->netlink_cmd.name, safe_strerror(errno), errno);
1153
1154 if (fcntl(zns->netlink_dplane.sock, F_SETFL, O_NONBLOCK) < 0)
1155 zlog_err("Can't set %s socket error: %s(%d)",
1156 zns->netlink_dplane.name, safe_strerror(errno), errno);
1157
1158 /* Set receive buffer size if it's set from command line */
1159 if (nl_rcvbufsize)
1160 netlink_recvbuf(&zns->netlink, nl_rcvbufsize);
1161
1162 netlink_install_filter(zns->netlink.sock,
1163 zns->netlink_cmd.snl.nl_pid,
1164 zns->netlink_dplane.snl.nl_pid);
1165
1166 zns->t_netlink = NULL;
1167
1168 thread_add_read(zrouter.master, kernel_read, zns,
1169 zns->netlink.sock, &zns->t_netlink);
1170
1171 rt_netlink_init();
1172 }
1173
1174 void kernel_terminate(struct zebra_ns *zns, bool complete)
1175 {
1176 THREAD_READ_OFF(zns->t_netlink);
1177
1178 if (zns->netlink.sock >= 0) {
1179 close(zns->netlink.sock);
1180 zns->netlink.sock = -1;
1181 }
1182
1183 if (zns->netlink_cmd.sock >= 0) {
1184 close(zns->netlink_cmd.sock);
1185 zns->netlink_cmd.sock = -1;
1186 }
1187
1188 /* During zebra shutdown, we need to leave the dataplane socket
1189 * around until all work is done.
1190 */
1191 if (complete) {
1192 if (zns->netlink_dplane.sock >= 0) {
1193 close(zns->netlink_dplane.sock);
1194 zns->netlink_dplane.sock = -1;
1195 }
1196 }
1197 }
1198 #endif /* HAVE_NETLINK */