]> git.proxmox.com Git - mirror_frr.git/blob - bfdd/bfd.c
bfdd: Handling local and remote admin-down
[mirror_frr.git] / bfdd / bfd.c
1 /*********************************************************************
2 * Copyright 2013 Cumulus Networks, LLC. All rights reserved.
3 * Copyright 2014,2015,2016,2017 Cumulus Networks, Inc. All rights reserved.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the Free
7 * Software Foundation; either version 2 of the License, or (at your option)
8 * any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; see the file COPYING; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 *
19 * bfd.c: implements the BFD protocol.
20 *
21 * Authors
22 * -------
23 * Shrijeet Mukherjee [shm@cumulusnetworks.com]
24 * Kanna Rajagopal [kanna@cumulusnetworks.com]
25 * Radhika Mahankali [Radhika@cumulusnetworks.com]
26 */
27
28 #include <zebra.h>
29
30 #include "lib/jhash.h"
31
32 #include "bfd.h"
33
34 DEFINE_MTYPE_STATIC(BFDD, BFDD_CONFIG, "long-lived configuration memory")
35 DEFINE_MTYPE_STATIC(BFDD, BFDD_SESSION_OBSERVER, "Session observer")
36 DEFINE_MTYPE_STATIC(BFDD, BFDD_VRF, "BFD VRF")
37
38 /*
39 * Prototypes
40 */
41 static uint32_t ptm_bfd_gen_ID(void);
42 static void ptm_bfd_echo_xmt_TO(struct bfd_session *bfd);
43 static struct bfd_session *bfd_find_disc(struct sockaddr_any *sa,
44 uint32_t ldisc);
45 static int bfd_session_update(struct bfd_session *bs, struct bfd_peer_cfg *bpc);
46 static const char *get_diag_str(int diag);
47
48 static void bs_admin_down_handler(struct bfd_session *bs, int nstate);
49 static void bs_down_handler(struct bfd_session *bs, int nstate);
50 static void bs_init_handler(struct bfd_session *bs, int nstate);
51 static void bs_up_handler(struct bfd_session *bs, int nstate);
52 static void bs_neighbour_admin_down_handler(struct bfd_session *bfd,
53 uint8_t diag);
54
55 /* Zeroed array with the size of an IPv6 address. */
56 struct in6_addr zero_addr;
57
58 /*
59 * Functions
60 */
61 void gen_bfd_key(struct bfd_key *key, struct sockaddr_any *peer,
62 struct sockaddr_any *local, bool mhop, const char *ifname,
63 const char *vrfname)
64 {
65 memset(key, 0, sizeof(*key));
66
67 switch (peer->sa_sin.sin_family) {
68 case AF_INET:
69 key->family = AF_INET;
70 memcpy(&key->peer, &peer->sa_sin.sin_addr,
71 sizeof(peer->sa_sin.sin_addr));
72 memcpy(&key->local, &local->sa_sin.sin_addr,
73 sizeof(local->sa_sin.sin_addr));
74 break;
75 case AF_INET6:
76 key->family = AF_INET6;
77 memcpy(&key->peer, &peer->sa_sin6.sin6_addr,
78 sizeof(peer->sa_sin6.sin6_addr));
79 memcpy(&key->local, &local->sa_sin6.sin6_addr,
80 sizeof(local->sa_sin6.sin6_addr));
81 break;
82 }
83
84 key->mhop = mhop;
85 if (ifname && ifname[0])
86 strlcpy(key->ifname, ifname, sizeof(key->ifname));
87 if (vrfname && vrfname[0])
88 strlcpy(key->vrfname, vrfname, sizeof(key->vrfname));
89 else
90 strlcpy(key->vrfname, VRF_DEFAULT_NAME, sizeof(key->vrfname));
91 }
92
93 struct bfd_session *bs_peer_find(struct bfd_peer_cfg *bpc)
94 {
95 struct bfd_session *bs;
96 struct peer_label *pl;
97 struct bfd_key key;
98
99 /* Try to find label first. */
100 if (bpc->bpc_has_label) {
101 pl = pl_find(bpc->bpc_label);
102 if (pl != NULL) {
103 bs = pl->pl_bs;
104 return bs;
105 }
106 }
107
108 /* Otherwise fallback to peer/local hash lookup. */
109 gen_bfd_key(&key, &bpc->bpc_peer, &bpc->bpc_local, bpc->bpc_mhop,
110 bpc->bpc_localif, bpc->bpc_vrfname);
111
112 return bfd_key_lookup(key);
113 }
114
115 /*
116 * Starts a disabled BFD session.
117 *
118 * A session is disabled when the specified interface/VRF doesn't exist
119 * yet. It might happen on FRR boot or with virtual interfaces.
120 */
121 int bfd_session_enable(struct bfd_session *bs)
122 {
123 struct interface *ifp = NULL;
124 struct vrf *vrf = NULL;
125 int psock;
126
127 /*
128 * If the interface or VRF doesn't exist, then we must register
129 * the session but delay its start.
130 */
131 if (bs->key.vrfname[0]) {
132 vrf = vrf_lookup_by_name(bs->key.vrfname);
133 if (vrf == NULL) {
134 log_error(
135 "session-enable: specified VRF doesn't exists.");
136 return 0;
137 }
138 }
139
140 if (bs->key.ifname[0]) {
141 if (vrf)
142 ifp = if_lookup_by_name(bs->key.ifname, vrf->vrf_id);
143 else
144 ifp = if_lookup_by_name_all_vrf(bs->key.ifname);
145 if (ifp == NULL) {
146 log_error(
147 "session-enable: specified interface doesn't exists.");
148 return 0;
149 }
150 if (bs->key.ifname[0] && !vrf) {
151 vrf = vrf_lookup_by_id(ifp->vrf_id);
152 if (vrf == NULL) {
153 log_error(
154 "session-enable: specified VRF doesn't exists.");
155 return 0;
156 }
157 }
158 }
159
160 /* Assign interface/VRF pointers. */
161 bs->vrf = vrf;
162 if (bs->vrf == NULL)
163 bs->vrf = vrf_lookup_by_id(VRF_DEFAULT);
164
165 if (bs->key.ifname[0]
166 && BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_MH) == 0)
167 bs->ifp = ifp;
168
169 /* Sanity check: don't leak open sockets. */
170 if (bs->sock != -1) {
171 log_debug("session-enable: previous socket open");
172 close(bs->sock);
173 bs->sock = -1;
174 }
175
176 /*
177 * Get socket for transmitting control packets. Note that if we
178 * could use the destination port (3784) for the source
179 * port we wouldn't need a socket per session.
180 */
181 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_IPV6) == 0) {
182 psock = bp_peer_socket(bs);
183 if (psock == -1)
184 return 0;
185 } else {
186 psock = bp_peer_socketv6(bs);
187 if (psock == -1)
188 return 0;
189 }
190
191 /*
192 * We've got a valid socket, lets start the timers and the
193 * protocol.
194 */
195 bs->sock = psock;
196 bfd_recvtimer_update(bs);
197 ptm_bfd_start_xmt_timer(bs, false);
198
199 return 0;
200 }
201
202 /*
203 * Disabled a running BFD session.
204 *
205 * A session is disabled when the specified interface/VRF gets removed
206 * (e.g. virtual interfaces).
207 */
208 void bfd_session_disable(struct bfd_session *bs)
209 {
210 /* Free up socket resources. */
211 if (bs->sock != -1) {
212 close(bs->sock);
213 bs->sock = -1;
214 }
215
216 /* Disable all timers. */
217 bfd_recvtimer_delete(bs);
218 bfd_echo_recvtimer_delete(bs);
219 bfd_xmttimer_delete(bs);
220 bfd_echo_xmttimer_delete(bs);
221 }
222
223 static uint32_t ptm_bfd_gen_ID(void)
224 {
225 uint32_t session_id;
226
227 /*
228 * RFC 5880, Section 6.8.1. recommends that we should generate
229 * random session identification numbers.
230 */
231 do {
232 session_id = ((random() << 16) & 0xFFFF0000)
233 | (random() & 0x0000FFFF);
234 } while (session_id == 0 || bfd_id_lookup(session_id) != NULL);
235
236 return session_id;
237 }
238
239 void ptm_bfd_start_xmt_timer(struct bfd_session *bfd, bool is_echo)
240 {
241 uint64_t jitter, xmt_TO;
242 int maxpercent;
243
244 xmt_TO = is_echo ? bfd->echo_xmt_TO : bfd->xmt_TO;
245
246 /*
247 * From section 6.5.2: trasmit interval should be randomly jittered
248 * between
249 * 75% and 100% of nominal value, unless detect_mult is 1, then should
250 * be
251 * between 75% and 90%.
252 */
253 maxpercent = (bfd->detect_mult == 1) ? 16 : 26;
254 jitter = (xmt_TO * (75 + (random() % maxpercent))) / 100;
255 /* XXX remove that division above */
256
257 if (is_echo)
258 bfd_echo_xmttimer_update(bfd, jitter);
259 else
260 bfd_xmttimer_update(bfd, jitter);
261 }
262
263 static void ptm_bfd_echo_xmt_TO(struct bfd_session *bfd)
264 {
265 /* Send the scheduled echo packet */
266 ptm_bfd_echo_snd(bfd);
267
268 /* Restart the timer for next time */
269 ptm_bfd_start_xmt_timer(bfd, true);
270 }
271
272 void ptm_bfd_xmt_TO(struct bfd_session *bfd, int fbit)
273 {
274 /* Send the scheduled control packet */
275 ptm_bfd_snd(bfd, fbit);
276
277 /* Restart the timer for next time */
278 ptm_bfd_start_xmt_timer(bfd, false);
279 }
280
281 void ptm_bfd_echo_stop(struct bfd_session *bfd)
282 {
283 bfd->echo_xmt_TO = 0;
284 bfd->echo_detect_TO = 0;
285 BFD_UNSET_FLAG(bfd->flags, BFD_SESS_FLAG_ECHO_ACTIVE);
286
287 bfd_echo_xmttimer_delete(bfd);
288 bfd_echo_recvtimer_delete(bfd);
289 }
290
291 void ptm_bfd_echo_start(struct bfd_session *bfd)
292 {
293 bfd->echo_detect_TO = (bfd->remote_detect_mult * bfd->echo_xmt_TO);
294 if (bfd->echo_detect_TO > 0)
295 ptm_bfd_echo_xmt_TO(bfd);
296 }
297
298 void ptm_bfd_sess_up(struct bfd_session *bfd)
299 {
300 int old_state = bfd->ses_state;
301
302 bfd->local_diag = 0;
303 bfd->ses_state = PTM_BFD_UP;
304 monotime(&bfd->uptime);
305
306 /* Connection is up, lets negotiate timers. */
307 bfd_set_polling(bfd);
308
309 /* Start sending control packets with poll bit immediately. */
310 ptm_bfd_snd(bfd, 0);
311
312 control_notify(bfd, bfd->ses_state);
313
314 if (old_state != bfd->ses_state) {
315 bfd->stats.session_up++;
316 log_info("state-change: [%s] %s -> %s", bs_to_string(bfd),
317 state_list[old_state].str,
318 state_list[bfd->ses_state].str);
319 }
320 }
321
322 void ptm_bfd_sess_dn(struct bfd_session *bfd, uint8_t diag)
323 {
324 int old_state = bfd->ses_state;
325
326 bfd->local_diag = diag;
327 bfd->discrs.remote_discr = 0;
328 bfd->ses_state = PTM_BFD_DOWN;
329 bfd->polling = 0;
330 bfd->demand_mode = 0;
331 monotime(&bfd->downtime);
332
333 ptm_bfd_snd(bfd, 0);
334
335 /* Slow down the control packets, the connection is down. */
336 bs_set_slow_timers(bfd);
337
338 /* only signal clients when going from up->down state */
339 if (old_state == PTM_BFD_UP)
340 control_notify(bfd, PTM_BFD_DOWN);
341
342 /* Stop echo packet transmission if they are active */
343 if (BFD_CHECK_FLAG(bfd->flags, BFD_SESS_FLAG_ECHO_ACTIVE))
344 ptm_bfd_echo_stop(bfd);
345
346 if (old_state != bfd->ses_state) {
347 bfd->stats.session_down++;
348 log_info("state-change: [%s] %s -> %s reason:%s",
349 bs_to_string(bfd), state_list[old_state].str,
350 state_list[bfd->ses_state].str,
351 get_diag_str(bfd->local_diag));
352 }
353 }
354
355 static struct bfd_session *bfd_find_disc(struct sockaddr_any *sa,
356 uint32_t ldisc)
357 {
358 struct bfd_session *bs;
359
360 bs = bfd_id_lookup(ldisc);
361 if (bs == NULL)
362 return NULL;
363
364 switch (bs->key.family) {
365 case AF_INET:
366 if (memcmp(&sa->sa_sin.sin_addr, &bs->key.peer,
367 sizeof(sa->sa_sin.sin_addr)))
368 return NULL;
369 break;
370 case AF_INET6:
371 if (memcmp(&sa->sa_sin6.sin6_addr, &bs->key.peer,
372 sizeof(sa->sa_sin6.sin6_addr)))
373 return NULL;
374 break;
375 }
376
377 return bs;
378 }
379
380 struct bfd_session *ptm_bfd_sess_find(struct bfd_pkt *cp,
381 struct sockaddr_any *peer,
382 struct sockaddr_any *local,
383 ifindex_t ifindex, vrf_id_t vrfid,
384 bool is_mhop)
385 {
386 struct interface *ifp;
387 struct vrf *vrf;
388 struct bfd_key key;
389
390 /* Find our session using the ID signaled by the remote end. */
391 if (cp->discrs.remote_discr)
392 return bfd_find_disc(peer, ntohl(cp->discrs.remote_discr));
393
394 /* Search for session without using discriminator. */
395 ifp = if_lookup_by_index(ifindex, vrfid);
396
397 vrf = vrf_lookup_by_id(vrfid);
398
399 gen_bfd_key(&key, peer, local, is_mhop, ifp ? ifp->name : NULL,
400 vrf ? vrf->name : VRF_DEFAULT_NAME);
401
402 /* XXX maybe remoteDiscr should be checked for remoteHeard cases. */
403 return bfd_key_lookup(key);
404 }
405
406 int bfd_xmt_cb(struct thread *t)
407 {
408 struct bfd_session *bs = THREAD_ARG(t);
409
410 ptm_bfd_xmt_TO(bs, 0);
411
412 return 0;
413 }
414
415 int bfd_echo_xmt_cb(struct thread *t)
416 {
417 struct bfd_session *bs = THREAD_ARG(t);
418
419 if (bs->echo_xmt_TO > 0)
420 ptm_bfd_echo_xmt_TO(bs);
421
422 return 0;
423 }
424
425 /* Was ptm_bfd_detect_TO() */
426 int bfd_recvtimer_cb(struct thread *t)
427 {
428 struct bfd_session *bs = THREAD_ARG(t);
429
430 switch (bs->ses_state) {
431 case PTM_BFD_INIT:
432 case PTM_BFD_UP:
433 ptm_bfd_sess_dn(bs, BD_CONTROL_EXPIRED);
434 bfd_recvtimer_update(bs);
435 break;
436
437 default:
438 /* Second detect time expiration, zero remote discr (section
439 * 6.5.1)
440 */
441 bs->discrs.remote_discr = 0;
442 break;
443 }
444
445 return 0;
446 }
447
448 /* Was ptm_bfd_echo_detect_TO() */
449 int bfd_echo_recvtimer_cb(struct thread *t)
450 {
451 struct bfd_session *bs = THREAD_ARG(t);
452
453 switch (bs->ses_state) {
454 case PTM_BFD_INIT:
455 case PTM_BFD_UP:
456 ptm_bfd_sess_dn(bs, BD_ECHO_FAILED);
457 break;
458 }
459
460 return 0;
461 }
462
463 struct bfd_session *bfd_session_new(void)
464 {
465 struct bfd_session *bs;
466
467 bs = XCALLOC(MTYPE_BFDD_CONFIG, sizeof(*bs));
468
469 bs->timers.desired_min_tx = BFD_DEFDESIREDMINTX;
470 bs->timers.required_min_rx = BFD_DEFREQUIREDMINRX;
471 bs->timers.required_min_echo = BFD_DEF_REQ_MIN_ECHO;
472 bs->detect_mult = BFD_DEFDETECTMULT;
473 bs->mh_ttl = BFD_DEF_MHOP_TTL;
474 bs->ses_state = PTM_BFD_DOWN;
475
476 /* Initiate connection with slow timers. */
477 bs_set_slow_timers(bs);
478
479 /* Initiate remote settings as well. */
480 bs->remote_timers = bs->cur_timers;
481 bs->remote_detect_mult = BFD_DEFDETECTMULT;
482
483 bs->sock = -1;
484 monotime(&bs->uptime);
485 bs->downtime = bs->uptime;
486
487 return bs;
488 }
489
490 int bfd_session_update_label(struct bfd_session *bs, const char *nlabel)
491 {
492 /* New label treatment:
493 * - Check if the label is taken;
494 * - Try to allocate the memory for it and register;
495 */
496 if (bs->pl == NULL) {
497 if (pl_find(nlabel) != NULL) {
498 /* Someone is already using it. */
499 return -1;
500 }
501
502 if (pl_new(nlabel, bs) == NULL)
503 return -1;
504
505 return 0;
506 }
507
508 /*
509 * Test label change consistency:
510 * - Do nothing if it's the same label;
511 * - Check if the future label is already taken;
512 * - Change label;
513 */
514 if (strcmp(nlabel, bs->pl->pl_label) == 0)
515 return -1;
516 if (pl_find(nlabel) != NULL)
517 return -1;
518
519 strlcpy(bs->pl->pl_label, nlabel, sizeof(bs->pl->pl_label));
520 return 0;
521 }
522
523 static void _bfd_session_update(struct bfd_session *bs,
524 struct bfd_peer_cfg *bpc)
525 {
526 if (bpc->bpc_echo) {
527 /* Check if echo mode is already active. */
528 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_ECHO))
529 goto skip_echo;
530
531 BFD_SET_FLAG(bs->flags, BFD_SESS_FLAG_ECHO);
532
533 /* Activate/update echo receive timeout timer. */
534 bs_echo_timer_handler(bs);
535 } else {
536 /* Check if echo mode is already disabled. */
537 if (!BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_ECHO))
538 goto skip_echo;
539
540 BFD_UNSET_FLAG(bs->flags, BFD_SESS_FLAG_ECHO);
541 ptm_bfd_echo_stop(bs);
542 }
543
544 skip_echo:
545 if (bpc->bpc_has_txinterval)
546 bs->timers.desired_min_tx = bpc->bpc_txinterval * 1000;
547
548 if (bpc->bpc_has_recvinterval)
549 bs->timers.required_min_rx = bpc->bpc_recvinterval * 1000;
550
551 if (bpc->bpc_has_detectmultiplier)
552 bs->detect_mult = bpc->bpc_detectmultiplier;
553
554 if (bpc->bpc_has_echointerval)
555 bs->timers.required_min_echo = bpc->bpc_echointerval * 1000;
556
557 if (bpc->bpc_has_label)
558 bfd_session_update_label(bs, bpc->bpc_label);
559
560 if (bpc->bpc_shutdown) {
561 /* Check if already shutdown. */
562 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_SHUTDOWN))
563 return;
564
565 BFD_SET_FLAG(bs->flags, BFD_SESS_FLAG_SHUTDOWN);
566
567 /* Disable all events. */
568 bfd_recvtimer_delete(bs);
569 bfd_echo_recvtimer_delete(bs);
570 bfd_xmttimer_delete(bs);
571 bfd_echo_xmttimer_delete(bs);
572
573 /* Change and notify state change. */
574 bs->ses_state = PTM_BFD_ADM_DOWN;
575 control_notify(bs, bs->ses_state);
576
577 /* Don't try to send packets with a disabled session. */
578 if (bs->sock != -1)
579 ptm_bfd_snd(bs, 0);
580 } else {
581 /* Check if already working. */
582 if (!BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_SHUTDOWN))
583 return;
584
585 BFD_UNSET_FLAG(bs->flags, BFD_SESS_FLAG_SHUTDOWN);
586
587 /* Change and notify state change. */
588 bs->ses_state = PTM_BFD_DOWN;
589 control_notify(bs, bs->ses_state);
590
591 /* Enable all timers. */
592 bfd_recvtimer_update(bs);
593 bfd_xmttimer_update(bs, bs->xmt_TO);
594 }
595 if (bpc->bpc_cbit) {
596 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_CBIT))
597 return;
598
599 BFD_SET_FLAG(bs->flags, BFD_SESS_FLAG_CBIT);
600 } else {
601 if (!BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_CBIT))
602 return;
603
604 BFD_UNSET_FLAG(bs->flags, BFD_SESS_FLAG_CBIT);
605 }
606 }
607
608 static int bfd_session_update(struct bfd_session *bs, struct bfd_peer_cfg *bpc)
609 {
610 /* User didn't want to update, return failure. */
611 if (bpc->bpc_createonly)
612 return -1;
613
614 _bfd_session_update(bs, bpc);
615
616 control_notify_config(BCM_NOTIFY_CONFIG_UPDATE, bs);
617
618 return 0;
619 }
620
621 void bfd_session_free(struct bfd_session *bs)
622 {
623 struct bfd_session_observer *bso;
624
625 bfd_session_disable(bs);
626
627 bfd_key_delete(bs->key);
628 bfd_id_delete(bs->discrs.my_discr);
629
630 /* Remove observer if any. */
631 TAILQ_FOREACH(bso, &bglobal.bg_obslist, bso_entry) {
632 if (bso->bso_bs != bs)
633 continue;
634
635 break;
636 }
637 if (bso != NULL)
638 bs_observer_del(bso);
639
640 pl_free(bs->pl);
641
642 XFREE(MTYPE_BFDD_CONFIG, bs);
643 }
644
645 struct bfd_session *ptm_bfd_sess_new(struct bfd_peer_cfg *bpc)
646 {
647 struct bfd_session *bfd, *l_bfd;
648
649 /* check to see if this needs a new session */
650 l_bfd = bs_peer_find(bpc);
651 if (l_bfd) {
652 /* Requesting a duplicated peer means update configuration. */
653 if (bfd_session_update(l_bfd, bpc) == 0)
654 return l_bfd;
655 else
656 return NULL;
657 }
658
659 /* Get BFD session storage with its defaults. */
660 bfd = bfd_session_new();
661 if (bfd == NULL) {
662 log_error("session-new: allocation failed");
663 return NULL;
664 }
665
666 /*
667 * Store interface/VRF name in case we need to delay session
668 * start. See `bfd_session_enable` for more information.
669 */
670 if (bpc->bpc_has_localif)
671 strlcpy(bfd->key.ifname, bpc->bpc_localif,
672 sizeof(bfd->key.ifname));
673
674 if (bpc->bpc_has_vrfname)
675 strlcpy(bfd->key.vrfname, bpc->bpc_vrfname,
676 sizeof(bfd->key.vrfname));
677 else
678 strlcpy(bfd->key.vrfname, VRF_DEFAULT_NAME,
679 sizeof(bfd->key.vrfname));
680
681 /* Copy remaining data. */
682 if (bpc->bpc_ipv4 == false)
683 BFD_SET_FLAG(bfd->flags, BFD_SESS_FLAG_IPV6);
684
685 bfd->key.family = (bpc->bpc_ipv4) ? AF_INET : AF_INET6;
686 switch (bfd->key.family) {
687 case AF_INET:
688 memcpy(&bfd->key.peer, &bpc->bpc_peer.sa_sin.sin_addr,
689 sizeof(bpc->bpc_peer.sa_sin.sin_addr));
690 memcpy(&bfd->key.local, &bpc->bpc_local.sa_sin.sin_addr,
691 sizeof(bpc->bpc_local.sa_sin.sin_addr));
692 break;
693
694 case AF_INET6:
695 memcpy(&bfd->key.peer, &bpc->bpc_peer.sa_sin6.sin6_addr,
696 sizeof(bpc->bpc_peer.sa_sin6.sin6_addr));
697 memcpy(&bfd->key.local, &bpc->bpc_local.sa_sin6.sin6_addr,
698 sizeof(bpc->bpc_local.sa_sin6.sin6_addr));
699 break;
700
701 default:
702 assert(1);
703 break;
704 }
705
706 if (bpc->bpc_mhop)
707 BFD_SET_FLAG(bfd->flags, BFD_SESS_FLAG_MH);
708
709 bfd->key.mhop = bpc->bpc_mhop;
710
711 if (bs_registrate(bfd) == NULL)
712 return NULL;
713
714 /* Apply other configurations. */
715 _bfd_session_update(bfd, bpc);
716
717 return bfd;
718 }
719
720 struct bfd_session *bs_registrate(struct bfd_session *bfd)
721 {
722 /* Registrate session into data structures. */
723 bfd_key_insert(bfd);
724 bfd->discrs.my_discr = ptm_bfd_gen_ID();
725 bfd_id_insert(bfd);
726
727 /* Try to enable session and schedule for packet receive/send. */
728 if (bfd_session_enable(bfd) == -1) {
729 /* Unrecoverable failure, remove the session/peer. */
730 bfd_session_free(bfd);
731 return NULL;
732 }
733
734 /* Add observer if we have moving parts. */
735 if (bfd->key.ifname[0] || bfd->key.vrfname[0] || bfd->sock == -1)
736 bs_observer_add(bfd);
737
738 log_info("session-new: %s", bs_to_string(bfd));
739
740 control_notify_config(BCM_NOTIFY_CONFIG_ADD, bfd);
741
742 return bfd;
743 }
744
745 int ptm_bfd_sess_del(struct bfd_peer_cfg *bpc)
746 {
747 struct bfd_session *bs;
748
749 /* Find session and call free(). */
750 bs = bs_peer_find(bpc);
751 if (bs == NULL)
752 return -1;
753
754 /* This pointer is being referenced, don't let it be deleted. */
755 if (bs->refcount > 0) {
756 log_error("session-delete: refcount failure: %" PRIu64
757 " references",
758 bs->refcount);
759 return -1;
760 }
761
762 log_info("session-delete: %s", bs_to_string(bs));
763
764 control_notify_config(BCM_NOTIFY_CONFIG_DELETE, bs);
765
766 bfd_session_free(bs);
767
768 return 0;
769 }
770
771 void bfd_set_polling(struct bfd_session *bs)
772 {
773 /*
774 * Start polling procedure: the only timers that require polling
775 * to change value without losing connection are:
776 *
777 * - Desired minimum transmission interval;
778 * - Required minimum receive interval;
779 *
780 * RFC 5880, Section 6.8.3.
781 */
782 bs->polling = 1;
783 }
784
785 /*
786 * bs_<state>_handler() functions implement the BFD state machine
787 * transition mechanism. `<state>` is the current session state and
788 * the parameter `nstate` is the peer new state.
789 */
790 static void bs_admin_down_handler(struct bfd_session *bs
791 __attribute__((__unused__)),
792 int nstate __attribute__((__unused__)))
793 {
794 /*
795 * We are administratively down, there is no state machine
796 * handling.
797 */
798 }
799
800 static void bs_down_handler(struct bfd_session *bs, int nstate)
801 {
802 switch (nstate) {
803 case PTM_BFD_ADM_DOWN:
804 /*
805 * Remote peer doesn't want to talk, so lets keep the
806 * connection down.
807 */
808 case PTM_BFD_UP:
809 /* Peer can't be up yet, wait it go to 'init' or 'down'. */
810 break;
811
812 case PTM_BFD_DOWN:
813 /*
814 * Remote peer agreed that the path is down, lets try to
815 * bring it up.
816 */
817 bs->ses_state = PTM_BFD_INIT;
818 break;
819
820 case PTM_BFD_INIT:
821 /*
822 * Remote peer told us his path is up, lets turn
823 * activate the session.
824 */
825 ptm_bfd_sess_up(bs);
826 break;
827
828 default:
829 log_debug("state-change: unhandled neighbor state: %d", nstate);
830 break;
831 }
832 }
833
834 static void bs_init_handler(struct bfd_session *bs, int nstate)
835 {
836 switch (nstate) {
837 case PTM_BFD_ADM_DOWN:
838 /*
839 * Remote peer doesn't want to talk, so lets make the
840 * connection down.
841 */
842 bs->ses_state = PTM_BFD_DOWN;
843 break;
844
845 case PTM_BFD_DOWN:
846 /* Remote peer hasn't moved to first stage yet. */
847 break;
848
849 case PTM_BFD_INIT:
850 case PTM_BFD_UP:
851 /* We agreed on the settings and the path is up. */
852 ptm_bfd_sess_up(bs);
853 break;
854
855 default:
856 log_debug("state-change: unhandled neighbor state: %d", nstate);
857 break;
858 }
859 }
860
861 static void bs_neighbour_admin_down_handler(struct bfd_session *bfd,
862 uint8_t diag)
863 {
864 int old_state = bfd->ses_state;
865
866 bfd->local_diag = diag;
867 bfd->discrs.remote_discr = 0;
868 bfd->ses_state = PTM_BFD_DOWN;
869 bfd->polling = 0;
870 bfd->demand_mode = 0;
871 monotime(&bfd->downtime);
872
873 /* Slow down the control packets, the connection is down. */
874 bs_set_slow_timers(bfd);
875
876 /* only signal clients when going from up->down state */
877 if (old_state == PTM_BFD_UP)
878 control_notify(bfd, PTM_BFD_ADM_DOWN);
879
880 /* Stop echo packet transmission if they are active */
881 if (BFD_CHECK_FLAG(bfd->flags, BFD_SESS_FLAG_ECHO_ACTIVE))
882 ptm_bfd_echo_stop(bfd);
883
884 if (old_state != bfd->ses_state) {
885 bfd->stats.session_down++;
886
887 log_info("state-change: [%s] %s -> %s reason:%s",
888 bs_to_string(bfd), state_list[old_state].str,
889 state_list[bfd->ses_state].str,
890 get_diag_str(bfd->local_diag));
891 }
892 }
893
894 static void bs_up_handler(struct bfd_session *bs, int nstate)
895 {
896 switch (nstate) {
897 case PTM_BFD_ADM_DOWN:
898 bs_neighbour_admin_down_handler(bs, BD_ADMIN_DOWN);
899 break;
900
901 case PTM_BFD_DOWN:
902 /* Peer lost or asked to shutdown connection. */
903 ptm_bfd_sess_dn(bs, BD_NEIGHBOR_DOWN);
904 break;
905
906 case PTM_BFD_INIT:
907 case PTM_BFD_UP:
908 /* Path is up and working. */
909 break;
910
911 default:
912 log_debug("state-change: unhandled neighbor state: %d", nstate);
913 break;
914 }
915 }
916
917 void bs_state_handler(struct bfd_session *bs, int nstate)
918 {
919 switch (bs->ses_state) {
920 case PTM_BFD_ADM_DOWN:
921 bs_admin_down_handler(bs, nstate);
922 break;
923 case PTM_BFD_DOWN:
924 bs_down_handler(bs, nstate);
925 break;
926 case PTM_BFD_INIT:
927 bs_init_handler(bs, nstate);
928 break;
929 case PTM_BFD_UP:
930 bs_up_handler(bs, nstate);
931 break;
932
933 default:
934 log_debug("state-change: [%s] is in invalid state: %d",
935 bs_to_string(bs), nstate);
936 break;
937 }
938 }
939
940 /*
941 * Handles echo timer manipulation after updating timer.
942 */
943 void bs_echo_timer_handler(struct bfd_session *bs)
944 {
945 uint32_t old_timer;
946
947 /*
948 * Before doing any echo handling, check if it is possible to
949 * use it.
950 *
951 * - Check for `echo-mode` configuration.
952 * - Check that we are not using multi hop (RFC 5883,
953 * Section 3).
954 * - Check that we are already at the up state.
955 */
956 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_ECHO) == 0
957 || BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_MH)
958 || bs->ses_state != PTM_BFD_UP)
959 return;
960
961 /* Remote peer asked to stop echo. */
962 if (bs->remote_timers.required_min_echo == 0) {
963 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_ECHO_ACTIVE))
964 ptm_bfd_echo_stop(bs);
965
966 return;
967 }
968
969 /*
970 * Calculate the echo transmission timer: we must not send
971 * echo packets faster than the minimum required time
972 * announced by the remote system.
973 *
974 * RFC 5880, Section 6.8.9.
975 */
976 old_timer = bs->echo_xmt_TO;
977 if (bs->remote_timers.required_min_echo > bs->timers.required_min_echo)
978 bs->echo_xmt_TO = bs->remote_timers.required_min_echo;
979 else
980 bs->echo_xmt_TO = bs->timers.required_min_echo;
981
982 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_ECHO_ACTIVE) == 0
983 || old_timer != bs->echo_xmt_TO)
984 ptm_bfd_echo_start(bs);
985 }
986
987 /*
988 * RFC 5880 Section 6.5.
989 *
990 * When a BFD control packet with the final bit is received, we must
991 * update the session parameters.
992 */
993 void bs_final_handler(struct bfd_session *bs)
994 {
995 /* Start using our new timers. */
996 bs->cur_timers.desired_min_tx = bs->timers.desired_min_tx;
997 bs->cur_timers.required_min_rx = bs->timers.required_min_rx;
998
999 /*
1000 * TODO: demand mode. See RFC 5880 Section 6.1.
1001 *
1002 * When using demand mode we must disable the detection timer
1003 * for lost control packets.
1004 */
1005 if (bs->demand_mode) {
1006 /* Notify watchers about changed timers. */
1007 control_notify_config(BCM_NOTIFY_CONFIG_UPDATE, bs);
1008 return;
1009 }
1010
1011 /*
1012 * Calculate detection time based on new timers.
1013 *
1014 * Transmission calculation:
1015 * We must respect the RequiredMinRxInterval from the remote
1016 * system: if our desired transmission timer is more than the
1017 * minimum receive rate, then we must lower it to at least the
1018 * minimum receive interval.
1019 *
1020 * RFC 5880, Section 6.8.3.
1021 */
1022 if (bs->timers.desired_min_tx > bs->remote_timers.required_min_rx)
1023 bs->xmt_TO = bs->remote_timers.required_min_rx;
1024 else
1025 bs->xmt_TO = bs->timers.desired_min_tx;
1026
1027 /* Apply new transmission timer immediately. */
1028 ptm_bfd_start_xmt_timer(bs, false);
1029
1030 /*
1031 * Detection timeout calculation:
1032 * The minimum detection timeout is the remote detection
1033 * multipler (number of packets to be missed) times the agreed
1034 * transmission interval.
1035 *
1036 * RFC 5880, Section 6.8.4.
1037 *
1038 * TODO: support sending/counting more packets inside detection
1039 * timeout.
1040 */
1041 if (bs->remote_timers.required_min_rx > bs->timers.desired_min_tx)
1042 bs->detect_TO = bs->remote_detect_mult
1043 * bs->remote_timers.required_min_rx;
1044 else
1045 bs->detect_TO = bs->remote_detect_mult
1046 * bs->timers.desired_min_tx;
1047
1048 /* Apply new receive timer immediately. */
1049 bfd_recvtimer_update(bs);
1050
1051 /* Notify watchers about changed timers. */
1052 control_notify_config(BCM_NOTIFY_CONFIG_UPDATE, bs);
1053 }
1054
1055 void bs_set_slow_timers(struct bfd_session *bs)
1056 {
1057 /*
1058 * BFD connection must use slow timers before going up or after
1059 * losing connectivity to avoid wasting bandwidth.
1060 *
1061 * RFC 5880, Section 6.8.3.
1062 */
1063 bs->cur_timers.desired_min_tx = BFD_DEF_SLOWTX;
1064 bs->cur_timers.required_min_rx = BFD_DEF_SLOWTX;
1065 bs->cur_timers.required_min_echo = 0;
1066
1067 /* Set the appropriated timeouts for slow connection. */
1068 bs->detect_TO = (BFD_DEFDETECTMULT * BFD_DEF_SLOWTX);
1069 bs->xmt_TO = BFD_DEF_SLOWTX;
1070 }
1071
1072 /*
1073 * Helper functions.
1074 */
1075 static const char *get_diag_str(int diag)
1076 {
1077 for (int i = 0; diag_list[i].str; i++) {
1078 if (diag_list[i].type == diag)
1079 return diag_list[i].str;
1080 }
1081 return "N/A";
1082 }
1083
1084 const char *satostr(struct sockaddr_any *sa)
1085 {
1086 #define INETSTR_BUFCOUNT 8
1087 static char buf[INETSTR_BUFCOUNT][INET6_ADDRSTRLEN];
1088 static int bufidx;
1089 struct sockaddr_in *sin = &sa->sa_sin;
1090 struct sockaddr_in6 *sin6 = &sa->sa_sin6;
1091
1092 bufidx += (bufidx + 1) % INETSTR_BUFCOUNT;
1093 buf[bufidx][0] = 0;
1094
1095 switch (sin->sin_family) {
1096 case AF_INET:
1097 inet_ntop(AF_INET, &sin->sin_addr, buf[bufidx],
1098 sizeof(buf[bufidx]));
1099 break;
1100 case AF_INET6:
1101 inet_ntop(AF_INET6, &sin6->sin6_addr, buf[bufidx],
1102 sizeof(buf[bufidx]));
1103 break;
1104
1105 default:
1106 strlcpy(buf[bufidx], "unknown", sizeof(buf[bufidx]));
1107 break;
1108 }
1109
1110 return buf[bufidx];
1111 }
1112
1113 const char *diag2str(uint8_t diag)
1114 {
1115 switch (diag) {
1116 case 0:
1117 return "ok";
1118 case 1:
1119 return "control detection time expired";
1120 case 2:
1121 return "echo function failed";
1122 case 3:
1123 return "neighbor signaled session down";
1124 case 4:
1125 return "forwarding plane reset";
1126 case 5:
1127 return "path down";
1128 case 6:
1129 return "concatenated path down";
1130 case 7:
1131 return "administratively down";
1132 case 8:
1133 return "reverse concatenated path down";
1134 default:
1135 return "unknown";
1136 }
1137 }
1138
1139 int strtosa(const char *addr, struct sockaddr_any *sa)
1140 {
1141 memset(sa, 0, sizeof(*sa));
1142
1143 if (inet_pton(AF_INET, addr, &sa->sa_sin.sin_addr) == 1) {
1144 sa->sa_sin.sin_family = AF_INET;
1145 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1146 sa->sa_sin.sin_len = sizeof(sa->sa_sin);
1147 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
1148 return 0;
1149 }
1150
1151 if (inet_pton(AF_INET6, addr, &sa->sa_sin6.sin6_addr) == 1) {
1152 sa->sa_sin6.sin6_family = AF_INET6;
1153 #ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
1154 sa->sa_sin6.sin6_len = sizeof(sa->sa_sin6);
1155 #endif /* HAVE_STRUCT_SOCKADDR_SA_LEN */
1156 return 0;
1157 }
1158
1159 return -1;
1160 }
1161
1162 void integer2timestr(uint64_t time, char *buf, size_t buflen)
1163 {
1164 unsigned int year, month, day, hour, minute, second;
1165 int rv;
1166
1167 #define MINUTES (60)
1168 #define HOURS (60 * MINUTES)
1169 #define DAYS (24 * HOURS)
1170 #define MONTHS (30 * DAYS)
1171 #define YEARS (12 * MONTHS)
1172 if (time >= YEARS) {
1173 year = time / YEARS;
1174 time -= year * YEARS;
1175
1176 rv = snprintf(buf, buflen, "%u year(s), ", year);
1177 buf += rv;
1178 buflen -= rv;
1179 }
1180 if (time >= MONTHS) {
1181 month = time / MONTHS;
1182 time -= month * MONTHS;
1183
1184 rv = snprintf(buf, buflen, "%u month(s), ", month);
1185 buf += rv;
1186 buflen -= rv;
1187 }
1188 if (time >= DAYS) {
1189 day = time / DAYS;
1190 time -= day * DAYS;
1191
1192 rv = snprintf(buf, buflen, "%u day(s), ", day);
1193 buf += rv;
1194 buflen -= rv;
1195 }
1196 if (time >= HOURS) {
1197 hour = time / HOURS;
1198 time -= hour * HOURS;
1199
1200 rv = snprintf(buf, buflen, "%u hour(s), ", hour);
1201 buf += rv;
1202 buflen -= rv;
1203 }
1204 if (time >= MINUTES) {
1205 minute = time / MINUTES;
1206 time -= minute * MINUTES;
1207
1208 rv = snprintf(buf, buflen, "%u minute(s), ", minute);
1209 buf += rv;
1210 buflen -= rv;
1211 }
1212 second = time % MINUTES;
1213 snprintf(buf, buflen, "%u second(s)", second);
1214 }
1215
1216 const char *bs_to_string(const struct bfd_session *bs)
1217 {
1218 static char buf[256];
1219 char addr_buf[INET6_ADDRSTRLEN];
1220 int pos;
1221 bool is_mhop = BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_MH);
1222
1223 pos = snprintf(buf, sizeof(buf), "mhop:%s", is_mhop ? "yes" : "no");
1224 pos += snprintf(buf + pos, sizeof(buf) - pos, " peer:%s",
1225 inet_ntop(bs->key.family, &bs->key.peer, addr_buf,
1226 sizeof(addr_buf)));
1227 pos += snprintf(buf + pos, sizeof(buf) - pos, " local:%s",
1228 inet_ntop(bs->key.family, &bs->key.local, addr_buf,
1229 sizeof(addr_buf)));
1230 if (bs->key.vrfname[0])
1231 pos += snprintf(buf + pos, sizeof(buf) - pos, " vrf:%s",
1232 bs->key.vrfname);
1233 if (bs->key.ifname[0])
1234 pos += snprintf(buf + pos, sizeof(buf) - pos, " ifname:%s",
1235 bs->key.ifname);
1236
1237 (void)pos;
1238
1239 return buf;
1240 }
1241
1242 int bs_observer_add(struct bfd_session *bs)
1243 {
1244 struct bfd_session_observer *bso;
1245
1246 bso = XCALLOC(MTYPE_BFDD_SESSION_OBSERVER, sizeof(*bso));
1247 bso->bso_isaddress = false;
1248 bso->bso_bs = bs;
1249 bso->bso_isinterface = !BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_MH);
1250 if (bso->bso_isinterface)
1251 strlcpy(bso->bso_entryname, bs->key.ifname,
1252 sizeof(bso->bso_entryname));
1253 /* Handle socket binding failures caused by missing local addresses. */
1254 if (bs->sock == -1) {
1255 bso->bso_isaddress = true;
1256 bso->bso_addr.family = bs->key.family;
1257 memcpy(&bso->bso_addr.u.prefix, &bs->key.local,
1258 sizeof(bs->key.local));
1259 }
1260
1261 TAILQ_INSERT_TAIL(&bglobal.bg_obslist, bso, bso_entry);
1262
1263 return 0;
1264 }
1265
1266 void bs_observer_del(struct bfd_session_observer *bso)
1267 {
1268 TAILQ_REMOVE(&bglobal.bg_obslist, bso, bso_entry);
1269 XFREE(MTYPE_BFDD_SESSION_OBSERVER, bso);
1270 }
1271
1272 void bs_to_bpc(struct bfd_session *bs, struct bfd_peer_cfg *bpc)
1273 {
1274 memset(bpc, 0, sizeof(*bpc));
1275
1276 bpc->bpc_ipv4 = (bs->key.family == AF_INET);
1277 bpc->bpc_mhop = bs->key.mhop;
1278
1279 switch (bs->key.family) {
1280 case AF_INET:
1281 bpc->bpc_peer.sa_sin.sin_family = AF_INET;
1282 memcpy(&bpc->bpc_peer.sa_sin.sin_addr, &bs->key.peer,
1283 sizeof(bpc->bpc_peer.sa_sin.sin_addr));
1284
1285 if (memcmp(&bs->key.local, &zero_addr, sizeof(bs->key.local))) {
1286 bpc->bpc_local.sa_sin.sin_family = AF_INET6;
1287 memcpy(&bpc->bpc_local.sa_sin.sin_addr, &bs->key.local,
1288 sizeof(bpc->bpc_local.sa_sin.sin_addr));
1289 }
1290 break;
1291
1292 case AF_INET6:
1293 bpc->bpc_peer.sa_sin.sin_family = AF_INET6;
1294 memcpy(&bpc->bpc_peer.sa_sin6.sin6_addr, &bs->key.peer,
1295 sizeof(bpc->bpc_peer.sa_sin6.sin6_addr));
1296
1297 bpc->bpc_local.sa_sin6.sin6_family = AF_INET6;
1298 memcpy(&bpc->bpc_local.sa_sin6.sin6_addr, &bs->key.local,
1299 sizeof(bpc->bpc_local.sa_sin6.sin6_addr));
1300 break;
1301 }
1302
1303 if (bs->key.ifname[0]) {
1304 bpc->bpc_has_localif = true;
1305 strlcpy(bpc->bpc_localif, bs->key.ifname,
1306 sizeof(bpc->bpc_localif));
1307 }
1308
1309 if (bs->key.vrfname[0]) {
1310 bpc->bpc_has_vrfname = true;
1311 strlcpy(bpc->bpc_vrfname, bs->key.vrfname,
1312 sizeof(bpc->bpc_vrfname));
1313 }
1314 }
1315
1316
1317 /*
1318 * BFD hash data structures to find sessions.
1319 */
1320 static struct hash *bfd_id_hash;
1321 static struct hash *bfd_key_hash;
1322
1323 static unsigned int bfd_id_hash_do(const void *p);
1324 static unsigned int bfd_key_hash_do(const void *p);
1325
1326 static void _bfd_free(struct hash_bucket *hb,
1327 void *arg __attribute__((__unused__)));
1328
1329 /* BFD hash for our discriminator. */
1330 static unsigned int bfd_id_hash_do(const void *p)
1331 {
1332 const struct bfd_session *bs = p;
1333
1334 return jhash_1word(bs->discrs.my_discr, 0);
1335 }
1336
1337 static bool bfd_id_hash_cmp(const void *n1, const void *n2)
1338 {
1339 const struct bfd_session *bs1 = n1, *bs2 = n2;
1340
1341 return bs1->discrs.my_discr == bs2->discrs.my_discr;
1342 }
1343
1344 /* BFD hash for single hop. */
1345 static unsigned int bfd_key_hash_do(const void *p)
1346 {
1347 const struct bfd_session *bs = p;
1348
1349 return jhash(&bs->key, sizeof(bs->key), 0);
1350 }
1351
1352 static bool bfd_key_hash_cmp(const void *n1, const void *n2)
1353 {
1354 const struct bfd_session *bs1 = n1, *bs2 = n2;
1355
1356 return memcmp(&bs1->key, &bs2->key, sizeof(bs1->key)) == 0;
1357 }
1358
1359
1360 /*
1361 * Hash public interface / exported functions.
1362 */
1363
1364 /* Lookup functions. */
1365 struct bfd_session *bfd_id_lookup(uint32_t id)
1366 {
1367 struct bfd_session bs;
1368
1369 bs.discrs.my_discr = id;
1370
1371 return hash_lookup(bfd_id_hash, &bs);
1372 }
1373
1374 struct bfd_key_walk_partial_lookup {
1375 struct bfd_session *given;
1376 struct bfd_session *result;
1377 };
1378
1379 /* ignore some parameters */
1380 static int bfd_key_lookup_ignore_partial_walker(struct hash_bucket *b,
1381 void *data)
1382 {
1383 struct bfd_key_walk_partial_lookup *ctx =
1384 (struct bfd_key_walk_partial_lookup *)data;
1385 struct bfd_session *given = ctx->given;
1386 struct bfd_session *parsed = b->data;
1387
1388 if (given->key.family != parsed->key.family)
1389 return HASHWALK_CONTINUE;
1390 if (given->key.mhop != parsed->key.mhop)
1391 return HASHWALK_CONTINUE;
1392 if (memcmp(&given->key.peer, &parsed->key.peer,
1393 sizeof(struct in6_addr)))
1394 return HASHWALK_CONTINUE;
1395 if (memcmp(given->key.vrfname, parsed->key.vrfname, MAXNAMELEN))
1396 return HASHWALK_CONTINUE;
1397 ctx->result = parsed;
1398 /* ignore localaddr or interface */
1399 return HASHWALK_ABORT;
1400 }
1401
1402 struct bfd_session *bfd_key_lookup(struct bfd_key key)
1403 {
1404 struct bfd_session bs, *bsp;
1405 struct bfd_key_walk_partial_lookup ctx;
1406 char peer_buf[INET6_ADDRSTRLEN];
1407
1408 bs.key = key;
1409 bsp = hash_lookup(bfd_key_hash, &bs);
1410 if (bsp)
1411 return bsp;
1412
1413 inet_ntop(bs.key.family, &bs.key.peer, peer_buf,
1414 sizeof(peer_buf));
1415 /* Handle cases where local-address is optional. */
1416 if (bs.key.family == AF_INET) {
1417 memset(&bs.key.local, 0, sizeof(bs.key.local));
1418 bsp = hash_lookup(bfd_key_hash, &bs);
1419 if (bsp) {
1420 char addr_buf[INET6_ADDRSTRLEN];
1421
1422 inet_ntop(bs.key.family, &key.local, addr_buf,
1423 sizeof(addr_buf));
1424 log_debug(" peer %s found, but loc-addr %s ignored",
1425 peer_buf, addr_buf);
1426 return bsp;
1427 }
1428 }
1429
1430 bs.key = key;
1431 /* Handle cases where ifname is optional. */
1432 if (bs.key.ifname[0]) {
1433 memset(bs.key.ifname, 0, sizeof(bs.key.ifname));
1434 bsp = hash_lookup(bfd_key_hash, &bs);
1435 if (bsp) {
1436 log_debug(" peer %s found, but ifp %s ignored",
1437 peer_buf, key.ifname);
1438 return bsp;
1439 }
1440 }
1441
1442 /* Handle cases where local-address and ifname are optional. */
1443 if (bs.key.family == AF_INET) {
1444 memset(&bs.key.local, 0, sizeof(bs.key.local));
1445 bsp = hash_lookup(bfd_key_hash, &bs);
1446 if (bsp) {
1447 char addr_buf[INET6_ADDRSTRLEN];
1448
1449 inet_ntop(bs.key.family, &bs.key.local, addr_buf,
1450 sizeof(addr_buf));
1451 log_debug(" peer %s found, but ifp %s"
1452 " and loc-addr %s ignored",
1453 peer_buf, key.ifname,
1454 addr_buf);
1455 return bsp;
1456 }
1457 }
1458 bs.key = key;
1459
1460 /* Handle case where a context more complex ctx is present.
1461 * input has no iface nor local-address, but a context may
1462 * exist
1463 */
1464 ctx.result = NULL;
1465 ctx.given = &bs;
1466 hash_walk(bfd_key_hash,
1467 &bfd_key_lookup_ignore_partial_walker,
1468 &ctx);
1469 /* change key */
1470 if (ctx.result) {
1471 bsp = ctx.result;
1472 log_debug(" peer %s found, but ifp"
1473 " and/or loc-addr params ignored");
1474 }
1475 return bsp;
1476 }
1477
1478 /*
1479 * Delete functions.
1480 *
1481 * Delete functions searches and remove the item from the hash and
1482 * returns a pointer to the removed item data. If the item was not found
1483 * then it returns NULL.
1484 *
1485 * The data stored inside the hash is not free()ed, so you must do it
1486 * manually after getting the pointer back.
1487 */
1488 struct bfd_session *bfd_id_delete(uint32_t id)
1489 {
1490 struct bfd_session bs;
1491
1492 bs.discrs.my_discr = id;
1493
1494 return hash_release(bfd_id_hash, &bs);
1495 }
1496
1497 struct bfd_session *bfd_key_delete(struct bfd_key key)
1498 {
1499 struct bfd_session bs, *bsp;
1500
1501 bs.key = key;
1502 bsp = hash_lookup(bfd_key_hash, &bs);
1503 if (bsp == NULL && key.ifname[0]) {
1504 memset(bs.key.ifname, 0, sizeof(bs.key.ifname));
1505 bsp = hash_lookup(bfd_key_hash, &bs);
1506 }
1507
1508 return hash_release(bfd_key_hash, bsp);
1509 }
1510
1511 /* Iteration functions. */
1512 void bfd_id_iterate(hash_iter_func hif, void *arg)
1513 {
1514 hash_iterate(bfd_id_hash, hif, arg);
1515 }
1516
1517 void bfd_key_iterate(hash_iter_func hif, void *arg)
1518 {
1519 hash_iterate(bfd_key_hash, hif, arg);
1520 }
1521
1522 /*
1523 * Insert functions.
1524 *
1525 * Inserts session into hash and returns `true` on success, otherwise
1526 * `false`.
1527 */
1528 bool bfd_id_insert(struct bfd_session *bs)
1529 {
1530 return (hash_get(bfd_id_hash, bs, hash_alloc_intern) == bs);
1531 }
1532
1533 bool bfd_key_insert(struct bfd_session *bs)
1534 {
1535 return (hash_get(bfd_key_hash, bs, hash_alloc_intern) == bs);
1536 }
1537
1538 void bfd_initialize(void)
1539 {
1540 bfd_id_hash = hash_create(bfd_id_hash_do, bfd_id_hash_cmp,
1541 "BFD session discriminator hash");
1542 bfd_key_hash = hash_create(bfd_key_hash_do, bfd_key_hash_cmp,
1543 "BFD session hash");
1544 }
1545
1546 static void _bfd_free(struct hash_bucket *hb,
1547 void *arg __attribute__((__unused__)))
1548 {
1549 struct bfd_session *bs = hb->data;
1550
1551 bfd_session_free(bs);
1552 }
1553
1554 void bfd_shutdown(void)
1555 {
1556 /*
1557 * Close and free all BFD sessions.
1558 *
1559 * _bfd_free() will call bfd_session_free() which will take care
1560 * of removing the session from all hashes, so we just run an
1561 * assert() here to make sure it really happened.
1562 */
1563 bfd_id_iterate(_bfd_free, NULL);
1564 assert(bfd_key_hash->count == 0);
1565
1566 /* Now free the hashes themselves. */
1567 hash_free(bfd_id_hash);
1568 hash_free(bfd_key_hash);
1569 }
1570
1571 struct bfd_session_iterator {
1572 int bsi_stop;
1573 bool bsi_mhop;
1574 const struct bfd_session *bsi_bs;
1575 };
1576
1577 static int _bfd_session_next(struct hash_bucket *hb, void *arg)
1578 {
1579 struct bfd_session_iterator *bsi = arg;
1580 struct bfd_session *bs = hb->data;
1581
1582 /* Previous entry signaled stop. */
1583 if (bsi->bsi_stop == 1) {
1584 /* Match the single/multi hop sessions. */
1585 if (bs->key.mhop != bsi->bsi_mhop)
1586 return HASHWALK_CONTINUE;
1587
1588 bsi->bsi_bs = bs;
1589 return HASHWALK_ABORT;
1590 }
1591
1592 /* We found the current item, stop in the next one. */
1593 if (bsi->bsi_bs == hb->data) {
1594 bsi->bsi_stop = 1;
1595 /* Set entry to NULL to signal end of list. */
1596 bsi->bsi_bs = NULL;
1597 } else if (bsi->bsi_bs == NULL && bsi->bsi_mhop == bs->key.mhop) {
1598 /* We want the first list item. */
1599 bsi->bsi_stop = 1;
1600 bsi->bsi_bs = hb->data;
1601 return HASHWALK_ABORT;
1602 }
1603
1604 return HASHWALK_CONTINUE;
1605 }
1606
1607 /*
1608 * bfd_session_next: uses the current session to find the next.
1609 *
1610 * `bs` might point to NULL to get the first item of the data structure.
1611 */
1612 const struct bfd_session *bfd_session_next(const struct bfd_session *bs,
1613 bool mhop)
1614 {
1615 struct bfd_session_iterator bsi;
1616
1617 bsi.bsi_stop = 0;
1618 bsi.bsi_bs = bs;
1619 bsi.bsi_mhop = mhop;
1620 hash_walk(bfd_key_hash, _bfd_session_next, &bsi);
1621 if (bsi.bsi_stop == 0)
1622 return NULL;
1623
1624 return bsi.bsi_bs;
1625 }
1626
1627 static void _bfd_session_remove_manual(struct hash_bucket *hb,
1628 void *arg __attribute__((__unused__)))
1629 {
1630 struct bfd_session *bs = hb->data;
1631
1632 /* Delete only manually configured sessions. */
1633 if (BFD_CHECK_FLAG(bs->flags, BFD_SESS_FLAG_CONFIG) == 0)
1634 return;
1635
1636 bs->refcount--;
1637 BFD_UNSET_FLAG(bs->flags, BFD_SESS_FLAG_CONFIG);
1638
1639 /* Don't delete sessions still in use. */
1640 if (bs->refcount != 0)
1641 return;
1642
1643 bfd_session_free(bs);
1644 }
1645
1646 /*
1647 * bfd_sessions_remove_manual: remove all manually configured sessions.
1648 *
1649 * NOTE: this function doesn't remove automatically created sessions.
1650 */
1651 void bfd_sessions_remove_manual(void)
1652 {
1653 hash_iterate(bfd_key_hash, _bfd_session_remove_manual, NULL);
1654 }
1655
1656 /*
1657 * VRF related functions.
1658 */
1659 static int bfd_vrf_new(struct vrf *vrf)
1660 {
1661 log_debug("VRF Created: %s(%u)", vrf->name, vrf->vrf_id);
1662 return 0;
1663 }
1664
1665 static int bfd_vrf_delete(struct vrf *vrf)
1666 {
1667 log_debug("VRF Deletion: %s(%u)", vrf->name, vrf->vrf_id);
1668 return 0;
1669 }
1670
1671 static int bfd_vrf_update(struct vrf *vrf)
1672 {
1673 if (!vrf_is_enabled(vrf))
1674 return 0;
1675 log_debug("VRF update: %s(%u)", vrf->name, vrf->vrf_id);
1676 /* a different name is given; update bfd list */
1677 bfdd_sessions_enable_vrf(vrf);
1678 return 0;
1679 }
1680
1681 static int bfd_vrf_enable(struct vrf *vrf)
1682 {
1683 struct bfd_vrf_global *bvrf;
1684
1685 /* a different name */
1686 if (!vrf->info) {
1687 bvrf = XCALLOC(MTYPE_BFDD_VRF, sizeof(struct bfd_vrf_global));
1688 bvrf->vrf = vrf;
1689 vrf->info = (void *)bvrf;
1690 } else
1691 bvrf = vrf->info;
1692 log_debug("VRF enable add %s id %u", vrf->name, vrf->vrf_id);
1693 if (vrf->vrf_id == VRF_DEFAULT ||
1694 vrf_get_backend() == VRF_BACKEND_NETNS) {
1695 if (!bvrf->bg_shop)
1696 bvrf->bg_shop = bp_udp_shop(vrf->vrf_id);
1697 if (!bvrf->bg_mhop)
1698 bvrf->bg_mhop = bp_udp_mhop(vrf->vrf_id);
1699 if (!bvrf->bg_shop6)
1700 bvrf->bg_shop6 = bp_udp6_shop(vrf->vrf_id);
1701 if (!bvrf->bg_mhop6)
1702 bvrf->bg_mhop6 = bp_udp6_mhop(vrf->vrf_id);
1703 if (!bvrf->bg_echo)
1704 bvrf->bg_echo = bp_echo_socket(vrf->vrf_id);
1705 if (!bvrf->bg_echov6)
1706 bvrf->bg_echov6 = bp_echov6_socket(vrf->vrf_id);
1707
1708 /* Add descriptors to the event loop. */
1709 if (!bvrf->bg_ev[0])
1710 thread_add_read(master, bfd_recv_cb, bvrf, bvrf->bg_shop,
1711 &bvrf->bg_ev[0]);
1712 if (!bvrf->bg_ev[1])
1713 thread_add_read(master, bfd_recv_cb, bvrf, bvrf->bg_mhop,
1714 &bvrf->bg_ev[1]);
1715 if (!bvrf->bg_ev[2])
1716 thread_add_read(master, bfd_recv_cb, bvrf, bvrf->bg_shop6,
1717 &bvrf->bg_ev[2]);
1718 if (!bvrf->bg_ev[3])
1719 thread_add_read(master, bfd_recv_cb, bvrf, bvrf->bg_mhop6,
1720 &bvrf->bg_ev[3]);
1721 if (!bvrf->bg_ev[4])
1722 thread_add_read(master, bfd_recv_cb, bvrf, bvrf->bg_echo,
1723 &bvrf->bg_ev[4]);
1724 if (!bvrf->bg_ev[5])
1725 thread_add_read(master, bfd_recv_cb, bvrf, bvrf->bg_echov6,
1726 &bvrf->bg_ev[5]);
1727 }
1728 if (vrf->vrf_id != VRF_DEFAULT) {
1729 bfdd_zclient_register(vrf->vrf_id);
1730 bfdd_sessions_enable_vrf(vrf);
1731 }
1732 return 0;
1733 }
1734
1735 static int bfd_vrf_disable(struct vrf *vrf)
1736 {
1737 struct bfd_vrf_global *bvrf;
1738
1739 if (!vrf->info)
1740 return 0;
1741 bvrf = vrf->info;
1742
1743 if (vrf->vrf_id != VRF_DEFAULT) {
1744 bfdd_sessions_disable_vrf(vrf);
1745 bfdd_zclient_unregister(vrf->vrf_id);
1746 }
1747
1748 log_debug("VRF disable %s id %d", vrf->name, vrf->vrf_id);
1749 /* Close all descriptors. */
1750 socket_close(&bvrf->bg_echo);
1751 socket_close(&bvrf->bg_shop);
1752 socket_close(&bvrf->bg_mhop);
1753 socket_close(&bvrf->bg_shop6);
1754 socket_close(&bvrf->bg_mhop6);
1755 socket_close(&bvrf->bg_echo);
1756 socket_close(&bvrf->bg_echov6);
1757
1758 /* free context */
1759 XFREE(MTYPE_BFDD_VRF, bvrf);
1760 vrf->info = NULL;
1761
1762 return 0;
1763 }
1764
1765 void bfd_vrf_init(void)
1766 {
1767 vrf_init(bfd_vrf_new, bfd_vrf_enable, bfd_vrf_disable,
1768 bfd_vrf_delete, bfd_vrf_update);
1769 }
1770
1771 void bfd_vrf_terminate(void)
1772 {
1773 vrf_terminate();
1774 }
1775
1776 struct bfd_vrf_global *bfd_vrf_look_by_session(struct bfd_session *bfd)
1777 {
1778 struct vrf *vrf;
1779
1780 if (!vrf_is_backend_netns()) {
1781 vrf = vrf_lookup_by_id(VRF_DEFAULT);
1782 if (vrf)
1783 return (struct bfd_vrf_global *)vrf->info;
1784 return NULL;
1785 }
1786 if (!bfd)
1787 return NULL;
1788 if (!bfd->vrf)
1789 return NULL;
1790 return bfd->vrf->info;
1791 }
1792
1793 void bfd_session_update_vrf_name(struct bfd_session *bs, struct vrf *vrf)
1794 {
1795 if (!vrf || !bs)
1796 return;
1797 /* update key */
1798 hash_release(bfd_key_hash, bs);
1799 /*
1800 * HACK: Change the BFD VRF in the running configuration directly,
1801 * bypassing the northbound layer. This is necessary to avoid deleting
1802 * the BFD and readding it in the new VRF, which would have
1803 * several implications.
1804 */
1805 if (yang_module_find("frr-bfdd") && bs->key.vrfname[0]) {
1806 struct lyd_node *bfd_dnode;
1807 char xpath[XPATH_MAXLEN], xpath_srcaddr[XPATH_MAXLEN + 32];
1808 char addr_buf[INET6_ADDRSTRLEN];
1809 int slen;
1810
1811 /* build xpath */
1812 if (bs->key.mhop) {
1813 inet_ntop(bs->key.family, &bs->key.local, addr_buf, sizeof(addr_buf));
1814 snprintf(xpath_srcaddr, sizeof(xpath_srcaddr), "[source-addr='%s']",
1815 addr_buf);
1816 } else
1817 xpath_srcaddr[0] = 0;
1818 inet_ntop(bs->key.family, &bs->key.peer, addr_buf, sizeof(addr_buf));
1819 slen = snprintf(xpath, sizeof(xpath),
1820 "/frr-bfdd:bfdd/bfd/sessions/%s%s[dest-addr='%s']",
1821 bs->key.mhop ? "multi-hop" : "single-hop", xpath_srcaddr,
1822 addr_buf);
1823 if (bs->key.ifname[0])
1824 slen += snprintf(xpath + slen, sizeof(xpath) - slen,
1825 "[interface='%s']", bs->key.ifname);
1826 else
1827 slen += snprintf(xpath + slen, sizeof(xpath) - slen,
1828 "[interface='']");
1829 snprintf(xpath + slen, sizeof(xpath) - slen, "[vrf='%s']/vrf",
1830 bs->key.vrfname);
1831
1832 pthread_rwlock_wrlock(&running_config->lock);
1833 {
1834 bfd_dnode = yang_dnode_get(
1835 running_config->dnode,
1836 xpath, bs->key.vrfname);
1837 if (bfd_dnode) {
1838 yang_dnode_change_leaf(bfd_dnode, vrf->name);
1839 running_config->version++;
1840 }
1841 pthread_rwlock_unlock(&running_config->lock);
1842 }
1843 }
1844 memset(bs->key.vrfname, 0, sizeof(bs->key.vrfname));
1845 strlcpy(bs->key.vrfname, vrf->name, sizeof(bs->key.vrfname));
1846 hash_get(bfd_key_hash, bs, hash_alloc_intern);
1847 }