cnat: Prepare extended snat policies
[vpp.git] / src / plugins / cnat / cnat_translation.c
1 /*
2  * Copyright (c) 2020 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 #include <vnet/fib/fib_source.h>
17 #include <vnet/fib/fib_table.h>
18 #include <vnet/fib/fib_entry_track.h>
19 #include <vnet/dpo/load_balance.h>
20 #include <vnet/dpo/drop_dpo.h>
21
22 #include <cnat/cnat_translation.h>
23 #include <cnat/cnat_session.h>
24 #include <cnat/cnat_client.h>
25
26 cnat_translation_t *cnat_translation_pool;
27 clib_bihash_8_8_t cnat_translation_db;
28 addr_resolution_t *tr_resolutions;
29 cnat_if_addr_add_cb_t *cnat_if_addr_add_cbs;
30
31 static fib_node_type_t cnat_translation_fib_node_type;
32
33 vlib_combined_counter_main_t cnat_translation_counters = {
34   .name = "cnat-translation",
35   .stat_segment_name = "/net/cnat-translation",
36 };
37
38 void
39 cnat_translation_watch_addr (index_t cti, u64 opaque, cnat_endpoint_t * ep,
40                              cnat_addr_resol_type_t type)
41 {
42   addr_resolution_t *ar;
43
44   if (INDEX_INVALID == ep->ce_sw_if_index)
45     return;
46
47   pool_get (tr_resolutions, ar);
48   ar->af = ep->ce_ip.version;
49   ar->sw_if_index = ep->ce_sw_if_index;
50   ar->type = type;
51   ar->opaque = opaque;
52   ar->cti = cti;
53 }
54
55 static void
56 cnat_resolve_ep_tuple (cnat_endpoint_tuple_t * path)
57 {
58   cnat_resolve_ep (&path->src_ep);
59   cnat_resolve_ep (&path->dst_ep);
60 }
61
62 void
63 cnat_translation_unwatch_addr (u32 cti, cnat_addr_resol_type_t type)
64 {
65   /* Delete tr resolution entries matching translation index */
66   addr_resolution_t *ar;
67   index_t *indexes = 0, *ari;
68   pool_foreach (ar, tr_resolutions)
69     {
70       if ((cti == INDEX_INVALID || ar->cti == cti) &&
71           (ar->type == type || CNAT_RESOLV_ADDR_ANY == type))
72         vec_add1 (indexes, ar - tr_resolutions);
73     }
74   vec_foreach (ari, indexes) pool_put_index (tr_resolutions, *ari);
75
76   vec_free (indexes);
77 }
78
79 static void
80 cnat_tracker_release (cnat_ep_trk_t * trk)
81 {
82   /* We only track fully resolved endpoints */
83   if (!(trk->ct_flags & CNAT_TRK_ACTIVE))
84     return;
85   fib_entry_untrack (trk->ct_fei, trk->ct_sibling);
86 }
87
88 static void
89 cnat_tracker_track (index_t cti, cnat_ep_trk_t * trk)
90 {
91   fib_prefix_t pfx;
92   /* We only track fully resolved endpoints */
93   if (trk->ct_ep[VLIB_TX].ce_flags & CNAT_EP_FLAG_RESOLVED &&
94       trk->ct_ep[VLIB_RX].ce_flags & CNAT_EP_FLAG_RESOLVED)
95     trk->ct_flags |= CNAT_TRK_ACTIVE;
96   else
97     {
98       trk->ct_flags &= ~CNAT_TRK_ACTIVE;
99       return;
100     }
101
102   ip_address_to_fib_prefix (&trk->ct_ep[VLIB_TX].ce_ip, &pfx);
103   trk->ct_fei = fib_entry_track (CNAT_FIB_TABLE,
104                                  &pfx,
105                                  cnat_translation_fib_node_type,
106                                  cti, &trk->ct_sibling);
107
108   fib_entry_contribute_forwarding (trk->ct_fei,
109                                    fib_forw_chain_type_from_fib_proto
110                                    (pfx.fp_proto), &trk->ct_dpo);
111 }
112
113 u8 *
114 format_cnat_lb_type (u8 *s, va_list *args)
115 {
116   cnat_lb_type_t lb_type = va_arg (*args, int);
117   if (CNAT_LB_DEFAULT == lb_type)
118     s = format (s, "default");
119   else if (CNAT_LB_MAGLEV == lb_type)
120     s = format (s, "maglev");
121   else
122     s = format (s, "unknown");
123   return (s);
124 }
125
126 uword
127 unformat_cnat_lb_type (unformat_input_t *input, va_list *args)
128 {
129   cnat_lb_type_t *a = va_arg (*args, cnat_lb_type_t *);
130   if (unformat (input, "default"))
131     *a = CNAT_LB_DEFAULT;
132   else if (unformat (input, "maglev"))
133     *a = CNAT_LB_MAGLEV;
134   else
135     return 0;
136   return 1;
137 }
138
139 /**
140  * Add a translation to the bihash
141  *
142  * @param cci the ID of the parent client (invalid if vip not resolved)
143  * @param vip the translation endpoint
144  * @param proto the translation proto
145  * @param cti the translation index to be used as value
146  */
147 static void
148 cnat_add_translation_to_db (index_t cci, cnat_endpoint_t * vip,
149                             ip_protocol_t proto, index_t cti)
150 {
151   clib_bihash_kv_8_8_t bkey;
152   u64 key;
153   if (INDEX_INVALID == cci)
154     {
155       key = proto << 8 | 0x80 | vip->ce_ip.version;
156       key = key << 16 | vip->ce_port;
157       key = key << 32 | (u32) vip->ce_sw_if_index;
158     }
159   else
160     {
161       key = proto << 8;
162       key = key << 16 | vip->ce_port;
163       key = key << 32 | (u32) cci;
164     }
165
166   bkey.key = key;
167   bkey.value = cti;
168
169   clib_bihash_add_del_8_8 (&cnat_translation_db, &bkey, 1);
170 }
171
172 /**
173  * Remove a translation from the bihash
174  *
175  * @param cci the ID of the parent client
176  * @param vip the translation endpoint
177  * @param proto the translation proto
178  */
179 static void
180 cnat_remove_translation_from_db (index_t cci, cnat_endpoint_t * vip,
181                                  ip_protocol_t proto)
182 {
183   clib_bihash_kv_8_8_t bkey;
184   u64 key;
185   if (INDEX_INVALID == cci)
186     {
187       key = proto << 8 | 0x80 | vip->ce_ip.version;
188       key = key << 16 | vip->ce_port;
189       key = key << 32 | (u32) vip->ce_sw_if_index;
190     }
191   else
192     {
193       key = proto << 8;
194       key = key << 16 | vip->ce_port;
195       key = key << 32 | (u32) cci;
196     }
197
198   bkey.key = key;
199
200   clib_bihash_add_del_8_8 (&cnat_translation_db, &bkey, 0);
201 }
202
203 typedef struct
204 {
205   cnat_ep_trk_t *trk;
206   u32 index;
207   u32 offset;
208   u32 skip;
209 } cnat_maglev_entry_t;
210
211 static int
212 cnat_maglev_entry_compare (void *_a, void *_b)
213 {
214   cnat_ep_trk_t *a = ((cnat_maglev_entry_t *) _a)->trk;
215   cnat_ep_trk_t *b = ((cnat_maglev_entry_t *) _b)->trk;
216   int rv = 0;
217   if ((rv =
218          ip_address_cmp (&a->ct_ep[VLIB_TX].ce_ip, &b->ct_ep[VLIB_TX].ce_ip)))
219     return rv;
220   if ((rv = a->ct_ep[VLIB_TX].ce_port - a->ct_ep[VLIB_TX].ce_port))
221     return rv;
222   if ((rv =
223          ip_address_cmp (&a->ct_ep[VLIB_RX].ce_ip, &b->ct_ep[VLIB_RX].ce_ip)))
224     return rv;
225   if ((rv = a->ct_ep[VLIB_RX].ce_port - a->ct_ep[VLIB_RX].ce_port))
226     return rv;
227   return 0;
228 }
229
230 static void
231 cnat_translation_init_maglev (cnat_translation_t *ct)
232 {
233   cnat_maglev_entry_t *backends = NULL, *bk;
234   cnat_main_t *cm = &cnat_main;
235   u32 done = 0;
236   cnat_ep_trk_t *trk;
237   int ep_idx = 0;
238
239   vec_foreach (trk, ct->ct_active_paths)
240     {
241       cnat_maglev_entry_t bk;
242       u32 h1, h2;
243
244       if (AF_IP4 == ip_addr_version (&trk->ct_ep[VLIB_TX].ce_ip))
245         {
246           u32 a, b, c;
247           a = ip_addr_v4 (&trk->ct_ep[VLIB_TX].ce_ip).data_u32;
248           b = (u64) trk->ct_ep[VLIB_TX].ce_port << 16 |
249               (u64) trk->ct_ep[VLIB_RX].ce_port;
250           c = ip_addr_v4 (&trk->ct_ep[VLIB_RX].ce_ip).data_u32;
251           hash_v3_mix32 (a, b, c);
252           hash_v3_finalize32 (a, b, c);
253           h1 = c;
254           h2 = b;
255         }
256       else
257         {
258           u64 a, b, c;
259           a = ip_addr_v6 (&trk->ct_ep[VLIB_TX].ce_ip).as_u64[0] ^
260               ip_addr_v6 (&trk->ct_ep[VLIB_TX].ce_ip).as_u64[1];
261           b = (u64) trk->ct_ep[VLIB_TX].ce_port << 16 |
262               (u64) trk->ct_ep[VLIB_RX].ce_port;
263           c = ip_addr_v6 (&trk->ct_ep[VLIB_RX].ce_ip).as_u64[0] ^
264               ip_addr_v6 (&trk->ct_ep[VLIB_RX].ce_ip).as_u64[1];
265           hash_mix64 (a, b, c);
266           h1 = c;
267           h2 = b;
268         }
269
270       bk.offset = h1 % cm->maglev_len;
271       bk.skip = h2 % (cm->maglev_len - 1) + 1;
272       bk.index = ep_idx++;
273       bk.trk = trk;
274       vec_add1 (backends, bk);
275     }
276
277   if (0 == ep_idx)
278     return;
279
280   vec_sort_with_function (backends, cnat_maglev_entry_compare);
281
282   /* Don't free if previous vector exists, just zero */
283   vec_validate (ct->lb_maglev, cm->maglev_len);
284   vec_set (ct->lb_maglev, -1);
285
286   while (1)
287     {
288       vec_foreach (bk, backends)
289         {
290           u32 next = 0;
291           u32 c = (bk->offset + next * bk->skip) % cm->maglev_len;
292           while (ct->lb_maglev[c] != (u32) -1)
293             {
294               next++;
295               c = (bk->offset + next * bk->skip) % cm->maglev_len;
296             }
297           ct->lb_maglev[c] = bk->index;
298           done++;
299           if (done == cm->maglev_len)
300             goto finished;
301         }
302     }
303
304 finished:
305   vec_free (backends);
306 }
307
308 static void
309 cnat_translation_stack (cnat_translation_t * ct)
310 {
311   fib_protocol_t fproto;
312   cnat_ep_trk_t *trk;
313   dpo_proto_t dproto;
314   u32 ep_idx = 0;
315   index_t lbi;
316
317   fproto = ip_address_family_to_fib_proto (ct->ct_vip.ce_ip.version);
318   dproto = fib_proto_to_dpo (fproto);
319
320   vec_reset_length (ct->ct_active_paths);
321
322   vec_foreach (trk, ct->ct_paths)
323     if (trk->ct_flags & CNAT_TRK_ACTIVE)
324       vec_add1 (ct->ct_active_paths, *trk);
325
326   lbi = load_balance_create (vec_len (ct->ct_active_paths),
327                              fib_proto_to_dpo (fproto), IP_FLOW_HASH_DEFAULT);
328
329   ep_idx = 0;
330   vec_foreach (trk, ct->ct_active_paths)
331     load_balance_set_bucket (lbi, ep_idx++, &trk->ct_dpo);
332
333   if (ep_idx > 0 && CNAT_LB_MAGLEV == ct->lb_type)
334     cnat_translation_init_maglev (ct);
335
336   dpo_set (&ct->ct_lb, DPO_LOAD_BALANCE, dproto, lbi);
337   dpo_stack (cnat_client_dpo, dproto, &ct->ct_lb, &ct->ct_lb);
338   ct->flags |= CNAT_TRANSLATION_STACKED;
339 }
340
341 int
342 cnat_translation_delete (u32 id)
343 {
344   cnat_translation_t *ct;
345   cnat_ep_trk_t *trk;
346
347   if (pool_is_free_index (cnat_translation_pool, id))
348     return (VNET_API_ERROR_NO_SUCH_ENTRY);
349
350   ct = pool_elt_at_index (cnat_translation_pool, id);
351
352   dpo_reset (&ct->ct_lb);
353
354   vec_foreach (trk, ct->ct_active_paths)
355     cnat_tracker_release (trk);
356
357   cnat_remove_translation_from_db (ct->ct_cci, &ct->ct_vip, ct->ct_proto);
358   cnat_client_translation_deleted (ct->ct_cci);
359   cnat_translation_unwatch_addr (id, CNAT_RESOLV_ADDR_ANY);
360   pool_put (cnat_translation_pool, ct);
361
362   return (0);
363 }
364
365 u32
366 cnat_translation_update (cnat_endpoint_t *vip, ip_protocol_t proto,
367                          cnat_endpoint_tuple_t *paths, u8 flags,
368                          cnat_lb_type_t lb_type)
369 {
370   cnat_endpoint_tuple_t *path;
371   const cnat_client_t *cc;
372   cnat_translation_t *ct;
373   cnat_ep_trk_t *trk;
374   index_t cci;
375
376   cnat_lazy_init ();
377   if (cnat_resolve_ep (vip))
378     {
379       /* vip only contains a sw_if_index for now */
380       ct = cnat_find_translation (vip->ce_sw_if_index, vip->ce_port, proto);
381       cci = INDEX_INVALID;
382     }
383   else
384     {
385       /* do we know of this ep's vip */
386       cci = cnat_client_add (&vip->ce_ip, flags);
387       cc = cnat_client_get (cci);
388
389       ct = cnat_find_translation (cc->parent_cci, vip->ce_port, proto);
390     }
391
392   if (NULL == ct)
393     {
394       pool_get_zero (cnat_translation_pool, ct);
395
396       clib_memcpy (&ct->ct_vip, vip, sizeof (*vip));
397       ct->ct_proto = proto;
398       ct->ct_cci = cci;
399       ct->index = ct - cnat_translation_pool;
400       ct->lb_type = lb_type;
401
402       cnat_add_translation_to_db (cci, vip, proto, ct->index);
403       cnat_client_translation_added (cci);
404
405       vlib_validate_combined_counter (&cnat_translation_counters, ct->index);
406       vlib_zero_combined_counter (&cnat_translation_counters, ct->index);
407     }
408   ct->flags = flags;
409
410   cnat_translation_unwatch_addr (ct->index, CNAT_RESOLV_ADDR_ANY);
411   cnat_translation_watch_addr (ct->index, 0, vip,
412                                CNAT_RESOLV_ADDR_TRANSLATION);
413
414   vec_foreach (trk, ct->ct_paths)
415   {
416     cnat_tracker_release (trk);
417   }
418
419   vec_reset_length (ct->ct_paths);
420   ct->flags &= ~CNAT_TRANSLATION_STACKED;
421
422   u64 path_idx = 0;
423   vec_foreach (path, paths)
424   {
425     cnat_resolve_ep_tuple (path);
426     cnat_translation_watch_addr (ct->index,
427                                  path_idx << 32 | VLIB_RX, &path->src_ep,
428                                  CNAT_RESOLV_ADDR_BACKEND);
429     cnat_translation_watch_addr (ct->index,
430                                  path_idx << 32 | VLIB_TX, &path->dst_ep,
431                                  CNAT_RESOLV_ADDR_BACKEND);
432     path_idx++;
433
434     vec_add2 (ct->ct_paths, trk, 1);
435
436     clib_memcpy (&trk->ct_ep[VLIB_TX], &path->dst_ep,
437                  sizeof (trk->ct_ep[VLIB_TX]));
438     clib_memcpy (&trk->ct_ep[VLIB_RX], &path->src_ep,
439                  sizeof (trk->ct_ep[VLIB_RX]));
440     trk->ct_flags = path->ep_flags;
441
442     cnat_tracker_track (ct->index, trk);
443   }
444
445   cnat_translation_stack (ct);
446
447   return (ct->index);
448 }
449
450 void
451 cnat_translation_walk (cnat_translation_walk_cb_t cb, void *ctx)
452 {
453   u32 api;
454
455   pool_foreach_index (api, cnat_translation_pool)
456    {
457     if (!cb(api, ctx))
458       break;
459   }
460 }
461
462 static u8 *
463 format_cnat_ep_trk (u8 * s, va_list * args)
464 {
465   cnat_ep_trk_t *ck = va_arg (*args, cnat_ep_trk_t *);
466   u32 indent = va_arg (*args, u32);
467
468   s = format (s, "%U->%U", format_cnat_endpoint, &ck->ct_ep[VLIB_RX],
469               format_cnat_endpoint, &ck->ct_ep[VLIB_TX]);
470   s = format (s, "\n%Ufib-entry:%d", format_white_space, indent, ck->ct_fei);
471   s = format (s, "\n%U%U",
472               format_white_space, indent, format_dpo_id, &ck->ct_dpo, 6);
473
474   return (s);
475 }
476
477 u8 *
478 format_cnat_translation (u8 * s, va_list * args)
479 {
480   cnat_translation_t *ct = va_arg (*args, cnat_translation_t *);
481   cnat_main_t *cm = &cnat_main;
482   cnat_ep_trk_t *ck;
483
484   s = format (s, "[%d] ", ct->index);
485   s = format (s, "%U %U ", format_cnat_endpoint, &ct->ct_vip,
486               format_ip_protocol, ct->ct_proto);
487   s = format (s, "lb:%U ", format_cnat_lb_type, ct->lb_type);
488
489   vec_foreach (ck, ct->ct_paths)
490     s = format (s, "\n%U", format_cnat_ep_trk, ck, 2);
491
492   /* If printing a trace, the LB object might be deleted */
493   if (!pool_is_free_index (load_balance_pool, ct->ct_lb.dpoi_index))
494     {
495       s = format (s, "\n via:");
496       s = format (s, "\n%U%U",
497                   format_white_space, 2, format_dpo_id, &ct->ct_lb, 2);
498     }
499
500   u32 bid = 0;
501   if (CNAT_LB_MAGLEV == ct->lb_type)
502     {
503       s = format (s, "\nmaglev backends map");
504       uword *bitmap = NULL;
505       clib_bitmap_alloc (bitmap, cm->maglev_len);
506       vec_foreach (ck, ct->ct_paths)
507         {
508           clib_bitmap_zero (bitmap);
509           for (u32 i = 0; i < vec_len (ct->lb_maglev); i++)
510             if (ct->lb_maglev[i] == bid)
511               clib_bitmap_set (bitmap, i, 1);
512           s = format (s, "\n  backend#%d: %U", bid, format_bitmap_hex, bitmap);
513
514           bid++;
515         }
516       clib_bitmap_free (bitmap);
517     }
518
519   return (s);
520 }
521
522 static clib_error_t *
523 cnat_translation_show (vlib_main_t * vm,
524                        unformat_input_t * input, vlib_cli_command_t * cmd)
525 {
526   index_t cti;
527   cnat_translation_t *ct;
528
529   cti = INDEX_INVALID;
530
531   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
532     {
533       if (unformat (input, "%d", &cti))
534         ;
535       else
536         return (clib_error_return (0, "unknown input '%U'",
537                                    format_unformat_error, input));
538     }
539
540   if (INDEX_INVALID == cti)
541     {
542       pool_foreach_index (cti, cnat_translation_pool)
543        {
544         ct = pool_elt_at_index (cnat_translation_pool, cti);
545         vlib_cli_output(vm, "%U", format_cnat_translation, ct);
546       }
547     }
548   else
549     {
550       vlib_cli_output (vm, "Invalid policy ID:%d", cti);
551     }
552
553   return (NULL);
554 }
555
556 int
557 cnat_translation_purge (void)
558 {
559   /* purge all the translations */
560   index_t tri, *trp, *trs = NULL;
561
562   pool_foreach_index (tri, cnat_translation_pool)
563    {
564     vec_add1(trs, tri);
565   }
566
567   vec_foreach (trp, trs) cnat_translation_delete (*trp);
568
569   ASSERT (0 == pool_elts (cnat_translation_pool));
570
571   vec_free (trs);
572
573   return (0);
574 }
575
576 VLIB_CLI_COMMAND (cnat_translation_show_cmd_node, static) = {
577   .path = "show cnat translation",
578   .function = cnat_translation_show,
579   .short_help = "show cnat translation <VIP>",
580   .is_mp_safe = 1,
581 };
582
583 static fib_node_t *
584 cnat_translation_get_node (fib_node_index_t index)
585 {
586   cnat_translation_t *ct = cnat_translation_get (index);
587   return (&(ct->ct_node));
588 }
589
590 static cnat_translation_t *
591 cnat_translation_get_from_node (fib_node_t * node)
592 {
593   return ((cnat_translation_t *) (((char *) node) -
594                                   STRUCT_OFFSET_OF (cnat_translation_t,
595                                                     ct_node)));
596 }
597
598 static void
599 cnat_translation_last_lock_gone (fib_node_t * node)
600 {
601  /**/}
602
603 /*
604  * A back walk has reached this ABF policy
605  */
606 static fib_node_back_walk_rc_t
607 cnat_translation_back_walk_notify (fib_node_t * node,
608                                    fib_node_back_walk_ctx_t * ctx)
609 {
610   /*
611    * re-stack the fmask on the n-eos of the via
612    */
613   cnat_translation_t *ct = cnat_translation_get_from_node (node);
614
615   /* If we have more than FIB_PATH_LIST_POPULAR paths
616    * we might get called during path tracking
617    * (cnat_tracker_track) */
618   if (!(ct->flags & CNAT_TRANSLATION_STACKED))
619     return (FIB_NODE_BACK_WALK_CONTINUE);
620
621   cnat_translation_stack (ct);
622
623   return (FIB_NODE_BACK_WALK_CONTINUE);
624 }
625
626 /*
627  * The translation's graph node virtual function table
628  */
629 static const fib_node_vft_t cnat_translation_vft = {
630   .fnv_get = cnat_translation_get_node,
631   .fnv_last_lock = cnat_translation_last_lock_gone,
632   .fnv_back_walk = cnat_translation_back_walk_notify,
633 };
634
635 static clib_error_t *
636 cnat_translation_cli_add_del (vlib_main_t * vm,
637                               unformat_input_t * input,
638                               vlib_cli_command_t * cmd)
639 {
640   u32 del_index = INDEX_INVALID;
641   ip_protocol_t proto = IP_PROTOCOL_TCP;
642   cnat_endpoint_t vip;
643   u8 flags = CNAT_FLAG_EXCLUSIVE;
644   cnat_endpoint_tuple_t tmp, *paths = NULL, *path;
645   unformat_input_t _line_input, *line_input = &_line_input;
646   clib_error_t *e = 0;
647   cnat_lb_type_t lb_type;
648
649   /* Get a line of input. */
650   if (!unformat_user (input, unformat_line_input, line_input))
651     return 0;
652
653   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
654     {
655       if (unformat (line_input, "add"))
656         del_index = INDEX_INVALID;
657       else if (unformat (line_input, "del %d", &del_index))
658         ;
659       else
660         if (unformat (line_input, "proto %U", unformat_ip_protocol, &proto))
661         ;
662       else if (unformat (line_input, "vip %U", unformat_cnat_ep, &vip))
663         flags = CNAT_FLAG_EXCLUSIVE;
664       else if (unformat (line_input, "real %U", unformat_cnat_ep, &vip))
665         flags = 0;
666       else if (unformat (line_input, "to %U", unformat_cnat_ep_tuple, &tmp))
667         {
668           vec_add2 (paths, path, 1);
669           clib_memcpy (path, &tmp, sizeof (cnat_endpoint_tuple_t));
670         }
671       else if (unformat (line_input, "%U", unformat_cnat_lb_type, &lb_type))
672         ;
673       else
674         {
675           e = clib_error_return (0, "unknown input '%U'",
676                                  format_unformat_error, line_input);
677           goto done;
678         }
679     }
680
681   if (INDEX_INVALID == del_index)
682     cnat_translation_update (&vip, proto, paths, flags, lb_type);
683   else
684     cnat_translation_delete (del_index);
685
686 done:
687   vec_free (paths);
688   unformat_free (line_input);
689   return (e);
690 }
691
692 VLIB_CLI_COMMAND (cnat_translation_cli_add_del_command, static) =
693 {
694   .path = "cnat translation",
695   .short_help = "cnat translation [add|del] proto [TCP|UDP] [vip|real] [ip|sw_if_index [v6]] [port] [to [ip|sw_if_index [v6]] [port]->[ip|sw_if_index [v6]] [port]]",
696   .function = cnat_translation_cli_add_del,
697 };
698
699 static void
700 cnat_if_addr_add_del_translation_cb (addr_resolution_t * ar,
701                                      ip_address_t * address, u8 is_del)
702 {
703   cnat_translation_t *ct;
704   ct = cnat_translation_get (ar->cti);
705   if (!is_del && ct->ct_vip.ce_flags & CNAT_EP_FLAG_RESOLVED)
706     return;
707
708   cnat_remove_translation_from_db (ct->ct_cci, &ct->ct_vip, ct->ct_proto);
709
710   if (is_del)
711     {
712       ct->ct_vip.ce_flags &= ~CNAT_EP_FLAG_RESOLVED;
713       ct->ct_cci = INDEX_INVALID;
714       cnat_client_translation_deleted (ct->ct_cci);
715       /* Are there remaining addresses ? */
716       if (0 == cnat_resolve_addr (ar->sw_if_index, ar->af, address))
717         is_del = 0;
718     }
719
720   if (!is_del)
721     {
722       ct->ct_cci = cnat_client_add (address, ct->flags);
723       cnat_client_translation_added (ct->ct_cci);
724       ip_address_copy (&ct->ct_vip.ce_ip, address);
725       ct->ct_vip.ce_flags |= CNAT_EP_FLAG_RESOLVED;
726     }
727
728   cnat_add_translation_to_db (ct->ct_cci, &ct->ct_vip, ct->ct_proto,
729                               ct->index);
730 }
731
732 static void
733 cnat_if_addr_add_del_backend_cb (addr_resolution_t * ar,
734                                  ip_address_t * address, u8 is_del)
735 {
736   cnat_translation_t *ct;
737   cnat_ep_trk_t *trk;
738   cnat_endpoint_t *ep;
739
740   u8 direction = ar->opaque & 0xf;
741   u32 path_idx = ar->opaque >> 32;
742
743   ct = cnat_translation_get (ar->cti);
744
745   trk = &ct->ct_paths[path_idx];
746   ep = &trk->ct_ep[direction];
747
748   if (!is_del && ep->ce_flags & CNAT_EP_FLAG_RESOLVED)
749     return;
750
751   ASSERT (ep->ce_sw_if_index == ar->sw_if_index);
752
753   if (is_del)
754     {
755       ep->ce_flags &= ~CNAT_EP_FLAG_RESOLVED;
756       /* Are there remaining addresses ? */
757       if (0 == cnat_resolve_addr (ar->sw_if_index, ar->af, address))
758         is_del = 0;
759     }
760
761   if (!is_del)
762     {
763       ip_address_copy (&ep->ce_ip, address);
764       ep->ce_flags |= CNAT_EP_FLAG_RESOLVED;
765     }
766
767   ct->flags &= ~CNAT_TRANSLATION_STACKED;
768   cnat_tracker_track (ar->cti, trk);
769
770   cnat_translation_stack (ct);
771   ct->flags |= CNAT_TRANSLATION_STACKED;
772 }
773
774 static void
775 cnat_if_addr_add_del_callback (u32 sw_if_index, ip_address_t * address,
776                                u8 is_del)
777 {
778   addr_resolution_t *ar;
779   pool_foreach (ar, tr_resolutions)
780     {
781       if (ar->sw_if_index != sw_if_index)
782         continue;
783       if (ar->af != ip_addr_version (address))
784         continue;
785       cnat_if_addr_add_cbs[ar->type](ar, address, is_del);
786     }
787 }
788
789 static void
790 cnat_ip6_if_addr_add_del_callback (struct ip6_main_t *im,
791                                    uword opaque, u32 sw_if_index,
792                                    ip6_address_t * address,
793                                    u32 address_length, u32 if_address_index,
794                                    u32 is_del)
795 {
796   ip_address_t addr;
797   ip_address_set (&addr, address, AF_IP6);
798   cnat_if_addr_add_del_callback (sw_if_index, &addr, is_del);
799 }
800
801 static void
802 cnat_ip4_if_addr_add_del_callback (struct ip4_main_t *im,
803                                    uword opaque, u32 sw_if_index,
804                                    ip4_address_t * address,
805                                    u32 address_length, u32 if_address_index,
806                                    u32 is_del)
807 {
808   ip_address_t addr;
809   ip_address_set (&addr, address, AF_IP4);
810   cnat_if_addr_add_del_callback (sw_if_index, &addr, is_del);
811 }
812
813 void
814 cnat_translation_register_addr_add_cb (cnat_addr_resol_type_t typ,
815                                        cnat_if_addr_add_cb_t fn)
816 {
817   vec_validate (cnat_if_addr_add_cbs, CNAT_ADDR_N_RESOLUTIONS);
818   cnat_if_addr_add_cbs[typ] = fn;
819 }
820
821 static clib_error_t *
822 cnat_translation_init (vlib_main_t * vm)
823 {
824   ip4_main_t *i4m = &ip4_main;
825   ip6_main_t *i6m = &ip6_main;
826   cnat_main_t *cm = &cnat_main;
827   cnat_translation_fib_node_type =
828     fib_node_register_new_type (&cnat_translation_vft);
829
830   clib_bihash_init_8_8 (&cnat_translation_db, "CNat translation DB",
831                         cm->translation_hash_buckets,
832                         cm->translation_hash_memory);
833
834   ip4_add_del_interface_address_callback_t cb4 = { 0 };
835   cb4.function = cnat_ip4_if_addr_add_del_callback;
836   vec_add1 (i4m->add_del_interface_address_callbacks, cb4);
837
838   ip6_add_del_interface_address_callback_t cb6 = { 0 };
839   cb6.function = cnat_ip6_if_addr_add_del_callback;
840   vec_add1 (i6m->add_del_interface_address_callbacks, cb6);
841
842   cnat_translation_register_addr_add_cb (CNAT_RESOLV_ADDR_BACKEND,
843                                          cnat_if_addr_add_del_backend_cb);
844   cnat_translation_register_addr_add_cb (CNAT_RESOLV_ADDR_TRANSLATION,
845                                          cnat_if_addr_add_del_translation_cb);
846
847   return (NULL);
848 }
849
850 VLIB_INIT_FUNCTION (cnat_translation_init);
851
852 /*
853  * fd.io coding-style-patch-verification: ON
854  *
855  * Local Variables:
856  * eval: (c-set-style "gnu")
857  * End:
858  */