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