[aarch64] Fixes CLI crashes on dpaa2 platform.
[vpp.git] / src / vnet / bfd / bfd_main.c
1 /*
2  * Copyright (c) 2011-2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /**
16  * @file
17  * @brief BFD nodes implementation
18  */
19
20 #if WITH_LIBSSL > 0
21 #include <openssl/sha.h>
22 #endif
23
24 #if __SSE4_2__
25 #include <x86intrin.h>
26 #endif
27
28 #include <vppinfra/random.h>
29 #include <vppinfra/error.h>
30 #include <vppinfra/hash.h>
31 #include <vppinfra/xxhash.h>
32 #include <vnet/ethernet/ethernet.h>
33 #include <vnet/ethernet/packet.h>
34 #include <vnet/bfd/bfd_debug.h>
35 #include <vnet/bfd/bfd_protocol.h>
36 #include <vnet/bfd/bfd_main.h>
37
38 static u64
39 bfd_calc_echo_checksum (u32 discriminator, u64 expire_time, u32 secret)
40 {
41   u64 checksum = 0;
42 #if __SSE4_2__ && !defined (__i386__)
43   checksum = _mm_crc32_u64 (0, discriminator);
44   checksum = _mm_crc32_u64 (checksum, expire_time);
45   checksum = _mm_crc32_u64 (checksum, secret);
46 #else
47   checksum = clib_xxhash (discriminator ^ expire_time ^ secret);
48 #endif
49   return checksum;
50 }
51
52 static u64
53 bfd_usec_to_clocks (const bfd_main_t * bm, u64 us)
54 {
55   return bm->cpu_cps * ((f64) us / USEC_PER_SECOND);
56 }
57
58 u32
59 bfd_clocks_to_usec (const bfd_main_t * bm, u64 clocks)
60 {
61   return (clocks / bm->cpu_cps) * USEC_PER_SECOND;
62 }
63
64 static vlib_node_registration_t bfd_process_node;
65
66 u8 *
67 format_bfd_auth_key (u8 * s, va_list * args)
68 {
69   const bfd_auth_key_t *key = va_arg (*args, bfd_auth_key_t *);
70   if (key)
71     {
72       s = format (s, "{auth-type=%u:%s, conf-key-id=%u, use-count=%u}, ",
73                   key->auth_type, bfd_auth_type_str (key->auth_type),
74                   key->conf_key_id, key->use_count);
75     }
76   else
77     {
78       s = format (s, "{none}");
79     }
80   return s;
81 }
82
83 /*
84  * We actually send all bfd pkts to the "error" node after scanning
85  * them, so the graph node has only one next-index. The "error-drop"
86  * node automatically bumps our per-node packet counters for us.
87  */
88 typedef enum
89 {
90   BFD_INPUT_NEXT_NORMAL,
91   BFD_INPUT_N_NEXT,
92 } bfd_input_next_t;
93
94 static void bfd_on_state_change (bfd_main_t * bm, bfd_session_t * bs, u64 now,
95                                  int handling_wakeup);
96
97 static void
98 bfd_set_defaults (bfd_main_t * bm, bfd_session_t * bs)
99 {
100   bs->local_state = BFD_STATE_down;
101   bs->local_diag = BFD_DIAG_CODE_no_diag;
102   bs->remote_state = BFD_STATE_down;
103   bs->remote_discr = 0;
104   bs->hop_type = BFD_HOP_TYPE_SINGLE;
105   bs->config_desired_min_tx_usec = BFD_DEFAULT_DESIRED_MIN_TX_USEC;
106   bs->config_desired_min_tx_clocks = bm->default_desired_min_tx_clocks;
107   bs->effective_desired_min_tx_clocks = bm->default_desired_min_tx_clocks;
108   bs->remote_min_rx_usec = 1;
109   bs->remote_min_rx_clocks = bfd_usec_to_clocks (bm, bs->remote_min_rx_usec);
110   bs->remote_min_echo_rx_usec = 0;
111   bs->remote_min_echo_rx_clocks = 0;
112   bs->remote_demand = 0;
113   bs->auth.remote_seq_number = 0;
114   bs->auth.remote_seq_number_known = 0;
115   bs->auth.local_seq_number = random_u32 (&bm->random_seed);
116   bs->echo_secret = random_u32 (&bm->random_seed);
117 }
118
119 static void
120 bfd_set_diag (bfd_session_t * bs, bfd_diag_code_e code)
121 {
122   if (bs->local_diag != code)
123     {
124       BFD_DBG ("set local_diag, bs_idx=%d: '%d:%s'", bs->bs_idx, code,
125                bfd_diag_code_string (code));
126       bs->local_diag = code;
127     }
128 }
129
130 static void
131 bfd_set_state (bfd_main_t * bm, bfd_session_t * bs,
132                bfd_state_e new_state, int handling_wakeup)
133 {
134   if (bs->local_state != new_state)
135     {
136       BFD_DBG ("Change state, bs_idx=%d: %s->%s", bs->bs_idx,
137                bfd_state_string (bs->local_state),
138                bfd_state_string (new_state));
139       bs->local_state = new_state;
140       bfd_on_state_change (bm, bs, clib_cpu_time_now (), handling_wakeup);
141     }
142 }
143
144 const char *
145 bfd_poll_state_string (bfd_poll_state_e state)
146 {
147   switch (state)
148     {
149 #define F(x)         \
150   case BFD_POLL_##x: \
151     return "BFD_POLL_" #x;
152       foreach_bfd_poll_state (F)
153 #undef F
154     }
155   return "UNKNOWN";
156 }
157
158 static void
159 bfd_set_poll_state (bfd_session_t * bs, bfd_poll_state_e state)
160 {
161   if (bs->poll_state != state)
162     {
163       BFD_DBG ("Setting poll state=%s, bs_idx=%u",
164                bfd_poll_state_string (state), bs->bs_idx);
165       bs->poll_state = state;
166     }
167 }
168
169 static void
170 bfd_recalc_tx_interval (bfd_main_t * bm, bfd_session_t * bs)
171 {
172   bs->transmit_interval_clocks =
173     clib_max (bs->effective_desired_min_tx_clocks, bs->remote_min_rx_clocks);
174   BFD_DBG ("Recalculated transmit interval " BFD_CLK_FMT,
175            BFD_CLK_PRN (bs->transmit_interval_clocks));
176 }
177
178 static void
179 bfd_recalc_echo_tx_interval (bfd_main_t * bm, bfd_session_t * bs)
180 {
181   bs->echo_transmit_interval_clocks =
182     clib_max (bs->effective_desired_min_tx_clocks,
183               bs->remote_min_echo_rx_clocks);
184   BFD_DBG ("Recalculated echo transmit interval " BFD_CLK_FMT,
185            BFD_CLK_PRN (bs->echo_transmit_interval_clocks));
186 }
187
188 static void
189 bfd_calc_next_tx (bfd_main_t * bm, bfd_session_t * bs, u64 now)
190 {
191   if (bs->local_detect_mult > 1)
192     {
193       /* common case - 75-100% of transmit interval */
194       bs->tx_timeout_clocks = bs->last_tx_clocks +
195         (1 - .25 * (random_f64 (&bm->random_seed))) *
196         bs->transmit_interval_clocks;
197       if (bs->tx_timeout_clocks < now)
198         {
199           /*
200            * the timeout is in the past, which means that either remote
201            * demand mode was set or performance/clock issues ...
202            */
203           BFD_DBG ("Missed %lu transmit events (now is %lu, calc "
204                    "tx_timeout is %lu)",
205                    (now - bs->tx_timeout_clocks) /
206                    bs->transmit_interval_clocks, now, bs->tx_timeout_clocks);
207           bs->tx_timeout_clocks = now;
208         }
209     }
210   else
211     {
212       /* special case - 75-90% of transmit interval */
213       bs->tx_timeout_clocks = bs->last_tx_clocks +
214         (.9 - .15 * (random_f64 (&bm->random_seed))) *
215         bs->transmit_interval_clocks;
216       if (bs->tx_timeout_clocks < now)
217         {
218           /*
219            * the timeout is in the past, which means that either remote
220            * demand mode was set or performance/clock issues ...
221            */
222           BFD_DBG ("Missed %lu transmit events (now is %lu, calc "
223                    "tx_timeout is %lu)",
224                    (now - bs->tx_timeout_clocks) /
225                    bs->transmit_interval_clocks, now, bs->tx_timeout_clocks);
226           bs->tx_timeout_clocks = now;
227         }
228     }
229   if (bs->tx_timeout_clocks)
230     {
231       BFD_DBG ("Next transmit in %lu clocks/%.02fs@%lu",
232                bs->tx_timeout_clocks - now,
233                (bs->tx_timeout_clocks - now) / bm->cpu_cps,
234                bs->tx_timeout_clocks);
235     }
236 }
237
238 static void
239 bfd_calc_next_echo_tx (bfd_main_t * bm, bfd_session_t * bs, u64 now)
240 {
241   bs->echo_tx_timeout_clocks =
242     bs->echo_last_tx_clocks + bs->echo_transmit_interval_clocks;
243   if (bs->echo_tx_timeout_clocks < now)
244     {
245       /* huh, we've missed it already, transmit now */
246       BFD_DBG ("Missed %lu echo transmit events (now is %lu, calc tx_timeout "
247                "is %lu)",
248                (now - bs->echo_tx_timeout_clocks) /
249                bs->echo_transmit_interval_clocks,
250                now, bs->echo_tx_timeout_clocks);
251       bs->echo_tx_timeout_clocks = now;
252     }
253   BFD_DBG ("Next echo transmit in %lu clocks/%.02fs@%lu",
254            bs->echo_tx_timeout_clocks - now,
255            (bs->echo_tx_timeout_clocks - now) / bm->cpu_cps,
256            bs->echo_tx_timeout_clocks);
257 }
258
259 static void
260 bfd_recalc_detection_time (bfd_main_t * bm, bfd_session_t * bs)
261 {
262   if (bs->local_state == BFD_STATE_init || bs->local_state == BFD_STATE_up)
263     {
264       bs->detection_time_clocks =
265         bs->remote_detect_mult *
266         clib_max (bs->effective_required_min_rx_clocks,
267                   bs->remote_desired_min_tx_clocks);
268       BFD_DBG ("Recalculated detection time %lu clocks/%.2fs",
269                bs->detection_time_clocks,
270                bs->detection_time_clocks / bm->cpu_cps);
271     }
272 }
273
274 static void
275 bfd_set_timer (bfd_main_t * bm, bfd_session_t * bs, u64 now,
276                int handling_wakeup)
277 {
278   u64 next = 0;
279   u64 rx_timeout = 0;
280   u64 tx_timeout = 0;
281   if (BFD_STATE_up == bs->local_state)
282     {
283       rx_timeout = bs->last_rx_clocks + bs->detection_time_clocks;
284     }
285   if (BFD_STATE_up != bs->local_state ||
286       (!bs->remote_demand && bs->remote_min_rx_usec) ||
287       BFD_POLL_NOT_NEEDED != bs->poll_state)
288     {
289       tx_timeout = bs->tx_timeout_clocks;
290     }
291   if (tx_timeout && rx_timeout)
292     {
293       next = clib_min (tx_timeout, rx_timeout);
294     }
295   else if (tx_timeout)
296     {
297       next = tx_timeout;
298     }
299   else if (rx_timeout)
300     {
301       next = rx_timeout;
302     }
303   if (bs->echo && next > bs->echo_tx_timeout_clocks)
304     {
305       next = bs->echo_tx_timeout_clocks;
306     }
307   BFD_DBG ("bs_idx=%u, tx_timeout=%lu, echo_tx_timeout=%lu, rx_timeout=%lu, "
308            "next=%s",
309            bs->bs_idx, tx_timeout, bs->echo_tx_timeout_clocks, rx_timeout,
310            next == tx_timeout
311            ? "tx" : (next == bs->echo_tx_timeout_clocks ? "echo tx" : "rx"));
312   /* sometimes the wheel expires an event a bit sooner than requested, account
313      for that here */
314   if (next && (now + bm->wheel_inaccuracy > bs->wheel_time_clocks ||
315                next < bs->wheel_time_clocks || !bs->wheel_time_clocks))
316     {
317       bs->wheel_time_clocks = next;
318       BFD_DBG ("timing_wheel_insert(%p, %lu (%ld clocks/%.2fs in the "
319                "future), %u);",
320                &bm->wheel, bs->wheel_time_clocks,
321                (i64) bs->wheel_time_clocks - clib_cpu_time_now (),
322                (i64) (bs->wheel_time_clocks - clib_cpu_time_now ()) /
323                bm->cpu_cps, bs->bs_idx);
324       timing_wheel_insert (&bm->wheel, bs->wheel_time_clocks, bs->bs_idx);
325       if (!handling_wakeup)
326         {
327           vlib_process_signal_event (bm->vlib_main,
328                                      bm->bfd_process_node_index,
329                                      BFD_EVENT_RESCHEDULE, bs->bs_idx);
330         }
331     }
332 }
333
334 static void
335 bfd_set_effective_desired_min_tx (bfd_main_t * bm,
336                                   bfd_session_t * bs, u64 now,
337                                   u64 desired_min_tx_clocks)
338 {
339   bs->effective_desired_min_tx_clocks = desired_min_tx_clocks;
340   BFD_DBG ("Set effective desired min tx to " BFD_CLK_FMT,
341            BFD_CLK_PRN (bs->effective_desired_min_tx_clocks));
342   bfd_recalc_detection_time (bm, bs);
343   bfd_recalc_tx_interval (bm, bs);
344   bfd_recalc_echo_tx_interval (bm, bs);
345   bfd_calc_next_tx (bm, bs, now);
346 }
347
348 static void
349 bfd_set_effective_required_min_rx (bfd_main_t * bm,
350                                    bfd_session_t * bs,
351                                    u64 required_min_rx_clocks)
352 {
353   bs->effective_required_min_rx_clocks = required_min_rx_clocks;
354   BFD_DBG ("Set effective required min rx to " BFD_CLK_FMT,
355            BFD_CLK_PRN (bs->effective_required_min_rx_clocks));
356   bfd_recalc_detection_time (bm, bs);
357 }
358
359 static void
360 bfd_set_remote_required_min_rx (bfd_main_t * bm, bfd_session_t * bs,
361                                 u64 now, u32 remote_required_min_rx_usec)
362 {
363   if (bs->remote_min_rx_usec != remote_required_min_rx_usec)
364     {
365       bs->remote_min_rx_usec = remote_required_min_rx_usec;
366       bs->remote_min_rx_clocks =
367         bfd_usec_to_clocks (bm, remote_required_min_rx_usec);
368       BFD_DBG ("Set remote min rx to " BFD_CLK_FMT,
369                BFD_CLK_PRN (bs->remote_min_rx_clocks));
370       bfd_recalc_detection_time (bm, bs);
371       bfd_recalc_tx_interval (bm, bs);
372     }
373 }
374
375 static void
376 bfd_set_remote_required_min_echo_rx (bfd_main_t * bm, bfd_session_t * bs,
377                                      u64 now,
378                                      u32 remote_required_min_echo_rx_usec)
379 {
380   if (bs->remote_min_echo_rx_usec != remote_required_min_echo_rx_usec)
381     {
382       bs->remote_min_echo_rx_usec = remote_required_min_echo_rx_usec;
383       bs->remote_min_echo_rx_clocks =
384         bfd_usec_to_clocks (bm, bs->remote_min_echo_rx_usec);
385       BFD_DBG ("Set remote min echo rx to " BFD_CLK_FMT,
386                BFD_CLK_PRN (bs->remote_min_echo_rx_clocks));
387       bfd_recalc_echo_tx_interval (bm, bs);
388     }
389 }
390
391 static void
392 bfd_notify_listeners (bfd_main_t * bm,
393                       bfd_listen_event_e event, const bfd_session_t * bs)
394 {
395   bfd_notify_fn_t *fn;
396   vec_foreach (fn, bm->listeners)
397   {
398     (*fn) (event, bs);
399   }
400 }
401
402 void
403 bfd_session_start (bfd_main_t * bm, bfd_session_t * bs)
404 {
405   BFD_DBG ("\nStarting session: %U", format_bfd_session, bs);
406   bfd_set_effective_required_min_rx (bm, bs,
407                                      bs->config_required_min_rx_clocks);
408   bfd_recalc_tx_interval (bm, bs);
409   vlib_process_signal_event (bm->vlib_main, bm->bfd_process_node_index,
410                              BFD_EVENT_NEW_SESSION, bs->bs_idx);
411   bfd_notify_listeners (bm, BFD_LISTEN_EVENT_CREATE, bs);
412 }
413
414 void
415 bfd_session_set_flags (bfd_session_t * bs, u8 admin_up_down)
416 {
417   bfd_main_t *bm = &bfd_main;
418   u64 now = clib_cpu_time_now ();
419   if (admin_up_down)
420     {
421       BFD_DBG ("Session set admin-up, bs-idx=%u", bs->bs_idx);
422       bfd_set_state (bm, bs, BFD_STATE_down, 0);
423       bfd_set_diag (bs, BFD_DIAG_CODE_no_diag);
424       bfd_calc_next_tx (bm, bs, now);
425       bfd_set_timer (bm, bs, now, 0);
426     }
427   else
428     {
429       BFD_DBG ("Session set admin-down, bs-idx=%u", bs->bs_idx);
430       bfd_set_diag (bs, BFD_DIAG_CODE_admin_down);
431       bfd_set_state (bm, bs, BFD_STATE_admin_down, 0);
432       bfd_calc_next_tx (bm, bs, now);
433       bfd_set_timer (bm, bs, now, 0);
434     }
435 }
436
437 u8 *
438 bfd_input_format_trace (u8 * s, va_list * args)
439 {
440   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
441   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
442   const bfd_input_trace_t *t = va_arg (*args, bfd_input_trace_t *);
443   const bfd_pkt_t *pkt = (bfd_pkt_t *) t->data;
444   if (t->len > STRUCT_SIZE_OF (bfd_pkt_t, head))
445     {
446       s = format (s, "BFD v%u, diag=%u(%s), state=%u(%s),\n"
447                   "    flags=(P:%u, F:%u, C:%u, A:%u, D:%u, M:%u), "
448                   "detect_mult=%u, length=%u\n",
449                   bfd_pkt_get_version (pkt), bfd_pkt_get_diag_code (pkt),
450                   bfd_diag_code_string (bfd_pkt_get_diag_code (pkt)),
451                   bfd_pkt_get_state (pkt),
452                   bfd_state_string (bfd_pkt_get_state (pkt)),
453                   bfd_pkt_get_poll (pkt), bfd_pkt_get_final (pkt),
454                   bfd_pkt_get_control_plane_independent (pkt),
455                   bfd_pkt_get_auth_present (pkt), bfd_pkt_get_demand (pkt),
456                   bfd_pkt_get_multipoint (pkt), pkt->head.detect_mult,
457                   pkt->head.length);
458       if (t->len >= sizeof (bfd_pkt_t) &&
459           pkt->head.length >= sizeof (bfd_pkt_t))
460         {
461           s = format (s, "    my discriminator: %u\n",
462                       clib_net_to_host_u32 (pkt->my_disc));
463           s = format (s, "    your discriminator: %u\n",
464                       clib_net_to_host_u32 (pkt->your_disc));
465           s = format (s, "    desired min tx interval: %u\n",
466                       clib_net_to_host_u32 (pkt->des_min_tx));
467           s = format (s, "    required min rx interval: %u\n",
468                       clib_net_to_host_u32 (pkt->req_min_rx));
469           s = format (s, "    required min echo rx interval: %u",
470                       clib_net_to_host_u32 (pkt->req_min_echo_rx));
471         }
472       if (t->len >= sizeof (bfd_pkt_with_common_auth_t) &&
473           pkt->head.length >= sizeof (bfd_pkt_with_common_auth_t) &&
474           bfd_pkt_get_auth_present (pkt))
475         {
476           const bfd_pkt_with_common_auth_t *with_auth = (void *) pkt;
477           const bfd_auth_common_t *common = &with_auth->common_auth;
478           s = format (s, "\n    auth len: %u\n", common->len);
479           s = format (s, "    auth type: %u:%s\n", common->type,
480                       bfd_auth_type_str (common->type));
481           if (t->len >= sizeof (bfd_pkt_with_sha1_auth_t) &&
482               pkt->head.length >= sizeof (bfd_pkt_with_sha1_auth_t) &&
483               (BFD_AUTH_TYPE_keyed_sha1 == common->type ||
484                BFD_AUTH_TYPE_meticulous_keyed_sha1 == common->type))
485             {
486               const bfd_pkt_with_sha1_auth_t *with_sha1 = (void *) pkt;
487               const bfd_auth_sha1_t *sha1 = &with_sha1->sha1_auth;
488               s = format (s, "    seq num: %u\n",
489                           clib_net_to_host_u32 (sha1->seq_num));
490               s = format (s, "    key id: %u\n", sha1->key_id);
491               s = format (s, "    hash: %U", format_hex_bytes, sha1->hash,
492                           sizeof (sha1->hash));
493             }
494         }
495       else
496         {
497           s = format (s, "\n");
498         }
499     }
500
501   return s;
502 }
503
504 static void
505 bfd_on_state_change (bfd_main_t * bm, bfd_session_t * bs, u64 now,
506                      int handling_wakeup)
507 {
508   BFD_DBG ("\nState changed: %U", format_bfd_session, bs);
509   bfd_event (bm, bs);
510   switch (bs->local_state)
511     {
512     case BFD_STATE_admin_down:
513       bs->echo = 0;
514       bfd_set_effective_desired_min_tx (bm, bs, now,
515                                         clib_max
516                                         (bs->config_desired_min_tx_clocks,
517                                          bm->default_desired_min_tx_clocks));
518       bfd_set_effective_required_min_rx (bm, bs,
519                                          bs->config_required_min_rx_clocks);
520       bfd_set_timer (bm, bs, now, handling_wakeup);
521       break;
522     case BFD_STATE_down:
523       bs->echo = 0;
524       bfd_set_effective_desired_min_tx (bm, bs, now,
525                                         clib_max
526                                         (bs->config_desired_min_tx_clocks,
527                                          bm->default_desired_min_tx_clocks));
528       bfd_set_effective_required_min_rx (bm, bs,
529                                          bs->config_required_min_rx_clocks);
530       bfd_set_timer (bm, bs, now, handling_wakeup);
531       break;
532     case BFD_STATE_init:
533       bs->echo = 0;
534       bfd_set_effective_desired_min_tx (bm, bs, now,
535                                         bs->config_desired_min_tx_clocks);
536       bfd_set_timer (bm, bs, now, handling_wakeup);
537       break;
538     case BFD_STATE_up:
539       bfd_set_effective_desired_min_tx (bm, bs, now,
540                                         bs->config_desired_min_tx_clocks);
541       if (BFD_POLL_NOT_NEEDED == bs->poll_state)
542         {
543           bfd_set_effective_required_min_rx (bm, bs,
544                                              bs->config_required_min_rx_clocks);
545         }
546       bfd_set_timer (bm, bs, now, handling_wakeup);
547       break;
548     }
549   bfd_notify_listeners (bm, BFD_LISTEN_EVENT_UPDATE, bs);
550 }
551
552 static void
553 bfd_on_config_change (vlib_main_t * vm, vlib_node_runtime_t * rt,
554                       bfd_main_t * bm, bfd_session_t * bs, u64 now)
555 {
556   /*
557    * if remote demand mode is set and we need to do a poll, set the next
558    * timeout so that the session wakes up immediately
559    */
560   if (bs->remote_demand && BFD_POLL_NEEDED == bs->poll_state &&
561       bs->poll_state_start_or_timeout_clocks < now)
562     {
563       bs->tx_timeout_clocks = now;
564     }
565   bfd_recalc_detection_time (bm, bs);
566   bfd_set_timer (bm, bs, now, 0);
567 }
568
569 static void
570 bfd_add_transport_layer (vlib_main_t * vm, u32 bi, bfd_session_t * bs)
571 {
572   switch (bs->transport)
573     {
574     case BFD_TRANSPORT_UDP4:
575       BFD_DBG ("Transport bfd via udp4, bs_idx=%u", bs->bs_idx);
576       bfd_add_udp4_transport (vm, bi, bs, 0 /* is_echo */ );
577       break;
578     case BFD_TRANSPORT_UDP6:
579       BFD_DBG ("Transport bfd via udp6, bs_idx=%u", bs->bs_idx);
580       bfd_add_udp6_transport (vm, bi, bs, 0 /* is_echo */ );
581       break;
582     }
583 }
584
585 static int
586 bfd_transport_control_frame (vlib_main_t * vm, u32 bi, bfd_session_t * bs)
587 {
588   switch (bs->transport)
589     {
590     case BFD_TRANSPORT_UDP4:
591       BFD_DBG ("Transport bfd via udp4, bs_idx=%u", bs->bs_idx);
592       return bfd_transport_udp4 (vm, bi, bs);
593       break;
594     case BFD_TRANSPORT_UDP6:
595       BFD_DBG ("Transport bfd via udp6, bs_idx=%u", bs->bs_idx);
596       return bfd_transport_udp6 (vm, bi, bs);
597       break;
598     }
599   return 0;
600 }
601
602 static int
603 bfd_echo_add_transport_layer (vlib_main_t * vm, u32 bi, bfd_session_t * bs)
604 {
605   switch (bs->transport)
606     {
607     case BFD_TRANSPORT_UDP4:
608       BFD_DBG ("Transport bfd echo via udp4, bs_idx=%u", bs->bs_idx);
609       return bfd_add_udp4_transport (vm, bi, bs, 1 /* is_echo */ );
610       break;
611     case BFD_TRANSPORT_UDP6:
612       BFD_DBG ("Transport bfd echo via udp6, bs_idx=%u", bs->bs_idx);
613       return bfd_add_udp6_transport (vm, bi, bs, 1 /* is_echo */ );
614       break;
615     }
616   return 0;
617 }
618
619 static int
620 bfd_transport_echo (vlib_main_t * vm, u32 bi, bfd_session_t * bs)
621 {
622   switch (bs->transport)
623     {
624     case BFD_TRANSPORT_UDP4:
625       BFD_DBG ("Transport bfd echo via udp4, bs_idx=%u", bs->bs_idx);
626       return bfd_transport_udp4 (vm, bi, bs);
627       break;
628     case BFD_TRANSPORT_UDP6:
629       BFD_DBG ("Transport bfd echo via udp6, bs_idx=%u", bs->bs_idx);
630       return bfd_transport_udp6 (vm, bi, bs);
631       break;
632     }
633   return 0;
634 }
635
636 #if WITH_LIBSSL > 0
637 static void
638 bfd_add_sha1_auth_section (vlib_buffer_t * b, bfd_session_t * bs)
639 {
640   bfd_pkt_with_sha1_auth_t *pkt = vlib_buffer_get_current (b);
641   bfd_auth_sha1_t *auth = &pkt->sha1_auth;
642   b->current_length += sizeof (*auth);
643   pkt->pkt.head.length += sizeof (*auth);
644   bfd_pkt_set_auth_present (&pkt->pkt);
645   memset (auth, 0, sizeof (*auth));
646   auth->type_len.type = bs->auth.curr_key->auth_type;
647   /*
648    * only meticulous authentication types require incrementing seq number
649    * for every message, but doing so doesn't violate the RFC
650    */
651   ++bs->auth.local_seq_number;
652   auth->type_len.len = sizeof (bfd_auth_sha1_t);
653   auth->key_id = bs->auth.curr_bfd_key_id;
654   auth->seq_num = clib_host_to_net_u32 (bs->auth.local_seq_number);
655   /*
656    * first copy the password into the packet, then calculate the hash
657    * and finally replace the password with the calculated hash
658    */
659   clib_memcpy (auth->hash, bs->auth.curr_key->key,
660                sizeof (bs->auth.curr_key->key));
661   unsigned char hash[sizeof (auth->hash)];
662   SHA1 ((unsigned char *) pkt, sizeof (*pkt), hash);
663   BFD_DBG ("hashing: %U", format_hex_bytes, pkt, sizeof (*pkt));
664   clib_memcpy (auth->hash, hash, sizeof (hash));
665 }
666 #endif
667
668 static void
669 bfd_add_auth_section (vlib_buffer_t * b, bfd_session_t * bs)
670 {
671   if (bs->auth.curr_key)
672     {
673       const bfd_auth_type_e auth_type = bs->auth.curr_key->auth_type;
674       switch (auth_type)
675         {
676         case BFD_AUTH_TYPE_reserved:
677           /* fallthrough */
678         case BFD_AUTH_TYPE_simple_password:
679           /* fallthrough */
680         case BFD_AUTH_TYPE_keyed_md5:
681           /* fallthrough */
682         case BFD_AUTH_TYPE_meticulous_keyed_md5:
683           clib_warning ("Internal error, unexpected BFD auth type '%d'",
684                         auth_type);
685           break;
686 #if WITH_LIBSSL > 0
687         case BFD_AUTH_TYPE_keyed_sha1:
688           /* fallthrough */
689         case BFD_AUTH_TYPE_meticulous_keyed_sha1:
690           bfd_add_sha1_auth_section (b, bs);
691           break;
692 #else
693         case BFD_AUTH_TYPE_keyed_sha1:
694           /* fallthrough */
695         case BFD_AUTH_TYPE_meticulous_keyed_sha1:
696           clib_warning ("Internal error, unexpected BFD auth type '%d'",
697                         auth_type);
698           break;
699 #endif
700         }
701     }
702 }
703
704 static int
705 bfd_is_echo_possible (bfd_session_t * bs)
706 {
707   if (BFD_STATE_up == bs->local_state && BFD_STATE_up == bs->remote_state &&
708       bs->remote_min_echo_rx_usec > 0)
709     {
710       switch (bs->transport)
711         {
712         case BFD_TRANSPORT_UDP4:
713           return bfd_udp_is_echo_available (BFD_TRANSPORT_UDP4);
714         case BFD_TRANSPORT_UDP6:
715           return bfd_udp_is_echo_available (BFD_TRANSPORT_UDP6);
716         }
717     }
718   return 0;
719 }
720
721 static void
722 bfd_init_control_frame (bfd_main_t * bm, bfd_session_t * bs,
723                         vlib_buffer_t * b)
724 {
725   bfd_pkt_t *pkt = vlib_buffer_get_current (b);
726   u32 bfd_length = 0;
727   bfd_length = sizeof (bfd_pkt_t);
728   memset (pkt, 0, sizeof (*pkt));
729   bfd_pkt_set_version (pkt, 1);
730   bfd_pkt_set_diag_code (pkt, bs->local_diag);
731   bfd_pkt_set_state (pkt, bs->local_state);
732   pkt->head.detect_mult = bs->local_detect_mult;
733   pkt->head.length = bfd_length;
734   pkt->my_disc = bs->local_discr;
735   pkt->your_disc = bs->remote_discr;
736   pkt->des_min_tx = clib_host_to_net_u32 (bs->config_desired_min_tx_usec);
737   if (bs->echo)
738     {
739       pkt->req_min_rx =
740         clib_host_to_net_u32 (bfd_clocks_to_usec
741                               (bm, bs->effective_required_min_rx_clocks));
742     }
743   else
744     {
745       pkt->req_min_rx =
746         clib_host_to_net_u32 (bs->config_required_min_rx_usec);
747     }
748   pkt->req_min_echo_rx = clib_host_to_net_u32 (1);
749   b->current_length = bfd_length;
750 }
751
752 static void
753 bfd_send_echo (vlib_main_t * vm, vlib_node_runtime_t * rt,
754                bfd_main_t * bm, bfd_session_t * bs, u64 now)
755 {
756   if (!bfd_is_echo_possible (bs))
757     {
758       BFD_DBG ("\nSwitching off echo function: %U", format_bfd_session, bs);
759       bs->echo = 0;
760       return;
761     }
762   /* sometimes the wheel expires an event a bit sooner than requested,
763      account
764      for that here */
765   if (now + bm->wheel_inaccuracy >= bs->echo_tx_timeout_clocks)
766     {
767       BFD_DBG ("\nSending echo packet: %U", format_bfd_session, bs);
768       u32 bi;
769       if (vlib_buffer_alloc (vm, &bi, 1) != 1)
770         {
771           clib_warning ("buffer allocation failure");
772           return;
773         }
774       vlib_buffer_t *b = vlib_get_buffer (vm, bi);
775       ASSERT (b->current_data == 0);
776       memset (vnet_buffer (b), 0, sizeof (*vnet_buffer (b)));
777       VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b);
778       bfd_echo_pkt_t *pkt = vlib_buffer_get_current (b);
779       memset (pkt, 0, sizeof (*pkt));
780       pkt->discriminator = bs->local_discr;
781       pkt->expire_time_clocks =
782         now + bs->echo_transmit_interval_clocks * bs->local_detect_mult;
783       pkt->checksum =
784         bfd_calc_echo_checksum (bs->local_discr, pkt->expire_time_clocks,
785                                 bs->echo_secret);
786       b->current_length = sizeof (*pkt);
787       if (!bfd_echo_add_transport_layer (vm, bi, bs))
788         {
789           BFD_ERR ("cannot send echo packet out, turning echo off");
790           bs->echo = 0;
791           vlib_buffer_free_one (vm, bi);
792           return;
793         }
794       if (!bfd_transport_echo (vm, bi, bs))
795         {
796           BFD_ERR ("cannot send echo packet out, turning echo off");
797           bs->echo = 0;
798           vlib_buffer_free_one (vm, bi);
799           return;
800         }
801       bs->echo_last_tx_clocks = now;
802       bfd_calc_next_echo_tx (bm, bs, now);
803     }
804   else
805     {
806       BFD_DBG
807         ("No need to send echo packet now, now is %lu, tx_timeout is %lu",
808          now, bs->echo_tx_timeout_clocks);
809     }
810 }
811
812 static void
813 bfd_send_periodic (vlib_main_t * vm, vlib_node_runtime_t * rt,
814                    bfd_main_t * bm, bfd_session_t * bs, u64 now)
815 {
816   if (!bs->remote_min_rx_usec && BFD_POLL_NOT_NEEDED == bs->poll_state)
817     {
818       BFD_DBG ("Remote min rx interval is zero, not sending periodic control "
819                "frame");
820       return;
821     }
822   if (BFD_POLL_NOT_NEEDED == bs->poll_state && bs->remote_demand &&
823       BFD_STATE_up == bs->local_state && BFD_STATE_up == bs->remote_state)
824     {
825       /*
826        * A system MUST NOT periodically transmit BFD Control packets if Demand
827        * mode is active on the remote system (bfd.RemoteDemandMode is 1,
828        * bfd.SessionState is Up, and bfd.RemoteSessionState is Up) and a Poll
829        * Sequence is not being transmitted.
830        */
831       BFD_DBG ("Remote demand is set, not sending periodic control frame");
832       return;
833     }
834   /*
835    * sometimes the wheel expires an event a bit sooner than requested, account
836    * for that here
837    */
838   if (now + bm->wheel_inaccuracy >= bs->tx_timeout_clocks)
839     {
840       BFD_DBG ("\nSending periodic control frame: %U", format_bfd_session,
841                bs);
842       u32 bi;
843       if (vlib_buffer_alloc (vm, &bi, 1) != 1)
844         {
845           clib_warning ("buffer allocation failure");
846           return;
847         }
848       vlib_buffer_t *b = vlib_get_buffer (vm, bi);
849       ASSERT (b->current_data == 0);
850       memset (vnet_buffer (b), 0, sizeof (*vnet_buffer (b)));
851       VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b);
852       bfd_init_control_frame (bm, bs, b);
853       switch (bs->poll_state)
854         {
855         case BFD_POLL_NEEDED:
856           if (now < bs->poll_state_start_or_timeout_clocks)
857             {
858               BFD_DBG ("Cannot start a poll sequence yet, need to wait "
859                        "for " BFD_CLK_FMT,
860                        BFD_CLK_PRN (bs->poll_state_start_or_timeout_clocks -
861                                     now));
862               break;
863             }
864           bs->poll_state_start_or_timeout_clocks = now;
865           bfd_set_poll_state (bs, BFD_POLL_IN_PROGRESS);
866           /* fallthrough */
867         case BFD_POLL_IN_PROGRESS:
868         case BFD_POLL_IN_PROGRESS_AND_QUEUED:
869           bfd_pkt_set_poll (vlib_buffer_get_current (b));
870           BFD_DBG ("Setting poll bit in packet, bs_idx=%u", bs->bs_idx);
871           break;
872         case BFD_POLL_NOT_NEEDED:
873           /* fallthrough */
874           break;
875         }
876       bfd_add_auth_section (b, bs);
877       bfd_add_transport_layer (vm, bi, bs);
878       if (!bfd_transport_control_frame (vm, bi, bs))
879         {
880           vlib_buffer_free_one (vm, bi);
881         }
882       bs->last_tx_clocks = now;
883       bfd_calc_next_tx (bm, bs, now);
884     }
885   else
886     {
887       BFD_DBG
888         ("No need to send control frame now, now is %lu, tx_timeout is %lu",
889          now, bs->tx_timeout_clocks);
890     }
891 }
892
893 void
894 bfd_init_final_control_frame (vlib_main_t * vm, vlib_buffer_t * b,
895                               bfd_main_t * bm, bfd_session_t * bs,
896                               int is_local)
897 {
898   BFD_DBG ("Send final control frame for bs_idx=%lu", bs->bs_idx);
899   bfd_init_control_frame (bm, bs, b);
900   bfd_pkt_set_final (vlib_buffer_get_current (b));
901   bfd_add_auth_section (b, bs);
902   u32 bi = vlib_get_buffer_index (vm, b);
903   bfd_add_transport_layer (vm, bi, bs);
904   bs->last_tx_clocks = clib_cpu_time_now ();
905   /*
906    * RFC allows to include changes in final frame, so if there were any
907    * pending, we already did that, thus we can clear any pending poll needs
908    */
909   bfd_set_poll_state (bs, BFD_POLL_NOT_NEEDED);
910 }
911
912 static void
913 bfd_check_rx_timeout (bfd_main_t * bm, bfd_session_t * bs, u64 now,
914                       int handling_wakeup)
915 {
916   /*
917    * sometimes the wheel expires an event a bit sooner than requested, account
918    * for that here
919    */
920   if (bs->last_rx_clocks + bs->detection_time_clocks <=
921       now + bm->wheel_inaccuracy)
922     {
923       BFD_DBG ("Rx timeout, session goes down");
924       bfd_set_diag (bs, BFD_DIAG_CODE_det_time_exp);
925       bfd_set_state (bm, bs, BFD_STATE_down, handling_wakeup);
926       /*
927        * If the remote system does not receive any
928        * BFD Control packets for a Detection Time, it SHOULD reset
929        * bfd.RemoteMinRxInterval to its initial value of 1 (per section 6.8.1,
930        * since it is no longer required to maintain previous session state)
931        * and then can transmit at its own rate.
932        */
933       bfd_set_remote_required_min_rx (bm, bs, now, 1);
934     }
935   else if (bs->echo &&
936            bs->echo_last_rx_clocks +
937            bs->echo_transmit_interval_clocks * bs->local_detect_mult <=
938            now + bm->wheel_inaccuracy)
939     {
940       BFD_DBG ("Echo rx timeout, session goes down");
941       bfd_set_diag (bs, BFD_DIAG_CODE_echo_failed);
942       bfd_set_state (bm, bs, BFD_STATE_down, handling_wakeup);
943     }
944 }
945
946 void
947 bfd_on_timeout (vlib_main_t * vm, vlib_node_runtime_t * rt, bfd_main_t * bm,
948                 bfd_session_t * bs, u64 now)
949 {
950   BFD_DBG ("Timeout for bs_idx=%lu", bs->bs_idx);
951   switch (bs->local_state)
952     {
953     case BFD_STATE_admin_down:
954       bfd_send_periodic (vm, rt, bm, bs, now);
955       break;
956     case BFD_STATE_down:
957       bfd_send_periodic (vm, rt, bm, bs, now);
958       break;
959     case BFD_STATE_init:
960       bfd_check_rx_timeout (bm, bs, now, 1);
961       bfd_send_periodic (vm, rt, bm, bs, now);
962       break;
963     case BFD_STATE_up:
964       bfd_check_rx_timeout (bm, bs, now, 1);
965       if (BFD_POLL_NOT_NEEDED == bs->poll_state && !bs->echo &&
966           bfd_is_echo_possible (bs))
967         {
968           /* switch on echo function as main detection method now */
969           BFD_DBG ("Switching on echo function, bs_idx=%u", bs->bs_idx);
970           bs->echo = 1;
971           bs->echo_last_rx_clocks = now;
972           bs->echo_tx_timeout_clocks = now;
973           bfd_set_effective_required_min_rx (bm, bs,
974                                              clib_max
975                                              (bm->min_required_min_rx_while_echo_clocks,
976                                               bs->config_required_min_rx_clocks));
977           bfd_set_poll_state (bs, BFD_POLL_NEEDED);
978         }
979       bfd_send_periodic (vm, rt, bm, bs, now);
980       if (bs->echo)
981         {
982           bfd_send_echo (vm, rt, bm, bs, now);
983         }
984       break;
985     }
986 }
987
988 /*
989  * bfd process node function
990  */
991 static uword
992 bfd_process (vlib_main_t * vm, vlib_node_runtime_t * rt, vlib_frame_t * f)
993 {
994   bfd_main_t *bm = &bfd_main;
995   u32 *expired = 0;
996   uword event_type, *event_data = 0;
997
998   /* So we can send events to the bfd process */
999   bm->bfd_process_node_index = bfd_process_node.index;
1000
1001   while (1)
1002     {
1003       u64 now = clib_cpu_time_now ();
1004       u64 next_expire = timing_wheel_next_expiring_elt_time (&bm->wheel);
1005       BFD_DBG ("timing_wheel_next_expiring_elt_time(%p) returns %lu",
1006                &bm->wheel, next_expire);
1007       if ((i64) next_expire < 0)
1008         {
1009           BFD_DBG ("wait for event without timeout");
1010           (void) vlib_process_wait_for_event (vm);
1011           event_type = vlib_process_get_events (vm, &event_data);
1012         }
1013       else
1014         {
1015           f64 timeout = ((i64) next_expire - (i64) now) / bm->cpu_cps;
1016           BFD_DBG ("wait for event with timeout %.02f", timeout);
1017           if (timeout < 0)
1018             {
1019               BFD_DBG ("negative timeout, already expired, skipping wait");
1020               event_type = ~0;
1021             }
1022           else
1023             {
1024               (void) vlib_process_wait_for_event_or_clock (vm, timeout);
1025               event_type = vlib_process_get_events (vm, &event_data);
1026             }
1027         }
1028       now = clib_cpu_time_now ();
1029       switch (event_type)
1030         {
1031         case ~0:                /* no events => timeout */
1032           /* nothing to do here */
1033           break;
1034         case BFD_EVENT_RESCHEDULE:
1035           /* nothing to do here - reschedule is done automatically after
1036            * each event or timeout */
1037           break;
1038         case BFD_EVENT_NEW_SESSION:
1039           if (!pool_is_free_index (bm->sessions, *event_data))
1040             {
1041               bfd_session_t *bs =
1042                 pool_elt_at_index (bm->sessions, *event_data);
1043               bfd_send_periodic (vm, rt, bm, bs, now);
1044               bfd_set_timer (bm, bs, now, 1);
1045             }
1046           else
1047             {
1048               BFD_DBG ("Ignoring event for non-existent session index %u",
1049                        (u32) * event_data);
1050             }
1051           break;
1052         case BFD_EVENT_CONFIG_CHANGED:
1053           if (!pool_is_free_index (bm->sessions, *event_data))
1054             {
1055               bfd_session_t *bs =
1056                 pool_elt_at_index (bm->sessions, *event_data);
1057               bfd_on_config_change (vm, rt, bm, bs, now);
1058             }
1059           else
1060             {
1061               BFD_DBG ("Ignoring event for non-existent session index %u",
1062                        (u32) * event_data);
1063             }
1064           break;
1065         default:
1066           clib_warning ("BUG: event type 0x%wx", event_type);
1067           break;
1068         }
1069       BFD_DBG ("advancing wheel, now is %lu", now);
1070       BFD_DBG ("timing_wheel_advance (%p, %lu, %p, 0);", &bm->wheel, now,
1071                expired);
1072       expired = timing_wheel_advance (&bm->wheel, now, expired, 0);
1073       BFD_DBG ("Expired %d elements", vec_len (expired));
1074       u32 *p = NULL;
1075       vec_foreach (p, expired)
1076       {
1077         const u32 bs_idx = *p;
1078         if (!pool_is_free_index (bm->sessions, bs_idx))
1079           {
1080             bfd_session_t *bs = pool_elt_at_index (bm->sessions, bs_idx);
1081             bfd_on_timeout (vm, rt, bm, bs, now);
1082             bfd_set_timer (bm, bs, now, 1);
1083           }
1084       }
1085       if (expired)
1086         {
1087           _vec_len (expired) = 0;
1088         }
1089       if (event_data)
1090         {
1091           _vec_len (event_data) = 0;
1092         }
1093     }
1094
1095   return 0;
1096 }
1097
1098 /*
1099  * bfd process node declaration
1100  */
1101 /* *INDENT-OFF* */
1102 VLIB_REGISTER_NODE (bfd_process_node, static) = {
1103   .function = bfd_process,
1104   .type = VLIB_NODE_TYPE_PROCESS,
1105   .name = "bfd-process",
1106   .n_next_nodes = 0,
1107   .next_nodes = {},
1108 };
1109 /* *INDENT-ON* */
1110
1111 static clib_error_t *
1112 bfd_sw_interface_up_down (vnet_main_t * vnm, u32 sw_if_index, u32 flags)
1113 {
1114   // bfd_main_t *bm = &bfd_main;
1115   // vnet_hw_interface_t *hi = vnet_get_sup_hw_interface (vnm, sw_if_index);
1116   if (!(flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP))
1117     {
1118       /* TODO */
1119     }
1120   return 0;
1121 }
1122
1123 VNET_SW_INTERFACE_ADMIN_UP_DOWN_FUNCTION (bfd_sw_interface_up_down);
1124
1125 static clib_error_t *
1126 bfd_hw_interface_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags)
1127 {
1128   // bfd_main_t *bm = &bfd_main;
1129   if (flags & VNET_HW_INTERFACE_FLAG_LINK_UP)
1130     {
1131       /* TODO */
1132     }
1133   return 0;
1134 }
1135
1136 VNET_HW_INTERFACE_LINK_UP_DOWN_FUNCTION (bfd_hw_interface_up_down);
1137
1138 void
1139 bfd_register_listener (bfd_notify_fn_t fn)
1140 {
1141   bfd_main_t *bm = &bfd_main;
1142
1143   vec_add1 (bm->listeners, fn);
1144 }
1145
1146 /*
1147  * setup function
1148  */
1149 static clib_error_t *
1150 bfd_main_init (vlib_main_t * vm)
1151 {
1152 #if BFD_DEBUG
1153   setbuf (stdout, NULL);
1154 #endif
1155   bfd_main_t *bm = &bfd_main;
1156   bm->random_seed = random_default_seed ();
1157   bm->vlib_main = vm;
1158   bm->vnet_main = vnet_get_main ();
1159   memset (&bm->wheel, 0, sizeof (bm->wheel));
1160   bm->cpu_cps = vm->clib_time.clocks_per_second;
1161   BFD_DBG ("cps is %.2f", bm->cpu_cps);
1162   bm->default_desired_min_tx_clocks =
1163     bfd_usec_to_clocks (bm, BFD_DEFAULT_DESIRED_MIN_TX_USEC);
1164   bm->min_required_min_rx_while_echo_clocks =
1165     bfd_usec_to_clocks (bm, BFD_REQUIRED_MIN_RX_USEC_WHILE_ECHO);
1166   const u64 now = clib_cpu_time_now ();
1167   timing_wheel_init (&bm->wheel, now, bm->cpu_cps);
1168   bm->wheel_inaccuracy = 2 << bm->wheel.log2_clocks_per_bin;
1169   return 0;
1170 }
1171
1172 VLIB_INIT_FUNCTION (bfd_main_init);
1173
1174 bfd_session_t *
1175 bfd_get_session (bfd_main_t * bm, bfd_transport_e t)
1176 {
1177   bfd_session_t *result;
1178   pool_get (bm->sessions, result);
1179   memset (result, 0, sizeof (*result));
1180   result->bs_idx = result - bm->sessions;
1181   result->transport = t;
1182   const unsigned limit = 1000;
1183   unsigned counter = 0;
1184   do
1185     {
1186       result->local_discr = random_u32 (&bm->random_seed);
1187       if (counter > limit)
1188         {
1189           clib_warning ("Couldn't allocate unused session discriminator even "
1190                         "after %u tries!", limit);
1191           pool_put (bm->sessions, result);
1192           return NULL;
1193         }
1194       ++counter;
1195     }
1196   while (hash_get (bm->session_by_disc, result->local_discr));
1197   bfd_set_defaults (bm, result);
1198   hash_set (bm->session_by_disc, result->local_discr, result->bs_idx);
1199   return result;
1200 }
1201
1202 void
1203 bfd_put_session (bfd_main_t * bm, bfd_session_t * bs)
1204 {
1205   bfd_notify_listeners (bm, BFD_LISTEN_EVENT_DELETE, bs);
1206   if (bs->auth.curr_key)
1207     {
1208       --bs->auth.curr_key->use_count;
1209     }
1210   if (bs->auth.next_key)
1211     {
1212       --bs->auth.next_key->use_count;
1213     }
1214   hash_unset (bm->session_by_disc, bs->local_discr);
1215   pool_put (bm->sessions, bs);
1216 }
1217
1218 bfd_session_t *
1219 bfd_find_session_by_idx (bfd_main_t * bm, uword bs_idx)
1220 {
1221   if (!pool_is_free_index (bm->sessions, bs_idx))
1222     {
1223       return pool_elt_at_index (bm->sessions, bs_idx);
1224     }
1225   return NULL;
1226 }
1227
1228 bfd_session_t *
1229 bfd_find_session_by_disc (bfd_main_t * bm, u32 disc)
1230 {
1231   uword *p = hash_get (bfd_main.session_by_disc, disc);
1232   if (p)
1233     {
1234       return pool_elt_at_index (bfd_main.sessions, *p);
1235     }
1236   return NULL;
1237 }
1238
1239 /**
1240  * @brief verify bfd packet - common checks
1241  *
1242  * @param pkt
1243  *
1244  * @return 1 if bfd packet is valid
1245  */
1246 int
1247 bfd_verify_pkt_common (const bfd_pkt_t * pkt)
1248 {
1249   if (1 != bfd_pkt_get_version (pkt))
1250     {
1251       BFD_ERR ("BFD verification failed - unexpected version: '%d'",
1252                bfd_pkt_get_version (pkt));
1253       return 0;
1254     }
1255   if (pkt->head.length < sizeof (bfd_pkt_t) ||
1256       (bfd_pkt_get_auth_present (pkt) &&
1257        pkt->head.length < sizeof (bfd_pkt_with_common_auth_t)))
1258     {
1259       BFD_ERR ("BFD verification failed - unexpected length: '%d' (auth "
1260                "present: %d)",
1261                pkt->head.length, bfd_pkt_get_auth_present (pkt));
1262       return 0;
1263     }
1264   if (!pkt->head.detect_mult)
1265     {
1266       BFD_ERR ("BFD verification failed - unexpected detect-mult: '%d'",
1267                pkt->head.detect_mult);
1268       return 0;
1269     }
1270   if (bfd_pkt_get_multipoint (pkt))
1271     {
1272       BFD_ERR ("BFD verification failed - unexpected multipoint: '%d'",
1273                bfd_pkt_get_multipoint (pkt));
1274       return 0;
1275     }
1276   if (!pkt->my_disc)
1277     {
1278       BFD_ERR ("BFD verification failed - unexpected my-disc: '%d'",
1279                pkt->my_disc);
1280       return 0;
1281     }
1282   if (!pkt->your_disc)
1283     {
1284       const u8 pkt_state = bfd_pkt_get_state (pkt);
1285       if (pkt_state != BFD_STATE_down && pkt_state != BFD_STATE_admin_down)
1286         {
1287           BFD_ERR ("BFD verification failed - unexpected state: '%s' "
1288                    "(your-disc is zero)", bfd_state_string (pkt_state));
1289           return 0;
1290         }
1291     }
1292   return 1;
1293 }
1294
1295 static void
1296 bfd_session_switch_auth_to_next (bfd_session_t * bs)
1297 {
1298   BFD_DBG ("Switching authentication key from %U to %U for bs_idx=%u",
1299            format_bfd_auth_key, bs->auth.curr_key, format_bfd_auth_key,
1300            bs->auth.next_key, bs->bs_idx);
1301   bs->auth.is_delayed = 0;
1302   if (bs->auth.curr_key)
1303     {
1304       --bs->auth.curr_key->use_count;
1305     }
1306   bs->auth.curr_key = bs->auth.next_key;
1307   bs->auth.next_key = NULL;
1308   bs->auth.curr_bfd_key_id = bs->auth.next_bfd_key_id;
1309 }
1310
1311 static int
1312 bfd_auth_type_is_meticulous (bfd_auth_type_e auth_type)
1313 {
1314   if (BFD_AUTH_TYPE_meticulous_keyed_md5 == auth_type ||
1315       BFD_AUTH_TYPE_meticulous_keyed_sha1 == auth_type)
1316     {
1317       return 1;
1318     }
1319   return 0;
1320 }
1321
1322 static int
1323 bfd_verify_pkt_auth_seq_num (bfd_session_t * bs,
1324                              u32 received_seq_num, int is_meticulous)
1325 {
1326   /*
1327    * RFC 5880 6.8.1:
1328    *
1329    * This variable MUST be set to zero after no packets have been
1330    * received on this session for at least twice the Detection Time.
1331    */
1332   u64 now = clib_cpu_time_now ();
1333   if (now - bs->last_rx_clocks > bs->detection_time_clocks * 2)
1334     {
1335       BFD_DBG ("BFD peer unresponsive for %lu clocks, which is > 2 * "
1336                "detection_time=%u clocks, resetting remote_seq_number_known "
1337                "flag",
1338                now - bs->last_rx_clocks, bs->detection_time_clocks * 2);
1339       bs->auth.remote_seq_number_known = 0;
1340     }
1341   if (bs->auth.remote_seq_number_known)
1342     {
1343       /* remote sequence number is known, verify its validity */
1344       const u32 max_u32 = 0xffffffff;
1345       /* the calculation might wrap, account for the special case... */
1346       if (bs->auth.remote_seq_number > max_u32 - 3 * bs->local_detect_mult)
1347         {
1348           /*
1349            * special case
1350            *
1351            *        x                   y                   z
1352            *  |----------+----------------------------+-----------|
1353            *  0          ^                            ^ 0xffffffff
1354            *             |        remote_seq_num------+
1355            *             |
1356            *             +-----(remote_seq_num + 3*detect_mult) % * 0xffffffff
1357            *
1358            *    x + y + z = 0xffffffff
1359            *    x + z = 3 * detect_mult
1360            */
1361           const u32 z = max_u32 - bs->auth.remote_seq_number;
1362           const u32 x = 3 * bs->local_detect_mult - z;
1363           if (received_seq_num > x &&
1364               received_seq_num < bs->auth.remote_seq_number + is_meticulous)
1365             {
1366               BFD_ERR
1367                 ("Recvd sequence number=%u out of ranges <0, %u>, <%u, %u>",
1368                  received_seq_num, x,
1369                  bs->auth.remote_seq_number + is_meticulous, max_u32);
1370               return 0;
1371             }
1372         }
1373       else
1374         {
1375           /* regular case */
1376           const u32 min = bs->auth.remote_seq_number + is_meticulous;
1377           const u32 max =
1378             bs->auth.remote_seq_number + 3 * bs->local_detect_mult;
1379           if (received_seq_num < min || received_seq_num > max)
1380             {
1381               BFD_ERR ("Recvd sequence number=%u out of range <%u, %u>",
1382                        received_seq_num, min, max);
1383               return 0;
1384             }
1385         }
1386     }
1387   return 1;
1388 }
1389
1390 static int
1391 bfd_verify_pkt_auth_key_sha1 (const bfd_pkt_t * pkt, u32 pkt_size,
1392                               bfd_session_t * bs, u8 bfd_key_id,
1393                               bfd_auth_key_t * auth_key)
1394 {
1395   ASSERT (auth_key->auth_type == BFD_AUTH_TYPE_keyed_sha1 ||
1396           auth_key->auth_type == BFD_AUTH_TYPE_meticulous_keyed_sha1);
1397
1398   u8 result[SHA_DIGEST_LENGTH];
1399   bfd_pkt_with_common_auth_t *with_common = (void *) pkt;
1400   if (pkt_size < sizeof (*with_common))
1401     {
1402       BFD_ERR ("Packet size too small to hold authentication common header");
1403       return 0;
1404     }
1405   if (with_common->common_auth.type != auth_key->auth_type)
1406     {
1407       BFD_ERR ("BFD auth type mismatch, packet auth=%d:%s doesn't match "
1408                "in-use auth=%d:%s",
1409                with_common->common_auth.type,
1410                bfd_auth_type_str (with_common->common_auth.type),
1411                auth_key->auth_type, bfd_auth_type_str (auth_key->auth_type));
1412       return 0;
1413     }
1414   bfd_pkt_with_sha1_auth_t *with_sha1 = (void *) pkt;
1415   if (pkt_size < sizeof (*with_sha1) ||
1416       with_sha1->sha1_auth.type_len.len < sizeof (with_sha1->sha1_auth))
1417     {
1418       BFD_ERR
1419         ("BFD size mismatch, payload size=%u, expected=%u, auth_len=%u, "
1420          "expected=%u", pkt_size, sizeof (*with_sha1),
1421          with_sha1->sha1_auth.type_len.len, sizeof (with_sha1->sha1_auth));
1422       return 0;
1423     }
1424   if (with_sha1->sha1_auth.key_id != bfd_key_id)
1425     {
1426       BFD_ERR
1427         ("BFD key ID mismatch, packet key ID=%u doesn't match key ID=%u%s",
1428          with_sha1->sha1_auth.key_id, bfd_key_id,
1429          bs->
1430          auth.is_delayed ? " (but a delayed auth change is scheduled)" : "");
1431       return 0;
1432     }
1433   SHA_CTX ctx;
1434   if (!SHA1_Init (&ctx))
1435     {
1436       BFD_ERR ("SHA1_Init failed");
1437       return 0;
1438     }
1439   /* ignore last 20 bytes - use the actual key data instead pkt data */
1440   if (!SHA1_Update (&ctx, with_sha1,
1441                     sizeof (*with_sha1) - sizeof (with_sha1->sha1_auth.hash)))
1442     {
1443       BFD_ERR ("SHA1_Update failed");
1444       return 0;
1445     }
1446   if (!SHA1_Update (&ctx, auth_key->key, sizeof (auth_key->key)))
1447     {
1448       BFD_ERR ("SHA1_Update failed");
1449       return 0;
1450     }
1451   if (!SHA1_Final (result, &ctx))
1452     {
1453       BFD_ERR ("SHA1_Final failed");
1454       return 0;
1455     }
1456   if (0 == memcmp (result, with_sha1->sha1_auth.hash, SHA_DIGEST_LENGTH))
1457     {
1458       return 1;
1459     }
1460   BFD_ERR ("SHA1 hash: %U doesn't match the expected value: %U",
1461            format_hex_bytes, with_sha1->sha1_auth.hash, SHA_DIGEST_LENGTH,
1462            format_hex_bytes, result, SHA_DIGEST_LENGTH);
1463   return 0;
1464 }
1465
1466 static int
1467 bfd_verify_pkt_auth_key (const bfd_pkt_t * pkt, u32 pkt_size,
1468                          bfd_session_t * bs, u8 bfd_key_id,
1469                          bfd_auth_key_t * auth_key)
1470 {
1471   switch (auth_key->auth_type)
1472     {
1473     case BFD_AUTH_TYPE_reserved:
1474       clib_warning ("Internal error, unexpected auth_type=%d:%s",
1475                     auth_key->auth_type,
1476                     bfd_auth_type_str (auth_key->auth_type));
1477       return 0;
1478     case BFD_AUTH_TYPE_simple_password:
1479       clib_warning
1480         ("Internal error, not implemented, unexpected auth_type=%d:%s",
1481          auth_key->auth_type, bfd_auth_type_str (auth_key->auth_type));
1482       return 0;
1483     case BFD_AUTH_TYPE_keyed_md5:
1484       /* fallthrough */
1485     case BFD_AUTH_TYPE_meticulous_keyed_md5:
1486       clib_warning
1487         ("Internal error, not implemented, unexpected auth_type=%d:%s",
1488          auth_key->auth_type, bfd_auth_type_str (auth_key->auth_type));
1489       return 0;
1490     case BFD_AUTH_TYPE_keyed_sha1:
1491       /* fallthrough */
1492     case BFD_AUTH_TYPE_meticulous_keyed_sha1:
1493 #if WITH_LIBSSL > 0
1494       do
1495         {
1496           const u32 seq_num = clib_net_to_host_u32 (((bfd_pkt_with_sha1_auth_t
1497                                                       *) pkt)->
1498                                                     sha1_auth.seq_num);
1499           return bfd_verify_pkt_auth_seq_num (bs, seq_num,
1500                                               bfd_auth_type_is_meticulous
1501                                               (auth_key->auth_type))
1502             && bfd_verify_pkt_auth_key_sha1 (pkt, pkt_size, bs, bfd_key_id,
1503                                              auth_key);
1504         }
1505       while (0);
1506 #else
1507       clib_warning
1508         ("Internal error, attempt to use SHA1 without SSL support");
1509       return 0;
1510 #endif
1511     }
1512   return 0;
1513 }
1514
1515 /**
1516  * @brief verify bfd packet - authentication
1517  *
1518  * @param pkt
1519  *
1520  * @return 1 if bfd packet is valid
1521  */
1522 int
1523 bfd_verify_pkt_auth (const bfd_pkt_t * pkt, u16 pkt_size, bfd_session_t * bs)
1524 {
1525   if (bfd_pkt_get_auth_present (pkt))
1526     {
1527       /* authentication present in packet */
1528       if (!bs->auth.curr_key)
1529         {
1530           /* currently not using authentication - can we turn it on? */
1531           if (bs->auth.is_delayed && bs->auth.next_key)
1532             {
1533               /* yes, switch is scheduled - make sure the auth is valid */
1534               if (bfd_verify_pkt_auth_key (pkt, pkt_size, bs,
1535                                            bs->auth.next_bfd_key_id,
1536                                            bs->auth.next_key))
1537                 {
1538                   /* auth matches next key, do the switch, packet is valid */
1539                   bfd_session_switch_auth_to_next (bs);
1540                   return 1;
1541                 }
1542             }
1543         }
1544       else
1545         {
1546           /* yes, using authentication, verify the key */
1547           if (bfd_verify_pkt_auth_key (pkt, pkt_size, bs,
1548                                        bs->auth.curr_bfd_key_id,
1549                                        bs->auth.curr_key))
1550             {
1551               /* verification passed, packet is valid */
1552               return 1;
1553             }
1554           else
1555             {
1556               /* verification failed - but maybe we need to switch key */
1557               if (bs->auth.is_delayed && bs->auth.next_key)
1558                 {
1559                   /* delayed switch present, verify if that key works */
1560                   if (bfd_verify_pkt_auth_key (pkt, pkt_size, bs,
1561                                                bs->auth.next_bfd_key_id,
1562                                                bs->auth.next_key))
1563                     {
1564                       /* auth matches next key, switch key, packet is valid */
1565                       bfd_session_switch_auth_to_next (bs);
1566                       return 1;
1567                     }
1568                 }
1569             }
1570         }
1571     }
1572   else
1573     {
1574       /* authentication in packet not present */
1575       if (pkt_size > sizeof (*pkt))
1576         {
1577           BFD_ERR ("BFD verification failed - unexpected packet size '%d' "
1578                    "(auth not present)", pkt_size);
1579           return 0;
1580         }
1581       if (bs->auth.curr_key)
1582         {
1583           /* currently authenticating - could we turn it off? */
1584           if (bs->auth.is_delayed && !bs->auth.next_key)
1585             {
1586               /* yes, delayed switch to NULL key is scheduled */
1587               bfd_session_switch_auth_to_next (bs);
1588               return 1;
1589             }
1590         }
1591       else
1592         {
1593           /* no auth in packet, no auth in use - packet is valid */
1594           return 1;
1595         }
1596     }
1597   return 0;
1598 }
1599
1600 void
1601 bfd_consume_pkt (bfd_main_t * bm, const bfd_pkt_t * pkt, u32 bs_idx)
1602 {
1603   bfd_session_t *bs = bfd_find_session_by_idx (bm, bs_idx);
1604   if (!bs || (pkt->your_disc && pkt->your_disc != bs->local_discr))
1605     {
1606       return;
1607     }
1608   BFD_DBG ("Scanning bfd packet, bs_idx=%d", bs->bs_idx);
1609   bs->remote_discr = pkt->my_disc;
1610   bs->remote_state = bfd_pkt_get_state (pkt);
1611   bs->remote_demand = bfd_pkt_get_demand (pkt);
1612   bs->remote_diag = bfd_pkt_get_diag_code (pkt);
1613   u64 now = clib_cpu_time_now ();
1614   bs->last_rx_clocks = now;
1615   if (bfd_pkt_get_auth_present (pkt))
1616     {
1617       bfd_auth_type_e auth_type =
1618         ((bfd_pkt_with_common_auth_t *) (pkt))->common_auth.type;
1619       switch (auth_type)
1620         {
1621         case BFD_AUTH_TYPE_reserved:
1622           /* fallthrough */
1623         case BFD_AUTH_TYPE_simple_password:
1624           /* fallthrough */
1625         case BFD_AUTH_TYPE_keyed_md5:
1626           /* fallthrough */
1627         case BFD_AUTH_TYPE_meticulous_keyed_md5:
1628           clib_warning ("Internal error, unexpected auth_type=%d:%s",
1629                         auth_type, bfd_auth_type_str (auth_type));
1630           break;
1631         case BFD_AUTH_TYPE_keyed_sha1:
1632           /* fallthrough */
1633         case BFD_AUTH_TYPE_meticulous_keyed_sha1:
1634           do
1635             {
1636               bfd_pkt_with_sha1_auth_t *with_sha1 =
1637                 (bfd_pkt_with_sha1_auth_t *) pkt;
1638               bs->auth.remote_seq_number =
1639                 clib_net_to_host_u32 (with_sha1->sha1_auth.seq_num);
1640               bs->auth.remote_seq_number_known = 1;
1641               BFD_DBG ("Received sequence number %u",
1642                        bs->auth.remote_seq_number);
1643             }
1644           while (0);
1645         }
1646     }
1647   bs->remote_desired_min_tx_clocks =
1648     bfd_usec_to_clocks (bm, clib_net_to_host_u32 (pkt->des_min_tx));
1649   bs->remote_detect_mult = pkt->head.detect_mult;
1650   bfd_set_remote_required_min_rx (bm, bs, now,
1651                                   clib_net_to_host_u32 (pkt->req_min_rx));
1652   bfd_set_remote_required_min_echo_rx (bm, bs, now,
1653                                        clib_net_to_host_u32
1654                                        (pkt->req_min_echo_rx));
1655   if (bfd_pkt_get_final (pkt))
1656     {
1657       if (BFD_POLL_IN_PROGRESS == bs->poll_state)
1658         {
1659           BFD_DBG ("Poll sequence terminated, bs_idx=%u", bs->bs_idx);
1660           bfd_set_poll_state (bs, BFD_POLL_NOT_NEEDED);
1661           if (BFD_STATE_up == bs->local_state)
1662             {
1663               bfd_set_effective_required_min_rx (bm, bs,
1664                                                  clib_max (bs->echo *
1665                                                            bm->min_required_min_rx_while_echo_clocks,
1666                                                            bs->config_required_min_rx_clocks));
1667             }
1668         }
1669       else if (BFD_POLL_IN_PROGRESS_AND_QUEUED == bs->poll_state)
1670         {
1671           /*
1672            * next poll sequence must be delayed by at least the round trip
1673            * time, so calculate that here
1674            */
1675           BFD_DBG ("Next poll sequence can commence in " BFD_CLK_FMT,
1676                    BFD_CLK_PRN (now -
1677                                 bs->poll_state_start_or_timeout_clocks));
1678           bs->poll_state_start_or_timeout_clocks =
1679             now + (now - bs->poll_state_start_or_timeout_clocks);
1680           BFD_DBG
1681             ("Poll sequence terminated, but another is needed, bs_idx=%u",
1682              bs->bs_idx);
1683           bfd_set_poll_state (bs, BFD_POLL_NEEDED);
1684         }
1685     }
1686   bfd_calc_next_tx (bm, bs, now);
1687   bfd_set_timer (bm, bs, now, 0);
1688   if (BFD_STATE_admin_down == bs->local_state)
1689     {
1690       BFD_DBG ("Session is admin-down, ignoring packet, bs_idx=%u",
1691                bs->bs_idx);
1692       return;
1693     }
1694   if (BFD_STATE_admin_down == bs->remote_state)
1695     {
1696       bfd_set_diag (bs, BFD_DIAG_CODE_neighbor_sig_down);
1697       bfd_set_state (bm, bs, BFD_STATE_down, 0);
1698     }
1699   else if (BFD_STATE_down == bs->local_state)
1700     {
1701       if (BFD_STATE_down == bs->remote_state)
1702         {
1703           bfd_set_diag (bs, BFD_DIAG_CODE_no_diag);
1704           bfd_set_state (bm, bs, BFD_STATE_init, 0);
1705         }
1706       else if (BFD_STATE_init == bs->remote_state)
1707         {
1708           bfd_set_diag (bs, BFD_DIAG_CODE_no_diag);
1709           bfd_set_state (bm, bs, BFD_STATE_up, 0);
1710         }
1711     }
1712   else if (BFD_STATE_init == bs->local_state)
1713     {
1714       if (BFD_STATE_up == bs->remote_state ||
1715           BFD_STATE_init == bs->remote_state)
1716         {
1717           bfd_set_diag (bs, BFD_DIAG_CODE_no_diag);
1718           bfd_set_state (bm, bs, BFD_STATE_up, 0);
1719         }
1720     }
1721   else                          /* BFD_STATE_up == bs->local_state */
1722     {
1723       if (BFD_STATE_down == bs->remote_state)
1724         {
1725           bfd_set_diag (bs, BFD_DIAG_CODE_neighbor_sig_down);
1726           bfd_set_state (bm, bs, BFD_STATE_down, 0);
1727         }
1728     }
1729 }
1730
1731 int
1732 bfd_consume_echo_pkt (bfd_main_t * bm, vlib_buffer_t * b)
1733 {
1734   bfd_echo_pkt_t *pkt = NULL;
1735   if (b->current_length != sizeof (*pkt))
1736     {
1737       return 0;
1738     }
1739   pkt = vlib_buffer_get_current (b);
1740   bfd_session_t *bs = bfd_find_session_by_disc (bm, pkt->discriminator);
1741   if (!bs)
1742     {
1743       return 0;
1744     }
1745   BFD_DBG ("Scanning bfd echo packet, bs_idx=%d", bs->bs_idx);
1746   u64 checksum =
1747     bfd_calc_echo_checksum (bs->local_discr, pkt->expire_time_clocks,
1748                             bs->echo_secret);
1749   if (checksum != pkt->checksum)
1750     {
1751       BFD_DBG ("Invalid echo packet, checksum mismatch");
1752       return 1;
1753     }
1754   u64 now = clib_cpu_time_now ();
1755   if (pkt->expire_time_clocks < now)
1756     {
1757       BFD_DBG ("Stale packet received, expire time %lu < now %lu",
1758                pkt->expire_time_clocks, now);
1759     }
1760   else
1761     {
1762       bs->echo_last_rx_clocks = now;
1763     }
1764   return 1;
1765 }
1766
1767 u8 *
1768 format_bfd_session (u8 * s, va_list * args)
1769 {
1770   const bfd_session_t *bs = va_arg (*args, bfd_session_t *);
1771   u32 indent = format_get_indent (s);
1772   s = format (s, "bs_idx=%u local-state=%s remote-state=%s\n"
1773               "%Ulocal-discriminator=%u remote-discriminator=%u\n"
1774               "%Ulocal-diag=%s echo-active=%s\n"
1775               "%Udesired-min-tx=%u required-min-rx=%u\n"
1776               "%Urequired-min-echo-rx=%u detect-mult=%u\n"
1777               "%Uremote-min-rx=%u remote-min-echo-rx=%u\n"
1778               "%Uremote-demand=%s poll-state=%s\n"
1779               "%Uauth: local-seq-num=%u remote-seq-num=%u\n"
1780               "%U      is-delayed=%s\n"
1781               "%U      curr-key=%U\n"
1782               "%U      next-key=%U",
1783               bs->bs_idx, bfd_state_string (bs->local_state),
1784               bfd_state_string (bs->remote_state), format_white_space, indent,
1785               bs->local_discr, bs->remote_discr, format_white_space, indent,
1786               bfd_diag_code_string (bs->local_diag),
1787               (bs->echo ? "yes" : "no"), format_white_space, indent,
1788               bs->config_desired_min_tx_usec, bs->config_required_min_rx_usec,
1789               format_white_space, indent, 1, bs->local_detect_mult,
1790               format_white_space, indent, bs->remote_min_rx_usec,
1791               bs->remote_min_echo_rx_usec, format_white_space, indent,
1792               (bs->remote_demand ? "yes" : "no"),
1793               bfd_poll_state_string (bs->poll_state), format_white_space,
1794               indent, bs->auth.local_seq_number, bs->auth.remote_seq_number,
1795               format_white_space, indent,
1796               (bs->auth.is_delayed ? "yes" : "no"), format_white_space,
1797               indent, format_bfd_auth_key, bs->auth.curr_key,
1798               format_white_space, indent, format_bfd_auth_key,
1799               bs->auth.next_key);
1800   return s;
1801 }
1802
1803 unsigned
1804 bfd_auth_type_supported (bfd_auth_type_e auth_type)
1805 {
1806   if (auth_type == BFD_AUTH_TYPE_keyed_sha1 ||
1807       auth_type == BFD_AUTH_TYPE_meticulous_keyed_sha1)
1808     {
1809       return 1;
1810     }
1811   return 0;
1812 }
1813
1814 vnet_api_error_t
1815 bfd_auth_activate (bfd_session_t * bs, u32 conf_key_id,
1816                    u8 bfd_key_id, u8 is_delayed)
1817 {
1818   bfd_main_t *bm = &bfd_main;
1819   const uword *key_idx_p =
1820     hash_get (bm->auth_key_by_conf_key_id, conf_key_id);
1821   if (!key_idx_p)
1822     {
1823       clib_warning ("Authentication key with config ID %u doesn't exist)",
1824                     conf_key_id);
1825       return VNET_API_ERROR_BFD_ENOENT;
1826     }
1827   const uword key_idx = *key_idx_p;
1828   bfd_auth_key_t *key = pool_elt_at_index (bm->auth_keys, key_idx);
1829   if (is_delayed)
1830     {
1831       if (bs->auth.next_key == key)
1832         {
1833           /* already using this key, no changes required */
1834           return 0;
1835         }
1836       bs->auth.next_key = key;
1837       bs->auth.next_bfd_key_id = bfd_key_id;
1838       bs->auth.is_delayed = 1;
1839     }
1840   else
1841     {
1842       if (bs->auth.curr_key == key)
1843         {
1844           /* already using this key, no changes required */
1845           return 0;
1846         }
1847       if (bs->auth.curr_key)
1848         {
1849           --bs->auth.curr_key->use_count;
1850         }
1851       bs->auth.curr_key = key;
1852       bs->auth.curr_bfd_key_id = bfd_key_id;
1853       bs->auth.is_delayed = 0;
1854     }
1855   ++key->use_count;
1856   BFD_DBG ("\nSession auth modified: %U", format_bfd_session, bs);
1857   return 0;
1858 }
1859
1860 vnet_api_error_t
1861 bfd_auth_deactivate (bfd_session_t * bs, u8 is_delayed)
1862 {
1863 #if WITH_LIBSSL > 0
1864   if (!is_delayed)
1865     {
1866       /* not delayed - deactivate the current key right now */
1867       if (bs->auth.curr_key)
1868         {
1869           --bs->auth.curr_key->use_count;
1870           bs->auth.curr_key = NULL;
1871         }
1872       bs->auth.is_delayed = 0;
1873     }
1874   else
1875     {
1876       /* delayed - mark as so */
1877       bs->auth.is_delayed = 1;
1878     }
1879   /*
1880    * clear the next key unconditionally - either the auth change is not delayed
1881    * in which case the caller expects the session to not use authentication
1882    * from this point forward, or it is delayed, in which case the next_key
1883    * needs to be set to NULL to make it so in the future
1884    */
1885   if (bs->auth.next_key)
1886     {
1887       --bs->auth.next_key->use_count;
1888       bs->auth.next_key = NULL;
1889     }
1890   BFD_DBG ("\nSession auth modified: %U", format_bfd_session, bs);
1891   return 0;
1892 #else
1893   clib_warning ("SSL missing, cannot deactivate BFD authentication");
1894   return VNET_API_ERROR_BFD_NOTSUPP;
1895 #endif
1896 }
1897
1898 vnet_api_error_t
1899 bfd_session_set_params (bfd_main_t * bm, bfd_session_t * bs,
1900                         u32 desired_min_tx_usec,
1901                         u32 required_min_rx_usec, u8 detect_mult)
1902 {
1903   if (bs->local_detect_mult != detect_mult ||
1904       bs->config_desired_min_tx_usec != desired_min_tx_usec ||
1905       bs->config_required_min_rx_usec != required_min_rx_usec)
1906     {
1907       BFD_DBG ("\nChanging session params: %U", format_bfd_session, bs);
1908       switch (bs->poll_state)
1909         {
1910         case BFD_POLL_NOT_NEEDED:
1911           if (BFD_STATE_up == bs->local_state ||
1912               BFD_STATE_init == bs->local_state)
1913             {
1914               /* poll sequence is not needed for detect multiplier change */
1915               if (bs->config_desired_min_tx_usec != desired_min_tx_usec ||
1916                   bs->config_required_min_rx_usec != required_min_rx_usec)
1917                 {
1918                   bfd_set_poll_state (bs, BFD_POLL_NEEDED);
1919                 }
1920             }
1921           break;
1922         case BFD_POLL_NEEDED:
1923         case BFD_POLL_IN_PROGRESS_AND_QUEUED:
1924           /*
1925            * nothing to do - will be handled in the future poll which is
1926            * already scheduled for execution
1927            */
1928           break;
1929         case BFD_POLL_IN_PROGRESS:
1930           /* poll sequence is not needed for detect multiplier change */
1931           if (bs->config_desired_min_tx_usec != desired_min_tx_usec ||
1932               bs->config_required_min_rx_usec != required_min_rx_usec)
1933             {
1934               BFD_DBG ("Poll in progress, queueing extra poll, bs_idx=%u",
1935                        bs->bs_idx);
1936               bfd_set_poll_state (bs, BFD_POLL_IN_PROGRESS_AND_QUEUED);
1937             }
1938         }
1939
1940       bs->local_detect_mult = detect_mult;
1941       bs->config_desired_min_tx_usec = desired_min_tx_usec;
1942       bs->config_desired_min_tx_clocks =
1943         bfd_usec_to_clocks (bm, desired_min_tx_usec);
1944       bs->config_required_min_rx_usec = required_min_rx_usec;
1945       bs->config_required_min_rx_clocks =
1946         bfd_usec_to_clocks (bm, required_min_rx_usec);
1947       BFD_DBG ("\nChanged session params: %U", format_bfd_session, bs);
1948
1949       vlib_process_signal_event (bm->vlib_main, bm->bfd_process_node_index,
1950                                  BFD_EVENT_CONFIG_CHANGED, bs->bs_idx);
1951     }
1952   else
1953     {
1954       BFD_DBG ("Ignore parameter change - no change, bs_idx=%u", bs->bs_idx);
1955     }
1956   return 0;
1957 }
1958
1959 vnet_api_error_t
1960 bfd_auth_set_key (u32 conf_key_id, u8 auth_type, u8 key_len,
1961                   const u8 * key_data)
1962 {
1963 #if WITH_LIBSSL > 0
1964   bfd_auth_key_t *auth_key = NULL;
1965   if (!key_len || key_len > bfd_max_key_len_for_auth_type (auth_type))
1966     {
1967       clib_warning ("Invalid authentication key length for auth_type=%d:%s "
1968                     "(key_len=%u, must be "
1969                     "non-zero, expected max=%u)",
1970                     auth_type, bfd_auth_type_str (auth_type), key_len,
1971                     (u32) bfd_max_key_len_for_auth_type (auth_type));
1972       return VNET_API_ERROR_INVALID_VALUE;
1973     }
1974   if (!bfd_auth_type_supported (auth_type))
1975     {
1976       clib_warning ("Unsupported auth type=%d:%s", auth_type,
1977                     bfd_auth_type_str (auth_type));
1978       return VNET_API_ERROR_BFD_NOTSUPP;
1979     }
1980   bfd_main_t *bm = &bfd_main;
1981   uword *key_idx_p = hash_get (bm->auth_key_by_conf_key_id, conf_key_id);
1982   if (key_idx_p)
1983     {
1984       /* modifying existing key - must not be used */
1985       const uword key_idx = *key_idx_p;
1986       auth_key = pool_elt_at_index (bm->auth_keys, key_idx);
1987       if (auth_key->use_count > 0)
1988         {
1989           clib_warning ("Authentication key with conf ID %u in use by %u BFD "
1990                         "session(s) - cannot modify",
1991                         conf_key_id, auth_key->use_count);
1992           return VNET_API_ERROR_BFD_EINUSE;
1993         }
1994     }
1995   else
1996     {
1997       /* adding new key */
1998       pool_get (bm->auth_keys, auth_key);
1999       auth_key->conf_key_id = conf_key_id;
2000       hash_set (bm->auth_key_by_conf_key_id, conf_key_id,
2001                 auth_key - bm->auth_keys);
2002     }
2003   auth_key->auth_type = auth_type;
2004   memset (auth_key->key, 0, sizeof (auth_key->key));
2005   clib_memcpy (auth_key->key, key_data, key_len);
2006   return 0;
2007 #else
2008   clib_warning ("SSL missing, cannot manipulate authentication keys");
2009   return VNET_API_ERROR_BFD_NOTSUPP;
2010 #endif
2011 }
2012
2013 vnet_api_error_t
2014 bfd_auth_del_key (u32 conf_key_id)
2015 {
2016 #if WITH_LIBSSL > 0
2017   bfd_auth_key_t *auth_key = NULL;
2018   bfd_main_t *bm = &bfd_main;
2019   uword *key_idx_p = hash_get (bm->auth_key_by_conf_key_id, conf_key_id);
2020   if (key_idx_p)
2021     {
2022       /* deleting existing key - must not be used */
2023       const uword key_idx = *key_idx_p;
2024       auth_key = pool_elt_at_index (bm->auth_keys, key_idx);
2025       if (auth_key->use_count > 0)
2026         {
2027           clib_warning ("Authentication key with conf ID %u in use by %u BFD "
2028                         "session(s) - cannot delete",
2029                         conf_key_id, auth_key->use_count);
2030           return VNET_API_ERROR_BFD_EINUSE;
2031         }
2032       hash_unset (bm->auth_key_by_conf_key_id, conf_key_id);
2033       memset (auth_key, 0, sizeof (*auth_key));
2034       pool_put (bm->auth_keys, auth_key);
2035     }
2036   else
2037     {
2038       /* no such key */
2039       clib_warning ("Authentication key with conf ID %u does not exist",
2040                     conf_key_id);
2041       return VNET_API_ERROR_BFD_ENOENT;
2042     }
2043   return 0;
2044 #else
2045   clib_warning ("SSL missing, cannot manipulate authentication keys");
2046   return VNET_API_ERROR_BFD_NOTSUPP;
2047 #endif
2048 }
2049
2050 bfd_main_t bfd_main;
2051
2052 /*
2053  * fd.io coding-style-patch-verification: ON
2054  *
2055  * Local Variables:
2056  * eval: (c-set-style "gnu")
2057  * End:
2058  */