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