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