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