mactime: upstream new features
[vpp.git] / src / plugins / mactime / mactime.c
1 /*
2  * mactime.c - time-based src mac address filtration
3  *
4  * Copyright (c) 2018 Cisco and/or its affiliates.
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <vnet/vnet.h>
19 #include <vnet/plugin/plugin.h>
20 #include <mactime/mactime.h>
21
22 #include <vlibapi/api.h>
23 #include <vlibmemory/api.h>
24 #include <vpp/app/version.h>
25
26 /* define message IDs */
27 #include <mactime/mactime_msg_enum.h>
28
29 /* define message structures */
30 #define vl_typedefs
31 #include <mactime/mactime_all_api_h.h>
32 #undef vl_typedefs
33
34 /* define generated endian-swappers */
35 #define vl_endianfun
36 #include <mactime/mactime_all_api_h.h>
37 #undef vl_endianfun
38
39 /* instantiate all the print functions we know about */
40 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
41 #define vl_printfun
42 #include <mactime/mactime_all_api_h.h>
43 #undef vl_printfun
44
45 /* Get the API version number */
46 #define vl_api_version(n,v) static u32 api_version=(v);
47 #include <mactime/mactime_all_api_h.h>
48 #undef vl_api_version
49
50 #define REPLY_MSG_ID_BASE mm->msg_id_base
51 #include <vlibapi/api_helper_macros.h>
52
53 mactime_main_t mactime_main;
54
55 /** \file time-base src-mac filter device-input feature arc implementation
56  */
57
58 /* List of message types that this plugin understands */
59
60 #define foreach_mactime_plugin_api_msg                  \
61 _(MACTIME_ENABLE_DISABLE, mactime_enable_disable)       \
62 _(MACTIME_ADD_DEL_RANGE, mactime_add_del_range)
63
64 static void
65 feature_init (mactime_main_t * mm)
66 {
67   if (mm->feature_initialized == 0)
68     {
69       /* Create the lookup table */
70       clib_bihash_init_8_8 (&mm->lookup_table, "mactime lookup table",
71                             mm->lookup_table_num_buckets,
72                             mm->lookup_table_memory_size);
73       clib_timebase_init (&mm->timebase, mm->timezone_offset,
74                           CLIB_TIMEBASE_DAYLIGHT_USA);
75       mm->allow_counters.name = "allow";
76       mm->allow_counters.stat_segment_name = "/mactime/allow";
77       mm->drop_counters.name = "drop";
78       mm->drop_counters.stat_segment_name = "/mactime/drop";
79       mm->feature_initialized = 1;
80     }
81 }
82
83 /** Action function shared between message handler and debug CLI
84 */
85 int
86 mactime_enable_disable (mactime_main_t * mm, u32 sw_if_index,
87                         int enable_disable)
88 {
89   vnet_sw_interface_t *sw;
90   int rv = 0;
91
92   feature_init (mm);
93
94   /* Utterly wrong? */
95   if (pool_is_free_index (mm->vnet_main->interface_main.sw_interfaces,
96                           sw_if_index))
97     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
98
99   /* Not a physical port? */
100   sw = vnet_get_sw_interface (mm->vnet_main, sw_if_index);
101   if (sw->type != VNET_SW_INTERFACE_TYPE_HARDWARE)
102     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
103
104   vnet_feature_enable_disable ("device-input", "mactime",
105                                sw_if_index, enable_disable, 0, 0);
106   vnet_feature_enable_disable ("interface-output", "mactime-tx",
107                                sw_if_index, enable_disable, 0, 0);
108   return rv;
109 }
110
111 static clib_error_t *
112 mactime_enable_disable_command_fn (vlib_main_t * vm,
113                                    unformat_input_t * input,
114                                    vlib_cli_command_t * cmd)
115 {
116   mactime_main_t *mm = &mactime_main;
117   u32 sw_if_index = ~0;
118   int enable_disable = 1;
119
120   int rv;
121
122   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
123     {
124       if (unformat (input, "disable"))
125         enable_disable = 0;
126       else if (unformat (input, "%U", unformat_vnet_sw_interface,
127                          mm->vnet_main, &sw_if_index))
128         ;
129       else if (unformat (input, "sw_if_index %d", &sw_if_index))
130         ;
131       else
132         break;
133     }
134
135   if (sw_if_index == ~0)
136     return clib_error_return (0, "Please specify an interface...");
137
138   rv = mactime_enable_disable (mm, sw_if_index, enable_disable);
139
140   switch (rv)
141     {
142     case 0:
143       break;
144
145     case VNET_API_ERROR_INVALID_SW_IF_INDEX:
146       return clib_error_return
147         (0, "Invalid interface, only works on physical ports");
148       break;
149
150     default:
151       return clib_error_return (0, "mactime_enable_disable returned %d", rv);
152     }
153   return 0;
154 }
155
156 /* *INDENT-OFF* */
157 VLIB_CLI_COMMAND (mactime_enable_disable_command, static) =
158 {
159   .path = "mactime enable-disable",
160   .short_help =
161   "mactime enable-disable <interface-name> [disable]",
162   .function = mactime_enable_disable_command_fn,
163 };
164 /* *INDENT-ON* */
165
166
167 /** Enable / disable time-base src mac filtration on an interface
168  */
169
170 static void vl_api_mactime_enable_disable_t_handler
171   (vl_api_mactime_enable_disable_t * mp)
172 {
173   vl_api_mactime_enable_disable_reply_t *rmp;
174   mactime_main_t *mm = &mactime_main;
175   int rv;
176
177   VALIDATE_SW_IF_INDEX (mp);
178
179   rv = mactime_enable_disable (mm, ntohl (mp->sw_if_index),
180                                (int) (mp->enable_disable));
181   BAD_SW_IF_INDEX_LABEL;
182   REPLY_MACRO (VL_API_MACTIME_ENABLE_DISABLE_REPLY);
183 }
184
185 /** Create a lookup table entry for the indicated mac address
186  */
187 void
188 mactime_send_create_entry_message (u8 * mac_address)
189 {
190   mactime_main_t *mm = &mactime_main;
191   api_main_t *am;
192   vl_shmem_hdr_t *shmem_hdr;
193   u8 *name;
194   vl_api_mactime_add_del_range_t *mp;
195
196   am = &api_main;
197   shmem_hdr = am->shmem_hdr;
198   mp = vl_msg_api_alloc_as_if_client (sizeof (*mp));
199   clib_memset (mp, 0, sizeof (*mp));
200   mp->_vl_msg_id = ntohs (VL_API_MACTIME_ADD_DEL_RANGE + mm->msg_id_base);
201   name = format (0, "mac-%U", format_mac_address, mac_address);
202
203   memcpy (mp->device_name, name, vec_len (name));
204   memcpy (mp->mac_address, mac_address, sizeof (mp->mac_address));
205   /* $$$ config: create allow / drop / range */
206   mp->allow = 1;
207   mp->is_add = 1;
208   vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *) & mp);
209 }
210
211 /** Add or delete static / dynamic accept/drop configuration for a src mac
212  */
213
214 static void vl_api_mactime_add_del_range_t_handler
215   (vl_api_mactime_add_del_range_t * mp)
216 {
217   mactime_main_t *mm = &mactime_main;
218   vl_api_mactime_add_del_range_reply_t *rmp;
219   mactime_device_t *dp;
220   clib_bihash_kv_8_8_t kv;
221   int found = 1;
222   clib_bihash_8_8_t *lut = &mm->lookup_table;
223   u64 data_quota;
224   int i, rv = 0;
225
226   feature_init (mm);
227
228   data_quota = clib_net_to_host_u64 (mp->data_quota);
229
230   clib_memset (&kv, 0, sizeof (kv));
231   memcpy (&kv.key, mp->mac_address, sizeof (mp->mac_address));
232
233   /* See if we have a lookup table entry for this src mac address */
234   if (clib_bihash_search_8_8 (lut, &kv, &kv) < 0)
235     found = 0;
236
237   /* Add an entry? */
238   if (mp->is_add)
239     {
240       /* Create the device entry? */
241       if (found == 0)
242         {
243           pool_get (mm->devices, dp);
244           clib_memset (dp, 0, sizeof (*dp));
245           vlib_validate_combined_counter (&mm->allow_counters,
246                                           dp - mm->devices);
247           vlib_zero_combined_counter (&mm->allow_counters, dp - mm->devices);
248           vlib_validate_combined_counter (&mm->drop_counters,
249                                           dp - mm->devices);
250           vlib_zero_combined_counter (&mm->drop_counters, dp - mm->devices);
251           mp->device_name[ARRAY_LEN (mp->device_name) - 1] = 0;
252           dp->device_name = format (0, "%s%c", mp->device_name, 0);
253           memcpy (dp->mac_address, mp->mac_address, sizeof (mp->mac_address));
254           for (i = 0; i < clib_net_to_host_u32 (mp->count); i++)
255             {
256               clib_timebase_range_t _r, *r = &_r;
257               r->start = mp->ranges[i].start;
258               r->end = mp->ranges[i].end;
259               vec_add1 (dp->ranges, r[0]);
260             }
261           /* If we found some time ranges */
262           if (i)
263             {
264               /* Set allow/drop based on msg flags */
265               if (mp->drop)
266                 dp->flags = MACTIME_DEVICE_FLAG_DYNAMIC_DROP;
267               if (mp->allow)
268                 dp->flags = MACTIME_DEVICE_FLAG_DYNAMIC_ALLOW;
269             }
270           else
271             {
272               /* no ranges, it's a static allow/drop */
273               if (mp->drop)
274                 dp->flags = MACTIME_DEVICE_FLAG_STATIC_DROP;
275               if (mp->allow)
276                 dp->flags = MACTIME_DEVICE_FLAG_STATIC_ALLOW;
277             }
278           if (mp->no_udp_10001)
279             dp->flags |= MACTIME_DEVICE_FLAG_DROP_UDP_10001;
280
281           dp->data_quota = data_quota;
282
283           /* Add the hash table entry */
284           kv.value = dp - mm->devices;
285           clib_bihash_add_del_8_8 (lut, &kv, 1 /* is_add */ );
286         }
287       else                      /* add more ranges, flags, etc. */
288         {
289           dp = pool_elt_at_index (mm->devices, kv.value);
290
291           for (i = 0; i < clib_net_to_host_u32 (mp->count); i++)
292             {
293               clib_timebase_range_t _r, *r = &_r;
294               r->start = mp->ranges[i].start;
295               r->end = mp->ranges[i].end;
296               vec_add1 (dp->ranges, r[0]);
297             }
298
299           if (vec_len (dp->ranges))
300             {
301               /* Set allow/drop based on msg flags */
302               if (mp->drop)
303                 dp->flags = MACTIME_DEVICE_FLAG_DYNAMIC_DROP;
304               if (mp->allow)
305                 dp->flags = MACTIME_DEVICE_FLAG_DYNAMIC_ALLOW;
306             }
307           else
308             {
309               /* no ranges, it's a static allow/drop */
310               if (mp->drop)
311                 dp->flags = MACTIME_DEVICE_FLAG_STATIC_DROP;
312               if (mp->allow)
313                 dp->flags = MACTIME_DEVICE_FLAG_STATIC_ALLOW;
314             }
315           if (mp->no_udp_10001)
316             dp->flags |= MACTIME_DEVICE_FLAG_DROP_UDP_10001;
317
318           dp->data_quota = data_quota;
319         }
320     }
321   else                          /* delete case */
322     {
323       if (found == 0)
324         {
325           rv = VNET_API_ERROR_NO_SUCH_ENTRY;
326           goto reply;
327         }
328
329       /* find the device entry */
330       dp = pool_elt_at_index (mm->devices, kv.value);
331
332       /* Remove it from the lookup table */
333       clib_bihash_add_del_8_8 (lut, &kv, 0 /* is_add */ );
334       vec_free (dp->ranges);
335       pool_put (mm->devices, dp);
336     }
337
338 reply:
339   REPLY_MACRO (VL_API_MACTIME_ADD_DEL_RANGE_REPLY);
340 }
341
342 /* Set up the API message handling tables */
343 static clib_error_t *
344 mactime_plugin_api_hookup (vlib_main_t * vm)
345 {
346   mactime_main_t *mm = &mactime_main;
347 #define _(N,n)                                                  \
348     vl_msg_api_set_handlers((VL_API_##N + mm->msg_id_base),     \
349                            #n,                                  \
350                            vl_api_##n##_t_handler,              \
351                            vl_noop_handler,                     \
352                            vl_api_##n##_t_endian,               \
353                            vl_api_##n##_t_print,                \
354                            sizeof(vl_api_##n##_t), 1);
355   foreach_mactime_plugin_api_msg;
356 #undef _
357
358   return 0;
359 }
360
361 #define vl_msg_name_crc_list
362 #include <mactime/mactime_all_api_h.h>
363 #undef vl_msg_name_crc_list
364
365 static void
366 setup_message_id_table (mactime_main_t * mm, api_main_t * am)
367 {
368 #define _(id,n,crc)   vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id + mm->msg_id_base);
369   foreach_vl_msg_name_crc_mactime;
370 #undef _
371 }
372
373 static clib_error_t *
374 mactime_init (vlib_main_t * vm)
375 {
376   mactime_main_t *mm = &mactime_main;
377   clib_error_t *error = 0;
378   u8 *name;
379
380   mm->vlib_main = vm;
381   mm->vnet_main = vnet_get_main ();
382
383   name = format (0, "mactime_%08x%c", api_version, 0);
384
385   /* Ask for a correctly-sized block of API message decode slots */
386   mm->msg_id_base = vl_msg_api_get_msg_ids
387     ((char *) name, VL_MSG_FIRST_AVAILABLE);
388
389   error = mactime_plugin_api_hookup (vm);
390
391   /* Add our API messages to the global name_crc hash table */
392   setup_message_id_table (mm, &api_main);
393
394   vec_free (name);
395
396   mm->lookup_table_num_buckets = MACTIME_NUM_BUCKETS;
397   mm->lookup_table_memory_size = MACTIME_MEMORY_SIZE;
398   mm->timezone_offset = -5;     /* US EST / EDT */
399   return error;
400 }
401
402 VLIB_INIT_FUNCTION (mactime_init);
403
404 static clib_error_t *
405 mactime_config (vlib_main_t * vm, unformat_input_t * input)
406 {
407   mactime_main_t *mm = &mactime_main;
408
409   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
410     {
411       if (unformat (input, "lookup-table-buckets %u",
412                     &mm->lookup_table_num_buckets))
413         ;
414       else if (unformat (input, "lookup-table-memory %U",
415                          unformat_memory_size, &mm->lookup_table_memory_size))
416         ;
417       else if (unformat (input, "timezone_offset %d", &mm->timezone_offset))
418         ;
419       else
420         {
421           return clib_error_return (0, "unknown input '%U'",
422                                     format_unformat_error, input);
423         }
424     }
425   return 0;
426 }
427
428 VLIB_CONFIG_FUNCTION (mactime_config, "mactime");
429
430 /* *INDENT-OFF* */
431 VNET_FEATURE_INIT (mactime, static) =
432 {
433   .arc_name = "device-input",
434   .node_name = "mactime",
435   .runs_before = VNET_FEATURES ("ethernet-input"),
436 };
437 /* *INDENT-ON */
438
439 /* *INDENT-OFF* */
440 VNET_FEATURE_INIT (mactime_tx, static) =
441 {
442   .arc_name = "interface-output",
443   .node_name = "mactime-tx",
444   .runs_before = VNET_FEATURES ("interface-tx"),
445 };
446 /* *INDENT-ON */
447
448 /* *INDENT-OFF* */
449 VLIB_PLUGIN_REGISTER () =
450 {
451   .version = VPP_BUILD_VER,
452   .description = "Time-based MAC Source Address Filter",
453 };
454 /* *INDENT-ON* */
455
456 u8 *
457 format_bytes_with_width (u8 * s, va_list * va)
458 {
459   uword nbytes = va_arg (*va, u64);
460   int width = va_arg (*va, int);
461   f64 nbytes_f64;
462   u8 *fmt;
463   char *suffix = "";
464
465   fmt = format (0, "%%%d.3f%%s%c", width, 0);
466
467   if (nbytes > (1024ULL * 1024ULL * 1024ULL))
468     {
469       nbytes_f64 = ((f64) nbytes) / (1024.0 * 1024.0 * 1024.0);
470       suffix = "G";
471     }
472   else if (nbytes > (1024ULL * 1024ULL))
473     {
474       nbytes_f64 = ((f64) nbytes) / (1024.0 * 1024.0);
475       suffix = "M";
476     }
477   else if (nbytes > 1024ULL)
478     {
479       nbytes_f64 = ((f64) nbytes) / (1024.0);
480       suffix = "K";
481     }
482   else
483     nbytes_f64 = (f64) nbytes;
484
485   s = format (s, (char *) fmt, nbytes_f64, suffix);
486   vec_free (fmt);
487   return s;
488 }
489
490 static clib_error_t *
491 show_mactime_command_fn (vlib_main_t * vm,
492                          unformat_input_t * input, vlib_cli_command_t * cmd)
493 {
494   mactime_main_t *mm = &mactime_main;
495   mactime_device_t *dp;
496   u8 *macstring = 0;
497   char *status_string;
498   u32 *pool_indices = 0;
499   int verbose = 0;
500   int current_status = 99;
501   int i, j;
502   f64 now;
503   vlib_counter_t allow, drop;
504   ethernet_arp_ip4_entry_t *n, *pool;
505
506   vec_reset_length (mm->arp_cache_copy);
507   pool = ip4_neighbors_pool ();
508
509   /* *INDENT-OFF* */
510   pool_foreach (n, pool,
511   ({
512     vec_add1 (mm->arp_cache_copy, n[0]);
513   }));
514   /* *INDENT-ON* */
515
516   now = clib_timebase_now (&mm->timebase);
517
518   if (PREDICT_FALSE ((now - mm->sunday_midnight) > 86400.0 * 7.0))
519     mm->sunday_midnight = clib_timebase_find_sunday_midnight (now);
520
521   if (unformat (input, "verbose %d", &verbose))
522     ;
523
524   if (unformat (input, "verbose"))
525     verbose = 1;
526
527   if (verbose)
528     vlib_cli_output (vm, "Time now: %U", format_clib_timebase_time, now);
529
530   /* *INDENT-OFF* */
531   pool_foreach (dp, mm->devices,
532   ({
533     vec_add1 (pool_indices, dp - mm->devices);
534   }));
535   /* *INDENT-ON* */
536
537   vlib_cli_output (vm, "%-15s %18s %14s %10s %11s %10s",
538                    "Device Name", "Addresses", "Status",
539                    "AllowPkt", "AllowByte", "DropPkt");
540
541   for (i = 0; i < vec_len (pool_indices); i++)
542     {
543       dp = pool_elt_at_index (mm->devices, pool_indices[i]);
544
545       /* Check dynamic ranges */
546       for (j = 0; j < vec_len (dp->ranges); j++)
547         {
548           clib_timebase_range_t *r = dp->ranges + j;
549           f64 start0, end0;
550
551           start0 = r->start + mm->sunday_midnight;
552           end0 = r->end + mm->sunday_midnight;
553           if (verbose > 1)
554             vlib_cli_output (vm, "  Range %d: %U - %U", j,
555                              format_clib_timebase_time, start0,
556                              format_clib_timebase_time, end0);
557
558           if (now >= start0 && now <= end0)
559             {
560               if (dp->flags & MACTIME_DEVICE_FLAG_DYNAMIC_ALLOW)
561                 current_status = 3;
562               else
563                 current_status = 2;
564               if (verbose)
565                 {
566                   vlib_cli_output (vm, "  Time in range %d:", j);
567                   vlib_cli_output (vm, "     %U - %U",
568                                    format_clib_timebase_time, start0,
569                                    format_clib_timebase_time, end0);
570                 }
571               goto print;
572             }
573         }
574       if (verbose && j)
575         vlib_cli_output (vm, "  No range match.");
576       if (dp->flags & MACTIME_DEVICE_FLAG_STATIC_DROP)
577         current_status = 0;
578       if (dp->flags & MACTIME_DEVICE_FLAG_STATIC_ALLOW)
579         current_status = 1;
580       if (dp->flags & MACTIME_DEVICE_FLAG_DYNAMIC_ALLOW)
581         current_status = 2;
582       if (dp->flags & MACTIME_DEVICE_FLAG_DYNAMIC_DROP)
583         current_status = 3;
584
585     print:
586       vec_reset_length (macstring);
587       macstring = format (0, "%U", format_mac_address, dp->mac_address);
588       switch (current_status)
589         {
590         case 0:
591           status_string = "static drop";
592           break;
593         case 1:
594           status_string = "static allow";
595           break;
596         case 2:
597           status_string = "dynamic drop";
598           break;
599         case 3:
600           status_string = "dynamic allow";
601           break;
602         default:
603           status_string = "code bug!";
604           break;
605         }
606       vlib_get_combined_counter (&mm->allow_counters, dp - mm->devices,
607                                  &allow);
608       vlib_get_combined_counter (&mm->drop_counters, dp - mm->devices, &drop);
609       vlib_cli_output (vm, "%-15s %18s %14s %10lld %U %10lld",
610                        dp->device_name, macstring, status_string,
611                        allow.packets, format_bytes_with_width, allow.bytes,
612                        10, drop.packets);
613       if (dp->data_quota > 0)
614         vlib_cli_output (vm, "%-54s %s%U", " ", "Quota ",
615                          format_bytes_with_width, dp->data_quota, 10);
616       /* This is really only good for small N... */
617       for (j = 0; j < vec_len (mm->arp_cache_copy); j++)
618         {
619           n = mm->arp_cache_copy + j;
620           if (!memcmp (dp->mac_address, n->mac.bytes, sizeof (n->mac)))
621             {
622               vlib_cli_output (vm, "%17s%U", " ", format_ip4_address,
623                                &n->ip4_address);
624             }
625         }
626     }
627   vec_free (macstring);
628   vec_free (pool_indices);
629
630   return 0;
631 }
632
633 /* *INDENT-OFF* */
634 VLIB_CLI_COMMAND (show_mactime_command, static) =
635 {
636   .path = "show mactime",
637   .short_help = "show mactime [verbose]",
638   .function = show_mactime_command_fn,
639 };
640 /* *INDENT-ON* */
641
642 static clib_error_t *
643 clear_mactime_command_fn (vlib_main_t * vm,
644                           unformat_input_t * input, vlib_cli_command_t * cmd)
645 {
646   mactime_main_t *mm = &mactime_main;
647
648   if (mm->feature_initialized == 0)
649     return clib_error_return (0, "feature not enabled");
650
651   vlib_clear_combined_counters (&mm->allow_counters);
652   vlib_clear_combined_counters (&mm->drop_counters);
653   vlib_cli_output (vm, "Mactime counters cleared...");
654   return 0;
655 }
656
657 /* *INDENT-OFF* */
658 VLIB_CLI_COMMAND (clear_mactime_command, static) =
659 {
660   .path = "clear mactime",
661   .short_help = "clear mactime counters",
662   .function = clear_mactime_command_fn,
663 };
664 /* *INDENT-ON* */
665
666
667
668 /*
669  * fd.io coding-style-patch-verification: ON
670  *
671  * Local Variables:
672  * eval: (c-set-style "gnu")
673  * End:
674  */