ipv6 connection tracking plugin
[vpp.git] / src / plugins / ct6 / ct6.c
1 /*
2  * ct6.c - skeleton vpp engine plug-in
3  *
4  * Copyright (c) <current-year> <your-organization>
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 <ct6/ct6.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 <ct6/ct6_msg_enum.h>
28
29 /* define message structures */
30 #define vl_typedefs
31 #include <ct6/ct6_all_api_h.h>
32 #undef vl_typedefs
33
34 /* define generated endian-swappers */
35 #define vl_endianfun
36 #include <ct6/ct6_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 <ct6/ct6_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 <ct6/ct6_all_api_h.h>
48 #undef vl_api_version
49
50 #define REPLY_MSG_ID_BASE cmp->msg_id_base
51 #include <vlibapi/api_helper_macros.h>
52
53 ct6_main_t ct6_main;
54
55 /* List of message types that this plugin understands */
56
57 #define foreach_ct6_plugin_api_msg                           \
58 _(CT6_ENABLE_DISABLE, ct6_enable_disable)
59
60 /* Action function shared between message handler and debug CLI */
61
62 static void
63 ct6_feature_init (ct6_main_t * cmp)
64 {
65   u32 nworkers = vlib_num_workers ();
66
67   if (cmp->feature_initialized)
68     return;
69
70   clib_bihash_init_48_8 (&cmp->session_hash, "ct6 session table",
71                          cmp->session_hash_buckets, cmp->session_hash_memory);
72   cmp->feature_initialized = 1;
73   vec_validate (cmp->sessions, nworkers);
74   vec_validate_init_empty (cmp->first_index, nworkers, ~0);
75   vec_validate_init_empty (cmp->last_index, nworkers, ~0);
76 }
77
78 int
79 ct6_in2out_enable_disable (ct6_main_t * cmp, u32 sw_if_index,
80                            int enable_disable)
81 {
82   vnet_sw_interface_t *sw;
83   int rv = 0;
84
85   ct6_feature_init (cmp);
86
87   /* Utterly wrong? */
88   if (pool_is_free_index (cmp->vnet_main->interface_main.sw_interfaces,
89                           sw_if_index))
90     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
91
92   /* Not a physical port? */
93   sw = vnet_get_sw_interface (cmp->vnet_main, sw_if_index);
94   if (sw->type != VNET_SW_INTERFACE_TYPE_HARDWARE)
95     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
96
97   vnet_feature_enable_disable ("interface-output", "ct6-in2out",
98                                sw_if_index, enable_disable, 0, 0);
99
100   return rv;
101 }
102
103 int
104 ct6_out2in_enable_disable (ct6_main_t * cmp, u32 sw_if_index,
105                            int enable_disable)
106 {
107   vnet_sw_interface_t *sw;
108   int rv = 0;
109
110   ct6_feature_init (cmp);
111
112   /* Utterly wrong? */
113   if (pool_is_free_index (cmp->vnet_main->interface_main.sw_interfaces,
114                           sw_if_index))
115     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
116
117   /* Not a physical port? */
118   sw = vnet_get_sw_interface (cmp->vnet_main, sw_if_index);
119   if (sw->type != VNET_SW_INTERFACE_TYPE_HARDWARE)
120     return VNET_API_ERROR_INVALID_SW_IF_INDEX;
121
122   vnet_feature_enable_disable ("ip6-unicast", "ct6-out2in",
123                                sw_if_index, enable_disable, 0, 0);
124
125   return rv;
126 }
127
128 static clib_error_t *
129 set_ct6_enable_disable_command_fn (vlib_main_t * vm,
130                                    unformat_input_t * input,
131                                    vlib_cli_command_t * cmd)
132 {
133   ct6_main_t *cmp = &ct6_main;
134   u32 sw_if_index = ~0;
135   int enable_disable = 1;
136   u32 inside = ~0;
137   int rv;
138
139   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
140     {
141       if (unformat (input, "disable"))
142         enable_disable = 0;
143       else if (unformat (input, "%U", unformat_vnet_sw_interface,
144                          cmp->vnet_main, &sw_if_index))
145         ;
146       else if (unformat (input, "inside") || unformat (input, "in"))
147         inside = 1;
148       else if (unformat (input, "outside") || unformat (input, "out"))
149         inside = 0;
150       else
151         break;
152     }
153
154   if (inside == ~0)
155     return clib_error_return (0, "Please specify inside or outside");
156
157   if (sw_if_index == ~0)
158     return clib_error_return (0, "Please specify an interface...");
159
160   if (inside == 1)
161     rv = ct6_in2out_enable_disable (cmp, sw_if_index, enable_disable);
162   else
163     rv = ct6_out2in_enable_disable (cmp, sw_if_index, enable_disable);
164
165   switch (rv)
166     {
167     case 0:
168       break;
169
170     case VNET_API_ERROR_INVALID_SW_IF_INDEX:
171       return clib_error_return
172         (0, "Invalid interface, only works on physical ports");
173       break;
174
175     default:
176       return clib_error_return (0, "ct6_enable_disable returned %d", rv);
177     }
178   return 0;
179 }
180
181 /* *INDENT-OFF* */
182 VLIB_CLI_COMMAND (set_ct6_command, static) =
183 {
184   .path = "set ct6",
185   .short_help =
186   "set ct6 [inside|outside] <interface-name> [disable]",
187   .function = set_ct6_enable_disable_command_fn,
188 };
189 /* *INDENT-ON* */
190
191 /* API message handler */
192 static void vl_api_ct6_enable_disable_t_handler
193   (vl_api_ct6_enable_disable_t * mp)
194 {
195   vl_api_ct6_enable_disable_reply_t *rmp;
196   ct6_main_t *cmp = &ct6_main;
197   int rv;
198
199   if (mp->is_inside)
200     rv = ct6_in2out_enable_disable (cmp, ntohl (mp->sw_if_index),
201                                     (int) (mp->enable_disable));
202   else
203     rv = ct6_out2in_enable_disable (cmp, ntohl (mp->sw_if_index),
204                                     (int) (mp->enable_disable));
205
206   REPLY_MACRO (VL_API_CT6_ENABLE_DISABLE_REPLY);
207 }
208
209 /* Set up the API message handling tables */
210 static clib_error_t *
211 ct6_plugin_api_hookup (vlib_main_t * vm)
212 {
213   ct6_main_t *cmp = &ct6_main;
214 #define _(N,n)                                                  \
215     vl_msg_api_set_handlers((VL_API_##N + cmp->msg_id_base),     \
216                            #n,                                  \
217                            vl_api_##n##_t_handler,              \
218                            vl_noop_handler,                     \
219                            vl_api_##n##_t_endian,               \
220                            vl_api_##n##_t_print,                \
221                            sizeof(vl_api_##n##_t), 1);
222   foreach_ct6_plugin_api_msg;
223 #undef _
224
225   return 0;
226 }
227
228 #define vl_msg_name_crc_list
229 #include <ct6/ct6_all_api_h.h>
230 #undef vl_msg_name_crc_list
231
232 static void
233 setup_message_id_table (ct6_main_t * cmp, api_main_t * am)
234 {
235 #define _(id,n,crc)   vl_msg_api_add_msg_name_crc (am, #n  #crc, id + cmp->msg_id_base);
236   foreach_vl_msg_name_crc_ct6;
237 #undef _
238 }
239
240 static clib_error_t *
241 ct6_init (vlib_main_t * vm)
242 {
243   ct6_main_t *cmp = &ct6_main;
244   clib_error_t *error = 0;
245   u8 *name;
246
247   cmp->vlib_main = vm;
248   cmp->vnet_main = vnet_get_main ();
249
250   name = format (0, "ct6_%08x%c", api_version, 0);
251
252   /* Ask for a correctly-sized block of API message decode slots */
253   cmp->msg_id_base = vl_msg_api_get_msg_ids
254     ((char *) name, VL_MSG_FIRST_AVAILABLE);
255
256   error = ct6_plugin_api_hookup (vm);
257
258   /* Add our API messages to the global name_crc hash table */
259   setup_message_id_table (cmp, &api_main);
260
261   vec_free (name);
262
263   /*
264    * Set default parameters...
265    * 256K sessions
266    * 64K buckets
267    * 2 minute inactivity timer
268    * 10000 concurrent sessions
269    */
270   cmp->session_hash_memory = 16ULL << 20;
271   cmp->session_hash_buckets = 64 << 10;
272   cmp->session_timeout_interval = 120.0;
273   cmp->max_sessions_per_worker = 10000;
274
275   /* ... so the packet generator can feed the in2out node ... */
276   ethernet_setup_node (vm, ct6_in2out_node.index);
277   return error;
278 }
279
280 VLIB_INIT_FUNCTION (ct6_init);
281
282 /* *INDENT-OFF* */
283 VNET_FEATURE_INIT (ct6out2in, static) =
284 {
285   .arc_name = "ip6-unicast",
286   .node_name = "ct6-out2in",
287   .runs_before = VNET_FEATURES ("ip6-lookup"),
288 };
289 /* *INDENT-ON */
290
291 /* *INDENT-OFF* */
292 VNET_FEATURE_INIT (ct6in2out, static) =
293 {
294   .arc_name = "interface-output",
295   .node_name = "ct6-in2out",
296   .runs_before = VNET_FEATURES ("interface-output"),
297 };
298 /* *INDENT-ON */
299
300 /* *INDENT-OFF* */
301 VLIB_PLUGIN_REGISTER () =
302 {
303   .version = VPP_BUILD_VER,
304   .description = "ipv6 connection tracker",
305 };
306 /* *INDENT-ON* */
307
308 u8 *
309 format_ct6_session (u8 * s, va_list * args)
310 {
311   ct6_main_t *cmp = va_arg (*args, ct6_main_t *);
312   int i = va_arg (*args, int);
313   ct6_session_t *s0 = va_arg (*args, ct6_session_t *);
314   int verbose = va_arg (*args, int);
315   clib_bihash_kv_48_8_t kvp0;
316
317   if (s0 == 0)
318     {
319       s = format (s, "\n%6s%6s%20s%6s%20s%6s",
320                   "Sess", "Prot", "Src", "Sport", "Dst", "Dport");
321       return s;
322     }
323
324   s = format (s, "\n%6d%6d%20U%6u%20U%6u",
325               s0 - cmp->sessions[i], s0->key.proto,
326               format_ip6_address, &s0->key.src,
327               clib_net_to_host_u16 (s0->key.sport),
328               format_ip6_address, &s0->key.dst,
329               clib_net_to_host_u16 (s0->key.dport));
330
331   clib_memcpy_fast (&kvp0, s0, sizeof (ct6_session_key_t));
332
333   if (clib_bihash_search_48_8 (&cmp->session_hash, &kvp0, &kvp0) < 0)
334     {
335       s = format (s, " LOOKUP FAIL!");
336     }
337   else
338     {
339       if (kvp0.value == s0 - cmp->sessions[s0->thread_index])
340         {
341           s = format (s, " OK");
342           if (verbose > 1)
343             {
344               s = format (s, " next %d prev %d", s0->next_index,
345                           s0->prev_index);
346               s = format (s, " hits %d expires %.2f", s0->hits, s0->expires);
347             }
348         }
349       else
350         s = format (s, " BOGUS LOOKUP RESULT!");
351     }
352
353   return s;
354 }
355
356 static clib_error_t *
357 show_ct6_command_fn_command_fn (vlib_main_t * vm,
358                                 unformat_input_t * input,
359                                 vlib_cli_command_t * cmd)
360 {
361   ct6_main_t *cmp = &ct6_main;
362   ct6_session_t *s0;
363   int verbose = 0;
364   u8 *s = 0;
365   int i;
366
367   if (!cmp->feature_initialized)
368     return clib_error_return (0, "ip6 connection tracking not enabled...");
369
370   if (unformat (input, "verbose %d", &verbose))
371     ;
372   else if (unformat (input, "verbose"))
373     verbose = 1;
374
375   for (i = 0; i < vec_len (cmp->sessions); i++)
376     {
377       s = format (s, "Thread %d: %d sessions\n", i,
378                   pool_elts (cmp->sessions[i]));
379
380       if (verbose == 0)
381         continue;
382
383       s =
384         format (s, "%U", format_ct6_session, cmp,
385                 0 /* pool */ , 0 /* header */ , verbose);
386
387       /* *INDENT-OFF* */
388       pool_foreach (s0, cmp->sessions[i],
389       ({
390         s = format (s, "%U", format_ct6_session, cmp, i, s0, verbose);
391       }));
392       /* *INDENT-ON* */
393     }
394   vlib_cli_output (cmp->vlib_main, "%v", s);
395   vec_free (s);
396   return 0;
397 }
398
399 /* *INDENT-OFF* */
400 VLIB_CLI_COMMAND (show_ct6_command_fn_command, static) =
401 {
402   .path = "show ip6 connection-tracker",
403   .short_help = "show ip6 connection-tracker",
404   .function = show_ct6_command_fn_command_fn,
405 };
406 /* *INDENT-ON* */
407
408 static void
409 increment_v6_address (ip6_address_t * a)
410 {
411   u64 v0, v1;
412
413   v0 = clib_net_to_host_u64 (a->as_u64[0]);
414   v1 = clib_net_to_host_u64 (a->as_u64[1]);
415
416   v1 += 1;
417   if (v1 == 0)
418     v0 += 1;
419   a->as_u64[0] = clib_net_to_host_u64 (v0);
420   a->as_u64[1] = clib_net_to_host_u64 (v1);
421 }
422
423
424 static clib_error_t *
425 test_ct6_command_fn_command_fn (vlib_main_t * vm,
426                                 unformat_input_t * input,
427                                 vlib_cli_command_t * cmd)
428 {
429   ct6_main_t *cmp = &ct6_main;
430   clib_bihash_kv_48_8_t kvp0;
431   ct6_session_key_t *key0;
432   ct6_session_t *s0;
433   u8 src[16], dst[16];
434   u32 recycled = 0, created = 0;
435   int i, num_sessions = 5;
436   u32 midpt_index;
437   u8 *s = 0;
438
439   cmp->max_sessions_per_worker = 4;
440
441   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
442     {
443       if (unformat (input, "num-sessions %d", &num_sessions))
444         ;
445       else
446         if (unformat
447             (input, "max-sessions %d", &cmp->max_sessions_per_worker))
448         ;
449       else
450         break;
451     }
452
453   ct6_feature_init (cmp);
454
455   /* Set up starting src/dst addresses */
456   memset (src, 0, sizeof (src));
457   memset (dst, 0, sizeof (dst));
458
459   src[0] = 0xdb;
460   dst[0] = 0xbe;
461
462   src[15] = 1;
463   dst[15] = 1;
464
465   /*
466    * See if we know about this flow.
467    * Key set up for the out2in path, the performant case
468    */
469   key0 = (ct6_session_key_t *) & kvp0;
470   memset (&kvp0, 0, sizeof (kvp0));
471
472   for (i = 0; i < num_sessions; i++)
473     {
474       clib_memcpy_fast (&key0->src, src, sizeof (src));
475       clib_memcpy_fast (&key0->dst, dst, sizeof (dst));
476       key0->as_u64[4] = 0;
477       key0->as_u64[5] = 0;
478       key0->sport = clib_host_to_net_u16 (1234);
479       key0->dport = clib_host_to_net_u16 (4321);
480       key0->proto = 17;         /* udp, fwiw */
481
482       s0 = ct6_create_or_recycle_session
483         (cmp, &kvp0, 3.0 /* now */ , 0 /* thread index */ ,
484          &recycled, &created);
485
486       s = format (s, "%U (%d, %d)", format_ct6_session, cmp,
487                   0 /* thread index */ , s0, 1 /* verbose */ ,
488                   recycled, created);
489       vlib_cli_output (vm, "%v", s);
490       vec_free (s);
491       increment_v6_address ((ip6_address_t *) src);
492       recycled = 0;
493       created = 0;
494     }
495
496   /* *INDENT-OFF* */
497   pool_foreach (s0, cmp->sessions[0],
498   ({
499     s = format (s, "%U", format_ct6_session, cmp, 0, s0, 1 /* verbose */);
500   }));
501   /* *INDENT-ON* */
502
503   vlib_cli_output (vm, "\nEnd state: first index %d last index %d\n%v",
504                    cmp->first_index[0], cmp->last_index[0], s);
505
506   vec_free (s);
507
508   midpt_index = cmp->max_sessions_per_worker / 3;
509
510   s0 = pool_elt_at_index (cmp->sessions[0], midpt_index);
511   vlib_cli_output (vm, "\nSimulate LRU hit on session %d",
512                    s0 - cmp->sessions[0]);
513
514   ct6_update_session_hit (cmp, s0, 234.0);
515
516   /* *INDENT-OFF* */
517   pool_foreach (s0, cmp->sessions[0],
518   ({
519     s = format (s, "%U", format_ct6_session, cmp, 0, s0, 1 /* verbose */);
520   }));
521   /* *INDENT-ON* */
522
523   vlib_cli_output (vm, "\nEnd state: first index %d last index %d\n%v",
524                    cmp->first_index[0], cmp->last_index[0], s);
525
526   vec_free (s);
527
528   return 0;
529 }
530
531 /* *INDENT-OFF* */
532 VLIB_CLI_COMMAND (test_ct6_command_fn_command, static) =
533 {
534   .path = "test ip6 connection-tracker",
535   .short_help = "test ip6 connection-tracker",
536   .function = test_ct6_command_fn_command_fn,
537 };
538 /* *INDENT-ON* */
539
540 static clib_error_t *
541 ct6_config (vlib_main_t * vm, unformat_input_t * input)
542 {
543   ct6_main_t *cmp = &ct6_main;
544
545   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
546     {
547       if (unformat (input, "session-hash-buckets %u",
548                     &cmp->session_hash_buckets))
549         ;
550       else if (unformat (input, "session-hash-memory %U",
551                          unformat_memory_size, &cmp->session_hash_memory))
552         ;
553       else if (unformat (input, "session-timeout %f",
554                          &cmp->session_timeout_interval))
555         ;
556       else
557         {
558           return clib_error_return (0, "unknown input '%U'",
559                                     format_unformat_error, input);
560         }
561     }
562   return 0;
563 }
564
565 VLIB_CONFIG_FUNCTION (ct6_config, "ct6");
566
567 /*
568  * fd.io coding-style-patch-verification: ON
569  *
570  * Local Variables:
571  * eval: (c-set-style "gnu")
572  * End:
573  */