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