NAT66 1:1 mapping (VPP-1108)
[vpp.git] / src / plugins / nat / nat.c
1 /*
2  * snat.c - simple nat plugin
3  *
4  * Copyright (c) 2016 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/ip/ip.h>
20 #include <vnet/ip/ip4.h>
21 #include <vnet/plugin/plugin.h>
22 #include <nat/nat.h>
23 #include <nat/nat_dpo.h>
24 #include <nat/nat_ipfix_logging.h>
25 #include <nat/nat_det.h>
26 #include <nat/nat64.h>
27 #include <nat/nat66.h>
28 #include <nat/dslite.h>
29 #include <nat/nat_reass.h>
30 #include <vnet/fib/fib_table.h>
31 #include <vnet/fib/ip4_fib.h>
32
33 #include <vpp/app/version.h>
34
35 snat_main_t snat_main;
36
37
38 /* Hook up input features */
39 VNET_FEATURE_INIT (ip4_snat_in2out, static) = {
40   .arc_name = "ip4-unicast",
41   .node_name = "nat44-in2out",
42   .runs_before = VNET_FEATURES ("nat44-out2in"),
43 };
44 VNET_FEATURE_INIT (ip4_snat_out2in, static) = {
45   .arc_name = "ip4-unicast",
46   .node_name = "nat44-out2in",
47   .runs_before = VNET_FEATURES ("ip4-lookup"),
48 };
49 VNET_FEATURE_INIT (ip4_nat_classify, static) = {
50   .arc_name = "ip4-unicast",
51   .node_name = "nat44-classify",
52   .runs_before = VNET_FEATURES ("ip4-lookup"),
53 };
54 VNET_FEATURE_INIT (ip4_snat_det_in2out, static) = {
55   .arc_name = "ip4-unicast",
56   .node_name = "nat44-det-in2out",
57   .runs_before = VNET_FEATURES ("nat44-det-out2in"),
58 };
59 VNET_FEATURE_INIT (ip4_snat_det_out2in, static) = {
60   .arc_name = "ip4-unicast",
61   .node_name = "nat44-det-out2in",
62   .runs_before = VNET_FEATURES ("ip4-lookup"),
63 };
64 VNET_FEATURE_INIT (ip4_nat_det_classify, static) = {
65   .arc_name = "ip4-unicast",
66   .node_name = "nat44-det-classify",
67   .runs_before = VNET_FEATURES ("ip4-lookup"),
68 };
69 VNET_FEATURE_INIT (ip4_snat_in2out_worker_handoff, static) = {
70   .arc_name = "ip4-unicast",
71   .node_name = "nat44-in2out-worker-handoff",
72   .runs_before = VNET_FEATURES ("nat44-out2in-worker-handoff"),
73 };
74 VNET_FEATURE_INIT (ip4_snat_out2in_worker_handoff, static) = {
75   .arc_name = "ip4-unicast",
76   .node_name = "nat44-out2in-worker-handoff",
77   .runs_before = VNET_FEATURES ("ip4-lookup"),
78 };
79 VNET_FEATURE_INIT (ip4_nat_handoff_classify, static) = {
80   .arc_name = "ip4-unicast",
81   .node_name = "nat44-handoff-classify",
82   .runs_before = VNET_FEATURES ("ip4-lookup"),
83 };
84 VNET_FEATURE_INIT (ip4_snat_in2out_fast, static) = {
85   .arc_name = "ip4-unicast",
86   .node_name = "nat44-in2out-fast",
87   .runs_before = VNET_FEATURES ("nat44-out2in-fast"),
88 };
89 VNET_FEATURE_INIT (ip4_snat_out2in_fast, static) = {
90   .arc_name = "ip4-unicast",
91   .node_name = "nat44-out2in-fast",
92   .runs_before = VNET_FEATURES ("ip4-lookup"),
93 };
94 VNET_FEATURE_INIT (ip4_snat_hairpin_dst, static) = {
95   .arc_name = "ip4-unicast",
96   .node_name = "nat44-hairpin-dst",
97   .runs_before = VNET_FEATURES ("ip4-lookup"),
98 };
99
100 /* Hook up output features */
101 VNET_FEATURE_INIT (ip4_snat_in2out_output, static) = {
102   .arc_name = "ip4-output",
103   .node_name = "nat44-in2out-output",
104   .runs_before = VNET_FEATURES ("interface-output"),
105 };
106 VNET_FEATURE_INIT (ip4_snat_in2out_output_worker_handoff, static) = {
107   .arc_name = "ip4-output",
108   .node_name = "nat44-in2out-output-worker-handoff",
109   .runs_before = VNET_FEATURES ("interface-output"),
110 };
111 VNET_FEATURE_INIT (ip4_snat_hairpin_src, static) = {
112   .arc_name = "ip4-output",
113   .node_name = "nat44-hairpin-src",
114   .runs_before = VNET_FEATURES ("interface-output"),
115 };
116
117 /* Hook up ip4-local features */
118 VNET_FEATURE_INIT (ip4_nat_hairpinning, static) =
119 {
120   .arc_name = "ip4-local",
121   .node_name = "nat44-hairpinning",
122   .runs_before = VNET_FEATURES("ip4-local-end-of-arc"),
123 };
124
125
126 /* *INDENT-OFF* */
127 VLIB_PLUGIN_REGISTER () = {
128     .version = VPP_BUILD_VER,
129     .description = "Network Address Translation",
130 };
131 /* *INDENT-ON* */
132
133 vlib_node_registration_t nat44_classify_node;
134 vlib_node_registration_t nat44_det_classify_node;
135 vlib_node_registration_t nat44_handoff_classify_node;
136
137 typedef enum {
138   NAT44_CLASSIFY_NEXT_IN2OUT,
139   NAT44_CLASSIFY_NEXT_OUT2IN,
140   NAT44_CLASSIFY_N_NEXT,
141 } nat44_classify_next_t;
142
143 void
144 nat_free_session_data (snat_main_t * sm, snat_session_t * s, u32 thread_index)
145 {
146   snat_session_key_t key;
147   clib_bihash_kv_8_8_t kv;
148   nat_ed_ses_key_t ed_key;
149   clib_bihash_kv_16_8_t ed_kv;
150   int i;
151   snat_address_t *a;
152   snat_main_per_thread_data_t *tsm =
153     vec_elt_at_index (sm->per_thread_data, thread_index);
154
155   /* Endpoint dependent session lookup tables */
156   if (is_ed_session (s))
157     {
158       ed_key.l_addr = s->out2in.addr;
159       ed_key.r_addr = s->ext_host_addr;
160       ed_key.fib_index = s->out2in.fib_index;
161       if (snat_is_unk_proto_session (s))
162         {
163           ed_key.proto = s->in2out.port;
164           ed_key.r_port = 0;
165           ed_key.l_port = 0;
166         }
167       else
168         {
169           ed_key.proto = snat_proto_to_ip_proto (s->in2out.protocol);
170           ed_key.l_port = s->out2in.port;
171           ed_key.r_port = s->ext_host_port;
172         }
173       ed_kv.key[0] = ed_key.as_u64[0];
174       ed_kv.key[1] = ed_key.as_u64[1];
175       if (clib_bihash_add_del_16_8 (&sm->out2in_ed, &ed_kv, 0))
176         clib_warning ("out2in_ed key del failed");
177
178       ed_key.l_addr = s->in2out.addr;
179       ed_key.fib_index = s->in2out.fib_index;
180       if (!snat_is_unk_proto_session (s))
181         ed_key.l_port = s->in2out.port;
182       if (is_twice_nat_session (s))
183         {
184           ed_key.r_addr = s->ext_host_nat_addr;
185           ed_key.r_port = s->ext_host_nat_port;
186         }
187       ed_kv.key[0] = ed_key.as_u64[0];
188       ed_kv.key[1] = ed_key.as_u64[1];
189       if (clib_bihash_add_del_16_8 (&sm->in2out_ed, &ed_kv, 0))
190         clib_warning ("in2out_ed key del failed");
191     }
192
193   if (snat_is_unk_proto_session (s))
194     return;
195
196   /* log NAT event */
197   snat_ipfix_logging_nat44_ses_delete(s->in2out.addr.as_u32,
198                                       s->out2in.addr.as_u32,
199                                       s->in2out.protocol,
200                                       s->in2out.port,
201                                       s->out2in.port,
202                                       s->in2out.fib_index);
203
204   /* Twice NAT address and port for external host */
205   if (is_twice_nat_session (s))
206     {
207       for (i = 0; i < vec_len (sm->twice_nat_addresses); i++)
208         {
209           key.protocol = s->in2out.protocol;
210           key.port = s->ext_host_nat_port;
211           a = sm->twice_nat_addresses + i;
212           if (a->addr.as_u32 == s->ext_host_nat_addr.as_u32)
213             {
214               snat_free_outside_address_and_port (sm->twice_nat_addresses,
215                                                   thread_index, &key, i);
216               break;
217             }
218         }
219     }
220
221   if (is_ed_session (s))
222     return;
223
224   /* Session lookup tables */
225   kv.key = s->in2out.as_u64;
226   if (clib_bihash_add_del_8_8 (&tsm->in2out, &kv, 0))
227     clib_warning ("in2out key del failed");
228   kv.key = s->out2in.as_u64;
229   if (clib_bihash_add_del_8_8 (&tsm->out2in, &kv, 0))
230     clib_warning ("out2in key del failed");
231
232   if (snat_is_session_static (s))
233     return;
234
235   if (s->outside_address_index != ~0)
236     snat_free_outside_address_and_port (sm->addresses, thread_index,
237                                         &s->out2in, s->outside_address_index);
238 }
239
240 snat_user_t *
241 nat_user_get_or_create (snat_main_t *sm, ip4_address_t *addr, u32 fib_index,
242                         u32 thread_index)
243 {
244   snat_user_t *u = 0;
245   snat_user_key_t user_key;
246   clib_bihash_kv_8_8_t kv, value;
247   snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
248   dlist_elt_t * per_user_list_head_elt;
249
250   user_key.addr.as_u32 = addr->as_u32;
251   user_key.fib_index = fib_index;
252   kv.key = user_key.as_u64;
253
254   /* Ever heard of the "user" = src ip4 address before? */
255   if (clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
256     {
257       /* no, make a new one */
258       pool_get (tsm->users, u);
259       memset (u, 0, sizeof (*u));
260       u->addr.as_u32 = addr->as_u32;
261       u->fib_index = fib_index;
262
263       pool_get (tsm->list_pool, per_user_list_head_elt);
264
265       u->sessions_per_user_list_head_index = per_user_list_head_elt -
266         tsm->list_pool;
267
268       clib_dlist_init (tsm->list_pool, u->sessions_per_user_list_head_index);
269
270       kv.value = u - tsm->users;
271
272       /* add user */
273       if (clib_bihash_add_del_8_8 (&tsm->user_hash, &kv, 1))
274         clib_warning ("user_hash keay add failed");
275     }
276   else
277     {
278       u = pool_elt_at_index (tsm->users, value.value);
279     }
280
281   return u;
282 }
283
284 snat_session_t *
285 nat_session_alloc_or_recycle (snat_main_t *sm, snat_user_t *u, u32 thread_index)
286 {
287   snat_session_t *s;
288   snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
289   u32 oldest_per_user_translation_list_index, session_index;
290   dlist_elt_t * oldest_per_user_translation_list_elt;
291   dlist_elt_t * per_user_translation_list_elt;
292
293   /* Over quota? Recycle the least recently used translation */
294   if ((u->nsessions + u->nstaticsessions) >= sm->max_translations_per_user)
295     {
296       oldest_per_user_translation_list_index =
297         clib_dlist_remove_head (tsm->list_pool,
298                                 u->sessions_per_user_list_head_index);
299
300       ASSERT (oldest_per_user_translation_list_index != ~0);
301
302       /* Add it back to the end of the LRU list */
303       clib_dlist_addtail (tsm->list_pool,
304                           u->sessions_per_user_list_head_index,
305                           oldest_per_user_translation_list_index);
306       /* Get the list element */
307       oldest_per_user_translation_list_elt =
308         pool_elt_at_index (tsm->list_pool,
309                            oldest_per_user_translation_list_index);
310
311       /* Get the session index from the list element */
312       session_index = oldest_per_user_translation_list_elt->value;
313
314       /* Get the session */
315       s = pool_elt_at_index (tsm->sessions, session_index);
316       nat_free_session_data (sm, s, thread_index);
317       s->outside_address_index = ~0;
318       s->flags = 0;
319       s->total_bytes = 0;
320       s->total_pkts = 0;
321     }
322   else
323     {
324       pool_get (tsm->sessions, s);
325       memset (s, 0, sizeof (*s));
326       s->outside_address_index = ~0;
327
328       /* Create list elts */
329       pool_get (tsm->list_pool, per_user_translation_list_elt);
330       clib_dlist_init (tsm->list_pool,
331                        per_user_translation_list_elt - tsm->list_pool);
332
333       per_user_translation_list_elt->value = s - tsm->sessions;
334       s->per_user_index = per_user_translation_list_elt - tsm->list_pool;
335       s->per_user_list_head_index = u->sessions_per_user_list_head_index;
336
337       clib_dlist_addtail (tsm->list_pool,
338                           s->per_user_list_head_index,
339                           per_user_translation_list_elt - tsm->list_pool);
340     }
341
342   return s;
343 }
344
345 static inline uword
346 nat44_classify_node_fn_inline (vlib_main_t * vm,
347                                vlib_node_runtime_t * node,
348                                vlib_frame_t * frame)
349 {
350   u32 n_left_from, * from, * to_next;
351   nat44_classify_next_t next_index;
352   snat_main_t *sm = &snat_main;
353
354   from = vlib_frame_vector_args (frame);
355   n_left_from = frame->n_vectors;
356   next_index = node->cached_next_index;
357
358   while (n_left_from > 0)
359     {
360       u32 n_left_to_next;
361
362       vlib_get_next_frame (vm, node, next_index,
363                            to_next, n_left_to_next);
364
365       while (n_left_from > 0 && n_left_to_next > 0)
366         {
367           u32 bi0;
368           vlib_buffer_t *b0;
369           u32 next0 = NAT44_CLASSIFY_NEXT_IN2OUT;
370           ip4_header_t *ip0;
371           snat_address_t *ap;
372           snat_session_key_t m_key0;
373           clib_bihash_kv_8_8_t kv0, value0;
374
375           /* speculatively enqueue b0 to the current next frame */
376           bi0 = from[0];
377           to_next[0] = bi0;
378           from += 1;
379           to_next += 1;
380           n_left_from -= 1;
381           n_left_to_next -= 1;
382
383           b0 = vlib_get_buffer (vm, bi0);
384           ip0 = vlib_buffer_get_current (b0);
385
386           vec_foreach (ap, sm->addresses)
387             {
388               if (ip0->dst_address.as_u32 == ap->addr.as_u32)
389                 {
390                   next0 = NAT44_CLASSIFY_NEXT_OUT2IN;
391                   goto enqueue0;
392                 }
393             }
394
395           if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
396             {
397               m_key0.addr = ip0->dst_address;
398               m_key0.port = 0;
399               m_key0.protocol = 0;
400               m_key0.fib_index = sm->outside_fib_index;
401               kv0.key = m_key0.as_u64;
402               if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv0, &value0))
403                 {
404                   next0 = NAT44_CLASSIFY_NEXT_OUT2IN;
405                   goto enqueue0;
406                 }
407               udp_header_t * udp0 = ip4_next_header (ip0);
408               m_key0.port = clib_net_to_host_u16 (udp0->dst_port);
409               m_key0.protocol = ip_proto_to_snat_proto (ip0->protocol);
410               kv0.key = m_key0.as_u64;
411               if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv0, &value0))
412                 next0 = NAT44_CLASSIFY_NEXT_OUT2IN;
413             }
414
415         enqueue0:
416           /* verify speculative enqueue, maybe switch current next frame */
417           vlib_validate_buffer_enqueue_x1 (vm, node, next_index,
418                                            to_next, n_left_to_next,
419                                            bi0, next0);
420         }
421
422       vlib_put_next_frame (vm, node, next_index, n_left_to_next);
423     }
424
425   return frame->n_vectors;
426 }
427
428 static uword
429 nat44_classify_node_fn (vlib_main_t * vm,
430                         vlib_node_runtime_t * node,
431                         vlib_frame_t * frame)
432 {
433   return nat44_classify_node_fn_inline (vm, node, frame);
434 };
435
436 VLIB_REGISTER_NODE (nat44_classify_node) = {
437   .function = nat44_classify_node_fn,
438   .name = "nat44-classify",
439   .vector_size = sizeof (u32),
440   .type = VLIB_NODE_TYPE_INTERNAL,
441   .n_next_nodes = NAT44_CLASSIFY_N_NEXT,
442   .next_nodes = {
443     [NAT44_CLASSIFY_NEXT_IN2OUT] = "nat44-in2out",
444     [NAT44_CLASSIFY_NEXT_OUT2IN] = "nat44-out2in",
445   },
446 };
447
448 VLIB_NODE_FUNCTION_MULTIARCH (nat44_classify_node,
449                               nat44_classify_node_fn);
450
451 static uword
452 nat44_det_classify_node_fn (vlib_main_t * vm,
453                             vlib_node_runtime_t * node,
454                             vlib_frame_t * frame)
455 {
456   return nat44_classify_node_fn_inline (vm, node, frame);
457 };
458
459 VLIB_REGISTER_NODE (nat44_det_classify_node) = {
460   .function = nat44_det_classify_node_fn,
461   .name = "nat44-det-classify",
462   .vector_size = sizeof (u32),
463   .type = VLIB_NODE_TYPE_INTERNAL,
464   .n_next_nodes = NAT44_CLASSIFY_N_NEXT,
465   .next_nodes = {
466     [NAT44_CLASSIFY_NEXT_IN2OUT] = "nat44-det-in2out",
467     [NAT44_CLASSIFY_NEXT_OUT2IN] = "nat44-det-out2in",
468   },
469 };
470
471 VLIB_NODE_FUNCTION_MULTIARCH (nat44_det_classify_node,
472                               nat44_det_classify_node_fn);
473
474 static uword
475 nat44_handoff_classify_node_fn (vlib_main_t * vm,
476                                 vlib_node_runtime_t * node,
477                                 vlib_frame_t * frame)
478 {
479   return nat44_classify_node_fn_inline (vm, node, frame);
480 };
481
482 VLIB_REGISTER_NODE (nat44_handoff_classify_node) = {
483   .function = nat44_handoff_classify_node_fn,
484   .name = "nat44-handoff-classify",
485   .vector_size = sizeof (u32),
486   .type = VLIB_NODE_TYPE_INTERNAL,
487   .n_next_nodes = NAT44_CLASSIFY_N_NEXT,
488   .next_nodes = {
489     [NAT44_CLASSIFY_NEXT_IN2OUT] = "nat44-in2out-worker-handoff",
490     [NAT44_CLASSIFY_NEXT_OUT2IN] = "nat44-out2in-worker-handoff",
491   },
492 };
493
494 VLIB_NODE_FUNCTION_MULTIARCH (nat44_handoff_classify_node,
495                               nat44_handoff_classify_node_fn);
496
497 /**
498  * @brief Add/del NAT address to FIB.
499  *
500  * Add the external NAT address to the FIB as receive entries. This ensures
501  * that VPP will reply to ARP for this address and we don't need to enable
502  * proxy ARP on the outside interface.
503  *
504  * @param addr IPv4 address.
505  * @param plen address prefix length
506  * @param sw_if_index Interface.
507  * @param is_add If 0 delete, otherwise add.
508  */
509 void
510 snat_add_del_addr_to_fib (ip4_address_t * addr, u8 p_len, u32 sw_if_index,
511                           int is_add)
512 {
513   fib_prefix_t prefix = {
514     .fp_len = p_len,
515     .fp_proto = FIB_PROTOCOL_IP4,
516     .fp_addr = {
517         .ip4.as_u32 = addr->as_u32,
518     },
519   };
520   u32 fib_index = ip4_fib_table_get_index_for_sw_if_index(sw_if_index);
521
522   if (is_add)
523     fib_table_entry_update_one_path(fib_index,
524                                     &prefix,
525                                     FIB_SOURCE_PLUGIN_HI,
526                                     (FIB_ENTRY_FLAG_CONNECTED |
527                                      FIB_ENTRY_FLAG_LOCAL |
528                                      FIB_ENTRY_FLAG_EXCLUSIVE),
529                                     DPO_PROTO_IP4,
530                                     NULL,
531                                     sw_if_index,
532                                     ~0,
533                                     1,
534                                     NULL,
535                                     FIB_ROUTE_PATH_FLAG_NONE);
536   else
537     fib_table_entry_delete(fib_index,
538                            &prefix,
539                            FIB_SOURCE_PLUGIN_HI);
540 }
541
542 void snat_add_address (snat_main_t *sm, ip4_address_t *addr, u32 vrf_id,
543                        u8 twice_nat)
544 {
545   snat_address_t * ap;
546   snat_interface_t *i;
547   vlib_thread_main_t *tm = vlib_get_thread_main ();
548
549   /* Check if address already exists */
550   vec_foreach (ap, twice_nat ? sm->twice_nat_addresses : sm->addresses)
551     {
552       if (ap->addr.as_u32 == addr->as_u32)
553         return;
554     }
555
556   if (twice_nat)
557     vec_add2 (sm->twice_nat_addresses, ap, 1);
558   else
559     vec_add2 (sm->addresses, ap, 1);
560
561   ap->addr = *addr;
562   if (vrf_id != ~0)
563     ap->fib_index =
564       fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, vrf_id,
565                                          FIB_SOURCE_PLUGIN_HI);
566   else
567     ap->fib_index = ~0;
568 #define _(N, i, n, s) \
569   clib_bitmap_alloc (ap->busy_##n##_port_bitmap, 65535); \
570   ap->busy_##n##_ports = 0; \
571   vec_validate_init_empty (ap->busy_##n##_ports_per_thread, tm->n_vlib_mains - 1, 0);
572   foreach_snat_protocol
573 #undef _
574
575   if (twice_nat)
576     return;
577
578   /* Add external address to FIB */
579   pool_foreach (i, sm->interfaces,
580   ({
581     if (nat_interface_is_inside(i) || sm->out2in_dpo)
582       continue;
583
584     snat_add_del_addr_to_fib(addr, 32, i->sw_if_index, 1);
585     break;
586   }));
587   pool_foreach (i, sm->output_feature_interfaces,
588   ({
589     if (nat_interface_is_inside(i) || sm->out2in_dpo)
590       continue;
591
592     snat_add_del_addr_to_fib(addr, 32, i->sw_if_index, 1);
593     break;
594   }));
595 }
596
597 static int is_snat_address_used_in_static_mapping (snat_main_t *sm,
598                                                    ip4_address_t addr)
599 {
600   snat_static_mapping_t *m;
601   pool_foreach (m, sm->static_mappings,
602   ({
603       if (m->external_addr.as_u32 == addr.as_u32)
604         return 1;
605   }));
606
607   return 0;
608 }
609
610 void increment_v4_address (ip4_address_t * a)
611 {
612   u32 v;
613
614   v = clib_net_to_host_u32(a->as_u32) + 1;
615   a->as_u32 = clib_host_to_net_u32(v);
616 }
617
618 static void
619 snat_add_static_mapping_when_resolved (snat_main_t * sm,
620                                        ip4_address_t l_addr,
621                                        u16 l_port,
622                                        u32 sw_if_index,
623                                        u16 e_port,
624                                        u32 vrf_id,
625                                        snat_protocol_t proto,
626                                        int addr_only,
627                                        int is_add,
628                                        u8 * tag)
629 {
630   snat_static_map_resolve_t *rp;
631
632   vec_add2 (sm->to_resolve, rp, 1);
633   rp->l_addr.as_u32 = l_addr.as_u32;
634   rp->l_port = l_port;
635   rp->sw_if_index = sw_if_index;
636   rp->e_port = e_port;
637   rp->vrf_id = vrf_id;
638   rp->proto = proto;
639   rp->addr_only = addr_only;
640   rp->is_add = is_add;
641   rp->tag = vec_dup (tag);
642 }
643
644 /**
645  * @brief Add static mapping.
646  *
647  * Create static mapping between local addr+port and external addr+port.
648  *
649  * @param l_addr Local IPv4 address.
650  * @param e_addr External IPv4 address.
651  * @param l_port Local port number.
652  * @param e_port External port number.
653  * @param vrf_id VRF ID.
654  * @param addr_only If 0 address port and pair mapping, otherwise address only.
655  * @param sw_if_index External port instead of specific IP address.
656  * @param is_add If 0 delete static mapping, otherwise add.
657  * @param twice_nat If 1 translate external host address and port.
658  * @param out2in_only If 1 rule match only out2in direction
659  * @param tag - opaque string tag
660  *
661  * @returns
662  */
663 int snat_add_static_mapping(ip4_address_t l_addr, ip4_address_t e_addr,
664                             u16 l_port, u16 e_port, u32 vrf_id, int addr_only,
665                             u32 sw_if_index, snat_protocol_t proto, int is_add,
666                             u8 twice_nat, u8 out2in_only, u8 * tag)
667 {
668   snat_main_t * sm = &snat_main;
669   snat_static_mapping_t *m;
670   snat_session_key_t m_key;
671   clib_bihash_kv_8_8_t kv, value;
672   snat_address_t *a = 0;
673   u32 fib_index = ~0;
674   uword * p;
675   snat_interface_t *interface;
676   int i;
677   snat_main_per_thread_data_t *tsm;
678   snat_user_key_t u_key;
679   snat_user_t *u;
680   dlist_elt_t * head, * elt;
681   u32 elt_index, head_index;
682   u32 ses_index;
683   u64 user_index;
684   snat_session_t * s;
685
686   /* If the external address is a specific interface address */
687   if (sw_if_index != ~0)
688     {
689       ip4_address_t * first_int_addr;
690
691       /* Might be already set... */
692       first_int_addr = ip4_interface_first_address
693         (sm->ip4_main, sw_if_index, 0 /* just want the address*/);
694
695       /* DHCP resolution required? */
696       if (first_int_addr == 0)
697         {
698           snat_add_static_mapping_when_resolved
699             (sm, l_addr, l_port, sw_if_index, e_port, vrf_id, proto,
700              addr_only,  is_add, tag);
701           return 0;
702         }
703         else
704         {
705           e_addr.as_u32 = first_int_addr->as_u32;
706           /* Identity mapping? */
707           if (l_addr.as_u32 == 0)
708             l_addr.as_u32 = e_addr.as_u32;
709         }
710     }
711
712   m_key.addr = e_addr;
713   m_key.port = addr_only ? 0 : e_port;
714   m_key.protocol = addr_only ? 0 : proto;
715   m_key.fib_index = sm->outside_fib_index;
716   kv.key = m_key.as_u64;
717   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
718     m = 0;
719   else
720     m = pool_elt_at_index (sm->static_mappings, value.value);
721
722   if (is_add)
723     {
724       if (m)
725         return VNET_API_ERROR_VALUE_EXIST;
726
727       if (twice_nat && addr_only)
728         return VNET_API_ERROR_UNSUPPORTED;
729
730       /* Convert VRF id to FIB index */
731       if (vrf_id != ~0)
732         {
733           p = hash_get (sm->ip4_main->fib_index_by_table_id, vrf_id);
734           if (!p)
735             return VNET_API_ERROR_NO_SUCH_FIB;
736           fib_index = p[0];
737         }
738       /* If not specified use inside VRF id from SNAT plugin startup config */
739       else
740         {
741           fib_index = sm->inside_fib_index;
742           vrf_id = sm->inside_vrf_id;
743         }
744
745       /* Find external address in allocated addresses and reserve port for
746          address and port pair mapping when dynamic translations enabled */
747       if (!(addr_only || sm->static_mapping_only || out2in_only))
748         {
749           for (i = 0; i < vec_len (sm->addresses); i++)
750             {
751               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
752                 {
753                   a = sm->addresses + i;
754                   /* External port must be unused */
755                   switch (proto)
756                     {
757 #define _(N, j, n, s) \
758                     case SNAT_PROTOCOL_##N: \
759                       if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, e_port)) \
760                         return VNET_API_ERROR_INVALID_VALUE; \
761                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 1); \
762                       if (e_port > 1024) \
763                         { \
764                           a->busy_##n##_ports++; \
765                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]++; \
766                         } \
767                       break;
768                       foreach_snat_protocol
769 #undef _
770                     default:
771                       clib_warning("unknown_protocol");
772                       return VNET_API_ERROR_INVALID_VALUE_2;
773                     }
774                   break;
775                 }
776             }
777           /* External address must be allocated */
778           if (!a && (l_addr.as_u32 != e_addr.as_u32))
779             return VNET_API_ERROR_NO_SUCH_ENTRY;
780         }
781
782       pool_get (sm->static_mappings, m);
783       memset (m, 0, sizeof (*m));
784       m->tag = vec_dup (tag);
785       m->local_addr = l_addr;
786       m->external_addr = e_addr;
787       m->addr_only = addr_only;
788       m->vrf_id = vrf_id;
789       m->fib_index = fib_index;
790       m->twice_nat = twice_nat;
791       m->out2in_only = out2in_only;
792       if (!addr_only)
793         {
794           m->local_port = l_port;
795           m->external_port = e_port;
796           m->proto = proto;
797         }
798
799       if (sm->workers)
800         {
801           ip4_header_t ip = {
802             .src_address = m->local_addr,
803           };
804           m->worker_index = sm->worker_in2out_cb (&ip, m->fib_index);
805           tsm = vec_elt_at_index (sm->per_thread_data, m->worker_index);
806         }
807       else
808         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
809
810       m_key.addr = m->local_addr;
811       m_key.port = m->local_port;
812       m_key.protocol = m->proto;
813       m_key.fib_index = m->fib_index;
814       kv.key = m_key.as_u64;
815       kv.value = m - sm->static_mappings;
816       if (!out2in_only)
817         clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 1);
818       if (twice_nat || out2in_only)
819         {
820           m_key.port = clib_host_to_net_u16 (l_port);
821           kv.key = m_key.as_u64;
822           kv.value = ~0ULL;
823           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 1))
824             clib_warning ("in2out key add failed");
825         }
826
827       m_key.addr = m->external_addr;
828       m_key.port = m->external_port;
829       m_key.fib_index = sm->outside_fib_index;
830       kv.key = m_key.as_u64;
831       kv.value = m - sm->static_mappings;
832       clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 1);
833       if (twice_nat || out2in_only)
834         {
835           m_key.port = clib_host_to_net_u16 (e_port);
836           kv.key = m_key.as_u64;
837           kv.value = ~0ULL;
838           if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 1))
839             clib_warning ("out2in key add failed");
840         }
841
842       /* Delete dynamic sessions matching local address (+ local port) */
843       if (!(sm->static_mapping_only))
844         {
845           u_key.addr = m->local_addr;
846           u_key.fib_index = m->fib_index;
847           kv.key = u_key.as_u64;
848           if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
849             {
850               user_index = value.value;
851               u = pool_elt_at_index (tsm->users, user_index);
852               if (u->nsessions)
853                 {
854                   head_index = u->sessions_per_user_list_head_index;
855                   head = pool_elt_at_index (tsm->list_pool, head_index);
856                   elt_index = head->next;
857                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
858                   ses_index = elt->value;
859                   while (ses_index != ~0)
860                     {
861                       s =  pool_elt_at_index (tsm->sessions, ses_index);
862                       elt = pool_elt_at_index (tsm->list_pool, elt->next);
863                       ses_index = elt->value;
864
865                       if (snat_is_session_static (s))
866                         continue;
867
868                       if (!addr_only)
869                         {
870                           if ((s->out2in.addr.as_u32 != e_addr.as_u32) &&
871                               (clib_net_to_host_u16 (s->out2in.port) != e_port))
872                             continue;
873                         }
874
875                       nat_free_session_data (sm, s, tsm - sm->per_thread_data);
876                       clib_dlist_remove (tsm->list_pool, s->per_user_index);
877                       pool_put_index (tsm->list_pool, s->per_user_index);
878                       pool_put (tsm->sessions, s);
879                       u->nsessions--;
880
881                       if (!addr_only)
882                         break;
883                     }
884                 }
885             }
886         }
887     }
888   else
889     {
890       if (!m)
891         return VNET_API_ERROR_NO_SUCH_ENTRY;
892
893       /* Free external address port */
894       if (!(addr_only || sm->static_mapping_only || out2in_only))
895         {
896           for (i = 0; i < vec_len (sm->addresses); i++)
897             {
898               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
899                 {
900                   a = sm->addresses + i;
901                   switch (proto)
902                     {
903 #define _(N, j, n, s) \
904                     case SNAT_PROTOCOL_##N: \
905                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 0); \
906                       if (e_port > 1024) \
907                         { \
908                           a->busy_##n##_ports--; \
909                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]--; \
910                         } \
911                       break;
912                       foreach_snat_protocol
913 #undef _
914                     default:
915                       clib_warning("unknown_protocol");
916                       return VNET_API_ERROR_INVALID_VALUE_2;
917                     }
918                   break;
919                 }
920             }
921         }
922
923       if (sm->num_workers > 1)
924         tsm = vec_elt_at_index (sm->per_thread_data, m->worker_index);
925       else
926         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
927
928       m_key.addr = m->local_addr;
929       m_key.port = m->local_port;
930       m_key.protocol = m->proto;
931       m_key.fib_index = m->fib_index;
932       kv.key = m_key.as_u64;
933       if (!out2in_only)
934         clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 0);
935       if (twice_nat || out2in_only)
936         {
937           m_key.port = clib_host_to_net_u16 (m->local_port);
938           kv.key = m_key.as_u64;
939           kv.value = ~0ULL;
940           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 0))
941             clib_warning ("in2out key del failed");
942         }
943
944       m_key.addr = m->external_addr;
945       m_key.port = m->external_port;
946       m_key.fib_index = sm->outside_fib_index;
947       kv.key = m_key.as_u64;
948       clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 0);
949       if (twice_nat || out2in_only)
950         {
951           m_key.port = clib_host_to_net_u16 (m->external_port);
952           kv.key = m_key.as_u64;
953           kv.value = ~0ULL;
954           if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 0))
955             clib_warning ("in2out key del failed");
956         }
957
958       /* Delete session(s) for static mapping if exist */
959       if (!(sm->static_mapping_only) ||
960           (sm->static_mapping_only && sm->static_mapping_connection_tracking))
961         {
962           u_key.addr = m->local_addr;
963           u_key.fib_index = m->fib_index;
964           kv.key = u_key.as_u64;
965           if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
966             {
967               user_index = value.value;
968               u = pool_elt_at_index (tsm->users, user_index);
969               if (u->nstaticsessions)
970                 {
971                   head_index = u->sessions_per_user_list_head_index;
972                   head = pool_elt_at_index (tsm->list_pool, head_index);
973                   elt_index = head->next;
974                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
975                   ses_index = elt->value;
976                   while (ses_index != ~0)
977                     {
978                       s =  pool_elt_at_index (tsm->sessions, ses_index);
979                       elt = pool_elt_at_index (tsm->list_pool, elt->next);
980                       ses_index = elt->value;
981
982                       if (!addr_only)
983                         {
984                           if ((s->out2in.addr.as_u32 != e_addr.as_u32) &&
985                               (clib_net_to_host_u16 (s->out2in.port) != e_port))
986                             continue;
987                         }
988
989                       nat_free_session_data (sm, s, tsm - sm->per_thread_data);
990                       clib_dlist_remove (tsm->list_pool, s->per_user_index);
991                       pool_put_index (tsm->list_pool, s->per_user_index);
992                       pool_put (tsm->sessions, s);
993                       u->nstaticsessions--;
994
995                       if (!addr_only)
996                         break;
997                     }
998                   if (addr_only)
999                     {
1000                       pool_put (tsm->users, u);
1001                       clib_bihash_add_del_8_8 (&tsm->user_hash, &kv, 0);
1002                     }
1003                 }
1004             }
1005         }
1006
1007       vec_free (m->tag);
1008       /* Delete static mapping from pool */
1009       pool_put (sm->static_mappings, m);
1010     }
1011
1012   if (!addr_only || (l_addr.as_u32 == e_addr.as_u32))
1013     return 0;
1014
1015   /* Add/delete external address to FIB */
1016   pool_foreach (interface, sm->interfaces,
1017   ({
1018     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1019       continue;
1020
1021     snat_add_del_addr_to_fib(&e_addr, 32, interface->sw_if_index, is_add);
1022     break;
1023   }));
1024   pool_foreach (interface, sm->output_feature_interfaces,
1025   ({
1026     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1027       continue;
1028
1029     snat_add_del_addr_to_fib(&e_addr, 32, interface->sw_if_index, is_add);
1030     break;
1031   }));
1032
1033   return 0;
1034 }
1035
1036 int nat44_add_del_lb_static_mapping (ip4_address_t e_addr, u16 e_port,
1037                                      snat_protocol_t proto, u32 vrf_id,
1038                                      nat44_lb_addr_port_t *locals, u8 is_add,
1039                                      u8 twice_nat, u8 out2in_only, u8 *tag)
1040 {
1041   snat_main_t * sm = &snat_main;
1042   snat_static_mapping_t *m;
1043   snat_session_key_t m_key;
1044   clib_bihash_kv_8_8_t kv, value;
1045   u32 fib_index;
1046   snat_address_t *a = 0;
1047   int i;
1048   nat44_lb_addr_port_t *local;
1049   u32 worker_index = 0, elt_index, head_index, ses_index;
1050   snat_main_per_thread_data_t *tsm;
1051   snat_user_key_t u_key;
1052   snat_user_t *u;
1053   snat_session_t * s;
1054   dlist_elt_t * head, * elt;
1055
1056   m_key.addr = e_addr;
1057   m_key.port = e_port;
1058   m_key.protocol = proto;
1059   m_key.fib_index = sm->outside_fib_index;
1060   kv.key = m_key.as_u64;
1061   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
1062     m = 0;
1063   else
1064     m = pool_elt_at_index (sm->static_mappings, value.value);
1065
1066   if (is_add)
1067     {
1068       if (m)
1069         return VNET_API_ERROR_VALUE_EXIST;
1070
1071       if (vec_len (locals) < 2)
1072         return VNET_API_ERROR_INVALID_VALUE;
1073
1074       fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
1075                                                      vrf_id,
1076                                                      FIB_SOURCE_PLUGIN_HI);
1077
1078       /* Find external address in allocated addresses and reserve port for
1079          address and port pair mapping when dynamic translations enabled */
1080       if (!(sm->static_mapping_only || out2in_only))
1081         {
1082           for (i = 0; i < vec_len (sm->addresses); i++)
1083             {
1084               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1085                 {
1086                   a = sm->addresses + i;
1087                   /* External port must be unused */
1088                   switch (proto)
1089                     {
1090 #define _(N, j, n, s) \
1091                     case SNAT_PROTOCOL_##N: \
1092                       if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, e_port)) \
1093                         return VNET_API_ERROR_INVALID_VALUE; \
1094                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 1); \
1095                       if (e_port > 1024) \
1096                         { \
1097                           a->busy_##n##_ports++; \
1098                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]++; \
1099                         } \
1100                       break;
1101                       foreach_snat_protocol
1102 #undef _
1103                     default:
1104                       clib_warning("unknown_protocol");
1105                       return VNET_API_ERROR_INVALID_VALUE_2;
1106                     }
1107                   break;
1108                 }
1109             }
1110           /* External address must be allocated */
1111           if (!a)
1112             return VNET_API_ERROR_NO_SUCH_ENTRY;
1113         }
1114
1115       pool_get (sm->static_mappings, m);
1116       memset (m, 0, sizeof (*m));
1117       m->tag = vec_dup (tag);
1118       m->external_addr = e_addr;
1119       m->addr_only = 0;
1120       m->vrf_id = vrf_id;
1121       m->fib_index = fib_index;
1122       m->external_port = e_port;
1123       m->proto = proto;
1124       m->twice_nat = twice_nat;
1125       m->out2in_only = out2in_only;
1126
1127       m_key.addr = m->external_addr;
1128       m_key.port = m->external_port;
1129       m_key.protocol = m->proto;
1130       m_key.fib_index = sm->outside_fib_index;
1131       kv.key = m_key.as_u64;
1132       kv.value = m - sm->static_mappings;
1133       if (clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 1))
1134         {
1135           clib_warning ("static_mapping_by_external key add failed");
1136           return VNET_API_ERROR_UNSPECIFIED;
1137         }
1138
1139       /* Assign worker */
1140       if (sm->workers)
1141         {
1142           worker_index = sm->first_worker_index +
1143             sm->workers[sm->next_worker++ % vec_len (sm->workers)];
1144           tsm = vec_elt_at_index (sm->per_thread_data, worker_index);
1145           m->worker_index = worker_index;
1146         }
1147       else
1148         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1149
1150       m_key.port = clib_host_to_net_u16 (m->external_port);
1151       kv.key = m_key.as_u64;
1152       kv.value = ~0ULL;
1153       if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 1))
1154         {
1155           clib_warning ("out2in key add failed");
1156           return VNET_API_ERROR_UNSPECIFIED;
1157         }
1158
1159       m_key.fib_index = m->fib_index;
1160       for (i = 0; i < vec_len (locals); i++)
1161         {
1162           m_key.addr = locals[i].addr;
1163           if (!out2in_only)
1164             {
1165               m_key.port = locals[i].port;
1166               kv.key = m_key.as_u64;
1167               kv.value = m - sm->static_mappings;
1168               clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 1);
1169             }
1170           locals[i].prefix = (i == 0) ? locals[i].probability :\
1171             (locals[i - 1].prefix + locals[i].probability);
1172           vec_add1 (m->locals, locals[i]);
1173
1174           m_key.port = clib_host_to_net_u16 (locals[i].port);
1175           kv.key = m_key.as_u64;
1176           kv.value = ~0ULL;
1177           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 1))
1178             {
1179               clib_warning ("in2out key add failed");
1180               return VNET_API_ERROR_UNSPECIFIED;
1181             }
1182         }
1183     }
1184   else
1185     {
1186       if (!m)
1187         return VNET_API_ERROR_NO_SUCH_ENTRY;
1188
1189       fib_table_unlock (m->fib_index, FIB_PROTOCOL_IP4, FIB_SOURCE_PLUGIN_HI);
1190
1191       /* Free external address port */
1192       if (!(sm->static_mapping_only || out2in_only))
1193         {
1194           for (i = 0; i < vec_len (sm->addresses); i++)
1195             {
1196               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1197                 {
1198                   a = sm->addresses + i;
1199                   switch (proto)
1200                     {
1201 #define _(N, j, n, s) \
1202                     case SNAT_PROTOCOL_##N: \
1203                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 0); \
1204                       if (e_port > 1024) \
1205                         { \
1206                           a->busy_##n##_ports--; \
1207                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]--; \
1208                         } \
1209                       break;
1210                       foreach_snat_protocol
1211 #undef _
1212                     default:
1213                       clib_warning("unknown_protocol");
1214                       return VNET_API_ERROR_INVALID_VALUE_2;
1215                     }
1216                   break;
1217                 }
1218             }
1219         }
1220
1221       tsm = vec_elt_at_index (sm->per_thread_data, m->worker_index);
1222       m_key.addr = m->external_addr;
1223       m_key.port = m->external_port;
1224       m_key.protocol = m->proto;
1225       m_key.fib_index = sm->outside_fib_index;
1226       kv.key = m_key.as_u64;
1227       if (clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 0))
1228         {
1229           clib_warning ("static_mapping_by_external key del failed");
1230           return VNET_API_ERROR_UNSPECIFIED;
1231         }
1232
1233       m_key.port = clib_host_to_net_u16 (m->external_port);
1234       kv.key = m_key.as_u64;
1235       if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 0))
1236         {
1237           clib_warning ("outi2in key del failed");
1238           return VNET_API_ERROR_UNSPECIFIED;
1239         }
1240
1241       vec_foreach (local, m->locals)
1242         {
1243           m_key.addr = local->addr;
1244           if (!out2in_only)
1245             {
1246               m_key.port = local->port;
1247               m_key.fib_index = m->fib_index;
1248               kv.key = m_key.as_u64;
1249               if (clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 0))
1250                 {
1251                   clib_warning ("static_mapping_by_local key del failed");
1252                   return VNET_API_ERROR_UNSPECIFIED;
1253                 }
1254             }
1255
1256           m_key.port = clib_host_to_net_u16 (local->port);
1257           kv.key = m_key.as_u64;
1258           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 0))
1259             {
1260               clib_warning ("in2out key del failed");
1261               return VNET_API_ERROR_UNSPECIFIED;
1262             }
1263           /* Delete sessions */
1264           u_key.addr = local->addr;
1265           u_key.fib_index = m->fib_index;
1266           kv.key = u_key.as_u64;
1267           if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
1268             {
1269               u = pool_elt_at_index (tsm->users, value.value);
1270               if (u->nstaticsessions)
1271                 {
1272                   head_index = u->sessions_per_user_list_head_index;
1273                   head = pool_elt_at_index (tsm->list_pool, head_index);
1274                   elt_index = head->next;
1275                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
1276                   ses_index = elt->value;
1277                   while (ses_index != ~0)
1278                     {
1279                       s =  pool_elt_at_index (tsm->sessions, ses_index);
1280                       elt = pool_elt_at_index (tsm->list_pool, elt->next);
1281                       ses_index = elt->value;
1282
1283                       if ((s->in2out.addr.as_u32 != local->addr.as_u32) &&
1284                           (clib_net_to_host_u16 (s->in2out.port) != local->port))
1285                         continue;
1286
1287                       nat_free_session_data (sm, s, tsm - sm->per_thread_data);
1288                       clib_dlist_remove (tsm->list_pool, s->per_user_index);
1289                       pool_put_index (tsm->list_pool, s->per_user_index);
1290                       pool_put (tsm->sessions, s);
1291                       u->nstaticsessions--;
1292                     }
1293                 }
1294             }
1295         }
1296       vec_free(m->locals);
1297       vec_free(m->tag);
1298
1299       pool_put (sm->static_mappings, m);
1300     }
1301
1302   return 0;
1303 }
1304
1305 int
1306 snat_del_address (snat_main_t *sm, ip4_address_t addr, u8 delete_sm,
1307                   u8 twice_nat)
1308 {
1309   snat_address_t *a = 0;
1310   snat_session_t *ses;
1311   u32 *ses_to_be_removed = 0, *ses_index;
1312   clib_bihash_kv_8_8_t kv, value;
1313   snat_user_key_t user_key;
1314   snat_user_t *u;
1315   snat_main_per_thread_data_t *tsm;
1316   snat_static_mapping_t *m;
1317   snat_interface_t *interface;
1318   int i;
1319   snat_address_t *addresses = twice_nat ? sm->twice_nat_addresses : sm->addresses;
1320
1321   /* Find SNAT address */
1322   for (i=0; i < vec_len (addresses); i++)
1323     {
1324       if (addresses[i].addr.as_u32 == addr.as_u32)
1325         {
1326           a = addresses + i;
1327           break;
1328         }
1329     }
1330   if (!a)
1331     return VNET_API_ERROR_NO_SUCH_ENTRY;
1332
1333   if (delete_sm)
1334     {
1335       pool_foreach (m, sm->static_mappings,
1336       ({
1337           if (m->external_addr.as_u32 == addr.as_u32)
1338             (void) snat_add_static_mapping (m->local_addr, m->external_addr,
1339                                             m->local_port, m->external_port,
1340                                             m->vrf_id, m->addr_only, ~0,
1341                                             m->proto, 0, m->twice_nat,
1342                                             m->out2in_only, m->tag);
1343       }));
1344     }
1345   else
1346     {
1347       /* Check if address is used in some static mapping */
1348       if (is_snat_address_used_in_static_mapping(sm, addr))
1349         {
1350           clib_warning ("address used in static mapping");
1351           return VNET_API_ERROR_UNSPECIFIED;
1352         }
1353     }
1354
1355   if (a->fib_index != ~0)
1356     fib_table_unlock(a->fib_index, FIB_PROTOCOL_IP4,
1357                      FIB_SOURCE_PLUGIN_HI);
1358
1359   /* Delete sessions using address */
1360   if (a->busy_tcp_ports || a->busy_udp_ports || a->busy_icmp_ports)
1361     {
1362       vec_foreach (tsm, sm->per_thread_data)
1363         {
1364           pool_foreach (ses, tsm->sessions, ({
1365             if (ses->out2in.addr.as_u32 == addr.as_u32)
1366               {
1367                 ses->outside_address_index = ~0;
1368                 nat_free_session_data (sm, ses, tsm - sm->per_thread_data);
1369                 clib_dlist_remove (tsm->list_pool, ses->per_user_index);
1370                 pool_put_index (tsm->list_pool, ses->per_user_index);
1371                 vec_add1 (ses_to_be_removed, ses - tsm->sessions);
1372                 user_key.addr = ses->in2out.addr;
1373                 user_key.fib_index = ses->in2out.fib_index;
1374                 kv.key = user_key.as_u64;
1375                 if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
1376                   {
1377                     u = pool_elt_at_index (tsm->users, value.value);
1378                     u->nsessions--;
1379                   }
1380               }
1381           }));
1382
1383           vec_foreach (ses_index, ses_to_be_removed)
1384             pool_put_index (tsm->sessions, ses_index[0]);
1385
1386           vec_free (ses_to_be_removed);
1387        }
1388     }
1389
1390   if (twice_nat)
1391     {
1392       vec_del1 (sm->twice_nat_addresses, i);
1393       return 0;
1394     }
1395   else
1396     vec_del1 (sm->addresses, i);
1397
1398   /* Delete external address from FIB */
1399   pool_foreach (interface, sm->interfaces,
1400   ({
1401     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1402       continue;
1403
1404     snat_add_del_addr_to_fib(&addr, 32, interface->sw_if_index, 0);
1405     break;
1406   }));
1407   pool_foreach (interface, sm->output_feature_interfaces,
1408   ({
1409     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1410       continue;
1411
1412     snat_add_del_addr_to_fib(&addr, 32, interface->sw_if_index, 0);
1413     break;
1414   }));
1415
1416   return 0;
1417 }
1418
1419 int snat_interface_add_del (u32 sw_if_index, u8 is_inside, int is_del)
1420 {
1421   snat_main_t *sm = &snat_main;
1422   snat_interface_t *i;
1423   const char * feature_name, *del_feature_name;
1424   snat_address_t * ap;
1425   snat_static_mapping_t * m;
1426   snat_det_map_t * dm;
1427
1428   if (sm->out2in_dpo && !is_inside)
1429     return VNET_API_ERROR_UNSUPPORTED;
1430
1431   if (sm->static_mapping_only && !(sm->static_mapping_connection_tracking))
1432     feature_name = is_inside ?  "nat44-in2out-fast" : "nat44-out2in-fast";
1433   else
1434     {
1435       if (sm->num_workers > 1 && !sm->deterministic)
1436         feature_name = is_inside ?  "nat44-in2out-worker-handoff" : "nat44-out2in-worker-handoff";
1437       else if (sm->deterministic)
1438         feature_name = is_inside ?  "nat44-det-in2out" : "nat44-det-out2in";
1439       else
1440         feature_name = is_inside ?  "nat44-in2out" : "nat44-out2in";
1441     }
1442
1443   if (sm->fq_in2out_index == ~0 && !sm->deterministic && sm->num_workers > 1)
1444     sm->fq_in2out_index = vlib_frame_queue_main_init (sm->in2out_node_index, 0);
1445
1446   if (sm->fq_out2in_index == ~0 && !sm->deterministic && sm->num_workers > 1)
1447     sm->fq_out2in_index = vlib_frame_queue_main_init (sm->out2in_node_index, 0);
1448
1449   pool_foreach (i, sm->interfaces,
1450   ({
1451     if (i->sw_if_index == sw_if_index)
1452       {
1453         if (is_del)
1454           {
1455             if (nat_interface_is_inside(i) && nat_interface_is_outside(i))
1456               {
1457                 if (is_inside)
1458                   i->flags &= ~NAT_INTERFACE_FLAG_IS_INSIDE;
1459                 else
1460                   i->flags &= ~NAT_INTERFACE_FLAG_IS_OUTSIDE;
1461
1462                 if (sm->num_workers > 1 && !sm->deterministic)
1463                   {
1464                     del_feature_name = "nat44-handoff-classify";
1465                     feature_name = !is_inside ?  "nat44-in2out-worker-handoff" :
1466                                                  "nat44-out2in-worker-handoff";
1467                   }
1468                 else if (sm->deterministic)
1469                   {
1470                     del_feature_name = "nat44-det-classify";
1471                     feature_name = !is_inside ?  "nat44-det-in2out" :
1472                                                  "nat44-det-out2in";
1473                   }
1474                 else
1475                   {
1476                     del_feature_name = "nat44-classify";
1477                     feature_name = !is_inside ?  "nat44-in2out" : "nat44-out2in";
1478                   }
1479
1480                 vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1481                                              sw_if_index, 0, 0, 0);
1482                 vnet_feature_enable_disable ("ip4-unicast", feature_name,
1483                                              sw_if_index, 1, 0, 0);
1484               }
1485             else
1486               {
1487                 vnet_feature_enable_disable ("ip4-unicast", feature_name,
1488                                              sw_if_index, 0, 0, 0);
1489                 pool_put (sm->interfaces, i);
1490               }
1491           }
1492         else
1493           {
1494             if ((nat_interface_is_inside(i) && is_inside) ||
1495                 (nat_interface_is_outside(i) && !is_inside))
1496               return 0;
1497
1498             if (sm->num_workers > 1 && !sm->deterministic)
1499               {
1500                 del_feature_name = !is_inside ?  "nat44-in2out-worker-handoff" :
1501                                                  "nat44-out2in-worker-handoff";
1502                 feature_name = "nat44-handoff-classify";
1503               }
1504             else if (sm->deterministic)
1505               {
1506                 del_feature_name = !is_inside ?  "nat44-det-in2out" :
1507                                                  "nat44-det-out2in";
1508                 feature_name = "nat44-det-classify";
1509               }
1510             else
1511               {
1512                 del_feature_name = !is_inside ?  "nat44-in2out" : "nat44-out2in";
1513                 feature_name = "nat44-classify";
1514               }
1515
1516             vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1517                                          sw_if_index, 0, 0, 0);
1518             vnet_feature_enable_disable ("ip4-unicast", feature_name,
1519                                          sw_if_index, 1, 0, 0);
1520             goto set_flags;
1521           }
1522
1523         goto fib;
1524       }
1525   }));
1526
1527   if (is_del)
1528     return VNET_API_ERROR_NO_SUCH_ENTRY;
1529
1530   pool_get (sm->interfaces, i);
1531   i->sw_if_index = sw_if_index;
1532   i->flags = 0;
1533   vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index, 1, 0, 0);
1534
1535 set_flags:
1536   if (is_inside)
1537     i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
1538   else
1539     i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
1540
1541   /* Add/delete external addresses to FIB */
1542 fib:
1543   if (is_inside && !sm->out2in_dpo)
1544     {
1545       vnet_feature_enable_disable ("ip4-local", "nat44-hairpinning",
1546                                    sw_if_index, !is_del, 0, 0);
1547       return 0;
1548     }
1549
1550   vec_foreach (ap, sm->addresses)
1551     snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, !is_del);
1552
1553   pool_foreach (m, sm->static_mappings,
1554   ({
1555     if (!(m->addr_only) || (m->local_addr.as_u32 == m->external_addr.as_u32))
1556       continue;
1557
1558     snat_add_del_addr_to_fib(&m->external_addr, 32, sw_if_index, !is_del);
1559   }));
1560
1561   pool_foreach (dm, sm->det_maps,
1562   ({
1563     snat_add_del_addr_to_fib(&dm->out_addr, dm->out_plen, sw_if_index, !is_del);
1564   }));
1565
1566   return 0;
1567 }
1568
1569 int snat_interface_add_del_output_feature (u32 sw_if_index,
1570                                            u8 is_inside,
1571                                            int is_del)
1572 {
1573   snat_main_t *sm = &snat_main;
1574   snat_interface_t *i;
1575   snat_address_t * ap;
1576   snat_static_mapping_t * m;
1577
1578   if (sm->deterministic ||
1579       (sm->static_mapping_only && !(sm->static_mapping_connection_tracking)))
1580     return VNET_API_ERROR_UNSUPPORTED;
1581
1582   if (is_inside)
1583     {
1584       vnet_feature_enable_disable ("ip4-unicast", "nat44-hairpin-dst",
1585                                    sw_if_index, !is_del, 0, 0);
1586       vnet_feature_enable_disable ("ip4-output", "nat44-hairpin-src",
1587                                    sw_if_index, !is_del, 0, 0);
1588       goto fq;
1589     }
1590
1591   if (sm->num_workers > 1)
1592     {
1593       vnet_feature_enable_disable ("ip4-unicast", "nat44-out2in-worker-handoff",
1594                                    sw_if_index, !is_del, 0, 0);
1595       vnet_feature_enable_disable ("ip4-output",
1596                                    "nat44-in2out-output-worker-handoff",
1597                                    sw_if_index, !is_del, 0, 0);
1598     }
1599   else
1600     {
1601       vnet_feature_enable_disable ("ip4-unicast", "nat44-out2in", sw_if_index,
1602                                    !is_del, 0, 0);
1603       vnet_feature_enable_disable ("ip4-output", "nat44-in2out-output",
1604                                    sw_if_index, !is_del, 0, 0);
1605     }
1606
1607 fq:
1608   if (sm->fq_in2out_output_index == ~0 && sm->num_workers > 1)
1609     sm->fq_in2out_output_index =
1610       vlib_frame_queue_main_init (sm->in2out_output_node_index, 0);
1611
1612   if (sm->fq_out2in_index == ~0 && sm->num_workers > 1)
1613     sm->fq_out2in_index = vlib_frame_queue_main_init (sm->out2in_node_index, 0);
1614
1615   pool_foreach (i, sm->output_feature_interfaces,
1616   ({
1617     if (i->sw_if_index == sw_if_index)
1618       {
1619         if (is_del)
1620           pool_put (sm->output_feature_interfaces, i);
1621         else
1622           return VNET_API_ERROR_VALUE_EXIST;
1623
1624         goto fib;
1625       }
1626   }));
1627
1628   if (is_del)
1629     return VNET_API_ERROR_NO_SUCH_ENTRY;
1630
1631   pool_get (sm->output_feature_interfaces, i);
1632   i->sw_if_index = sw_if_index;
1633   i->flags = 0;
1634   if (is_inside)
1635     i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
1636   else
1637     i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
1638
1639   /* Add/delete external addresses to FIB */
1640 fib:
1641   if (is_inside)
1642     return 0;
1643
1644   vec_foreach (ap, sm->addresses)
1645     snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, !is_del);
1646
1647   pool_foreach (m, sm->static_mappings,
1648   ({
1649     if (!(m->addr_only))
1650       continue;
1651
1652     snat_add_del_addr_to_fib(&m->external_addr, 32, sw_if_index, !is_del);
1653   }));
1654
1655   return 0;
1656 }
1657
1658 int snat_set_workers (uword * bitmap)
1659 {
1660   snat_main_t *sm = &snat_main;
1661   int i, j = 0;
1662
1663   if (sm->num_workers < 2)
1664     return VNET_API_ERROR_FEATURE_DISABLED;
1665
1666   if (clib_bitmap_last_set (bitmap) >= sm->num_workers)
1667     return VNET_API_ERROR_INVALID_WORKER;
1668
1669   vec_free (sm->workers);
1670   clib_bitmap_foreach (i, bitmap,
1671     ({
1672       vec_add1(sm->workers, i);
1673       sm->per_thread_data[sm->first_worker_index + i].snat_thread_index = j;
1674       j++;
1675     }));
1676
1677   sm->port_per_thread = (0xffff - 1024) / _vec_len (sm->workers);
1678   sm->num_snat_thread = _vec_len (sm->workers);
1679
1680   return 0;
1681 }
1682
1683
1684 static void
1685 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
1686                                        uword opaque,
1687                                        u32 sw_if_index,
1688                                        ip4_address_t * address,
1689                                        u32 address_length,
1690                                        u32 if_address_index,
1691                                        u32 is_delete);
1692
1693 static int
1694 nat_alloc_addr_and_port_default (snat_address_t * addresses,
1695                                  u32 fib_index,
1696                                  u32 thread_index,
1697                                  snat_session_key_t * k,
1698                                  u32 * address_indexp,
1699                                  u16 port_per_thread,
1700                                  u32 snat_thread_index);
1701
1702 static clib_error_t * snat_init (vlib_main_t * vm)
1703 {
1704   snat_main_t * sm = &snat_main;
1705   clib_error_t * error = 0;
1706   ip4_main_t * im = &ip4_main;
1707   ip_lookup_main_t * lm = &im->lookup_main;
1708   uword *p;
1709   vlib_thread_registration_t *tr;
1710   vlib_thread_main_t *tm = vlib_get_thread_main ();
1711   uword *bitmap = 0;
1712   u32 i;
1713   ip4_add_del_interface_address_callback_t cb4;
1714
1715   sm->vlib_main = vm;
1716   sm->vnet_main = vnet_get_main();
1717   sm->ip4_main = im;
1718   sm->ip4_lookup_main = lm;
1719   sm->api_main = &api_main;
1720   sm->first_worker_index = 0;
1721   sm->next_worker = 0;
1722   sm->num_workers = 0;
1723   sm->num_snat_thread = 1;
1724   sm->workers = 0;
1725   sm->port_per_thread = 0xffff - 1024;
1726   sm->fq_in2out_index = ~0;
1727   sm->fq_out2in_index = ~0;
1728   sm->udp_timeout = SNAT_UDP_TIMEOUT;
1729   sm->tcp_established_timeout = SNAT_TCP_ESTABLISHED_TIMEOUT;
1730   sm->tcp_transitory_timeout = SNAT_TCP_TRANSITORY_TIMEOUT;
1731   sm->icmp_timeout = SNAT_ICMP_TIMEOUT;
1732   sm->alloc_addr_and_port = nat_alloc_addr_and_port_default;
1733   sm->forwarding_enabled = 0;
1734
1735   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
1736   if (p)
1737     {
1738       tr = (vlib_thread_registration_t *) p[0];
1739       if (tr)
1740         {
1741           sm->num_workers = tr->count;
1742           sm->first_worker_index = tr->first_index;
1743         }
1744     }
1745
1746   vec_validate (sm->per_thread_data, tm->n_vlib_mains - 1);
1747
1748   /* Use all available workers by default */
1749   if (sm->num_workers > 1)
1750     {
1751       for (i=0; i < sm->num_workers; i++)
1752         bitmap = clib_bitmap_set (bitmap, i, 1);
1753       snat_set_workers(bitmap);
1754       clib_bitmap_free (bitmap);
1755     }
1756   else
1757     {
1758       sm->per_thread_data[0].snat_thread_index = 0;
1759     }
1760
1761   error = snat_api_init(vm, sm);
1762   if (error)
1763     return error;
1764
1765   /* Set up the interface address add/del callback */
1766   cb4.function = snat_ip4_add_del_interface_address_cb;
1767   cb4.function_opaque = 0;
1768
1769   vec_add1 (im->add_del_interface_address_callbacks, cb4);
1770
1771   nat_dpo_module_init ();
1772
1773   /* Init IPFIX logging */
1774   snat_ipfix_logging_init(vm);
1775
1776   /* Init NAT64 */
1777   error = nat64_init(vm);
1778   if (error)
1779     return error;
1780
1781   dslite_init(vm);
1782
1783   nat66_init();
1784
1785   /* Init virtual fragmenentation reassembly */
1786   return nat_reass_init(vm);
1787 }
1788
1789 VLIB_INIT_FUNCTION (snat_init);
1790
1791 void snat_free_outside_address_and_port (snat_address_t * addresses,
1792                                          u32 thread_index,
1793                                          snat_session_key_t * k,
1794                                          u32 address_index)
1795 {
1796   snat_address_t *a;
1797   u16 port_host_byte_order = clib_net_to_host_u16 (k->port);
1798
1799   ASSERT (address_index < vec_len (addresses));
1800
1801   a = addresses + address_index;
1802
1803   switch (k->protocol)
1804     {
1805 #define _(N, i, n, s) \
1806     case SNAT_PROTOCOL_##N: \
1807       ASSERT (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, \
1808         port_host_byte_order) == 1); \
1809       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, \
1810         port_host_byte_order, 0); \
1811       a->busy_##n##_ports--; \
1812       a->busy_##n##_ports_per_thread[thread_index]--; \
1813       break;
1814       foreach_snat_protocol
1815 #undef _
1816     default:
1817       clib_warning("unknown_protocol");
1818       return;
1819     }
1820 }
1821
1822 /**
1823  * @brief Match NAT44 static mapping.
1824  *
1825  * @param sm          NAT main.
1826  * @param match       Address and port to match.
1827  * @param mapping     External or local address and port of the matched mapping.
1828  * @param by_external If 0 match by local address otherwise match by external
1829  *                    address.
1830  * @param is_addr_only If matched mapping is address only
1831  * @param twice_nat If matched mapping is twice NAT.
1832  *
1833  * @returns 0 if match found otherwise 1.
1834  */
1835 int snat_static_mapping_match (snat_main_t * sm,
1836                                snat_session_key_t match,
1837                                snat_session_key_t * mapping,
1838                                u8 by_external,
1839                                u8 *is_addr_only,
1840                                u8 *twice_nat)
1841 {
1842   clib_bihash_kv_8_8_t kv, value;
1843   snat_static_mapping_t *m;
1844   snat_session_key_t m_key;
1845   clib_bihash_8_8_t *mapping_hash = &sm->static_mapping_by_local;
1846   u32 rand, lo = 0, hi, mid;
1847
1848   if (by_external)
1849     mapping_hash = &sm->static_mapping_by_external;
1850
1851   m_key.addr = match.addr;
1852   m_key.port = clib_net_to_host_u16 (match.port);
1853   m_key.protocol = match.protocol;
1854   m_key.fib_index = match.fib_index;
1855
1856   kv.key = m_key.as_u64;
1857
1858   if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
1859     {
1860       /* Try address only mapping */
1861       m_key.port = 0;
1862       m_key.protocol = 0;
1863       kv.key = m_key.as_u64;
1864       if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
1865         return 1;
1866     }
1867
1868   m = pool_elt_at_index (sm->static_mappings, value.value);
1869
1870   if (by_external)
1871     {
1872       if (vec_len (m->locals))
1873         {
1874           hi = vec_len (m->locals) - 1;
1875           rand = 1 + (random_u32 (&sm->random_seed) % m->locals[hi].prefix);
1876           while (lo < hi)
1877             {
1878               mid = ((hi - lo) >> 1) + lo;
1879               (rand > m->locals[mid].prefix) ? (lo = mid + 1) : (hi = mid);
1880             }
1881           if (!(m->locals[lo].prefix >= rand))
1882             return 1;
1883           mapping->addr = m->locals[lo].addr;
1884           mapping->port = clib_host_to_net_u16 (m->locals[lo].port);
1885         }
1886       else
1887         {
1888           mapping->addr = m->local_addr;
1889           /* Address only mapping doesn't change port */
1890           mapping->port = m->addr_only ? match.port
1891             : clib_host_to_net_u16 (m->local_port);
1892         }
1893       mapping->fib_index = m->fib_index;
1894       mapping->protocol = m->proto;
1895     }
1896   else
1897     {
1898       mapping->addr = m->external_addr;
1899       /* Address only mapping doesn't change port */
1900       mapping->port = m->addr_only ? match.port
1901         : clib_host_to_net_u16 (m->external_port);
1902       mapping->fib_index = sm->outside_fib_index;
1903     }
1904
1905   if (PREDICT_FALSE(is_addr_only != 0))
1906     *is_addr_only = m->addr_only;
1907
1908   if (PREDICT_FALSE(twice_nat != 0))
1909     *twice_nat = m->twice_nat;
1910
1911   return 0;
1912 }
1913
1914 static_always_inline u16
1915 snat_random_port (u16 min, u16 max)
1916 {
1917   snat_main_t *sm = &snat_main;
1918   return min + random_u32 (&sm->random_seed) /
1919     (random_u32_max() / (max - min + 1) + 1);
1920 }
1921
1922 int
1923 snat_alloc_outside_address_and_port (snat_address_t * addresses,
1924                                      u32 fib_index,
1925                                      u32 thread_index,
1926                                      snat_session_key_t * k,
1927                                      u32 * address_indexp,
1928                                      u16 port_per_thread,
1929                                      u32 snat_thread_index)
1930 {
1931   snat_main_t *sm = &snat_main;
1932
1933   return sm->alloc_addr_and_port(addresses, fib_index, thread_index, k,
1934                                  address_indexp, port_per_thread,
1935                                  snat_thread_index);
1936 }
1937
1938 static int
1939 nat_alloc_addr_and_port_default (snat_address_t * addresses,
1940                                  u32 fib_index,
1941                                  u32 thread_index,
1942                                  snat_session_key_t * k,
1943                                  u32 * address_indexp,
1944                                  u16 port_per_thread,
1945                                  u32 snat_thread_index)
1946 {
1947   int i, gi = 0;
1948   snat_address_t *a, *ga = 0;
1949   u32 portnum;
1950
1951   for (i = 0; i < vec_len (addresses); i++)
1952     {
1953       a = addresses + i;
1954       switch (k->protocol)
1955         {
1956 #define _(N, j, n, s) \
1957         case SNAT_PROTOCOL_##N: \
1958           if (a->busy_##n##_ports_per_thread[thread_index] < port_per_thread) \
1959             { \
1960               if (a->fib_index == fib_index) \
1961                 { \
1962                   while (1) \
1963                     { \
1964                       portnum = (port_per_thread * \
1965                         snat_thread_index) + \
1966                         snat_random_port(1, port_per_thread) + 1024; \
1967                       if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, portnum)) \
1968                         continue; \
1969                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, portnum, 1); \
1970                       a->busy_##n##_ports_per_thread[thread_index]++; \
1971                       a->busy_##n##_ports++; \
1972                       k->addr = a->addr; \
1973                       k->port = clib_host_to_net_u16(portnum); \
1974                       *address_indexp = i; \
1975                       return 0; \
1976                     } \
1977                 } \
1978               else if (a->fib_index == ~0) \
1979                 { \
1980                   ga = a; \
1981                   gi = i; \
1982                 } \
1983             } \
1984           break;
1985           foreach_snat_protocol
1986 #undef _
1987         default:
1988           clib_warning("unknown protocol");
1989           return 1;
1990         }
1991
1992     }
1993
1994   if (ga)
1995     {
1996       a = ga;
1997       switch (k->protocol)
1998         {
1999 #define _(N, j, n, s) \
2000         case SNAT_PROTOCOL_##N: \
2001           while (1) \
2002             { \
2003               portnum = (port_per_thread * \
2004                 snat_thread_index) + \
2005                 snat_random_port(1, port_per_thread) + 1024; \
2006               if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, portnum)) \
2007                 continue; \
2008               clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, portnum, 1); \
2009               a->busy_##n##_ports_per_thread[thread_index]++; \
2010               a->busy_##n##_ports++; \
2011               k->addr = a->addr; \
2012               k->port = clib_host_to_net_u16(portnum); \
2013               *address_indexp = gi; \
2014               return 0; \
2015             }
2016           break;
2017           foreach_snat_protocol
2018 #undef _
2019         default:
2020           clib_warning ("unknown protocol");
2021           return 1;
2022         }
2023     }
2024
2025   /* Totally out of translations to use... */
2026   snat_ipfix_logging_addresses_exhausted(0);
2027   return 1;
2028 }
2029
2030 static int
2031 nat_alloc_addr_and_port_mape (snat_address_t * addresses,
2032                               u32 fib_index,
2033                               u32 thread_index,
2034                               snat_session_key_t * k,
2035                               u32 * address_indexp,
2036                               u16 port_per_thread,
2037                               u32 snat_thread_index)
2038 {
2039   snat_main_t *sm = &snat_main;
2040   snat_address_t *a = addresses;
2041   u16 m, ports, portnum, A, j;
2042   m = 16 - (sm->psid_offset + sm->psid_length);
2043   ports = (1 << (16 - sm->psid_length)) - (1 << m);
2044
2045   if (!vec_len (addresses))
2046     goto exhausted;
2047
2048   switch (k->protocol)
2049     {
2050 #define _(N, i, n, s) \
2051     case SNAT_PROTOCOL_##N: \
2052       if (a->busy_##n##_ports < ports) \
2053         { \
2054           while (1) \
2055             { \
2056               A = snat_random_port(1, pow2_mask(sm->psid_offset)); \
2057               j = snat_random_port(0, pow2_mask(m)); \
2058               portnum = A | (sm->psid << sm->psid_offset) | (j << (16 - m)); \
2059               if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, portnum)) \
2060                 continue; \
2061               clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, portnum, 1); \
2062               a->busy_##n##_ports++; \
2063               k->addr = a->addr; \
2064               k->port = clib_host_to_net_u16 (portnum); \
2065               *address_indexp = i; \
2066               return 0; \
2067             } \
2068         } \
2069       break;
2070       foreach_snat_protocol
2071 #undef _
2072     default:
2073       clib_warning("unknown protocol");
2074       return 1;
2075     }
2076
2077 exhausted:
2078   /* Totally out of translations to use... */
2079   snat_ipfix_logging_addresses_exhausted(0);
2080   return 1;
2081 }
2082
2083 void
2084 nat44_add_del_address_dpo (ip4_address_t addr, u8 is_add)
2085 {
2086   dpo_id_t dpo_v4 = DPO_INVALID;
2087   fib_prefix_t pfx = {
2088     .fp_proto = FIB_PROTOCOL_IP4,
2089     .fp_len = 32,
2090     .fp_addr.ip4.as_u32 = addr.as_u32,
2091   };
2092
2093   if (is_add)
2094     {
2095       nat_dpo_create (DPO_PROTO_IP4, 0, &dpo_v4);
2096       fib_table_entry_special_dpo_add (0, &pfx, FIB_SOURCE_PLUGIN_HI,
2097                                        FIB_ENTRY_FLAG_EXCLUSIVE, &dpo_v4);
2098       dpo_reset (&dpo_v4);
2099     }
2100   else
2101     {
2102       fib_table_entry_special_remove (0, &pfx, FIB_SOURCE_PLUGIN_HI);
2103     }
2104 }
2105
2106 uword
2107 unformat_snat_protocol (unformat_input_t * input, va_list * args)
2108 {
2109   u32 *r = va_arg (*args, u32 *);
2110
2111   if (0);
2112 #define _(N, i, n, s) else if (unformat (input, s)) *r = SNAT_PROTOCOL_##N;
2113   foreach_snat_protocol
2114 #undef _
2115   else
2116     return 0;
2117   return 1;
2118 }
2119
2120 u8 *
2121 format_snat_protocol (u8 * s, va_list * args)
2122 {
2123   u32 i = va_arg (*args, u32);
2124   u8 *t = 0;
2125
2126   switch (i)
2127     {
2128 #define _(N, j, n, str) case SNAT_PROTOCOL_##N: t = (u8 *) str; break;
2129       foreach_snat_protocol
2130 #undef _
2131     default:
2132       s = format (s, "unknown");
2133       return s;
2134     }
2135   s = format (s, "%s", t);
2136   return s;
2137 }
2138
2139 static u32
2140 snat_get_worker_in2out_cb (ip4_header_t * ip0, u32 rx_fib_index0)
2141 {
2142   snat_main_t *sm = &snat_main;
2143   u32 next_worker_index = 0;
2144   u32 hash;
2145
2146   next_worker_index = sm->first_worker_index;
2147   hash = ip0->src_address.as_u32 + (ip0->src_address.as_u32 >> 8) +
2148          (ip0->src_address.as_u32 >> 16) + (ip0->src_address.as_u32 >>24);
2149
2150   if (PREDICT_TRUE (is_pow2 (_vec_len (sm->workers))))
2151     next_worker_index += sm->workers[hash & (_vec_len (sm->workers) - 1)];
2152   else
2153     next_worker_index += sm->workers[hash % _vec_len (sm->workers)];
2154
2155   return next_worker_index;
2156 }
2157
2158 static u32
2159 snat_get_worker_out2in_cb (ip4_header_t * ip0, u32 rx_fib_index0)
2160 {
2161   snat_main_t *sm = &snat_main;
2162   udp_header_t *udp;
2163   u16 port;
2164   snat_session_key_t m_key;
2165   clib_bihash_kv_8_8_t kv, value;
2166   snat_static_mapping_t *m;
2167   nat_ed_ses_key_t key;
2168   clib_bihash_kv_16_8_t s_kv, s_value;
2169   snat_main_per_thread_data_t *tsm;
2170   snat_session_t *s;
2171   int i;
2172   u32 proto;
2173   u32 next_worker_index = 0;
2174
2175   /* first try static mappings without port */
2176   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
2177     {
2178       m_key.addr = ip0->dst_address;
2179       m_key.port = 0;
2180       m_key.protocol = 0;
2181       m_key.fib_index = rx_fib_index0;
2182       kv.key = m_key.as_u64;
2183       if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
2184         {
2185           m = pool_elt_at_index (sm->static_mappings, value.value);
2186           return m->worker_index;
2187         }
2188     }
2189
2190   proto = ip_proto_to_snat_proto (ip0->protocol);
2191   udp = ip4_next_header (ip0);
2192   port = udp->dst_port;
2193
2194   if (PREDICT_FALSE (ip4_is_fragment (ip0)))
2195     {
2196       if (PREDICT_FALSE (nat_reass_is_drop_frag (0)))
2197         return vlib_get_thread_index ();
2198
2199       if (PREDICT_TRUE (!ip4_is_first_fragment (ip0)))
2200         {
2201           nat_reass_ip4_t *reass;
2202
2203           reass = nat_ip4_reass_find (ip0->src_address, ip0->dst_address,
2204                                       ip0->fragment_id, ip0->protocol);
2205
2206           if (reass && (reass->thread_index != (u32) ~ 0))
2207             return reass->thread_index;
2208           else
2209             return vlib_get_thread_index ();
2210         }
2211     }
2212
2213   /* unknown protocol */
2214   if (PREDICT_FALSE (proto == ~0))
2215     {
2216       key.l_addr = ip0->dst_address;
2217       key.r_addr = ip0->src_address;
2218       key.fib_index = rx_fib_index0;
2219       key.proto = ip0->protocol;
2220       key.r_port = 0;
2221       key.l_port = 0;
2222       s_kv.key[0] = key.as_u64[0];
2223       s_kv.key[1] = key.as_u64[1];
2224
2225       if (!clib_bihash_search_16_8 (&sm->out2in_ed, &s_kv, &s_value))
2226         {
2227           for (i = 0; i < _vec_len (sm->per_thread_data); i++)
2228             {
2229               tsm = vec_elt_at_index (sm->per_thread_data, i);
2230               if (!pool_is_free_index(tsm->sessions, s_value.value))
2231                 {
2232                   s = pool_elt_at_index (tsm->sessions, s_value.value);
2233                   if (s->out2in.addr.as_u32 == ip0->dst_address.as_u32 &&
2234                       s->out2in.port == ip0->protocol &&
2235                       snat_is_unk_proto_session (s))
2236                     return i;
2237                 }
2238             }
2239          }
2240
2241       /* if no session use current thread */
2242       return vlib_get_thread_index ();
2243     }
2244
2245   if (PREDICT_FALSE (ip0->protocol == IP_PROTOCOL_ICMP))
2246     {
2247       icmp46_header_t * icmp = (icmp46_header_t *) udp;
2248       icmp_echo_header_t *echo = (icmp_echo_header_t *)(icmp + 1);
2249       if (!icmp_is_error_message (icmp))
2250         port = echo->identifier;
2251       else
2252         {
2253           ip4_header_t *inner_ip = (ip4_header_t *)(echo + 1);
2254           proto = ip_proto_to_snat_proto (inner_ip->protocol);
2255           void *l4_header = ip4_next_header (inner_ip);
2256           switch (proto)
2257             {
2258             case SNAT_PROTOCOL_ICMP:
2259               icmp = (icmp46_header_t*)l4_header;
2260               echo = (icmp_echo_header_t *)(icmp + 1);
2261               port = echo->identifier;
2262               break;
2263             case SNAT_PROTOCOL_UDP:
2264             case SNAT_PROTOCOL_TCP:
2265               port = ((tcp_udp_header_t*)l4_header)->src_port;
2266               break;
2267             default:
2268               return vlib_get_thread_index ();
2269             }
2270         }
2271     }
2272
2273   /* try static mappings with port */
2274   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
2275     {
2276       m_key.addr = ip0->dst_address;
2277       m_key.port = clib_net_to_host_u16 (port);
2278       m_key.protocol = proto;
2279       m_key.fib_index = rx_fib_index0;
2280       kv.key = m_key.as_u64;
2281       if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
2282         {
2283           m = pool_elt_at_index (sm->static_mappings, value.value);
2284           return m->worker_index;
2285         }
2286     }
2287
2288   /* worker by outside port */
2289   next_worker_index = sm->first_worker_index;
2290   next_worker_index +=
2291     sm->workers[(clib_net_to_host_u16 (port) - 1024) / sm->port_per_thread];
2292   return next_worker_index;
2293 }
2294
2295 static clib_error_t *
2296 snat_config (vlib_main_t * vm, unformat_input_t * input)
2297 {
2298   snat_main_t * sm = &snat_main;
2299   u32 translation_buckets = 1024;
2300   u32 translation_memory_size = 128<<20;
2301   u32 user_buckets = 128;
2302   u32 user_memory_size = 64<<20;
2303   u32 max_translations_per_user = 100;
2304   u32 outside_vrf_id = 0;
2305   u32 inside_vrf_id = 0;
2306   u32 static_mapping_buckets = 1024;
2307   u32 static_mapping_memory_size = 64<<20;
2308   u32 nat64_bib_buckets = 1024;
2309   u32 nat64_bib_memory_size = 128 << 20;
2310   u32 nat64_st_buckets = 2048;
2311   u32 nat64_st_memory_size = 256 << 20;
2312   u8 static_mapping_only = 0;
2313   u8 static_mapping_connection_tracking = 0;
2314   snat_main_per_thread_data_t *tsm;
2315   dslite_main_t * dm = &dslite_main;
2316
2317   sm->deterministic = 0;
2318   sm->out2in_dpo = 0;
2319
2320   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2321     {
2322       if (unformat (input, "translation hash buckets %d", &translation_buckets))
2323         ;
2324       else if (unformat (input, "translation hash memory %d",
2325                          &translation_memory_size));
2326       else if (unformat (input, "user hash buckets %d", &user_buckets))
2327         ;
2328       else if (unformat (input, "user hash memory %d",
2329                          &user_memory_size))
2330         ;
2331       else if (unformat (input, "max translations per user %d",
2332                          &max_translations_per_user))
2333         ;
2334       else if (unformat (input, "outside VRF id %d",
2335                          &outside_vrf_id))
2336         ;
2337       else if (unformat (input, "inside VRF id %d",
2338                          &inside_vrf_id))
2339         ;
2340       else if (unformat (input, "static mapping only"))
2341         {
2342           static_mapping_only = 1;
2343           if (unformat (input, "connection tracking"))
2344             static_mapping_connection_tracking = 1;
2345         }
2346       else if (unformat (input, "deterministic"))
2347         sm->deterministic = 1;
2348       else if (unformat (input, "nat64 bib hash buckets %d",
2349                          &nat64_bib_buckets))
2350         ;
2351       else if (unformat (input, "nat64 bib hash memory %d",
2352                          &nat64_bib_memory_size))
2353         ;
2354       else if (unformat (input, "nat64 st hash buckets %d", &nat64_st_buckets))
2355         ;
2356       else if (unformat (input, "nat64 st hash memory %d",
2357                          &nat64_st_memory_size))
2358         ;
2359       else if (unformat (input, "out2in dpo"))
2360         sm->out2in_dpo = 1;
2361       else if (unformat (input, "dslite ce"))
2362         dslite_set_ce(dm, 1);
2363       else
2364         return clib_error_return (0, "unknown input '%U'",
2365                                   format_unformat_error, input);
2366     }
2367
2368   /* for show commands, etc. */
2369   sm->translation_buckets = translation_buckets;
2370   sm->translation_memory_size = translation_memory_size;
2371   /* do not exceed load factor 10 */
2372   sm->max_translations = 10 * translation_buckets;
2373   sm->user_buckets = user_buckets;
2374   sm->user_memory_size = user_memory_size;
2375   sm->max_translations_per_user = max_translations_per_user;
2376   sm->outside_vrf_id = outside_vrf_id;
2377   sm->outside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
2378                                                              outside_vrf_id,
2379                                                              FIB_SOURCE_PLUGIN_HI);
2380   sm->inside_vrf_id = inside_vrf_id;
2381   sm->inside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
2382                                                             inside_vrf_id,
2383                                                             FIB_SOURCE_PLUGIN_HI);
2384   sm->static_mapping_only = static_mapping_only;
2385   sm->static_mapping_connection_tracking = static_mapping_connection_tracking;
2386
2387   nat64_set_hash(nat64_bib_buckets, nat64_bib_memory_size, nat64_st_buckets,
2388                  nat64_st_memory_size);
2389
2390   if (sm->deterministic)
2391     {
2392       sm->in2out_node_index = snat_det_in2out_node.index;
2393       sm->in2out_output_node_index = ~0;
2394       sm->out2in_node_index = snat_det_out2in_node.index;
2395       sm->icmp_match_in2out_cb = icmp_match_in2out_det;
2396       sm->icmp_match_out2in_cb = icmp_match_out2in_det;
2397     }
2398   else
2399     {
2400       sm->worker_in2out_cb = snat_get_worker_in2out_cb;
2401       sm->worker_out2in_cb = snat_get_worker_out2in_cb;
2402       sm->in2out_node_index = snat_in2out_node.index;
2403       sm->in2out_output_node_index = snat_in2out_output_node.index;
2404       sm->out2in_node_index = snat_out2in_node.index;
2405       if (!static_mapping_only ||
2406           (static_mapping_only && static_mapping_connection_tracking))
2407         {
2408           sm->icmp_match_in2out_cb = icmp_match_in2out_slow;
2409           sm->icmp_match_out2in_cb = icmp_match_out2in_slow;
2410
2411           vec_foreach (tsm, sm->per_thread_data)
2412             {
2413               clib_bihash_init_8_8 (&tsm->in2out, "in2out", translation_buckets,
2414                                     translation_memory_size);
2415
2416               clib_bihash_init_8_8 (&tsm->out2in, "out2in", translation_buckets,
2417                                     translation_memory_size);
2418
2419               clib_bihash_init_8_8 (&tsm->user_hash, "users", user_buckets,
2420                                     user_memory_size);
2421             }
2422
2423           clib_bihash_init_16_8 (&sm->in2out_ed, "in2out-ed",
2424                                  translation_buckets, translation_memory_size);
2425
2426           clib_bihash_init_16_8 (&sm->out2in_ed, "out2in-ed",
2427                                  translation_buckets, translation_memory_size);
2428         }
2429       else
2430         {
2431           sm->icmp_match_in2out_cb = icmp_match_in2out_fast;
2432           sm->icmp_match_out2in_cb = icmp_match_out2in_fast;
2433         }
2434       clib_bihash_init_8_8 (&sm->static_mapping_by_local,
2435                             "static_mapping_by_local", static_mapping_buckets,
2436                             static_mapping_memory_size);
2437
2438       clib_bihash_init_8_8 (&sm->static_mapping_by_external,
2439                             "static_mapping_by_external", static_mapping_buckets,
2440                             static_mapping_memory_size);
2441     }
2442
2443   return 0;
2444 }
2445
2446 VLIB_CONFIG_FUNCTION (snat_config, "nat");
2447
2448 u8 * format_snat_session_state (u8 * s, va_list * args)
2449 {
2450   u32 i = va_arg (*args, u32);
2451   u8 *t = 0;
2452
2453   switch (i)
2454     {
2455 #define _(v, N, str) case SNAT_SESSION_##N: t = (u8 *) str; break;
2456     foreach_snat_session_state
2457 #undef _
2458     default:
2459       t = format (t, "unknown");
2460     }
2461   s = format (s, "%s", t);
2462   return s;
2463 }
2464
2465 u8 * format_snat_key (u8 * s, va_list * args)
2466 {
2467   snat_session_key_t * key = va_arg (*args, snat_session_key_t *);
2468
2469   s = format (s, "%U proto %U port %d fib %d",
2470               format_ip4_address, &key->addr,
2471               format_snat_protocol, key->protocol,
2472               clib_net_to_host_u16 (key->port), key->fib_index);
2473   return s;
2474 }
2475
2476 u8 * format_snat_session (u8 * s, va_list * args)
2477 {
2478   snat_main_t * sm __attribute__((unused)) = va_arg (*args, snat_main_t *);
2479   snat_session_t * sess = va_arg (*args, snat_session_t *);
2480
2481   if (snat_is_unk_proto_session (sess))
2482     {
2483       s = format (s, "  i2o %U proto %u fib %u\n",
2484                   format_ip4_address, &sess->in2out.addr,
2485                   clib_net_to_host_u16 (sess->in2out.port),
2486                   sess->in2out.fib_index);
2487       s = format (s, "    o2i %U proto %u fib %u\n",
2488                   format_ip4_address, &sess->out2in.addr,
2489                   clib_net_to_host_u16 (sess->out2in.port),
2490                   sess->out2in.fib_index);
2491     }
2492   else
2493     {
2494       s = format (s, "  i2o %U\n", format_snat_key, &sess->in2out);
2495       s = format (s, "    o2i %U\n", format_snat_key, &sess->out2in);
2496     }
2497   if (is_twice_nat_session (sess))
2498     {
2499       s = format (s, "       external host o2i %U:%d i2o %U:%d\n",
2500                   format_ip4_address, &sess->ext_host_addr,
2501                   clib_net_to_host_u16 (sess->ext_host_port),
2502                   format_ip4_address, &sess->ext_host_nat_addr,
2503                   clib_net_to_host_u16 (sess->ext_host_nat_port));
2504     }
2505   else
2506     {
2507       if (sess->ext_host_addr.as_u32)
2508           s = format (s, "       external host %U\n",
2509                       format_ip4_address, &sess->ext_host_addr);
2510     }
2511   s = format (s, "       last heard %.2f\n", sess->last_heard);
2512   s = format (s, "       total pkts %d, total bytes %lld\n",
2513               sess->total_pkts, sess->total_bytes);
2514   if (snat_is_session_static (sess))
2515     s = format (s, "       static translation\n");
2516   else
2517     s = format (s, "       dynamic translation\n");
2518   if (sess->flags & SNAT_SESSION_FLAG_LOAD_BALANCING)
2519     s = format (s, "       load-balancing\n");
2520   if (is_twice_nat_session (sess))
2521     s = format (s, "       twice-nat\n");
2522
2523   return s;
2524 }
2525
2526 u8 * format_snat_user (u8 * s, va_list * args)
2527 {
2528   snat_main_per_thread_data_t * sm = va_arg (*args, snat_main_per_thread_data_t *);
2529   snat_user_t * u = va_arg (*args, snat_user_t *);
2530   int verbose = va_arg (*args, int);
2531   dlist_elt_t * head, * elt;
2532   u32 elt_index, head_index;
2533   u32 session_index;
2534   snat_session_t * sess;
2535
2536   s = format (s, "%U: %d dynamic translations, %d static translations\n",
2537               format_ip4_address, &u->addr, u->nsessions, u->nstaticsessions);
2538
2539   if (verbose == 0)
2540     return s;
2541
2542   if (u->nsessions || u->nstaticsessions)
2543     {
2544       head_index = u->sessions_per_user_list_head_index;
2545       head = pool_elt_at_index (sm->list_pool, head_index);
2546
2547       elt_index = head->next;
2548       elt = pool_elt_at_index (sm->list_pool, elt_index);
2549       session_index = elt->value;
2550
2551       while (session_index != ~0)
2552         {
2553           sess = pool_elt_at_index (sm->sessions, session_index);
2554
2555           s = format (s, "  %U\n", format_snat_session, sm, sess);
2556
2557           elt_index = elt->next;
2558           elt = pool_elt_at_index (sm->list_pool, elt_index);
2559           session_index = elt->value;
2560         }
2561     }
2562
2563   return s;
2564 }
2565
2566 u8 * format_snat_static_mapping (u8 * s, va_list * args)
2567 {
2568   snat_static_mapping_t *m = va_arg (*args, snat_static_mapping_t *);
2569   nat44_lb_addr_port_t *local;
2570
2571   if (m->addr_only)
2572       s = format (s, "local %U external %U vrf %d %s",
2573                   format_ip4_address, &m->local_addr,
2574                   format_ip4_address, &m->external_addr,
2575                   m->vrf_id, m->twice_nat ? "twice-nat" : "");
2576   else
2577    {
2578       if (vec_len (m->locals))
2579         {
2580           s = format (s, "%U vrf %d external %U:%d %s %s",
2581                       format_snat_protocol, m->proto,
2582                       m->vrf_id,
2583                       format_ip4_address, &m->external_addr, m->external_port,
2584                       m->twice_nat ? "twice-nat" : "",
2585                       m->out2in_only ? "out2in-only" : "");
2586           vec_foreach (local, m->locals)
2587             s = format (s, "\n  local %U:%d probability %d\%",
2588                         format_ip4_address, &local->addr, local->port,
2589                         local->probability);
2590         }
2591       else
2592         s = format (s, "%U local %U:%d external %U:%d vrf %d %s %s",
2593                     format_snat_protocol, m->proto,
2594                     format_ip4_address, &m->local_addr, m->local_port,
2595                     format_ip4_address, &m->external_addr, m->external_port,
2596                     m->vrf_id, m->twice_nat ? "twice-nat" : "",
2597                     m->out2in_only ? "out2in-only" : "");
2598    }
2599   return s;
2600 }
2601
2602 u8 * format_snat_static_map_to_resolve (u8 * s, va_list * args)
2603 {
2604   snat_static_map_resolve_t *m = va_arg (*args, snat_static_map_resolve_t *);
2605   vnet_main_t *vnm = vnet_get_main();
2606
2607   if (m->addr_only)
2608       s = format (s, "local %U external %U vrf %d",
2609                   format_ip4_address, &m->l_addr,
2610                   format_vnet_sw_if_index_name, vnm, m->sw_if_index,
2611                   m->vrf_id);
2612   else
2613       s = format (s, "%U local %U:%d external %U:%d vrf %d",
2614                   format_snat_protocol, m->proto,
2615                   format_ip4_address, &m->l_addr, m->l_port,
2616                   format_vnet_sw_if_index_name, vnm, m->sw_if_index,
2617                   m->e_port, m->vrf_id);
2618
2619   return s;
2620 }
2621
2622 u8 * format_det_map_ses (u8 * s, va_list * args)
2623 {
2624   snat_det_map_t * det_map = va_arg (*args, snat_det_map_t *);
2625   ip4_address_t in_addr, out_addr;
2626   u32 in_offset, out_offset;
2627   snat_det_session_t * ses = va_arg (*args, snat_det_session_t *);
2628   u32 * i = va_arg (*args, u32 *);
2629
2630   u32 user_index = *i / SNAT_DET_SES_PER_USER;
2631   in_addr.as_u32 = clib_host_to_net_u32 (
2632     clib_net_to_host_u32(det_map->in_addr.as_u32) + user_index);
2633   in_offset = clib_net_to_host_u32(in_addr.as_u32) -
2634     clib_net_to_host_u32(det_map->in_addr.as_u32);
2635   out_offset = in_offset / det_map->sharing_ratio;
2636   out_addr.as_u32 = clib_host_to_net_u32(
2637     clib_net_to_host_u32(det_map->out_addr.as_u32) + out_offset);
2638   s = format (s, "in %U:%d out %U:%d external host %U:%d state: %U expire: %d\n",
2639               format_ip4_address, &in_addr,
2640               clib_net_to_host_u16 (ses->in_port),
2641               format_ip4_address, &out_addr,
2642               clib_net_to_host_u16 (ses->out.out_port),
2643               format_ip4_address, &ses->out.ext_host_addr,
2644               clib_net_to_host_u16 (ses->out.ext_host_port),
2645               format_snat_session_state, ses->state,
2646               ses->expire);
2647
2648   return s;
2649 }
2650
2651 static void
2652 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
2653                                        uword opaque,
2654                                        u32 sw_if_index,
2655                                        ip4_address_t * address,
2656                                        u32 address_length,
2657                                        u32 if_address_index,
2658                                        u32 is_delete)
2659 {
2660   snat_main_t *sm = &snat_main;
2661   snat_static_map_resolve_t *rp;
2662   u32 *indices_to_delete = 0;
2663   ip4_address_t l_addr;
2664   int i, j;
2665   int rv;
2666   u8 twice_nat = 0;
2667   snat_address_t *addresses = sm->addresses;
2668
2669   for (i = 0; i < vec_len(sm->auto_add_sw_if_indices); i++)
2670     {
2671       if (sw_if_index == sm->auto_add_sw_if_indices[i])
2672           goto match;
2673     }
2674
2675   for (i = 0; i < vec_len(sm->auto_add_sw_if_indices_twice_nat); i++)
2676     {
2677       twice_nat = 1;
2678       addresses = sm->twice_nat_addresses;
2679       if (sw_if_index == sm->auto_add_sw_if_indices_twice_nat[i])
2680           goto match;
2681     }
2682
2683   return;
2684
2685 match:
2686   if (!is_delete)
2687     {
2688       /* Don't trip over lease renewal, static config */
2689       for (j = 0; j < vec_len(addresses); j++)
2690         if (addresses[j].addr.as_u32 == address->as_u32)
2691           return;
2692
2693       snat_add_address (sm, address, ~0, twice_nat);
2694       /* Scan static map resolution vector */
2695       for (j = 0; j < vec_len (sm->to_resolve); j++)
2696         {
2697           rp = sm->to_resolve + j;
2698           /* On this interface? */
2699           if (rp->sw_if_index == sw_if_index)
2700             {
2701               /* Indetity mapping? */
2702               if (rp->l_addr.as_u32 == 0)
2703                 l_addr.as_u32 = address[0].as_u32;
2704               else
2705                 l_addr.as_u32 = rp->l_addr.as_u32;
2706               /* Add the static mapping */
2707               rv = snat_add_static_mapping (l_addr,
2708                                             address[0],
2709                                             rp->l_port,
2710                                             rp->e_port,
2711                                             rp->vrf_id,
2712                                             rp->addr_only,
2713                                             ~0 /* sw_if_index */,
2714                                             rp->proto,
2715                                             rp->is_add,
2716                                             0, 0, rp->tag);
2717               if (rv)
2718                 clib_warning ("snat_add_static_mapping returned %d",
2719                               rv);
2720               vec_free (rp->tag);
2721               vec_add1 (indices_to_delete, j);
2722             }
2723         }
2724       /* If we resolved any of the outstanding static mappings */
2725       if (vec_len(indices_to_delete))
2726         {
2727           /* Delete them */
2728           for (j = vec_len(indices_to_delete)-1; j >= 0; j--)
2729             vec_delete(sm->to_resolve, 1, j);
2730           vec_free(indices_to_delete);
2731         }
2732       return;
2733     }
2734   else
2735     {
2736       (void) snat_del_address(sm, address[0], 1, twice_nat);
2737       return;
2738     }
2739 }
2740
2741
2742 int snat_add_interface_address (snat_main_t *sm, u32 sw_if_index, int is_del,
2743                                 u8 twice_nat)
2744 {
2745   ip4_main_t * ip4_main = sm->ip4_main;
2746   ip4_address_t * first_int_addr;
2747   snat_static_map_resolve_t *rp;
2748   u32 *indices_to_delete = 0;
2749   int i, j;
2750   u32 *auto_add_sw_if_indices =
2751     twice_nat ? sm->auto_add_sw_if_indices_twice_nat : sm->auto_add_sw_if_indices;
2752
2753   first_int_addr = ip4_interface_first_address (ip4_main, sw_if_index,
2754                                                 0 /* just want the address*/);
2755
2756   for (i = 0; i < vec_len(auto_add_sw_if_indices); i++)
2757     {
2758       if (auto_add_sw_if_indices[i] == sw_if_index)
2759         {
2760           if (is_del)
2761             {
2762               /* if have address remove it */
2763               if (first_int_addr)
2764                   (void) snat_del_address (sm, first_int_addr[0], 1, twice_nat);
2765               else
2766                 {
2767                   for (j = 0; j < vec_len (sm->to_resolve); j++)
2768                     {
2769                       rp = sm->to_resolve + j;
2770                       if (rp->sw_if_index == sw_if_index)
2771                         vec_add1 (indices_to_delete, j);
2772                     }
2773                   if (vec_len(indices_to_delete))
2774                     {
2775                       for (j = vec_len(indices_to_delete)-1; j >= 0; j--)
2776                         vec_del1(sm->to_resolve, j);
2777                       vec_free(indices_to_delete);
2778                     }
2779                 }
2780               if (twice_nat)
2781                 vec_del1(sm->auto_add_sw_if_indices_twice_nat, i);
2782               else
2783                 vec_del1(sm->auto_add_sw_if_indices, i);
2784             }
2785           else
2786             return VNET_API_ERROR_VALUE_EXIST;
2787
2788           return 0;
2789         }
2790     }
2791
2792   if (is_del)
2793     return VNET_API_ERROR_NO_SUCH_ENTRY;
2794
2795   /* add to the auto-address list */
2796   if (twice_nat)
2797     vec_add1(sm->auto_add_sw_if_indices_twice_nat, sw_if_index);
2798   else
2799     vec_add1(sm->auto_add_sw_if_indices, sw_if_index);
2800
2801   /* If the address is already bound - or static - add it now */
2802   if (first_int_addr)
2803       snat_add_address (sm, first_int_addr, ~0, twice_nat);
2804
2805   return 0;
2806 }
2807
2808 int
2809 nat44_del_session (snat_main_t *sm, ip4_address_t *addr, u16 port,
2810                    snat_protocol_t proto, u32 vrf_id, int is_in)
2811 {
2812   snat_main_per_thread_data_t *tsm;
2813   clib_bihash_kv_8_8_t kv, value;
2814   ip4_header_t ip;
2815   u32 fib_index = fib_table_find (FIB_PROTOCOL_IP4, vrf_id);
2816   snat_session_key_t key;
2817   snat_session_t *s;
2818   clib_bihash_8_8_t *t;
2819   snat_user_key_t u_key;
2820   snat_user_t *u;
2821
2822   ip.dst_address.as_u32 = ip.src_address.as_u32 = addr->as_u32;
2823   if (sm->num_workers)
2824     tsm =
2825       vec_elt_at_index (sm->per_thread_data,
2826                         sm->worker_in2out_cb (&ip, fib_index));
2827   else
2828     tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
2829
2830   key.addr.as_u32 = addr->as_u32;
2831   key.port = clib_host_to_net_u16 (port);
2832   key.protocol = proto;
2833   key.fib_index = fib_index;
2834   kv.key = key.as_u64;
2835   t = is_in ? &tsm->in2out : &tsm->out2in;
2836   if (!clib_bihash_search_8_8 (t, &kv, &value))
2837     {
2838       s = pool_elt_at_index (tsm->sessions, value.value);
2839       kv.key = s->in2out.as_u64;
2840       clib_bihash_add_del_8_8 (&tsm->in2out, &kv, 0);
2841       kv.key = s->out2in.as_u64;
2842       clib_bihash_add_del_8_8 (&tsm->out2in, &kv, 0);
2843       u_key.addr = s->in2out.addr;
2844       u_key.fib_index = s->in2out.fib_index;
2845       kv.key = u_key.as_u64;
2846       if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
2847         {
2848           u = pool_elt_at_index (tsm->users, value.value);
2849           u->nsessions--;
2850         }
2851       clib_dlist_remove (tsm->list_pool, s->per_user_index);
2852       pool_put (tsm->sessions, s);
2853       return 0;
2854     }
2855
2856   return VNET_API_ERROR_NO_SUCH_ENTRY;
2857 }
2858
2859 void
2860 nat_set_alloc_addr_and_port_mape (u16 psid, u16 psid_offset, u16 psid_length)
2861 {
2862   snat_main_t *sm = &snat_main;
2863
2864   sm->alloc_addr_and_port = nat_alloc_addr_and_port_mape;
2865   sm->psid = psid;
2866   sm->psid_offset = psid_offset;
2867   sm->psid_length = psid_length;
2868 }
2869
2870 void
2871 nat_set_alloc_addr_and_port_default (void)
2872 {
2873   snat_main_t *sm = &snat_main;
2874
2875   sm->alloc_addr_and_port = nat_alloc_addr_and_port_default;
2876 }
2877