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