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