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