BFD: set per session UDP source port per RFC
[vpp.git] / src / vnet / bfd / bfd_udp.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 #include <vppinfra/types.h>
16 #include <vlibmemory/api.h>
17 #include <vlib/vlib.h>
18 #include <vlib/buffer.h>
19 #include <vnet/ip/format.h>
20 #include <vnet/ethernet/packet.h>
21 #include <vnet/ip/udp_packet.h>
22 #include <vnet/ip/lookup.h>
23 #include <vnet/ip/icmp46_packet.h>
24 #include <vnet/ip/ip4.h>
25 #include <vnet/ip/ip6.h>
26 #include <vnet/ip/udp.h>
27 #include <vnet/ip/ip6_packet.h>
28 #include <vnet/adj/adj.h>
29 #include <vnet/adj/adj_nbr.h>
30 #include <vnet/bfd/bfd_debug.h>
31 #include <vnet/bfd/bfd_udp.h>
32 #include <vnet/bfd/bfd_main.h>
33 #include <vnet/bfd/bfd_api.h>
34
35 typedef struct
36 {
37   bfd_main_t *bfd_main;
38   /* hashmap - bfd session index by bfd key - used for CLI/API lookup, where
39    * discriminator is unknown */
40   mhash_t bfd_session_idx_by_bfd_key;
41 } bfd_udp_main_t;
42
43 static vlib_node_registration_t bfd_udp4_input_node;
44 static vlib_node_registration_t bfd_udp6_input_node;
45
46 bfd_udp_main_t bfd_udp_main;
47
48 static u16
49 bfd_udp_bs_idx_to_sport (u32 bs_idx)
50 {
51   /* The source port MUST be in the range 49152 through 65535. The same UDP
52    * source port number MUST be used for all BFD Control packets associated
53    * with a particular session.  The source port number SHOULD be unique among
54    * all BFD sessions on the system. If more than 16384 BFD sessions are
55    * simultaneously active, UDP source port numbers MAY be reused on
56    * multiple sessions, but the number of distinct uses of the same UDP
57    * source port number SHOULD be minimized.
58    */
59   return 49152 + bs_idx % (65535 - 49152 + 1);
60 }
61
62 void
63 bfd_add_udp4_transport (vlib_main_t * vm, vlib_buffer_t * b,
64                         const bfd_session_t * bs)
65 {
66   const bfd_udp_session_t *bus = &bs->udp;
67   const bfd_udp_key_t *key = &bus->key;
68
69   b->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
70   vnet_buffer (b)->ip.adj_index[VLIB_RX] = bus->adj_index;
71   vnet_buffer (b)->ip.adj_index[VLIB_TX] = bus->adj_index;
72   typedef struct
73   {
74     ip4_header_t ip4;
75     udp_header_t udp;
76   } ip4_udp_headers;
77   ip4_udp_headers *headers = NULL;
78   vlib_buffer_advance (b, -sizeof (*headers));
79   headers = vlib_buffer_get_current (b);
80   memset (headers, 0, sizeof (*headers));
81   headers->ip4.ip_version_and_header_length = 0x45;
82   headers->ip4.ttl = 255;
83   headers->ip4.protocol = IP_PROTOCOL_UDP;
84   headers->ip4.src_address.as_u32 = key->local_addr.ip4.as_u32;
85   headers->ip4.dst_address.as_u32 = key->peer_addr.ip4.as_u32;
86
87   headers->udp.src_port =
88     clib_host_to_net_u16 (bfd_udp_bs_idx_to_sport (bs->bs_idx));
89   headers->udp.dst_port = clib_host_to_net_u16 (UDP_DST_PORT_bfd4);
90
91   /* fix ip length, checksum and udp length */
92   const u16 ip_length = vlib_buffer_length_in_chain (vm, b);
93
94   headers->ip4.length = clib_host_to_net_u16 (ip_length);
95   headers->ip4.checksum = ip4_header_checksum (&headers->ip4);
96
97   const u16 udp_length = ip_length - (sizeof (headers->ip4));
98   headers->udp.length = clib_host_to_net_u16 (udp_length);
99 }
100
101 void
102 bfd_add_udp6_transport (vlib_main_t * vm, vlib_buffer_t * b,
103                         const bfd_session_t * bs)
104 {
105   const bfd_udp_session_t *bus = &bs->udp;
106   const bfd_udp_key_t *key = &bus->key;
107
108   b->flags |= VNET_BUFFER_LOCALLY_ORIGINATED;
109   vnet_buffer (b)->ip.adj_index[VLIB_RX] = bus->adj_index;
110   vnet_buffer (b)->ip.adj_index[VLIB_TX] = bus->adj_index;
111   typedef struct
112   {
113     ip6_header_t ip6;
114     udp_header_t udp;
115   } ip6_udp_headers;
116   ip6_udp_headers *headers = NULL;
117   vlib_buffer_advance (b, -sizeof (*headers));
118   headers = vlib_buffer_get_current (b);
119   memset (headers, 0, sizeof (*headers));
120   headers->ip6.ip_version_traffic_class_and_flow_label =
121     clib_host_to_net_u32 (0x6 << 28);
122   headers->ip6.hop_limit = 255;
123   headers->ip6.protocol = IP_PROTOCOL_UDP;
124   clib_memcpy (&headers->ip6.src_address, &key->local_addr.ip6,
125                sizeof (headers->ip6.src_address));
126   clib_memcpy (&headers->ip6.dst_address, &key->peer_addr.ip6,
127                sizeof (headers->ip6.dst_address));
128
129   headers->udp.src_port =
130     clib_host_to_net_u16 (bfd_udp_bs_idx_to_sport (bs->bs_idx));
131   headers->udp.dst_port = clib_host_to_net_u16 (UDP_DST_PORT_bfd6);
132
133   /* fix ip payload length and udp length */
134   const u16 udp_length =
135     vlib_buffer_length_in_chain (vm, b) - (sizeof (headers->ip6));
136   headers->udp.length = clib_host_to_net_u16 (udp_length);
137   headers->ip6.payload_length = headers->udp.length;
138
139   /* IPv6 UDP checksum is mandatory */
140   int bogus = 0;
141   headers->udp.checksum =
142     ip6_tcp_udp_icmp_compute_checksum (vm, b, &headers->ip6, &bogus);
143   ASSERT (bogus == 0);
144   if (headers->udp.checksum == 0)
145     {
146       headers->udp.checksum = 0xffff;
147     }
148 }
149
150 static bfd_session_t *
151 bfd_lookup_session (bfd_udp_main_t * bum, const bfd_udp_key_t * key)
152 {
153   uword *p = mhash_get (&bum->bfd_session_idx_by_bfd_key, key);
154   if (p)
155     {
156       return bfd_find_session_by_idx (bum->bfd_main, *p);
157     }
158   return 0;
159 }
160
161 static void
162 bfd_udp_key_init (bfd_udp_key_t * key, u32 sw_if_index,
163                   const ip46_address_t * local_addr,
164                   const ip46_address_t * peer_addr)
165 {
166   memset (key, 0, sizeof (*key));
167   key->sw_if_index = sw_if_index;
168   key->local_addr.as_u64[0] = local_addr->as_u64[0];
169   key->local_addr.as_u64[1] = local_addr->as_u64[1];
170   key->peer_addr.as_u64[0] = peer_addr->as_u64[0];
171   key->peer_addr.as_u64[1] = peer_addr->as_u64[1];
172 }
173
174 static vnet_api_error_t
175 bfd_udp_add_session_internal (bfd_udp_main_t * bum, u32 sw_if_index,
176                               u32 desired_min_tx_usec,
177                               u32 required_min_rx_usec, u8 detect_mult,
178                               const ip46_address_t * local_addr,
179                               const ip46_address_t * peer_addr,
180                               bfd_session_t ** bs_out)
181 {
182   /* get a pool entry and if we end up not needing it, give it back */
183   bfd_transport_t t = BFD_TRANSPORT_UDP4;
184   if (!ip46_address_is_ip4 (local_addr))
185     {
186       t = BFD_TRANSPORT_UDP6;
187     }
188   bfd_session_t *bs = bfd_get_session (bum->bfd_main, t);
189   bfd_udp_session_t *bus = &bs->udp;
190   memset (bus, 0, sizeof (*bus));
191   bfd_udp_key_t *key = &bus->key;
192   bfd_udp_key_init (key, sw_if_index, local_addr, peer_addr);
193   const bfd_session_t *tmp = bfd_lookup_session (bum, key);
194   if (tmp)
195     {
196       clib_warning ("duplicate bfd-udp session, existing bs_idx=%d",
197                     tmp->bs_idx);
198       bfd_put_session (bum->bfd_main, bs);
199       return VNET_API_ERROR_BFD_EEXIST;
200     }
201   mhash_set (&bum->bfd_session_idx_by_bfd_key, key, bs->bs_idx, NULL);
202   BFD_DBG ("session created, bs_idx=%u, sw_if_index=%d, local=%U, peer=%U",
203            bs->bs_idx, key->sw_if_index, format_ip46_address,
204            &key->local_addr, IP46_TYPE_ANY, format_ip46_address,
205            &key->peer_addr, IP46_TYPE_ANY);
206   if (BFD_TRANSPORT_UDP4 == t)
207     {
208       bus->adj_index = adj_nbr_add_or_lock (FIB_PROTOCOL_IP4, VNET_LINK_IP4,
209                                             &key->peer_addr,
210                                             key->sw_if_index);
211       BFD_DBG ("adj_nbr_add_or_lock(FIB_PROTOCOL_IP4, VNET_LINK_IP4, %U, %d) "
212                "returns %d", format_ip46_address, &key->peer_addr,
213                IP46_TYPE_ANY, key->sw_if_index, bus->adj_index);
214     }
215   else
216     {
217       bus->adj_index = adj_nbr_add_or_lock (FIB_PROTOCOL_IP6, VNET_LINK_IP6,
218                                             &key->peer_addr,
219                                             key->sw_if_index);
220       BFD_DBG ("adj_nbr_add_or_lock(FIB_PROTOCOL_IP6, VNET_LINK_IP6, %U, %d) "
221                "returns %d", format_ip46_address, &key->peer_addr,
222                IP46_TYPE_ANY, key->sw_if_index, bus->adj_index);
223     }
224   *bs_out = bs;
225   return bfd_session_set_params (bum->bfd_main, bs, desired_min_tx_usec,
226                                  required_min_rx_usec, detect_mult);
227 }
228
229 static vnet_api_error_t
230 bfd_udp_validate_api_input (u32 sw_if_index,
231                             const ip46_address_t * local_addr,
232                             const ip46_address_t * peer_addr)
233 {
234   vnet_sw_interface_t *sw_if =
235     vnet_get_sw_interface (vnet_get_main (), sw_if_index);
236   u8 local_ip_valid = 0;
237   ip_interface_address_t *ia = NULL;
238   if (!sw_if)
239     {
240       clib_warning ("got NULL sw_if");
241       return VNET_API_ERROR_INVALID_SW_IF_INDEX;
242     }
243   if (ip46_address_is_ip4 (local_addr))
244     {
245       if (!ip46_address_is_ip4 (peer_addr))
246         {
247           clib_warning ("IP family mismatch");
248           return VNET_API_ERROR_INVALID_ARGUMENT;
249         }
250       ip4_main_t *im = &ip4_main;
251
252       /* *INDENT-OFF* */
253       foreach_ip_interface_address (
254           &im->lookup_main, ia, sw_if_index, 0 /* honor unnumbered */, ({
255             ip4_address_t *x =
256                 ip_interface_address_get_address (&im->lookup_main, ia);
257             if (x->as_u32 == local_addr->ip4.as_u32)
258               {
259                 /* valid address for this interface */
260                 local_ip_valid = 1;
261                 break;
262               }
263           }));
264       /* *INDENT-ON* */
265     }
266   else
267     {
268       if (ip46_address_is_ip4 (peer_addr))
269         {
270           clib_warning ("IP family mismatch");
271           return VNET_API_ERROR_INVALID_ARGUMENT;
272         }
273       ip6_main_t *im = &ip6_main;
274       /* *INDENT-OFF* */
275       foreach_ip_interface_address (
276           &im->lookup_main, ia, sw_if_index, 0 /* honor unnumbered */, ({
277             ip6_address_t *x =
278                 ip_interface_address_get_address (&im->lookup_main, ia);
279             if (local_addr->ip6.as_u64[0] == x->as_u64[0] &&
280                 local_addr->ip6.as_u64[1] == x->as_u64[1])
281               {
282                 /* valid address for this interface */
283                 local_ip_valid = 1;
284                 break;
285               }
286           }));
287       /* *INDENT-ON* */
288     }
289
290   if (!local_ip_valid)
291     {
292       clib_warning ("address not found on interface");
293       return VNET_API_ERROR_ADDRESS_NOT_FOUND_FOR_INTERFACE;
294     }
295
296   return 0;
297 }
298
299 static vnet_api_error_t
300 bfd_udp_find_session_by_api_input (u32 sw_if_index,
301                                    const ip46_address_t * local_addr,
302                                    const ip46_address_t * peer_addr,
303                                    bfd_session_t ** bs_out)
304 {
305   vnet_api_error_t rv =
306     bfd_udp_validate_api_input (sw_if_index, local_addr, peer_addr);
307   if (!rv)
308     {
309       bfd_udp_main_t *bum = &bfd_udp_main;
310       bfd_udp_key_t key;
311       bfd_udp_key_init (&key, sw_if_index, local_addr, peer_addr);
312       bfd_session_t *bs = bfd_lookup_session (bum, &key);
313       if (bs)
314         {
315           *bs_out = bs;
316         }
317       else
318         {
319           clib_warning
320             ("BFD session not found (sw_if_index=%u, local=%U, peer=%U",
321              sw_if_index, format_ip46_address, local_addr, IP46_TYPE_ANY,
322              format_ip46_address, peer_addr, IP46_TYPE_ANY);
323           return VNET_API_ERROR_BFD_ENOENT;
324         }
325     }
326   return rv;
327 }
328
329 static vnet_api_error_t
330 bfd_api_verify_common (u32 sw_if_index, u32 desired_min_tx_usec,
331                        u32 required_min_rx_usec, u8 detect_mult,
332                        const ip46_address_t * local_addr,
333                        const ip46_address_t * peer_addr)
334 {
335   vnet_api_error_t rv =
336     bfd_udp_validate_api_input (sw_if_index, local_addr, peer_addr);
337   if (rv)
338     {
339       return rv;
340     }
341   if (detect_mult < 1)
342     {
343       clib_warning ("detect_mult < 1");
344       return VNET_API_ERROR_INVALID_ARGUMENT;
345     }
346   if (desired_min_tx_usec < 1)
347     {
348       clib_warning ("desired_min_tx_usec < 1");
349       return VNET_API_ERROR_INVALID_ARGUMENT;
350     }
351   return 0;
352 }
353
354 static void
355 bfd_udp_del_session_internal (bfd_session_t * bs)
356 {
357   bfd_udp_main_t *bum = &bfd_udp_main;
358   BFD_DBG ("free bfd-udp session, bs_idx=%d", bs->bs_idx);
359   mhash_unset (&bum->bfd_session_idx_by_bfd_key, &bs->udp.key, NULL);
360   adj_unlock (bs->udp.adj_index);
361   bfd_put_session (bum->bfd_main, bs);
362 }
363
364 vnet_api_error_t
365 bfd_udp_add_session (u32 sw_if_index, const ip46_address_t * local_addr,
366                      const ip46_address_t * peer_addr,
367                      u32 desired_min_tx_usec, u32 required_min_rx_usec,
368                      u8 detect_mult, u8 is_authenticated, u32 conf_key_id,
369                      u8 bfd_key_id)
370 {
371   vnet_api_error_t rv =
372     bfd_api_verify_common (sw_if_index, desired_min_tx_usec,
373                            required_min_rx_usec, detect_mult,
374                            local_addr, peer_addr);
375   bfd_session_t *bs = NULL;
376   if (!rv)
377     {
378       rv =
379         bfd_udp_add_session_internal (&bfd_udp_main, sw_if_index,
380                                       desired_min_tx_usec,
381                                       required_min_rx_usec, detect_mult,
382                                       local_addr, peer_addr, &bs);
383     }
384   if (!rv && is_authenticated)
385     {
386 #if WITH_LIBSSL > 0
387       rv = bfd_auth_activate (bs, conf_key_id, bfd_key_id,
388                               0 /* is not delayed */ );
389 #else
390       clib_warning ("SSL missing, cannot add authenticated BFD session");
391       rv = VNET_API_ERROR_BFD_NOTSUPP;
392 #endif
393       if (rv)
394         {
395           bfd_udp_del_session_internal (bs);
396         }
397     }
398   if (!rv)
399     {
400       bfd_session_start (bfd_udp_main.bfd_main, bs);
401     }
402
403   return rv;
404 }
405
406 vnet_api_error_t
407 bfd_udp_mod_session (u32 sw_if_index,
408                      const ip46_address_t * local_addr,
409                      const ip46_address_t * peer_addr,
410                      u32 desired_min_tx_usec,
411                      u32 required_min_rx_usec, u8 detect_mult)
412 {
413   bfd_session_t *bs = NULL;
414   vnet_api_error_t rv =
415     bfd_udp_find_session_by_api_input (sw_if_index, local_addr, peer_addr,
416                                        &bs);
417   if (rv)
418     {
419       return rv;
420     }
421
422   return bfd_session_set_params (bfd_udp_main.bfd_main, bs,
423                                  desired_min_tx_usec, required_min_rx_usec,
424                                  detect_mult);
425 }
426
427 vnet_api_error_t
428 bfd_udp_del_session (u32 sw_if_index,
429                      const ip46_address_t * local_addr,
430                      const ip46_address_t * peer_addr)
431 {
432   bfd_session_t *bs = NULL;
433   vnet_api_error_t rv =
434     bfd_udp_find_session_by_api_input (sw_if_index, local_addr, peer_addr,
435                                        &bs);
436   if (rv)
437     {
438       return rv;
439     }
440   bfd_udp_del_session_internal (bs);
441   return 0;
442 }
443
444 vnet_api_error_t
445 bfd_udp_session_set_flags (u32 sw_if_index,
446                            const ip46_address_t * local_addr,
447                            const ip46_address_t * peer_addr, u8 admin_up_down)
448 {
449   bfd_session_t *bs = NULL;
450   vnet_api_error_t rv =
451     bfd_udp_find_session_by_api_input (sw_if_index, local_addr, peer_addr,
452                                        &bs);
453   if (rv)
454     {
455       return rv;
456     }
457   bfd_session_set_flags (bs, admin_up_down);
458   return 0;
459 }
460
461 vnet_api_error_t
462 bfd_auth_set_key (u32 conf_key_id, u8 auth_type, u8 key_len,
463                   const u8 * key_data)
464 {
465 #if WITH_LIBSSL > 0
466   bfd_auth_key_t *auth_key = NULL;
467   if (!key_len || key_len > bfd_max_len_for_auth_type (auth_type))
468     {
469       clib_warning ("Invalid authentication key length for auth_type=%d:%s "
470                     "(key_len=%u, must be "
471                     "non-zero, expected max=%u)",
472                     auth_type, bfd_auth_type_str (auth_type), key_len,
473                     (u32) bfd_max_len_for_auth_type (auth_type));
474       return VNET_API_ERROR_INVALID_VALUE;
475     }
476   if (!bfd_auth_type_supported (auth_type))
477     {
478       clib_warning ("Unsupported auth type=%d:%s", auth_type,
479                     bfd_auth_type_str (auth_type));
480       return VNET_API_ERROR_BFD_NOTSUPP;
481     }
482   bfd_main_t *bm = bfd_udp_main.bfd_main;
483   uword *key_idx_p = hash_get (bm->auth_key_by_conf_key_id, conf_key_id);
484   if (key_idx_p)
485     {
486       /* modifying existing key - must not be used */
487       const uword key_idx = *key_idx_p;
488       auth_key = pool_elt_at_index (bm->auth_keys, key_idx);
489       if (auth_key->use_count > 0)
490         {
491           clib_warning ("Authentication key with conf ID %u in use by %u BFD "
492                         "sessions - cannot modify",
493                         conf_key_id, auth_key->use_count);
494           return VNET_API_ERROR_BFD_EINUSE;
495         }
496     }
497   else
498     {
499       /* adding new key */
500       pool_get (bm->auth_keys, auth_key);
501       auth_key->conf_key_id = conf_key_id;
502       hash_set (bm->auth_key_by_conf_key_id, conf_key_id,
503                 auth_key - bm->auth_keys);
504     }
505   auth_key->auth_type = auth_type;
506   memset (auth_key->key, 0, sizeof (auth_key->key));
507   clib_memcpy (auth_key->key, key_data, key_len);
508   return 0;
509 #else
510   clib_warning ("SSL missing, cannot manipulate authentication keys");
511   return VNET_API_ERROR_BFD_NOTSUPP;
512 #endif
513 }
514
515 vnet_api_error_t
516 bfd_auth_del_key (u32 conf_key_id)
517 {
518 #if WITH_LIBSSL > 0
519   bfd_auth_key_t *auth_key = NULL;
520   bfd_main_t *bm = bfd_udp_main.bfd_main;
521   uword *key_idx_p = hash_get (bm->auth_key_by_conf_key_id, conf_key_id);
522   if (key_idx_p)
523     {
524       /* deleting existing key - must not be used */
525       const uword key_idx = *key_idx_p;
526       auth_key = pool_elt_at_index (bm->auth_keys, key_idx);
527       if (auth_key->use_count > 0)
528         {
529           clib_warning ("Authentication key with conf ID %u in use by %u BFD "
530                         "sessions - cannot delete",
531                         conf_key_id, auth_key->use_count);
532           return VNET_API_ERROR_BFD_EINUSE;
533         }
534       hash_unset (bm->auth_key_by_conf_key_id, conf_key_id);
535       memset (auth_key, 0, sizeof (*auth_key));
536       pool_put (bm->auth_keys, auth_key);
537     }
538   else
539     {
540       /* no such key */
541       clib_warning ("Authentication key with conf ID %u does not exist",
542                     conf_key_id);
543       return VNET_API_ERROR_BFD_ENOENT;
544     }
545   return 0;
546 #else
547   clib_warning ("SSL missing, cannot manipulate authentication keys");
548   return VNET_API_ERROR_BFD_NOTSUPP;
549 #endif
550 }
551
552 vnet_api_error_t
553 bfd_udp_auth_activate (u32 sw_if_index,
554                        const ip46_address_t * local_addr,
555                        const ip46_address_t * peer_addr,
556                        u32 conf_key_id, u8 key_id, u8 is_delayed)
557 {
558 #if WITH_LIBSSL > 0
559   bfd_session_t *bs = NULL;
560   vnet_api_error_t rv =
561     bfd_udp_find_session_by_api_input (sw_if_index, local_addr, peer_addr,
562                                        &bs);
563   if (rv)
564     {
565       return rv;
566     }
567   return bfd_auth_activate (bs, conf_key_id, key_id, is_delayed);
568 #else
569   clib_warning ("SSL missing, cannot activate BFD authentication");
570   return VNET_API_ERROR_BFD_NOTSUPP;
571 #endif
572 }
573
574 vnet_api_error_t
575 bfd_udp_auth_deactivate (u32 sw_if_index,
576                          const ip46_address_t * local_addr,
577                          const ip46_address_t * peer_addr, u8 is_delayed)
578 {
579   bfd_session_t *bs = NULL;
580   vnet_api_error_t rv =
581     bfd_udp_find_session_by_api_input (sw_if_index, local_addr, peer_addr,
582                                        &bs);
583   if (rv)
584     {
585       return rv;
586     }
587   return bfd_auth_deactivate (bs, is_delayed);
588 }
589
590 typedef enum
591 {
592   BFD_UDP_INPUT_NEXT_NORMAL,
593   BFD_UDP_INPUT_NEXT_REPLY,
594   BFD_UDP_INPUT_N_NEXT,
595 } bfd_udp_input_next_t;
596
597 /* Packet counters */
598 #define foreach_bfd_udp_error(F)           \
599   F (NONE, "good bfd packets (processed)") \
600   F (BAD, "invalid bfd packets")           \
601   F (DISABLED, "bfd packets received on disabled interfaces")
602
603 #define F(sym, string) static char BFD_UDP_ERR_##sym##_STR[] = string;
604 foreach_bfd_udp_error (F);
605 #undef F
606
607 static char *bfd_udp_error_strings[] = {
608 #define F(sym, string) BFD_UDP_ERR_##sym##_STR,
609   foreach_bfd_udp_error (F)
610 #undef F
611 };
612
613 typedef enum
614 {
615 #define F(sym, str) BFD_UDP_ERROR_##sym,
616   foreach_bfd_udp_error (F)
617 #undef F
618     BFD_UDP_N_ERROR,
619 } bfd_udp_error_t;
620
621 static void
622 bfd_udp4_find_headers (vlib_buffer_t * b, const ip4_header_t ** ip4,
623                        const udp_header_t ** udp)
624 {
625   /* sanity check first */
626   const i32 start = vnet_buffer (b)->ip.start_of_ip_header;
627   if (start < 0 && start < sizeof (b->pre_data))
628     {
629       BFD_ERR ("Start of ip header is before pre_data, ignoring");
630       *ip4 = NULL;
631       *udp = NULL;
632       return;
633     }
634   *ip4 = (ip4_header_t *) (b->data + start);
635   if ((u8 *) * ip4 > (u8 *) vlib_buffer_get_current (b))
636     {
637       BFD_ERR ("Start of ip header is beyond current data, ignoring");
638       *ip4 = NULL;
639       *udp = NULL;
640       return;
641     }
642   *udp = (udp_header_t *) ((*ip4) + 1);
643 }
644
645 static bfd_udp_error_t
646 bfd_udp4_verify_transport (const ip4_header_t * ip4,
647                            const udp_header_t * udp, const bfd_session_t * bs)
648 {
649   const bfd_udp_session_t *bus = &bs->udp;
650   const bfd_udp_key_t *key = &bus->key;
651   if (ip4->src_address.as_u32 != key->peer_addr.ip4.as_u32)
652     {
653       BFD_ERR ("IPv4 src addr mismatch, got %U, expected %U",
654                format_ip4_address, ip4->src_address.as_u8, format_ip4_address,
655                key->peer_addr.ip4.as_u8);
656       return BFD_UDP_ERROR_BAD;
657     }
658   if (ip4->dst_address.as_u32 != key->local_addr.ip4.as_u32)
659     {
660       BFD_ERR ("IPv4 dst addr mismatch, got %U, expected %U",
661                format_ip4_address, ip4->dst_address.as_u8, format_ip4_address,
662                key->local_addr.ip4.as_u8);
663       return BFD_UDP_ERROR_BAD;
664     }
665   const u8 expected_ttl = 255;
666   if (ip4->ttl != expected_ttl)
667     {
668       BFD_ERR ("IPv4 unexpected TTL value %u, expected %u", ip4->ttl,
669                expected_ttl);
670       return BFD_UDP_ERROR_BAD;
671     }
672   if (clib_net_to_host_u16 (udp->src_port) < 49152)
673     {
674       BFD_ERR ("Invalid UDP src port %u, out of range <49152,65535>",
675                udp->src_port);
676     }
677   return BFD_UDP_ERROR_NONE;
678 }
679
680 typedef struct
681 {
682   u32 bs_idx;
683   bfd_pkt_t pkt;
684 } bfd_rpc_update_t;
685
686 static void
687 bfd_rpc_update_session_cb (const bfd_rpc_update_t * a)
688 {
689   bfd_consume_pkt (bfd_udp_main.bfd_main, &a->pkt, a->bs_idx);
690 }
691
692 static void
693 bfd_rpc_update_session (u32 bs_idx, const bfd_pkt_t * pkt)
694 {
695   /* packet length was already verified to be correct by the caller */
696   const u32 data_size = sizeof (bfd_rpc_update_t) -
697     STRUCT_SIZE_OF (bfd_rpc_update_t, pkt) + pkt->head.length;
698   u8 data[data_size];
699   bfd_rpc_update_t *update = (bfd_rpc_update_t *) data;
700   update->bs_idx = bs_idx;
701   clib_memcpy (&update->pkt, pkt, pkt->head.length);
702   vl_api_rpc_call_main_thread (bfd_rpc_update_session_cb, data, data_size);
703 }
704
705 static bfd_udp_error_t
706 bfd_udp4_scan (vlib_main_t * vm, vlib_node_runtime_t * rt,
707                vlib_buffer_t * b, bfd_session_t ** bs_out)
708 {
709   const bfd_pkt_t *pkt = vlib_buffer_get_current (b);
710   if (sizeof (*pkt) > b->current_length)
711     {
712       BFD_ERR
713         ("Payload size %d too small to hold bfd packet of minimum size %d",
714          b->current_length, sizeof (*pkt));
715       return BFD_UDP_ERROR_BAD;
716     }
717   const ip4_header_t *ip4;
718   const udp_header_t *udp;
719   bfd_udp4_find_headers (b, &ip4, &udp);
720   if (!ip4 || !udp)
721     {
722       BFD_ERR ("Couldn't find ip4 or udp header");
723       return BFD_UDP_ERROR_BAD;
724     }
725   const u32 udp_payload_length = udp->length - sizeof (*udp);
726   if (pkt->head.length > udp_payload_length)
727     {
728       BFD_ERR
729         ("BFD packet length is larger than udp payload length (%u > %u)",
730          pkt->head.length, udp_payload_length);
731       return BFD_UDP_ERROR_BAD;
732     }
733   if (!bfd_verify_pkt_common (pkt))
734     {
735       return BFD_UDP_ERROR_BAD;
736     }
737   bfd_session_t *bs = NULL;
738   if (pkt->your_disc)
739     {
740       BFD_DBG ("Looking up BFD session using discriminator %u",
741                pkt->your_disc);
742       bs = bfd_find_session_by_disc (bfd_udp_main.bfd_main, pkt->your_disc);
743     }
744   else
745     {
746       bfd_udp_key_t key;
747       memset (&key, 0, sizeof (key));
748       key.sw_if_index = vnet_buffer (b)->sw_if_index[VLIB_RX];
749       key.local_addr.ip4.as_u32 = ip4->dst_address.as_u32;
750       key.peer_addr.ip4.as_u32 = ip4->src_address.as_u32;
751       BFD_DBG ("Looking up BFD session using key (sw_if_index=%u, local=%U, "
752                "peer=%U)",
753                key.sw_if_index, format_ip4_address, key.local_addr.ip4.as_u8,
754                format_ip4_address, key.peer_addr.ip4.as_u8);
755       bs = bfd_lookup_session (&bfd_udp_main, &key);
756     }
757   if (!bs)
758     {
759       BFD_ERR ("BFD session lookup failed - no session matches BFD pkt");
760       return BFD_UDP_ERROR_BAD;
761     }
762   BFD_DBG ("BFD session found, bs_idx=%u", bs->bs_idx);
763   if (!bfd_verify_pkt_auth (pkt, b->current_length, bs))
764     {
765       BFD_ERR ("Packet verification failed, dropping packet");
766       return BFD_UDP_ERROR_BAD;
767     }
768   bfd_udp_error_t err;
769   if (BFD_UDP_ERROR_NONE != (err = bfd_udp4_verify_transport (ip4, udp, bs)))
770     {
771       return err;
772     }
773   bfd_rpc_update_session (bs->bs_idx, pkt);
774   *bs_out = bs;
775   return BFD_UDP_ERROR_NONE;
776 }
777
778 static void
779 bfd_udp6_find_headers (vlib_buffer_t * b, const ip6_header_t ** ip6,
780                        const udp_header_t ** udp)
781 {
782   /* sanity check first */
783   const i32 start = vnet_buffer (b)->ip.start_of_ip_header;
784   if (start < 0 && start < sizeof (b->pre_data))
785     {
786       BFD_ERR ("Start of ip header is before pre_data, ignoring");
787       *ip6 = NULL;
788       *udp = NULL;
789       return;
790     }
791   *ip6 = (ip6_header_t *) (b->data + start);
792   if ((u8 *) * ip6 > (u8 *) vlib_buffer_get_current (b))
793     {
794       BFD_ERR ("Start of ip header is beyond current data, ignoring");
795       *ip6 = NULL;
796       *udp = NULL;
797       return;
798     }
799   if ((*ip6)->protocol != IP_PROTOCOL_UDP)
800     {
801       BFD_ERR ("Unexpected protocol in IPv6 header '%u', expected '%u' (== "
802                "IP_PROTOCOL_UDP)", (*ip6)->protocol, IP_PROTOCOL_UDP);
803       *ip6 = NULL;
804       *udp = NULL;
805       return;
806     }
807   *udp = (udp_header_t *) ((*ip6) + 1);
808 }
809
810 static bfd_udp_error_t
811 bfd_udp6_verify_transport (const ip6_header_t * ip6,
812                            const udp_header_t * udp, const bfd_session_t * bs)
813 {
814   const bfd_udp_session_t *bus = &bs->udp;
815   const bfd_udp_key_t *key = &bus->key;
816   if (ip6->src_address.as_u64[0] != key->peer_addr.ip6.as_u64[0] &&
817       ip6->src_address.as_u64[1] != key->peer_addr.ip6.as_u64[1])
818     {
819       BFD_ERR ("IP src addr mismatch, got %U, expected %U",
820                format_ip6_address, ip6, format_ip6_address,
821                &key->peer_addr.ip6);
822       return BFD_UDP_ERROR_BAD;
823     }
824   if (ip6->dst_address.as_u64[0] != key->local_addr.ip6.as_u64[0] &&
825       ip6->dst_address.as_u64[1] != key->local_addr.ip6.as_u64[1])
826     {
827       BFD_ERR ("IP dst addr mismatch, got %U, expected %U",
828                format_ip6_address, ip6, format_ip6_address,
829                &key->local_addr.ip6);
830       return BFD_UDP_ERROR_BAD;
831     }
832   const u8 expected_hop_limit = 255;
833   if (ip6->hop_limit != expected_hop_limit)
834     {
835       BFD_ERR ("IPv6 unexpected hop-limit value %u, expected %u",
836                ip6->hop_limit, expected_hop_limit);
837       return BFD_UDP_ERROR_BAD;
838     }
839   if (clib_net_to_host_u16 (udp->src_port) < 49152)
840     {
841       BFD_ERR ("Invalid UDP src port %u, out of range <49152,65535>",
842                udp->src_port);
843     }
844   return BFD_UDP_ERROR_NONE;
845 }
846
847 static bfd_udp_error_t
848 bfd_udp6_scan (vlib_main_t * vm, vlib_node_runtime_t * rt,
849                vlib_buffer_t * b, bfd_session_t ** bs_out)
850 {
851   const bfd_pkt_t *pkt = vlib_buffer_get_current (b);
852   if (sizeof (*pkt) > b->current_length)
853     {
854       BFD_ERR
855         ("Payload size %d too small to hold bfd packet of minimum size %d",
856          b->current_length, sizeof (*pkt));
857       return BFD_UDP_ERROR_BAD;
858     }
859   const ip6_header_t *ip6;
860   const udp_header_t *udp;
861   bfd_udp6_find_headers (b, &ip6, &udp);
862   if (!ip6 || !udp)
863     {
864       BFD_ERR ("Couldn't find ip6 or udp header");
865       return BFD_UDP_ERROR_BAD;
866     }
867   const u32 udp_payload_length = udp->length - sizeof (*udp);
868   if (pkt->head.length > udp_payload_length)
869     {
870       BFD_ERR
871         ("BFD packet length is larger than udp payload length (%u > %u)",
872          pkt->head.length, udp_payload_length);
873       return BFD_UDP_ERROR_BAD;
874     }
875   if (!bfd_verify_pkt_common (pkt))
876     {
877       return BFD_UDP_ERROR_BAD;
878     }
879   bfd_session_t *bs = NULL;
880   if (pkt->your_disc)
881     {
882       BFD_DBG ("Looking up BFD session using discriminator %u",
883                pkt->your_disc);
884       bs = bfd_find_session_by_disc (bfd_udp_main.bfd_main, pkt->your_disc);
885     }
886   else
887     {
888       bfd_udp_key_t key;
889       memset (&key, 0, sizeof (key));
890       key.sw_if_index = vnet_buffer (b)->sw_if_index[VLIB_RX];
891       key.local_addr.ip6.as_u64[0] = ip6->dst_address.as_u64[0];
892       key.local_addr.ip6.as_u64[1] = ip6->dst_address.as_u64[1];
893       key.peer_addr.ip6.as_u64[0] = ip6->src_address.as_u64[0];
894       key.peer_addr.ip6.as_u64[1] = ip6->src_address.as_u64[1];
895       BFD_DBG ("Looking up BFD session using key (sw_if_index=%u, local=%U, "
896                "peer=%U)",
897                key.sw_if_index, format_ip6_address, &key.local_addr,
898                format_ip6_address, &key.peer_addr);
899       bs = bfd_lookup_session (&bfd_udp_main, &key);
900     }
901   if (!bs)
902     {
903       BFD_ERR ("BFD session lookup failed - no session matches BFD pkt");
904       return BFD_UDP_ERROR_BAD;
905     }
906   BFD_DBG ("BFD session found, bs_idx=%u", bs->bs_idx);
907   if (!bfd_verify_pkt_auth (pkt, b->current_length, bs))
908     {
909       BFD_ERR ("Packet verification failed, dropping packet");
910       return BFD_UDP_ERROR_BAD;
911     }
912   bfd_udp_error_t err;
913   if (BFD_UDP_ERROR_NONE != (err = bfd_udp6_verify_transport (ip6, udp, bs)))
914     {
915       return err;
916     }
917   bfd_rpc_update_session (bs->bs_idx, pkt);
918   *bs_out = bs;
919   return BFD_UDP_ERROR_NONE;
920 }
921
922 /*
923  * Process a frame of bfd packets
924  * Expect 1 packet / frame
925  */
926 static uword
927 bfd_udp_input (vlib_main_t * vm, vlib_node_runtime_t * rt,
928                vlib_frame_t * f, int is_ipv6)
929 {
930   u32 n_left_from, *from;
931   bfd_input_trace_t *t0;
932
933   from = vlib_frame_vector_args (f);    /* array of buffer indices */
934   n_left_from = f->n_vectors;   /* number of buffer indices */
935
936   while (n_left_from > 0)
937     {
938       u32 bi0;
939       vlib_buffer_t *b0;
940       u32 next0, error0;
941
942       bi0 = from[0];
943       b0 = vlib_get_buffer (vm, bi0);
944
945       bfd_session_t *bs = NULL;
946
947       /* If this pkt is traced, snapshot the data */
948       if (b0->flags & VLIB_BUFFER_IS_TRACED)
949         {
950           int len;
951           t0 = vlib_add_trace (vm, rt, b0, sizeof (*t0));
952           len = (b0->current_length < sizeof (t0->data)) ? b0->current_length
953             : sizeof (t0->data);
954           t0->len = len;
955           clib_memcpy (t0->data, vlib_buffer_get_current (b0), len);
956         }
957
958       /* scan this bfd pkt. error0 is the counter index to bmp */
959       if (is_ipv6)
960         {
961           error0 = bfd_udp6_scan (vm, rt, b0, &bs);
962         }
963       else
964         {
965           error0 = bfd_udp4_scan (vm, rt, b0, &bs);
966         }
967       b0->error = rt->errors[error0];
968
969       next0 = BFD_UDP_INPUT_NEXT_NORMAL;
970       if (BFD_UDP_ERROR_NONE == error0)
971         {
972           /*
973            *  if everything went fine, check for poll bit, if present, re-use
974            *  the buffer and based on (now updated) session parameters, send
975            *  the final packet back
976            */
977           const bfd_pkt_t *pkt = vlib_buffer_get_current (b0);
978           if (bfd_pkt_get_poll (pkt))
979             {
980               bfd_init_final_control_frame (vm, b0, bs);
981               if (is_ipv6)
982                 {
983                   vlib_node_increment_counter (vm, bfd_udp6_input_node.index,
984                                                b0->error, 1);
985                 }
986               else
987                 {
988                   vlib_node_increment_counter (vm, bfd_udp4_input_node.index,
989                                                b0->error, 1);
990                 }
991               next0 = BFD_UDP_INPUT_NEXT_REPLY;
992             }
993         }
994       vlib_set_next_frame_buffer (vm, rt, next0, bi0);
995
996       from += 1;
997       n_left_from -= 1;
998     }
999
1000   return f->n_vectors;
1001 }
1002
1003 static uword
1004 bfd_udp4_input (vlib_main_t * vm, vlib_node_runtime_t * rt, vlib_frame_t * f)
1005 {
1006   return bfd_udp_input (vm, rt, f, 0);
1007 }
1008
1009 /*
1010  * bfd input graph node declaration
1011  */
1012 /* *INDENT-OFF* */
1013 VLIB_REGISTER_NODE (bfd_udp4_input_node, static) = {
1014   .function = bfd_udp4_input,
1015   .name = "bfd-udp4-input",
1016   .vector_size = sizeof (u32),
1017   .type = VLIB_NODE_TYPE_INTERNAL,
1018
1019   .n_errors = BFD_UDP_N_ERROR,
1020   .error_strings = bfd_udp_error_strings,
1021
1022   .format_trace = bfd_input_format_trace,
1023
1024   .n_next_nodes = BFD_UDP_INPUT_N_NEXT,
1025   .next_nodes =
1026       {
1027               [BFD_UDP_INPUT_NEXT_NORMAL] = "error-drop",
1028               [BFD_UDP_INPUT_NEXT_REPLY] = "ip4-lookup",
1029       },
1030 };
1031 /* *INDENT-ON* */
1032
1033 static uword
1034 bfd_udp6_input (vlib_main_t * vm, vlib_node_runtime_t * rt, vlib_frame_t * f)
1035 {
1036   return bfd_udp_input (vm, rt, f, 1);
1037 }
1038
1039 /* *INDENT-OFF* */
1040 VLIB_REGISTER_NODE (bfd_udp6_input_node, static) = {
1041   .function = bfd_udp6_input,
1042   .name = "bfd-udp6-input",
1043   .vector_size = sizeof (u32),
1044   .type = VLIB_NODE_TYPE_INTERNAL,
1045
1046   .n_errors = BFD_UDP_N_ERROR,
1047   .error_strings = bfd_udp_error_strings,
1048
1049   .format_trace = bfd_input_format_trace,
1050
1051   .n_next_nodes = BFD_UDP_INPUT_N_NEXT,
1052   .next_nodes =
1053       {
1054               [BFD_UDP_INPUT_NEXT_NORMAL] = "error-drop",
1055               [BFD_UDP_INPUT_NEXT_REPLY] = "ip6-lookup",
1056       },
1057 };
1058 /* *INDENT-ON* */
1059
1060 static clib_error_t *
1061 bfd_sw_interface_up_down (vnet_main_t * vnm, u32 sw_if_index, u32 flags)
1062 {
1063   // vnet_hw_interface_t *hi = vnet_get_sup_hw_interface (vnm, sw_if_index);
1064   if (!(flags & VNET_SW_INTERFACE_FLAG_ADMIN_UP))
1065     {
1066       /* TODO */
1067     }
1068   return 0;
1069 }
1070
1071 VNET_SW_INTERFACE_ADMIN_UP_DOWN_FUNCTION (bfd_sw_interface_up_down);
1072
1073 static clib_error_t *
1074 bfd_hw_interface_up_down (vnet_main_t * vnm, u32 hw_if_index, u32 flags)
1075 {
1076   if (flags & VNET_HW_INTERFACE_FLAG_LINK_UP)
1077     {
1078       /* TODO */
1079     }
1080   return 0;
1081 }
1082
1083 VNET_HW_INTERFACE_LINK_UP_DOWN_FUNCTION (bfd_hw_interface_up_down);
1084
1085 /*
1086  * setup function
1087  */
1088 static clib_error_t *
1089 bfd_udp_init (vlib_main_t * vm)
1090 {
1091   mhash_init (&bfd_udp_main.bfd_session_idx_by_bfd_key, sizeof (uword),
1092               sizeof (bfd_udp_key_t));
1093   bfd_udp_main.bfd_main = &bfd_main;
1094   udp_register_dst_port (vm, UDP_DST_PORT_bfd4, bfd_udp4_input_node.index, 1);
1095   udp_register_dst_port (vm, UDP_DST_PORT_bfd6, bfd_udp6_input_node.index, 0);
1096   return 0;
1097 }
1098
1099 VLIB_INIT_FUNCTION (bfd_udp_init);
1100
1101 /*
1102  * fd.io coding-style-patch-verification: ON
1103  *
1104  * Local Variables:
1105  * eval: (c-set-style "gnu")
1106  * End:
1107  */