BFD: minor fixes
[vpp.git] / src / vnet / bfd / bfd_main.c
1 /*
2  * Copyright (c) 2011-2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /**
16  * @file
17  * @brief BFD nodes implementation
18  */
19
20 #include <vppinfra/random.h>
21 #include <vppinfra/error.h>
22 #include <vppinfra/hash.h>
23 #include <vnet/ethernet/ethernet.h>
24 #include <vnet/ethernet/packet.h>
25 #include <vnet/bfd/bfd_debug.h>
26 #include <vnet/bfd/bfd_protocol.h>
27 #include <vnet/bfd/bfd_main.h>
28 #if WITH_LIBSSL > 0
29 #include <openssl/sha.h>
30 #endif
31
32 static u64
33 bfd_usec_to_clocks (const bfd_main_t * bm, u64 us)
34 {
35   return bm->cpu_cps * ((f64) us / USEC_PER_SECOND);
36 }
37
38 // static u64 bfd_clocks_to_usec (const bfd_main_t *bm, u64 clocks)
39 //{
40 //  return (clocks / bm->cpu_cps) * USEC_PER_SECOND;
41 //}
42
43 static vlib_node_registration_t bfd_process_node;
44
45 /* set to 0 here, real values filled at startup */
46 static u32 bfd_node_index_by_transport[] = {
47 #define F(t, n) [BFD_TRANSPORT_##t] = 0,
48   foreach_bfd_transport (F)
49 #undef F
50 };
51
52 static u8 *
53 format_bfd_auth_key (u8 * s, va_list * args)
54 {
55   const bfd_auth_key_t *key = va_arg (*args, bfd_auth_key_t *);
56   if (key)
57     {
58       s = format (s, "{auth-type=%u:%s, conf-key-id=%u, use-count=%u}, ",
59                   key->auth_type, bfd_auth_type_str (key->auth_type),
60                   key->conf_key_id, key->use_count);
61     }
62   else
63     {
64       s = format (s, "{none}");
65     }
66   return s;
67 }
68
69 /*
70  * We actually send all bfd pkts to the "error" node after scanning
71  * them, so the graph node has only one next-index. The "error-drop"
72  * node automatically bumps our per-node packet counters for us.
73  */
74 typedef enum
75 {
76   BFD_INPUT_NEXT_NORMAL,
77   BFD_INPUT_N_NEXT,
78 } bfd_input_next_t;
79
80 static void bfd_on_state_change (bfd_main_t * bm, bfd_session_t * bs, u64 now,
81                                  int handling_wakeup);
82
83 static void
84 bfd_set_defaults (bfd_main_t * bm, bfd_session_t * bs)
85 {
86   bs->local_state = BFD_STATE_down;
87   bs->local_diag = BFD_DIAG_CODE_no_diag;
88   bs->remote_state = BFD_STATE_down;
89   bs->local_demand = 0;
90   bs->remote_discr = 0;
91   bs->config_desired_min_tx_usec = BFD_DEFAULT_DESIRED_MIN_TX_US;
92   bs->config_desired_min_tx_clocks = bm->default_desired_min_tx_clocks;
93   bs->effective_desired_min_tx_clocks = bm->default_desired_min_tx_clocks;
94   bs->remote_min_rx_usec = 1;
95   bs->remote_min_rx_clocks = bfd_usec_to_clocks (bm, bs->remote_min_rx_usec);
96   bs->remote_demand = 0;
97   bs->auth.remote_seq_number = 0;
98   bs->auth.remote_seq_number_known = 0;
99   bs->auth.local_seq_number = random_u32 (&bm->random_seed);
100 }
101
102 static void
103 bfd_set_diag (bfd_session_t * bs, bfd_diag_code_e code)
104 {
105   if (bs->local_diag != code)
106     {
107       BFD_DBG ("set local_diag, bs_idx=%d: '%d:%s'", bs->bs_idx, code,
108                bfd_diag_code_string (code));
109       bs->local_diag = code;
110     }
111 }
112
113 static void
114 bfd_set_state (bfd_main_t * bm, bfd_session_t * bs,
115                bfd_state_e new_state, int handling_wakeup)
116 {
117   if (bs->local_state != new_state)
118     {
119       BFD_DBG ("Change state, bs_idx=%d: %s->%s", bs->bs_idx,
120                bfd_state_string (bs->local_state),
121                bfd_state_string (new_state));
122       bs->local_state = new_state;
123       bfd_on_state_change (bm, bs, clib_cpu_time_now (), handling_wakeup);
124     }
125 }
126
127 static void
128 bfd_recalc_tx_interval (bfd_main_t * bm, bfd_session_t * bs)
129 {
130   if (!bs->local_demand)
131     {
132       bs->transmit_interval_clocks =
133         clib_max (bs->effective_desired_min_tx_clocks,
134                   bs->remote_min_rx_clocks);
135     }
136   else
137     {
138       /* TODO */
139     }
140   BFD_DBG ("Recalculated transmit interval %lu clocks/%.2fs",
141            bs->transmit_interval_clocks,
142            bs->transmit_interval_clocks / bm->cpu_cps);
143 }
144
145 static void
146 bfd_calc_next_tx (bfd_main_t * bm, bfd_session_t * bs, u64 now)
147 {
148   if (!bs->local_demand)
149     {
150       if (bs->local_detect_mult > 1)
151         {
152           /* common case - 75-100% of transmit interval */
153           bs->tx_timeout_clocks = bs->last_tx_clocks +
154             (1 - .25 * (random_f64 (&bm->random_seed))) *
155             bs->transmit_interval_clocks;
156           if (bs->tx_timeout_clocks < now)
157             {
158               /* huh, we've missed it already, transmit now */
159               BFD_DBG ("Missed %lu transmit events (now is %lu, calc "
160                        "tx_timeout is %lu)",
161                        (now - bs->tx_timeout_clocks) /
162                        bs->transmit_interval_clocks,
163                        now, bs->tx_timeout_clocks);
164               bs->tx_timeout_clocks = now;
165             }
166         }
167       else
168         {
169           /* special case - 75-90% of transmit interval */
170           bs->tx_timeout_clocks =
171             bs->last_tx_clocks +
172             (.9 - .15 * (random_f64 (&bm->random_seed))) *
173             bs->transmit_interval_clocks;
174           if (bs->tx_timeout_clocks < now)
175             {
176               /* huh, we've missed it already, transmit now */
177               BFD_DBG ("Missed %lu transmit events (now is %lu, calc "
178                        "tx_timeout is %lu)",
179                        (now - bs->tx_timeout_clocks) /
180                        bs->transmit_interval_clocks,
181                        now, bs->tx_timeout_clocks);
182               bs->tx_timeout_clocks = now;
183             }
184         }
185     }
186   else
187     {
188       /* TODO */
189     }
190   if (bs->tx_timeout_clocks)
191     {
192       BFD_DBG ("Next transmit in %lu clocks/%.02fs@%lu",
193                bs->tx_timeout_clocks - now,
194                (bs->tx_timeout_clocks - now) / bm->cpu_cps,
195                bs->tx_timeout_clocks);
196     }
197 }
198
199 static void
200 bfd_recalc_detection_time (bfd_main_t * bm, bfd_session_t * bs)
201 {
202   if (!bs->local_demand)
203     {
204       /* asynchronous mode */
205       bs->detection_time_clocks =
206         bs->remote_detect_mult *
207         clib_max (bs->effective_required_min_rx_clocks,
208                   bs->remote_desired_min_tx_clocks);
209     }
210   else
211     {
212       /* demand mode */
213       bs->detection_time_clocks =
214         bs->local_detect_mult * clib_max (bs->config_desired_min_tx_clocks,
215                                           bs->remote_min_rx_clocks);
216     }
217   BFD_DBG ("Recalculated detection time %lu clocks/%.2fs",
218            bs->detection_time_clocks,
219            bs->detection_time_clocks / bm->cpu_cps);
220 }
221
222 static void
223 bfd_set_timer (bfd_main_t * bm, bfd_session_t * bs, u64 now,
224                int handling_wakeup)
225 {
226   u64 next = 0;
227   u64 rx_timeout = 0;
228   if (BFD_STATE_up == bs->local_state)
229     {
230       rx_timeout = bs->last_rx_clocks + bs->detection_time_clocks;
231     }
232   if (bs->tx_timeout_clocks && rx_timeout)
233     {
234       next = clib_min (bs->tx_timeout_clocks, rx_timeout);
235     }
236   else if (bs->tx_timeout_clocks)
237     {
238       next = bs->tx_timeout_clocks;
239     }
240   else if (rx_timeout)
241     {
242       next = rx_timeout;
243     }
244   BFD_DBG ("bs_idx=%u, tx_timeout=%lu, rx_timeout=%lu, next=%s", bs->bs_idx,
245            bs->tx_timeout_clocks, rx_timeout,
246            next == bs->tx_timeout_clocks ? "tx" : "rx");
247   /* sometimes the wheel expires an event a bit sooner than requested, account
248      for that here */
249   if (next && (now + bm->wheel_inaccuracy > bs->wheel_time_clocks ||
250                next < bs->wheel_time_clocks || !bs->wheel_time_clocks))
251     {
252       bs->wheel_time_clocks = next;
253       BFD_DBG ("timing_wheel_insert(%p, %lu (%ld clocks/%.2fs in the "
254                "future), %u);",
255                &bm->wheel, bs->wheel_time_clocks,
256                (i64) bs->wheel_time_clocks - clib_cpu_time_now (),
257                (i64) (bs->wheel_time_clocks - clib_cpu_time_now ()) /
258                bm->cpu_cps, bs->bs_idx);
259       timing_wheel_insert (&bm->wheel, bs->wheel_time_clocks, bs->bs_idx);
260       if (!handling_wakeup)
261         {
262           vlib_process_signal_event (bm->vlib_main,
263                                      bm->bfd_process_node_index,
264                                      BFD_EVENT_RESCHEDULE, bs->bs_idx);
265         }
266     }
267 }
268
269 static void
270 bfd_set_effective_desired_min_tx (bfd_main_t * bm,
271                                   bfd_session_t * bs, u64 now,
272                                   u64 desired_min_tx_clocks,
273                                   int handling_wakeup)
274 {
275   bs->effective_desired_min_tx_clocks = desired_min_tx_clocks;
276   BFD_DBG ("Set effective desired min tx to " BFD_CLK_FMT,
277            BFD_CLK_PRN (bs->effective_desired_min_tx_clocks));
278   bfd_recalc_detection_time (bm, bs);
279   bfd_recalc_tx_interval (bm, bs);
280   bfd_calc_next_tx (bm, bs, now);
281   bfd_set_timer (bm, bs, now, handling_wakeup);
282 }
283
284 static void
285 bfd_set_effective_required_min_rx (bfd_main_t * bm,
286                                    bfd_session_t * bs, u64 now,
287                                    u64 required_min_rx_clocks,
288                                    int handling_wakeup)
289 {
290   bs->effective_required_min_rx_clocks = required_min_rx_clocks;
291   BFD_DBG ("Set effective required min rx to " BFD_CLK_FMT,
292            BFD_CLK_PRN (bs->effective_required_min_rx_clocks));
293   bfd_recalc_detection_time (bm, bs);
294   bfd_set_timer (bm, bs, now, handling_wakeup);
295 }
296
297 static void
298 bfd_set_remote_required_min_rx (bfd_main_t * bm, bfd_session_t * bs,
299                                 u64 now,
300                                 u32 remote_required_min_rx_usec,
301                                 int handling_wakeup)
302 {
303   bs->remote_min_rx_usec = remote_required_min_rx_usec;
304   bs->remote_min_rx_clocks =
305     bfd_usec_to_clocks (bm, remote_required_min_rx_usec);
306   BFD_DBG ("Set remote min rx to " BFD_CLK_FMT,
307            BFD_CLK_PRN (bs->remote_min_rx_clocks));
308   bfd_recalc_detection_time (bm, bs);
309   bfd_recalc_tx_interval (bm, bs);
310   bfd_calc_next_tx (bm, bs, now);
311   bfd_set_timer (bm, bs, now, handling_wakeup);
312 }
313
314 void
315 bfd_session_start (bfd_main_t * bm, bfd_session_t * bs)
316 {
317   BFD_DBG ("%U", format_bfd_session, bs);
318   bfd_recalc_tx_interval (bm, bs);
319   vlib_process_signal_event (bm->vlib_main, bm->bfd_process_node_index,
320                              BFD_EVENT_NEW_SESSION, bs->bs_idx);
321 }
322
323 vnet_api_error_t
324 bfd_del_session (uword bs_idx)
325 {
326   const bfd_main_t *bm = &bfd_main;
327   if (!pool_is_free_index (bm->sessions, bs_idx))
328     {
329       bfd_session_t *bs = pool_elt_at_index (bm->sessions, bs_idx);
330       pool_put (bm->sessions, bs);
331       return 0;
332     }
333   else
334     {
335       BFD_ERR ("no such session");
336       return VNET_API_ERROR_BFD_ENOENT;
337     }
338   return 0;
339 }
340
341 void
342 bfd_session_set_flags (bfd_session_t * bs, u8 admin_up_down)
343 {
344   bfd_main_t *bm = &bfd_main;
345   if (admin_up_down)
346     {
347       bfd_set_state (bm, bs, BFD_STATE_down, 0);
348     }
349   else
350     {
351       bfd_set_diag (bs, BFD_DIAG_CODE_neighbor_sig_down);
352       bfd_set_state (bm, bs, BFD_STATE_admin_down, 0);
353     }
354 }
355
356 u8 *
357 bfd_input_format_trace (u8 * s, va_list * args)
358 {
359   CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *);
360   CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *);
361   const bfd_input_trace_t *t = va_arg (*args, bfd_input_trace_t *);
362   const bfd_pkt_t *pkt = (bfd_pkt_t *) t->data;
363   if (t->len > STRUCT_SIZE_OF (bfd_pkt_t, head))
364     {
365       s = format (s, "BFD v%u, diag=%u(%s), state=%u(%s),\n"
366                   "    flags=(P:%u, F:%u, C:%u, A:%u, D:%u, M:%u), "
367                   "detect_mult=%u, length=%u\n",
368                   bfd_pkt_get_version (pkt), bfd_pkt_get_diag_code (pkt),
369                   bfd_diag_code_string (bfd_pkt_get_diag_code (pkt)),
370                   bfd_pkt_get_state (pkt),
371                   bfd_state_string (bfd_pkt_get_state (pkt)),
372                   bfd_pkt_get_poll (pkt), bfd_pkt_get_final (pkt),
373                   bfd_pkt_get_control_plane_independent (pkt),
374                   bfd_pkt_get_auth_present (pkt), bfd_pkt_get_demand (pkt),
375                   bfd_pkt_get_multipoint (pkt), pkt->head.detect_mult,
376                   pkt->head.length);
377       if (t->len >= sizeof (bfd_pkt_t) &&
378           pkt->head.length >= sizeof (bfd_pkt_t))
379         {
380           s = format (s, "    my discriminator: %u\n", pkt->my_disc);
381           s = format (s, "    your discriminator: %u\n", pkt->your_disc);
382           s = format (s, "    desired min tx interval: %u\n",
383                       clib_net_to_host_u32 (pkt->des_min_tx));
384           s = format (s, "    required min rx interval: %u\n",
385                       clib_net_to_host_u32 (pkt->req_min_rx));
386           s = format (s, "    required min echo rx interval: %u",
387                       clib_net_to_host_u32 (pkt->req_min_echo_rx));
388         }
389     }
390
391   return s;
392 }
393
394 static void
395 bfd_on_state_change (bfd_main_t * bm, bfd_session_t * bs, u64 now,
396                      int handling_wakeup)
397 {
398   BFD_DBG ("State changed: %U", format_bfd_session, bs);
399   bfd_event (bm, bs);
400   switch (bs->local_state)
401     {
402     case BFD_STATE_admin_down:
403       bfd_set_effective_required_min_rx (bm, bs, now,
404                                          bs->config_required_min_rx_clocks,
405                                          handling_wakeup);
406       bfd_set_effective_desired_min_tx (bm, bs, now,
407                                         clib_max
408                                         (bs->config_desired_min_tx_clocks,
409                                          bm->default_desired_min_tx_clocks),
410                                         handling_wakeup);
411       break;
412     case BFD_STATE_down:
413       bfd_set_effective_required_min_rx (bm, bs, now,
414                                          bs->config_required_min_rx_clocks,
415                                          handling_wakeup);
416       bfd_set_effective_desired_min_tx (bm, bs, now,
417                                         clib_max
418                                         (bs->config_desired_min_tx_clocks,
419                                          bm->default_desired_min_tx_clocks),
420                                         handling_wakeup);
421       break;
422     case BFD_STATE_init:
423       bfd_set_effective_desired_min_tx (bm, bs, now,
424                                         clib_max
425                                         (bs->config_desired_min_tx_clocks,
426                                          bm->default_desired_min_tx_clocks),
427                                         handling_wakeup);
428       break;
429     case BFD_STATE_up:
430       if (POLL_NOT_NEEDED == bs->poll_state)
431         {
432           bfd_set_effective_required_min_rx (bm, bs, now,
433                                              bs->config_required_min_rx_clocks,
434                                              handling_wakeup);
435         }
436       bfd_set_effective_desired_min_tx (bm, bs, now,
437                                         bs->config_desired_min_tx_clocks,
438                                         handling_wakeup);
439       break;
440     }
441 }
442
443 static void
444 bfd_on_config_change (vlib_main_t * vm, vlib_node_runtime_t * rt,
445                       bfd_main_t * bm, bfd_session_t * bs, u64 now)
446 {
447   if (bs->remote_demand)
448     {
449       /* TODO - initiate poll sequence here */
450     }
451   else
452     {
453       /* asynchronous - poll is part of periodic - nothing to do here */
454     }
455   bfd_recalc_detection_time (bm, bs);
456   bfd_set_timer (bm, bs, now, 0);
457 }
458
459 static void
460 bfd_add_transport_layer (vlib_main_t * vm, vlib_buffer_t * b,
461                          bfd_session_t * bs)
462 {
463   switch (bs->transport)
464     {
465     case BFD_TRANSPORT_UDP4:
466       BFD_DBG ("Transport bfd via udp4, bs_idx=%u", bs->bs_idx);
467       bfd_add_udp4_transport (vm, b, &bs->udp);
468       break;
469     case BFD_TRANSPORT_UDP6:
470       BFD_DBG ("Transport bfd via udp6, bs_idx=%u", bs->bs_idx);
471       bfd_add_udp6_transport (vm, b, &bs->udp);
472       break;
473     }
474 }
475
476 static vlib_buffer_t *
477 bfd_create_frame_to_next_node (vlib_main_t * vm, bfd_session_t * bs)
478 {
479   u32 bi;
480   if (vlib_buffer_alloc (vm, &bi, 1) != 1)
481     {
482       clib_warning ("buffer allocation failure");
483       return NULL;
484     }
485
486   vlib_buffer_t *b = vlib_get_buffer (vm, bi);
487   ASSERT (b->current_data == 0);
488
489   vlib_frame_t *f =
490     vlib_get_frame_to_node (vm, bfd_node_index_by_transport[bs->transport]);
491
492   u32 *to_next = vlib_frame_vector_args (f);
493   to_next[0] = bi;
494   f->n_vectors = 1;
495
496   vlib_put_frame_to_node (vm, bfd_node_index_by_transport[bs->transport], f);
497   return b;
498 }
499
500 #if WITH_LIBSSL > 0
501 static void
502 bfd_add_sha1_auth_section (vlib_buffer_t * b, bfd_session_t * bs)
503 {
504   bfd_pkt_with_sha1_auth_t *pkt = vlib_buffer_get_current (b);
505   bfd_auth_sha1_t *auth = &pkt->sha1_auth;
506   b->current_length += sizeof (*auth);
507   pkt->pkt.head.length += sizeof (*auth);
508   bfd_pkt_set_auth_present (&pkt->pkt);
509   memset (auth, 0, sizeof (*auth));
510   auth->type_len.type = bs->auth.curr_key->auth_type;
511   /*
512    * only meticulous authentication types require incrementing seq number
513    * for every message, but doing so doesn't violate the RFC
514    */
515   ++bs->auth.local_seq_number;
516   auth->type_len.len = sizeof (bfd_auth_sha1_t);
517   auth->key_id = bs->auth.curr_bfd_key_id;
518   auth->seq_num = clib_host_to_net_u32 (bs->auth.local_seq_number);
519   /*
520    * first copy the password into the packet, then calculate the hash
521    * and finally replace the password with the calculated hash
522    */
523   clib_memcpy (auth->hash, bs->auth.curr_key->key,
524                sizeof (bs->auth.curr_key->key));
525   unsigned char hash[sizeof (auth->hash)];
526   SHA1 ((unsigned char *) pkt, sizeof (*pkt), hash);
527   BFD_DBG ("hashing: %U", format_hex_bytes, pkt, sizeof (*pkt));
528   clib_memcpy (auth->hash, hash, sizeof (hash));
529 }
530 #endif
531
532 static void
533 bfd_add_auth_section (vlib_buffer_t * b, bfd_session_t * bs)
534 {
535   if (bs->auth.curr_key)
536     {
537       const bfd_auth_type_e auth_type = bs->auth.curr_key->auth_type;
538       switch (auth_type)
539         {
540         case BFD_AUTH_TYPE_reserved:
541           /* fallthrough */
542         case BFD_AUTH_TYPE_simple_password:
543           /* fallthrough */
544         case BFD_AUTH_TYPE_keyed_md5:
545           /* fallthrough */
546         case BFD_AUTH_TYPE_meticulous_keyed_md5:
547           clib_warning ("Internal error, unexpected BFD auth type '%d'",
548                         auth_type);
549           break;
550 #if WITH_LIBSSL > 0
551         case BFD_AUTH_TYPE_keyed_sha1:
552           /* fallthrough */
553         case BFD_AUTH_TYPE_meticulous_keyed_sha1:
554           bfd_add_sha1_auth_section (b, bs);
555           break;
556 #else
557         case BFD_AUTH_TYPE_keyed_sha1:
558           /* fallthrough */
559         case BFD_AUTH_TYPE_meticulous_keyed_sha1:
560           clib_warning ("Internal error, unexpected BFD auth type '%d'",
561                         auth_type);
562           break;
563 #endif
564         }
565     }
566 }
567
568 static void
569 bfd_init_control_frame (vlib_buffer_t * b, bfd_session_t * bs)
570 {
571   bfd_pkt_t *pkt = vlib_buffer_get_current (b);
572
573   u32 bfd_length = 0;
574   bfd_length = sizeof (bfd_pkt_t);
575   memset (pkt, 0, sizeof (*pkt));
576   bfd_pkt_set_version (pkt, 1);
577   bfd_pkt_set_diag_code (pkt, bs->local_diag);
578   bfd_pkt_set_state (pkt, bs->local_state);
579   if (bs->local_demand && BFD_STATE_up == bs->local_state &&
580       BFD_STATE_up == bs->remote_state)
581     {
582       bfd_pkt_set_demand (pkt);
583     }
584   pkt->head.detect_mult = bs->local_detect_mult;
585   pkt->head.length = clib_host_to_net_u32 (bfd_length);
586   pkt->my_disc = bs->local_discr;
587   pkt->your_disc = bs->remote_discr;
588   pkt->des_min_tx = clib_host_to_net_u32 (bs->config_desired_min_tx_usec);
589   pkt->req_min_rx = clib_host_to_net_u32 (bs->config_required_min_rx_usec);
590   pkt->req_min_echo_rx = clib_host_to_net_u32 (1);
591   b->current_length = bfd_length;
592 }
593
594 static void
595 bfd_send_periodic (vlib_main_t * vm, vlib_node_runtime_t * rt,
596                    bfd_main_t * bm, bfd_session_t * bs, u64 now,
597                    int handling_wakeup)
598 {
599   if (!bs->remote_min_rx_usec)
600     {
601       BFD_DBG
602         ("bfd.RemoteMinRxInterval is zero, not sending periodic control "
603          "frame");
604       return;
605     }
606   /* FIXME
607      A system MUST NOT periodically transmit BFD Control packets if Demand
608      mode is active on the remote system (bfd.RemoteDemandMode is 1,
609      bfd.SessionState is Up, and bfd.RemoteSessionState is Up) and a Poll
610      Sequence is not being transmitted.
611    */
612   /* sometimes the wheel expires an event a bit sooner than requested, account
613      for that here */
614   if (now + bm->wheel_inaccuracy >= bs->tx_timeout_clocks)
615     {
616       BFD_DBG ("Send periodic control frame for bs_idx=%lu", bs->bs_idx);
617       vlib_buffer_t *b = bfd_create_frame_to_next_node (vm, bs);
618       if (!b)
619         {
620           return;
621         }
622       bfd_init_control_frame (b, bs);
623       if (POLL_NOT_NEEDED != bs->poll_state)
624         {
625           /* here we are either beginning a new poll sequence or retrying .. */
626           bfd_pkt_set_poll (vlib_buffer_get_current (b));
627           bs->poll_state = POLL_IN_PROGRESS;
628           BFD_DBG ("Setting poll bit in packet, bs_idx=%u", bs->bs_idx);
629         }
630       bfd_add_auth_section (b, bs);
631       bfd_add_transport_layer (vm, b, bs);
632       bs->last_tx_clocks = now;
633       bfd_calc_next_tx (bm, bs, now);
634     }
635   else
636     {
637       BFD_DBG
638         ("No need to send control frame now, now is %lu, tx_timeout is %lu",
639          now, bs->tx_timeout_clocks);
640     }
641   bfd_set_timer (bm, bs, now, handling_wakeup);
642 }
643
644 void
645 bfd_init_final_control_frame (vlib_main_t * vm, vlib_buffer_t * b,
646                               bfd_session_t * bs)
647 {
648   BFD_DBG ("Send final control frame for bs_idx=%lu", bs->bs_idx);
649   bfd_init_control_frame (b, bs);
650   bfd_pkt_set_final (vlib_buffer_get_current (b));
651   bfd_add_auth_section (b, bs);
652   bfd_add_transport_layer (vm, b, bs);
653   bs->last_tx_clocks = clib_cpu_time_now ();
654   /*
655    * RFC allows to include changes in final frame, so if there were any
656    * pending, we already did that, thus we can clear any pending poll needs
657    */
658   bs->poll_state = POLL_NOT_NEEDED;
659 }
660
661 static void
662 bfd_check_rx_timeout (bfd_main_t * bm, bfd_session_t * bs, u64 now,
663                       int handling_wakeup)
664 {
665   /* sometimes the wheel expires an event a bit sooner than requested, account
666      for that here */
667   if (bs->last_rx_clocks + bs->detection_time_clocks <=
668       now + bm->wheel_inaccuracy)
669     {
670       BFD_DBG ("Rx timeout, session goes down");
671       bfd_set_diag (bs, BFD_DIAG_CODE_det_time_exp);
672       bfd_set_state (bm, bs, BFD_STATE_down, handling_wakeup);
673       /*
674        * If the remote system does not receive any
675        * BFD Control packets for a Detection Time, it SHOULD reset
676        * bfd.RemoteMinRxInterval to its initial value of 1 (per section 6.8.1,
677        * since it is no longer required to maintain previous session state)
678        * and then can transmit at its own rate.
679        */
680       bfd_set_remote_required_min_rx (bm, bs, now, 1, handling_wakeup);
681     }
682 }
683
684 void
685 bfd_on_timeout (vlib_main_t * vm, vlib_node_runtime_t * rt, bfd_main_t * bm,
686                 bfd_session_t * bs, u64 now)
687 {
688   BFD_DBG ("Timeout for bs_idx=%lu", bs->bs_idx);
689   switch (bs->local_state)
690     {
691     case BFD_STATE_admin_down:
692       BFD_ERR ("Unexpected timeout when in %s state",
693                bfd_state_string (bs->local_state));
694       abort ();
695       break;
696     case BFD_STATE_down:
697       bfd_send_periodic (vm, rt, bm, bs, now, 1);
698       break;
699     case BFD_STATE_init:
700       BFD_ERR ("Unexpected timeout when in %s state",
701                bfd_state_string (bs->local_state));
702       abort ();
703       break;
704     case BFD_STATE_up:
705       bfd_check_rx_timeout (bm, bs, now, 1);
706       bfd_send_periodic (vm, rt, bm, bs, now, 1);
707       break;
708     }
709 }
710
711 /*
712  * bfd process node function
713  */
714 static uword
715 bfd_process (vlib_main_t * vm, vlib_node_runtime_t * rt, vlib_frame_t * f)
716 {
717   bfd_main_t *bm = &bfd_main;
718   u32 *expired = 0;
719   uword event_type, *event_data = 0;
720
721   /* So we can send events to the bfd process */
722   bm->bfd_process_node_index = bfd_process_node.index;
723
724   while (1)
725     {
726       u64 now = clib_cpu_time_now ();
727       u64 next_expire = timing_wheel_next_expiring_elt_time (&bm->wheel);
728       BFD_DBG ("timing_wheel_next_expiring_elt_time(%p) returns %lu",
729                &bm->wheel, next_expire);
730       if ((i64) next_expire < 0)
731         {
732           BFD_DBG ("wait for event without timeout");
733           (void) vlib_process_wait_for_event (vm);
734           event_type = vlib_process_get_events (vm, &event_data);
735         }
736       else
737         {
738           f64 timeout = ((i64) next_expire - (i64) now) / bm->cpu_cps;
739           BFD_DBG ("wait for event with timeout %.02f", timeout);
740           if (timeout < 0)
741             {
742               BFD_DBG ("negative timeout, already expired, skipping wait");
743               event_type = ~0;
744             }
745           else
746             {
747               (void) vlib_process_wait_for_event_or_clock (vm, timeout);
748               event_type = vlib_process_get_events (vm, &event_data);
749             }
750         }
751       now = clib_cpu_time_now ();
752       switch (event_type)
753         {
754         case ~0:                /* no events => timeout */
755           /* nothing to do here */
756           break;
757         case BFD_EVENT_RESCHEDULE:
758           /* nothing to do here - reschedule is done automatically after
759            * each event or timeout */
760           break;
761         case BFD_EVENT_NEW_SESSION:
762           if (!pool_is_free_index (bm->sessions, *event_data))
763             {
764               bfd_session_t *bs =
765                 pool_elt_at_index (bm->sessions, *event_data);
766               bfd_send_periodic (vm, rt, bm, bs, now, 1);
767             }
768           else
769             {
770               BFD_DBG ("Ignoring event for non-existent session index %u",
771                        (u32) * event_data);
772             }
773           break;
774         case BFD_EVENT_CONFIG_CHANGED:
775           if (!pool_is_free_index (bm->sessions, *event_data))
776             {
777               bfd_session_t *bs =
778                 pool_elt_at_index (bm->sessions, *event_data);
779               bfd_on_config_change (vm, rt, bm, bs, now);
780             }
781           else
782             {
783               BFD_DBG ("Ignoring event for non-existent session index %u",
784                        (u32) * event_data);
785             }
786           break;
787         default:
788           clib_warning ("BUG: event type 0x%wx", event_type);
789           break;
790         }
791       BFD_DBG ("advancing wheel, now is %lu", now);
792       BFD_DBG ("timing_wheel_advance (%p, %lu, %p, 0);", &bm->wheel, now,
793                expired);
794       expired = timing_wheel_advance (&bm->wheel, now, expired, 0);
795       BFD_DBG ("Expired %d elements", vec_len (expired));
796       u32 *p = NULL;
797       vec_foreach (p, expired)
798       {
799         const u32 bs_idx = *p;
800         if (!pool_is_free_index (bm->sessions, bs_idx))
801           {
802             bfd_session_t *bs = pool_elt_at_index (bm->sessions, bs_idx);
803             bfd_on_timeout (vm, rt, bm, bs, now);
804           }
805       }
806       if (expired)
807         {
808           _vec_len (expired) = 0;
809         }
810       if (event_data)
811         {
812           _vec_len (event_data) = 0;
813         }
814     }
815
816   return 0;
817 }
818
819 /*
820  * bfd process node declaration
821  */
822 /* *INDENT-OFF* */
823 VLIB_REGISTER_NODE (bfd_process_node, static) = {
824   .function = bfd_process,
825   .type = VLIB_NODE_TYPE_PROCESS,
826   .name = "bfd-process",
827   .n_next_nodes = 0,
828   .next_nodes = {},
829 };
830 /* *INDENT-ON* */
831
832 static clib_error_t *
833 bfd_sw_interface_up_down (vnet_main_t * vnm, u32 sw_if_index, u32 flags)
834 {
835   // bfd_main_t *bm = &bfd_main;
836   // vnet_hw_interface_t *hi = vnet_get_sup_hw_interface (vnm, sw_if_index);
837   if (!(flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP))
838     {
839       /* TODO */
840     }
841   return 0;
842 }
843
844 VNET_SW_INTERFACE_ADMIN_UP_DOWN_FUNCTION (bfd_sw_interface_up_down);
845
846 static clib_error_t *
847 bfd_hw_interface_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags)
848 {
849   // bfd_main_t *bm = &bfd_main;
850   if (flags & VNET_HW_INTERFACE_FLAG_LINK_UP)
851     {
852       /* TODO */
853     }
854   return 0;
855 }
856
857 VNET_HW_INTERFACE_LINK_UP_DOWN_FUNCTION (bfd_hw_interface_up_down);
858
859 /*
860  * setup function
861  */
862 static clib_error_t *
863 bfd_main_init (vlib_main_t * vm)
864 {
865 #if BFD_DEBUG
866   setbuf (stdout, NULL);
867 #endif
868   bfd_main_t *bm = &bfd_main;
869   bm->random_seed = random_default_seed ();
870   bm->vlib_main = vm;
871   bm->vnet_main = vnet_get_main ();
872   memset (&bm->wheel, 0, sizeof (bm->wheel));
873   bm->cpu_cps = vm->clib_time.clocks_per_second;
874   BFD_DBG ("cps is %.2f", bm->cpu_cps);
875   bm->default_desired_min_tx_clocks =
876     bfd_usec_to_clocks (bm, BFD_DEFAULT_DESIRED_MIN_TX_US);
877   const u64 now = clib_cpu_time_now ();
878   timing_wheel_init (&bm->wheel, now, bm->cpu_cps);
879   bm->wheel_inaccuracy = 2 << bm->wheel.log2_clocks_per_bin;
880
881   vlib_node_t *node = NULL;
882 #define F(t, n)                                                 \
883   node = vlib_get_node_by_name (vm, (u8 *)n);                   \
884   bfd_node_index_by_transport[BFD_TRANSPORT_##t] = node->index; \
885   BFD_DBG ("node '%s' has index %u", n, node->index);
886   foreach_bfd_transport (F);
887 #undef F
888   return 0;
889 }
890
891 VLIB_INIT_FUNCTION (bfd_main_init);
892
893 bfd_session_t *
894 bfd_get_session (bfd_main_t * bm, bfd_transport_t t)
895 {
896   bfd_session_t *result;
897   pool_get (bm->sessions, result);
898   memset (result, 0, sizeof (*result));
899   result->bs_idx = result - bm->sessions;
900   result->transport = t;
901   result->local_discr = random_u32 (&bm->random_seed);
902   bfd_set_defaults (bm, result);
903   hash_set (bm->session_by_disc, result->local_discr, result->bs_idx);
904   return result;
905 }
906
907 void
908 bfd_put_session (bfd_main_t * bm, bfd_session_t * bs)
909 {
910   if (bs->auth.curr_key)
911     {
912       --bs->auth.curr_key->use_count;
913     }
914   if (bs->auth.next_key)
915     {
916       --bs->auth.next_key->use_count;
917     }
918   hash_unset (bm->session_by_disc, bs->local_discr);
919   pool_put (bm->sessions, bs);
920 }
921
922 bfd_session_t *
923 bfd_find_session_by_idx (bfd_main_t * bm, uword bs_idx)
924 {
925   if (!pool_is_free_index (bm->sessions, bs_idx))
926     {
927       return pool_elt_at_index (bm->sessions, bs_idx);
928     }
929   return NULL;
930 }
931
932 bfd_session_t *
933 bfd_find_session_by_disc (bfd_main_t * bm, u32 disc)
934 {
935   uword *p = hash_get (bfd_main.session_by_disc, disc);
936   if (p)
937     {
938       return pool_elt_at_index (bfd_main.sessions, *p);
939     }
940   return NULL;
941 }
942
943 /**
944  * @brief verify bfd packet - common checks
945  *
946  * @param pkt
947  *
948  * @return 1 if bfd packet is valid
949  */
950 int
951 bfd_verify_pkt_common (const bfd_pkt_t * pkt)
952 {
953   if (1 != bfd_pkt_get_version (pkt))
954     {
955       BFD_ERR ("BFD verification failed - unexpected version: '%d'",
956                bfd_pkt_get_version (pkt));
957       return 0;
958     }
959   if (pkt->head.length < sizeof (bfd_pkt_t) ||
960       (bfd_pkt_get_auth_present (pkt) &&
961        pkt->head.length < sizeof (bfd_pkt_with_common_auth_t)))
962     {
963       BFD_ERR ("BFD verification failed - unexpected length: '%d' (auth "
964                "present: %d)",
965                pkt->head.length, bfd_pkt_get_auth_present (pkt));
966       return 0;
967     }
968   if (!pkt->head.detect_mult)
969     {
970       BFD_ERR ("BFD verification failed - unexpected detect-mult: '%d'",
971                pkt->head.detect_mult);
972       return 0;
973     }
974   if (bfd_pkt_get_multipoint (pkt))
975     {
976       BFD_ERR ("BFD verification failed - unexpected multipoint: '%d'",
977                bfd_pkt_get_multipoint (pkt));
978       return 0;
979     }
980   if (!pkt->my_disc)
981     {
982       BFD_ERR ("BFD verification failed - unexpected my-disc: '%d'",
983                pkt->my_disc);
984       return 0;
985     }
986   if (!pkt->your_disc)
987     {
988       const u8 pkt_state = bfd_pkt_get_state (pkt);
989       if (pkt_state != BFD_STATE_down && pkt_state != BFD_STATE_admin_down)
990         {
991           BFD_ERR ("BFD verification failed - unexpected state: '%s' "
992                    "(your-disc is zero)", bfd_state_string (pkt_state));
993           return 0;
994         }
995     }
996   return 1;
997 }
998
999 static void
1000 bfd_session_switch_auth_to_next (bfd_session_t * bs)
1001 {
1002   BFD_DBG ("Switching authentication key from %U to %U for bs_idx=%u",
1003            format_bfd_auth_key, bs->auth.curr_key, format_bfd_auth_key,
1004            bs->auth.next_key, bs->bs_idx);
1005   bs->auth.is_delayed = 0;
1006   if (bs->auth.curr_key)
1007     {
1008       --bs->auth.curr_key->use_count;
1009     }
1010   bs->auth.curr_key = bs->auth.next_key;
1011   bs->auth.next_key = NULL;
1012   bs->auth.curr_bfd_key_id = bs->auth.next_bfd_key_id;
1013 }
1014
1015 static int
1016 bfd_auth_type_is_meticulous (bfd_auth_type_e auth_type)
1017 {
1018   if (BFD_AUTH_TYPE_meticulous_keyed_md5 == auth_type ||
1019       BFD_AUTH_TYPE_meticulous_keyed_sha1 == auth_type)
1020     {
1021       return 1;
1022     }
1023   return 0;
1024 }
1025
1026 static int
1027 bfd_verify_pkt_auth_seq_num (bfd_session_t * bs,
1028                              u32 received_seq_num, int is_meticulous)
1029 {
1030   /*
1031    * RFC 5880 6.8.1:
1032    *
1033    * This variable MUST be set to zero after no packets have been
1034    * received on this session for at least twice the Detection Time.
1035    */
1036   u64 now = clib_cpu_time_now ();
1037   if (now - bs->last_rx_clocks > bs->detection_time_clocks * 2)
1038     {
1039       BFD_DBG ("BFD peer unresponsive for %lu clocks, which is > 2 * "
1040                "detection_time=%u clocks, resetting remote_seq_number_known "
1041                "flag",
1042                now - bs->last_rx_clocks, bs->detection_time_clocks * 2);
1043       bs->auth.remote_seq_number_known = 0;
1044     }
1045   if (bs->auth.remote_seq_number_known)
1046     {
1047       /* remote sequence number is known, verify its validity */
1048       const u32 max_u32 = 0xffffffff;
1049       /* the calculation might wrap, account for the special case... */
1050       if (bs->auth.remote_seq_number > max_u32 - 3 * bs->local_detect_mult)
1051         {
1052           /*
1053            * special case
1054            *
1055            *        x                   y                   z
1056            *  |----------+----------------------------+-----------|
1057            *  0          ^                            ^ 0xffffffff
1058            *             |        remote_seq_num------+
1059            *             |
1060            *             +-----(remote_seq_num + 3*detect_mult) % * 0xffffffff
1061            *
1062            *    x + y + z = 0xffffffff
1063            *    x + z = 3 * detect_mult
1064            */
1065           const u32 z = max_u32 - bs->auth.remote_seq_number;
1066           const u32 x = 3 * bs->local_detect_mult - z;
1067           if (received_seq_num > x &&
1068               received_seq_num < bs->auth.remote_seq_number + is_meticulous)
1069             {
1070               BFD_ERR
1071                 ("Recvd sequence number=%u out of ranges <0, %u>, <%u, %u>",
1072                  received_seq_num, x,
1073                  bs->auth.remote_seq_number + is_meticulous, max_u32);
1074               return 0;
1075             }
1076         }
1077       else
1078         {
1079           /* regular case */
1080           const u32 min = bs->auth.remote_seq_number + is_meticulous;
1081           const u32 max =
1082             bs->auth.remote_seq_number + 3 * bs->local_detect_mult;
1083           if (received_seq_num < min || received_seq_num > max)
1084             {
1085               BFD_ERR ("Recvd sequence number=%u out of range <%u, %u>",
1086                        received_seq_num, min, max);
1087               return 0;
1088             }
1089         }
1090     }
1091   return 1;
1092 }
1093
1094 static int
1095 bfd_verify_pkt_auth_key_sha1 (const bfd_pkt_t * pkt, u32 pkt_size,
1096                               bfd_session_t * bs, u8 bfd_key_id,
1097                               bfd_auth_key_t * auth_key)
1098 {
1099   ASSERT (auth_key->auth_type == BFD_AUTH_TYPE_keyed_sha1 ||
1100           auth_key->auth_type == BFD_AUTH_TYPE_meticulous_keyed_sha1);
1101
1102   u8 result[SHA_DIGEST_LENGTH];
1103   bfd_pkt_with_common_auth_t *with_common = (void *) pkt;
1104   if (pkt_size < sizeof (*with_common))
1105     {
1106       BFD_ERR ("Packet size too small to hold authentication common header");
1107       return 0;
1108     }
1109   if (with_common->common_auth.type != auth_key->auth_type)
1110     {
1111       BFD_ERR ("BFD auth type mismatch, packet auth=%d:%s doesn't match "
1112                "in-use auth=%d:%s",
1113                with_common->common_auth.type,
1114                bfd_auth_type_str (with_common->common_auth.type),
1115                auth_key->auth_type, bfd_auth_type_str (auth_key->auth_type));
1116       return 0;
1117     }
1118   bfd_pkt_with_sha1_auth_t *with_sha1 = (void *) pkt;
1119   if (pkt_size < sizeof (*with_sha1) ||
1120       with_sha1->sha1_auth.type_len.len < sizeof (with_sha1->sha1_auth))
1121     {
1122       BFD_ERR
1123         ("BFD size mismatch, payload size=%u, expected=%u, auth_len=%u, "
1124          "expected=%u", pkt_size, sizeof (*with_sha1),
1125          with_sha1->sha1_auth.type_len.len, sizeof (with_sha1->sha1_auth));
1126       return 0;
1127     }
1128   if (with_sha1->sha1_auth.key_id != bfd_key_id)
1129     {
1130       BFD_ERR
1131         ("BFD key ID mismatch, packet key ID=%u doesn't match key ID=%u%s",
1132          with_sha1->sha1_auth.key_id, bfd_key_id,
1133          bs->
1134          auth.is_delayed ? " (but a delayed auth change is scheduled)" : "");
1135       return 0;
1136     }
1137   SHA_CTX ctx;
1138   if (!SHA1_Init (&ctx))
1139     {
1140       BFD_ERR ("SHA1_Init failed");
1141       return 0;
1142     }
1143   /* ignore last 20 bytes - use the actual key data instead pkt data */
1144   if (!SHA1_Update (&ctx, with_sha1,
1145                     sizeof (*with_sha1) - sizeof (with_sha1->sha1_auth.hash)))
1146     {
1147       BFD_ERR ("SHA1_Update failed");
1148       return 0;
1149     }
1150   if (!SHA1_Update (&ctx, auth_key->key, sizeof (auth_key->key)))
1151     {
1152       BFD_ERR ("SHA1_Update failed");
1153       return 0;
1154     }
1155   if (!SHA1_Final (result, &ctx))
1156     {
1157       BFD_ERR ("SHA1_Final failed");
1158       return 0;
1159     }
1160   if (0 == memcmp (result, with_sha1->sha1_auth.hash, SHA_DIGEST_LENGTH))
1161     {
1162       return 1;
1163     }
1164   BFD_ERR ("SHA1 hash: %U doesn't match the expected value: %U",
1165            format_hex_bytes, with_sha1->sha1_auth.hash, SHA_DIGEST_LENGTH,
1166            format_hex_bytes, result, SHA_DIGEST_LENGTH);
1167   return 0;
1168 }
1169
1170 static int
1171 bfd_verify_pkt_auth_key (const bfd_pkt_t * pkt, u32 pkt_size,
1172                          bfd_session_t * bs, u8 bfd_key_id,
1173                          bfd_auth_key_t * auth_key)
1174 {
1175   switch (auth_key->auth_type)
1176     {
1177     case BFD_AUTH_TYPE_reserved:
1178       clib_warning ("Internal error, unexpected auth_type=%d:%s",
1179                     auth_key->auth_type,
1180                     bfd_auth_type_str (auth_key->auth_type));
1181       return 0;
1182     case BFD_AUTH_TYPE_simple_password:
1183       clib_warning
1184         ("Internal error, not implemented, unexpected auth_type=%d:%s",
1185          auth_key->auth_type, bfd_auth_type_str (auth_key->auth_type));
1186       return 0;
1187     case BFD_AUTH_TYPE_keyed_md5:
1188       /* fallthrough */
1189     case BFD_AUTH_TYPE_meticulous_keyed_md5:
1190       clib_warning
1191         ("Internal error, not implemented, unexpected auth_type=%d:%s",
1192          auth_key->auth_type, bfd_auth_type_str (auth_key->auth_type));
1193       return 0;
1194     case BFD_AUTH_TYPE_keyed_sha1:
1195       /* fallthrough */
1196     case BFD_AUTH_TYPE_meticulous_keyed_sha1:
1197 #if WITH_LIBSSL > 0
1198       do
1199         {
1200           const u32 seq_num = clib_net_to_host_u32 (((bfd_pkt_with_sha1_auth_t
1201                                                       *) pkt)->
1202                                                     sha1_auth.seq_num);
1203           return bfd_verify_pkt_auth_seq_num (bs, seq_num,
1204                                               bfd_auth_type_is_meticulous
1205                                               (auth_key->auth_type))
1206             && bfd_verify_pkt_auth_key_sha1 (pkt, pkt_size, bs, bfd_key_id,
1207                                              auth_key);
1208         }
1209       while (0);
1210 #else
1211       clib_warning
1212         ("Internal error, attempt to use SHA1 without SSL support");
1213       return 0;
1214 #endif
1215     }
1216   return 0;
1217 }
1218
1219 /**
1220  * @brief verify bfd packet - authentication
1221  *
1222  * @param pkt
1223  *
1224  * @return 1 if bfd packet is valid
1225  */
1226 int
1227 bfd_verify_pkt_auth (const bfd_pkt_t * pkt, u16 pkt_size, bfd_session_t * bs)
1228 {
1229   if (bfd_pkt_get_auth_present (pkt))
1230     {
1231       /* authentication present in packet */
1232       if (!bs->auth.curr_key)
1233         {
1234           /* currently not using authentication - can we turn it on? */
1235           if (bs->auth.is_delayed && bs->auth.next_key)
1236             {
1237               /* yes, switch is scheduled - make sure the auth is valid */
1238               if (bfd_verify_pkt_auth_key (pkt, pkt_size, bs,
1239                                            bs->auth.next_bfd_key_id,
1240                                            bs->auth.next_key))
1241                 {
1242                   /* auth matches next key, do the switch, packet is valid */
1243                   bfd_session_switch_auth_to_next (bs);
1244                   return 1;
1245                 }
1246             }
1247         }
1248       else
1249         {
1250           /* yes, using authentication, verify the key */
1251           if (bfd_verify_pkt_auth_key (pkt, pkt_size, bs,
1252                                        bs->auth.curr_bfd_key_id,
1253                                        bs->auth.curr_key))
1254             {
1255               /* verification passed, packet is valid */
1256               return 1;
1257             }
1258           else
1259             {
1260               /* verification failed - but maybe we need to switch key */
1261               if (bs->auth.is_delayed && bs->auth.next_key)
1262                 {
1263                   /* delayed switch present, verify if that key works */
1264                   if (bfd_verify_pkt_auth_key (pkt, pkt_size, bs,
1265                                                bs->auth.next_bfd_key_id,
1266                                                bs->auth.next_key))
1267                     {
1268                       /* auth matches next key, switch key, packet is valid */
1269                       bfd_session_switch_auth_to_next (bs);
1270                       return 1;
1271                     }
1272                 }
1273             }
1274         }
1275     }
1276   else
1277     {
1278       /* authentication in packet not present */
1279       if (pkt_size > sizeof (*pkt))
1280         {
1281           BFD_ERR ("BFD verification failed - unexpected packet size '%d' "
1282                    "(auth not present)", pkt_size);
1283           return 0;
1284         }
1285       if (bs->auth.curr_key)
1286         {
1287           /* currently authenticating - could we turn it off? */
1288           if (bs->auth.is_delayed && !bs->auth.next_key)
1289             {
1290               /* yes, delayed switch to NULL key is scheduled */
1291               bfd_session_switch_auth_to_next (bs);
1292               return 1;
1293             }
1294         }
1295       else
1296         {
1297           /* no auth in packet, no auth in use - packet is valid */
1298           return 1;
1299         }
1300     }
1301   return 0;
1302 }
1303
1304 void
1305 bfd_consume_pkt (bfd_main_t * bm, const bfd_pkt_t * pkt, u32 bs_idx)
1306 {
1307   bfd_session_t *bs = bfd_find_session_by_idx (bm, bs_idx);
1308   if (!bs)
1309     {
1310       return;
1311     }
1312   BFD_DBG ("Scanning bfd packet, bs_idx=%d", bs->bs_idx);
1313   bs->remote_discr = pkt->my_disc;
1314   bs->remote_state = bfd_pkt_get_state (pkt);
1315   bs->remote_demand = bfd_pkt_get_demand (pkt);
1316   u64 now = clib_cpu_time_now ();
1317   bs->last_rx_clocks = now;
1318   if (bfd_pkt_get_auth_present (pkt))
1319     {
1320       bfd_auth_type_e auth_type =
1321         ((bfd_pkt_with_common_auth_t *) (pkt))->common_auth.type;
1322       switch (auth_type)
1323         {
1324         case BFD_AUTH_TYPE_reserved:
1325           /* fallthrough */
1326         case BFD_AUTH_TYPE_simple_password:
1327           /* fallthrough */
1328         case BFD_AUTH_TYPE_keyed_md5:
1329           /* fallthrough */
1330         case BFD_AUTH_TYPE_meticulous_keyed_md5:
1331           clib_warning ("Internal error, unexpected auth_type=%d:%s",
1332                         auth_type, bfd_auth_type_str (auth_type));
1333           break;
1334         case BFD_AUTH_TYPE_keyed_sha1:
1335           /* fallthrough */
1336         case BFD_AUTH_TYPE_meticulous_keyed_sha1:
1337           do
1338             {
1339               bfd_pkt_with_sha1_auth_t *with_sha1 =
1340                 (bfd_pkt_with_sha1_auth_t *) pkt;
1341               bs->auth.remote_seq_number =
1342                 clib_net_to_host_u32 (with_sha1->sha1_auth.seq_num);
1343               bs->auth.remote_seq_number_known = 1;
1344               BFD_DBG ("Received sequence number %u",
1345                        bs->auth.remote_seq_number);
1346             }
1347           while (0);
1348         }
1349     }
1350   bs->remote_desired_min_tx_clocks =
1351     bfd_usec_to_clocks (bm, clib_net_to_host_u32 (pkt->des_min_tx));
1352   bs->remote_detect_mult = pkt->head.detect_mult;
1353   bfd_set_remote_required_min_rx (bm, bs, now,
1354                                   clib_net_to_host_u32 (pkt->req_min_rx), 0);
1355   /* FIXME
1356      If the Required Min Echo RX Interval field is zero, the
1357      transmission of Echo packets, if any, MUST cease.
1358
1359      If a Poll Sequence is being transmitted by the local system and
1360      the Final (F) bit in the received packet is set, the Poll Sequence
1361      MUST be terminated.
1362    */
1363   /* FIXME 6.8.2 */
1364   /* FIXME 6.8.4 */
1365   if (bs->poll_state == POLL_IN_PROGRESS && bfd_pkt_get_final (pkt))
1366     {
1367       bs->poll_state = POLL_NOT_NEEDED;
1368       BFD_DBG ("Poll sequence terminated, bs_idx=%u", bs->bs_idx);
1369       if (BFD_STATE_up == bs->local_state)
1370         {
1371           bfd_set_effective_required_min_rx (bm, bs, now,
1372                                              bs->config_required_min_rx_clocks,
1373                                              0);
1374           bfd_recalc_detection_time (bm, bs);
1375         }
1376     }
1377   if (BFD_STATE_admin_down == bs->local_state)
1378     return;
1379   if (BFD_STATE_admin_down == bs->remote_state)
1380     {
1381       bfd_set_diag (bs, BFD_DIAG_CODE_neighbor_sig_down);
1382       bfd_set_state (bm, bs, BFD_STATE_down, 0);
1383     }
1384   else if (BFD_STATE_down == bs->local_state)
1385     {
1386       if (BFD_STATE_down == bs->remote_state)
1387         {
1388           bfd_set_state (bm, bs, BFD_STATE_init, 0);
1389         }
1390       else if (BFD_STATE_init == bs->remote_state)
1391         {
1392           bfd_set_state (bm, bs, BFD_STATE_up, 0);
1393         }
1394     }
1395   else if (BFD_STATE_init == bs->local_state)
1396     {
1397       if (BFD_STATE_up == bs->remote_state ||
1398           BFD_STATE_init == bs->remote_state)
1399         {
1400           bfd_set_state (bm, bs, BFD_STATE_up, 0);
1401         }
1402     }
1403   else                          /* BFD_STATE_up == bs->local_state */
1404     {
1405       if (BFD_STATE_down == bs->remote_state)
1406         {
1407           bfd_set_diag (bs, BFD_DIAG_CODE_neighbor_sig_down);
1408           bfd_set_state (bm, bs, BFD_STATE_down, 0);
1409         }
1410     }
1411 }
1412
1413 static const char *
1414 bfd_poll_state_string (bfd_poll_state_e state)
1415 {
1416   switch (state)
1417     {
1418 #define F(x)     \
1419   case POLL_##x: \
1420     return "POLL_" #x;
1421       foreach_bfd_poll_state (F)
1422 #undef F
1423     }
1424   return "UNKNOWN";
1425 }
1426
1427 u8 *
1428 format_bfd_session (u8 * s, va_list * args)
1429 {
1430   const bfd_session_t *bs = va_arg (*args, bfd_session_t *);
1431   s = format (s, "BFD(%u): bfd.SessionState=%s, "
1432               "bfd.RemoteSessionState=%s, "
1433               "bfd.LocalDiscr=%u, "
1434               "bfd.RemoteDiscr=%u, "
1435               "bfd.LocalDiag=%s, "
1436               "bfd.DesiredMinTxInterval=%u, "
1437               "bfd.RequiredMinRxInterval=%u, "
1438               "bfd.RequiredMinEchoRxInterval=%u, "
1439               "bfd.RemoteMinRxInterval=%u, "
1440               "bfd.DemandMode=%s, "
1441               "bfd.RemoteDemandMode=%s, "
1442               "bfd.DetectMult=%u, "
1443               "Auth: {local-seq-num=%u, "
1444               "remote-seq-num=%u, "
1445               "is-delayed=%s, "
1446               "curr-key=%U, "
1447               "next-key=%U},"
1448               "poll-state: %s",
1449               bs->bs_idx, bfd_state_string (bs->local_state),
1450               bfd_state_string (bs->remote_state), bs->local_discr,
1451               bs->remote_discr, bfd_diag_code_string (bs->local_diag),
1452               bs->config_desired_min_tx_usec, bs->config_required_min_rx_usec,
1453               1, bs->remote_min_rx_usec, (bs->local_demand ? "yes" : "no"),
1454               (bs->remote_demand ? "yes" : "no"), bs->local_detect_mult,
1455               bs->auth.local_seq_number, bs->auth.remote_seq_number,
1456               (bs->auth.is_delayed ? "yes" : "no"), format_bfd_auth_key,
1457               bs->auth.curr_key, format_bfd_auth_key, bs->auth.next_key,
1458               bfd_poll_state_string (bs->poll_state));
1459   return s;
1460 }
1461
1462 unsigned
1463 bfd_auth_type_supported (bfd_auth_type_e auth_type)
1464 {
1465   if (auth_type == BFD_AUTH_TYPE_keyed_sha1 ||
1466       auth_type == BFD_AUTH_TYPE_meticulous_keyed_sha1)
1467     {
1468       return 1;
1469     }
1470   return 0;
1471 }
1472
1473 vnet_api_error_t
1474 bfd_auth_activate (bfd_session_t * bs, u32 conf_key_id,
1475                    u8 bfd_key_id, u8 is_delayed)
1476 {
1477   bfd_main_t *bm = &bfd_main;
1478   const uword *key_idx_p =
1479     hash_get (bm->auth_key_by_conf_key_id, conf_key_id);
1480   if (!key_idx_p)
1481     {
1482       clib_warning ("Authentication key with config ID %u doesn't exist)",
1483                     conf_key_id);
1484       return VNET_API_ERROR_BFD_ENOENT;
1485     }
1486   const uword key_idx = *key_idx_p;
1487   bfd_auth_key_t *key = pool_elt_at_index (bm->auth_keys, key_idx);
1488   if (is_delayed)
1489     {
1490       if (bs->auth.next_key == key)
1491         {
1492           /* already using this key, no changes required */
1493           return 0;
1494         }
1495       bs->auth.next_key = key;
1496       bs->auth.next_bfd_key_id = bfd_key_id;
1497       bs->auth.is_delayed = 1;
1498     }
1499   else
1500     {
1501       if (bs->auth.curr_key == key)
1502         {
1503           /* already using this key, no changes required */
1504           return 0;
1505         }
1506       if (bs->auth.curr_key)
1507         {
1508           --bs->auth.curr_key->use_count;
1509         }
1510       bs->auth.curr_key = key;
1511       bs->auth.curr_bfd_key_id = bfd_key_id;
1512       bs->auth.is_delayed = 0;
1513     }
1514   ++key->use_count;
1515   BFD_DBG ("Session auth modified: %U", format_bfd_session, bs);
1516   return 0;
1517 }
1518
1519 vnet_api_error_t
1520 bfd_auth_deactivate (bfd_session_t * bs, u8 is_delayed)
1521 {
1522 #if WITH_LIBSSL > 0
1523   if (!is_delayed)
1524     {
1525       /* not delayed - deactivate the current key right now */
1526       if (bs->auth.curr_key)
1527         {
1528           --bs->auth.curr_key->use_count;
1529           bs->auth.curr_key = NULL;
1530         }
1531       bs->auth.is_delayed = 0;
1532     }
1533   else
1534     {
1535       /* delayed - mark as so */
1536       bs->auth.is_delayed = 1;
1537     }
1538   /*
1539    * clear the next key unconditionally - either the auth change is not delayed
1540    * in which case the caller expects the session to not use authentication
1541    * from this point forward, or it is delayed, in which case the next_key
1542    * needs to be set to NULL to make it so in the future
1543    */
1544   if (bs->auth.next_key)
1545     {
1546       --bs->auth.next_key->use_count;
1547       bs->auth.next_key = NULL;
1548     }
1549   BFD_DBG ("Session auth modified: %U", format_bfd_session, bs);
1550   return 0;
1551 #else
1552   clib_warning ("SSL missing, cannot deactivate BFD authentication");
1553   return VNET_API_ERROR_BFD_NOTSUPP;
1554 #endif
1555 }
1556
1557 vnet_api_error_t
1558 bfd_session_set_params (bfd_main_t * bm, bfd_session_t * bs,
1559                         u32 desired_min_tx_usec,
1560                         u32 required_min_rx_usec, u8 detect_mult)
1561 {
1562   if (bs->local_detect_mult != detect_mult ||
1563       bs->config_desired_min_tx_usec != desired_min_tx_usec ||
1564       bs->config_required_min_rx_usec != required_min_rx_usec)
1565     {
1566       BFD_DBG ("Changing session params: %U", format_bfd_session, bs);
1567       switch (bs->poll_state)
1568         {
1569         case POLL_NOT_NEEDED:
1570           if (BFD_STATE_up == bs->local_state ||
1571               BFD_STATE_init == bs->local_state)
1572             {
1573               /* poll sequence is not needed for detect multiplier change */
1574               if (bs->config_desired_min_tx_usec != desired_min_tx_usec ||
1575                   bs->config_required_min_rx_usec != required_min_rx_usec)
1576                 {
1577                   bs->poll_state = POLL_NEEDED;
1578                   BFD_DBG ("Set poll state=%s, bs_idx=%u",
1579                            bfd_poll_state_string (bs->poll_state),
1580                            bs->bs_idx);
1581                 }
1582             }
1583           break;
1584         case POLL_NEEDED:
1585           /* nothing to do */
1586           break;
1587         case POLL_IN_PROGRESS:
1588           /* can't change params now ... */
1589           BFD_ERR ("Poll in progress, cannot change params for session with "
1590                    "bs_idx=%u", bs->bs_idx);
1591           return VNET_API_ERROR_BFD_EAGAIN;
1592         }
1593
1594       bs->local_detect_mult = detect_mult;
1595       bs->config_desired_min_tx_usec = desired_min_tx_usec;
1596       bs->config_desired_min_tx_clocks =
1597         bfd_usec_to_clocks (bm, desired_min_tx_usec);
1598       bs->config_required_min_rx_usec = required_min_rx_usec;
1599       bs->config_required_min_rx_clocks =
1600         bfd_usec_to_clocks (bm, required_min_rx_usec);
1601       BFD_DBG ("Changed session params: %U", format_bfd_session, bs);
1602
1603       vlib_process_signal_event (bm->vlib_main, bm->bfd_process_node_index,
1604                                  BFD_EVENT_CONFIG_CHANGED, bs->bs_idx);
1605     }
1606   else
1607     {
1608       BFD_DBG ("Ignore parameter change - no change, bs_idx=%u", bs->bs_idx);
1609     }
1610   return 0;
1611 }
1612
1613 bfd_main_t bfd_main;
1614
1615 /*
1616  * fd.io coding-style-patch-verification: ON
1617  *
1618  * Local Variables:
1619  * eval: (c-set-style "gnu")
1620  * End:
1621  */