NAT44: Delete dynamic sessions matching new 1:1NAT (VPP-1158)
[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   snat_user_key_t u_key;
678   snat_user_t *u;
679   dlist_elt_t * head, * elt;
680   u32 elt_index, head_index;
681   u32 ses_index;
682   u64 user_index;
683   snat_session_t * s;
684
685   /* If the external address is a specific interface address */
686   if (sw_if_index != ~0)
687     {
688       ip4_address_t * first_int_addr;
689
690       /* Might be already set... */
691       first_int_addr = ip4_interface_first_address
692         (sm->ip4_main, sw_if_index, 0 /* just want the address*/);
693
694       /* DHCP resolution required? */
695       if (first_int_addr == 0)
696         {
697           snat_add_static_mapping_when_resolved
698             (sm, l_addr, l_port, sw_if_index, e_port, vrf_id, proto,
699              addr_only,  is_add, tag);
700           return 0;
701         }
702         else
703         {
704           e_addr.as_u32 = first_int_addr->as_u32;
705           /* Identity mapping? */
706           if (l_addr.as_u32 == 0)
707             l_addr.as_u32 = e_addr.as_u32;
708         }
709     }
710
711   m_key.addr = e_addr;
712   m_key.port = addr_only ? 0 : e_port;
713   m_key.protocol = addr_only ? 0 : proto;
714   m_key.fib_index = sm->outside_fib_index;
715   kv.key = m_key.as_u64;
716   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
717     m = 0;
718   else
719     m = pool_elt_at_index (sm->static_mappings, value.value);
720
721   if (is_add)
722     {
723       if (m)
724         return VNET_API_ERROR_VALUE_EXIST;
725
726       if (twice_nat && addr_only)
727         return VNET_API_ERROR_UNSUPPORTED;
728
729       /* Convert VRF id to FIB index */
730       if (vrf_id != ~0)
731         {
732           p = hash_get (sm->ip4_main->fib_index_by_table_id, vrf_id);
733           if (!p)
734             return VNET_API_ERROR_NO_SUCH_FIB;
735           fib_index = p[0];
736         }
737       /* If not specified use inside VRF id from SNAT plugin startup config */
738       else
739         {
740           fib_index = sm->inside_fib_index;
741           vrf_id = sm->inside_vrf_id;
742         }
743
744       /* Find external address in allocated addresses and reserve port for
745          address and port pair mapping when dynamic translations enabled */
746       if (!(addr_only || sm->static_mapping_only || out2in_only))
747         {
748           for (i = 0; i < vec_len (sm->addresses); i++)
749             {
750               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
751                 {
752                   a = sm->addresses + i;
753                   /* External port must be unused */
754                   switch (proto)
755                     {
756 #define _(N, j, n, s) \
757                     case SNAT_PROTOCOL_##N: \
758                       if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, e_port)) \
759                         return VNET_API_ERROR_INVALID_VALUE; \
760                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 1); \
761                       if (e_port > 1024) \
762                         { \
763                           a->busy_##n##_ports++; \
764                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]++; \
765                         } \
766                       break;
767                       foreach_snat_protocol
768 #undef _
769                     default:
770                       clib_warning("unknown_protocol");
771                       return VNET_API_ERROR_INVALID_VALUE_2;
772                     }
773                   break;
774                 }
775             }
776           /* External address must be allocated */
777           if (!a)
778             return VNET_API_ERROR_NO_SUCH_ENTRY;
779         }
780
781       pool_get (sm->static_mappings, m);
782       memset (m, 0, sizeof (*m));
783       m->tag = vec_dup (tag);
784       m->local_addr = l_addr;
785       m->external_addr = e_addr;
786       m->addr_only = addr_only;
787       m->vrf_id = vrf_id;
788       m->fib_index = fib_index;
789       m->twice_nat = twice_nat;
790       m->out2in_only = out2in_only;
791       if (!addr_only)
792         {
793           m->local_port = l_port;
794           m->external_port = e_port;
795           m->proto = proto;
796         }
797
798       if (sm->workers)
799         {
800           ip4_header_t ip = {
801             .src_address = m->local_addr,
802           };
803           m->worker_index = sm->worker_in2out_cb (&ip, m->fib_index);
804           tsm = vec_elt_at_index (sm->per_thread_data, m->worker_index);
805         }
806       else
807         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
808
809       m_key.addr = m->local_addr;
810       m_key.port = m->local_port;
811       m_key.protocol = m->proto;
812       m_key.fib_index = m->fib_index;
813       kv.key = m_key.as_u64;
814       kv.value = m - sm->static_mappings;
815       if (!out2in_only)
816         clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 1);
817       if (twice_nat || out2in_only)
818         {
819           m_key.port = clib_host_to_net_u16 (l_port);
820           kv.key = m_key.as_u64;
821           kv.value = ~0ULL;
822           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 1))
823             clib_warning ("in2out key add failed");
824         }
825
826       m_key.addr = m->external_addr;
827       m_key.port = m->external_port;
828       m_key.fib_index = sm->outside_fib_index;
829       kv.key = m_key.as_u64;
830       kv.value = m - sm->static_mappings;
831       clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 1);
832       if (twice_nat || out2in_only)
833         {
834           m_key.port = clib_host_to_net_u16 (e_port);
835           kv.key = m_key.as_u64;
836           kv.value = ~0ULL;
837           if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 1))
838             clib_warning ("out2in key add failed");
839         }
840
841       /* Delete dynamic sessions matching local address (+ local port) */
842       if (!(sm->static_mapping_only))
843         {
844           u_key.addr = m->local_addr;
845           u_key.fib_index = m->fib_index;
846           kv.key = u_key.as_u64;
847           if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
848             {
849               user_index = value.value;
850               u = pool_elt_at_index (tsm->users, user_index);
851               if (u->nsessions)
852                 {
853                   head_index = u->sessions_per_user_list_head_index;
854                   head = pool_elt_at_index (tsm->list_pool, head_index);
855                   elt_index = head->next;
856                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
857                   ses_index = elt->value;
858                   while (ses_index != ~0)
859                     {
860                       s =  pool_elt_at_index (tsm->sessions, ses_index);
861                       elt = pool_elt_at_index (tsm->list_pool, elt->next);
862                       ses_index = elt->value;
863
864                       if (snat_is_session_static (s))
865                         continue;
866
867                       if (!addr_only)
868                         {
869                           if ((s->out2in.addr.as_u32 != e_addr.as_u32) &&
870                               (clib_net_to_host_u16 (s->out2in.port) != e_port))
871                             continue;
872                         }
873
874                       nat_free_session_data (sm, s, tsm - sm->per_thread_data);
875                       clib_dlist_remove (tsm->list_pool, s->per_user_index);
876                       pool_put_index (tsm->list_pool, s->per_user_index);
877                       pool_put (tsm->sessions, s);
878                       u->nsessions--;
879
880                       if (!addr_only)
881                         break;
882                     }
883                 }
884             }
885         }
886     }
887   else
888     {
889       if (!m)
890         return VNET_API_ERROR_NO_SUCH_ENTRY;
891
892       /* Free external address port */
893       if (!(addr_only || sm->static_mapping_only || out2in_only))
894         {
895           for (i = 0; i < vec_len (sm->addresses); i++)
896             {
897               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
898                 {
899                   a = sm->addresses + i;
900                   switch (proto)
901                     {
902 #define _(N, j, n, s) \
903                     case SNAT_PROTOCOL_##N: \
904                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 0); \
905                       if (e_port > 1024) \
906                         { \
907                           a->busy_##n##_ports--; \
908                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]--; \
909                         } \
910                       break;
911                       foreach_snat_protocol
912 #undef _
913                     default:
914                       clib_warning("unknown_protocol");
915                       return VNET_API_ERROR_INVALID_VALUE_2;
916                     }
917                   break;
918                 }
919             }
920         }
921
922       if (sm->num_workers > 1)
923         tsm = vec_elt_at_index (sm->per_thread_data, m->worker_index);
924       else
925         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
926
927       m_key.addr = m->local_addr;
928       m_key.port = m->local_port;
929       m_key.protocol = m->proto;
930       m_key.fib_index = m->fib_index;
931       kv.key = m_key.as_u64;
932       if (!out2in_only)
933         clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 0);
934       if (twice_nat || out2in_only)
935         {
936           m_key.port = clib_host_to_net_u16 (m->local_port);
937           kv.key = m_key.as_u64;
938           kv.value = ~0ULL;
939           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 0))
940             clib_warning ("in2out key del failed");
941         }
942
943       m_key.addr = m->external_addr;
944       m_key.port = m->external_port;
945       m_key.fib_index = sm->outside_fib_index;
946       kv.key = m_key.as_u64;
947       clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 0);
948       if (twice_nat || out2in_only)
949         {
950           m_key.port = clib_host_to_net_u16 (m->external_port);
951           kv.key = m_key.as_u64;
952           kv.value = ~0ULL;
953           if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 0))
954             clib_warning ("in2out key del failed");
955         }
956
957       /* Delete session(s) for static mapping if exist */
958       if (!(sm->static_mapping_only) ||
959           (sm->static_mapping_only && sm->static_mapping_connection_tracking))
960         {
961           u_key.addr = m->local_addr;
962           u_key.fib_index = m->fib_index;
963           kv.key = u_key.as_u64;
964           if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
965             {
966               user_index = value.value;
967               u = pool_elt_at_index (tsm->users, user_index);
968               if (u->nstaticsessions)
969                 {
970                   head_index = u->sessions_per_user_list_head_index;
971                   head = pool_elt_at_index (tsm->list_pool, head_index);
972                   elt_index = head->next;
973                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
974                   ses_index = elt->value;
975                   while (ses_index != ~0)
976                     {
977                       s =  pool_elt_at_index (tsm->sessions, ses_index);
978                       elt = pool_elt_at_index (tsm->list_pool, elt->next);
979                       ses_index = elt->value;
980
981                       if (!addr_only)
982                         {
983                           if ((s->out2in.addr.as_u32 != e_addr.as_u32) &&
984                               (clib_net_to_host_u16 (s->out2in.port) != e_port))
985                             continue;
986                         }
987
988                       nat_free_session_data (sm, s, tsm - sm->per_thread_data);
989                       clib_dlist_remove (tsm->list_pool, s->per_user_index);
990                       pool_put_index (tsm->list_pool, s->per_user_index);
991                       pool_put (tsm->sessions, s);
992                       u->nstaticsessions--;
993
994                       if (!addr_only)
995                         break;
996                     }
997                   if (addr_only)
998                     {
999                       pool_put (tsm->users, u);
1000                       clib_bihash_add_del_8_8 (&tsm->user_hash, &kv, 0);
1001                     }
1002                 }
1003             }
1004         }
1005
1006       vec_free (m->tag);
1007       /* Delete static mapping from pool */
1008       pool_put (sm->static_mappings, m);
1009     }
1010
1011   if (!addr_only || (l_addr.as_u32 == e_addr.as_u32))
1012     return 0;
1013
1014   /* Add/delete external address to FIB */
1015   pool_foreach (interface, sm->interfaces,
1016   ({
1017     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1018       continue;
1019
1020     snat_add_del_addr_to_fib(&e_addr, 32, interface->sw_if_index, is_add);
1021     break;
1022   }));
1023   pool_foreach (interface, sm->output_feature_interfaces,
1024   ({
1025     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1026       continue;
1027
1028     snat_add_del_addr_to_fib(&e_addr, 32, interface->sw_if_index, is_add);
1029     break;
1030   }));
1031
1032   return 0;
1033 }
1034
1035 int nat44_add_del_lb_static_mapping (ip4_address_t e_addr, u16 e_port,
1036                                      snat_protocol_t proto, u32 vrf_id,
1037                                      nat44_lb_addr_port_t *locals, u8 is_add,
1038                                      u8 twice_nat, u8 out2in_only, u8 *tag)
1039 {
1040   snat_main_t * sm = &snat_main;
1041   snat_static_mapping_t *m;
1042   snat_session_key_t m_key;
1043   clib_bihash_kv_8_8_t kv, value;
1044   u32 fib_index;
1045   snat_address_t *a = 0;
1046   int i;
1047   nat44_lb_addr_port_t *local;
1048   u32 worker_index = 0, elt_index, head_index, ses_index;
1049   snat_main_per_thread_data_t *tsm;
1050   snat_user_key_t u_key;
1051   snat_user_t *u;
1052   snat_session_t * s;
1053   dlist_elt_t * head, * elt;
1054
1055   m_key.addr = e_addr;
1056   m_key.port = e_port;
1057   m_key.protocol = proto;
1058   m_key.fib_index = sm->outside_fib_index;
1059   kv.key = m_key.as_u64;
1060   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
1061     m = 0;
1062   else
1063     m = pool_elt_at_index (sm->static_mappings, value.value);
1064
1065   if (is_add)
1066     {
1067       if (m)
1068         return VNET_API_ERROR_VALUE_EXIST;
1069
1070       if (vec_len (locals) < 2)
1071         return VNET_API_ERROR_INVALID_VALUE;
1072
1073       fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
1074                                                      vrf_id,
1075                                                      FIB_SOURCE_PLUGIN_HI);
1076
1077       /* Find external address in allocated addresses and reserve port for
1078          address and port pair mapping when dynamic translations enabled */
1079       if (!(sm->static_mapping_only || out2in_only))
1080         {
1081           for (i = 0; i < vec_len (sm->addresses); i++)
1082             {
1083               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1084                 {
1085                   a = sm->addresses + i;
1086                   /* External port must be unused */
1087                   switch (proto)
1088                     {
1089 #define _(N, j, n, s) \
1090                     case SNAT_PROTOCOL_##N: \
1091                       if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, e_port)) \
1092                         return VNET_API_ERROR_INVALID_VALUE; \
1093                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 1); \
1094                       if (e_port > 1024) \
1095                         { \
1096                           a->busy_##n##_ports++; \
1097                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]++; \
1098                         } \
1099                       break;
1100                       foreach_snat_protocol
1101 #undef _
1102                     default:
1103                       clib_warning("unknown_protocol");
1104                       return VNET_API_ERROR_INVALID_VALUE_2;
1105                     }
1106                   break;
1107                 }
1108             }
1109           /* External address must be allocated */
1110           if (!a)
1111             return VNET_API_ERROR_NO_SUCH_ENTRY;
1112         }
1113
1114       pool_get (sm->static_mappings, m);
1115       memset (m, 0, sizeof (*m));
1116       m->tag = vec_dup (tag);
1117       m->external_addr = e_addr;
1118       m->addr_only = 0;
1119       m->vrf_id = vrf_id;
1120       m->fib_index = fib_index;
1121       m->external_port = e_port;
1122       m->proto = proto;
1123       m->twice_nat = twice_nat;
1124       m->out2in_only = out2in_only;
1125
1126       m_key.addr = m->external_addr;
1127       m_key.port = m->external_port;
1128       m_key.protocol = m->proto;
1129       m_key.fib_index = sm->outside_fib_index;
1130       kv.key = m_key.as_u64;
1131       kv.value = m - sm->static_mappings;
1132       if (clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 1))
1133         {
1134           clib_warning ("static_mapping_by_external key add failed");
1135           return VNET_API_ERROR_UNSPECIFIED;
1136         }
1137
1138       /* Assign worker */
1139       if (sm->workers)
1140         {
1141           worker_index = sm->first_worker_index +
1142             sm->workers[sm->next_worker++ % vec_len (sm->workers)];
1143           tsm = vec_elt_at_index (sm->per_thread_data, worker_index);
1144           m->worker_index = worker_index;
1145         }
1146       else
1147         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1148
1149       m_key.port = clib_host_to_net_u16 (m->external_port);
1150       kv.key = m_key.as_u64;
1151       kv.value = ~0ULL;
1152       if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 1))
1153         {
1154           clib_warning ("out2in key add failed");
1155           return VNET_API_ERROR_UNSPECIFIED;
1156         }
1157
1158       m_key.fib_index = m->fib_index;
1159       for (i = 0; i < vec_len (locals); i++)
1160         {
1161           m_key.addr = locals[i].addr;
1162           if (!out2in_only)
1163             {
1164               m_key.port = locals[i].port;
1165               kv.key = m_key.as_u64;
1166               kv.value = m - sm->static_mappings;
1167               clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 1);
1168             }
1169           locals[i].prefix = (i == 0) ? locals[i].probability :\
1170             (locals[i - 1].prefix + locals[i].probability);
1171           vec_add1 (m->locals, locals[i]);
1172
1173           m_key.port = clib_host_to_net_u16 (locals[i].port);
1174           kv.key = m_key.as_u64;
1175           kv.value = ~0ULL;
1176           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 1))
1177             {
1178               clib_warning ("in2out key add failed");
1179               return VNET_API_ERROR_UNSPECIFIED;
1180             }
1181         }
1182     }
1183   else
1184     {
1185       if (!m)
1186         return VNET_API_ERROR_NO_SUCH_ENTRY;
1187
1188       fib_table_unlock (m->fib_index, FIB_PROTOCOL_IP4, FIB_SOURCE_PLUGIN_HI);
1189
1190       /* Free external address port */
1191       if (!(sm->static_mapping_only || out2in_only))
1192         {
1193           for (i = 0; i < vec_len (sm->addresses); i++)
1194             {
1195               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1196                 {
1197                   a = sm->addresses + i;
1198                   switch (proto)
1199                     {
1200 #define _(N, j, n, s) \
1201                     case SNAT_PROTOCOL_##N: \
1202                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 0); \
1203                       if (e_port > 1024) \
1204                         { \
1205                           a->busy_##n##_ports--; \
1206                           a->busy_##n##_ports_per_thread[(e_port - 1024) / sm->port_per_thread]--; \
1207                         } \
1208                       break;
1209                       foreach_snat_protocol
1210 #undef _
1211                     default:
1212                       clib_warning("unknown_protocol");
1213                       return VNET_API_ERROR_INVALID_VALUE_2;
1214                     }
1215                   break;
1216                 }
1217             }
1218         }
1219
1220       tsm = vec_elt_at_index (sm->per_thread_data, m->worker_index);
1221       m_key.addr = m->external_addr;
1222       m_key.port = m->external_port;
1223       m_key.protocol = m->proto;
1224       m_key.fib_index = sm->outside_fib_index;
1225       kv.key = m_key.as_u64;
1226       if (clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 0))
1227         {
1228           clib_warning ("static_mapping_by_external key del failed");
1229           return VNET_API_ERROR_UNSPECIFIED;
1230         }
1231
1232       m_key.port = clib_host_to_net_u16 (m->external_port);
1233       kv.key = m_key.as_u64;
1234       if (clib_bihash_add_del_8_8(&tsm->out2in, &kv, 0))
1235         {
1236           clib_warning ("outi2in key del failed");
1237           return VNET_API_ERROR_UNSPECIFIED;
1238         }
1239
1240       vec_foreach (local, m->locals)
1241         {
1242           m_key.addr = local->addr;
1243           if (!out2in_only)
1244             {
1245               m_key.port = local->port;
1246               m_key.fib_index = m->fib_index;
1247               kv.key = m_key.as_u64;
1248               if (clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 0))
1249                 {
1250                   clib_warning ("static_mapping_by_local key del failed");
1251                   return VNET_API_ERROR_UNSPECIFIED;
1252                 }
1253             }
1254
1255           m_key.port = clib_host_to_net_u16 (local->port);
1256           kv.key = m_key.as_u64;
1257           if (clib_bihash_add_del_8_8(&tsm->in2out, &kv, 0))
1258             {
1259               clib_warning ("in2out key del failed");
1260               return VNET_API_ERROR_UNSPECIFIED;
1261             }
1262           /* Delete sessions */
1263           u_key.addr = local->addr;
1264           u_key.fib_index = m->fib_index;
1265           kv.key = u_key.as_u64;
1266           if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
1267             {
1268               u = pool_elt_at_index (tsm->users, value.value);
1269               if (u->nstaticsessions)
1270                 {
1271                   head_index = u->sessions_per_user_list_head_index;
1272                   head = pool_elt_at_index (tsm->list_pool, head_index);
1273                   elt_index = head->next;
1274                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
1275                   ses_index = elt->value;
1276                   while (ses_index != ~0)
1277                     {
1278                       s =  pool_elt_at_index (tsm->sessions, ses_index);
1279                       elt = pool_elt_at_index (tsm->list_pool, elt->next);
1280                       ses_index = elt->value;
1281
1282                       if ((s->in2out.addr.as_u32 != local->addr.as_u32) &&
1283                           (clib_net_to_host_u16 (s->in2out.port) != local->port))
1284                         continue;
1285
1286                       nat_free_session_data (sm, s, tsm - sm->per_thread_data);
1287                       clib_dlist_remove (tsm->list_pool, s->per_user_index);
1288                       pool_put_index (tsm->list_pool, s->per_user_index);
1289                       pool_put (tsm->sessions, s);
1290                       u->nstaticsessions--;
1291                     }
1292                 }
1293             }
1294         }
1295       vec_free(m->locals);
1296       vec_free(m->tag);
1297
1298       pool_put (sm->static_mappings, m);
1299     }
1300
1301   return 0;
1302 }
1303
1304 int
1305 snat_del_address (snat_main_t *sm, ip4_address_t addr, u8 delete_sm,
1306                   u8 twice_nat)
1307 {
1308   snat_address_t *a = 0;
1309   snat_session_t *ses;
1310   u32 *ses_to_be_removed = 0, *ses_index;
1311   clib_bihash_kv_8_8_t kv, value;
1312   snat_user_key_t user_key;
1313   snat_user_t *u;
1314   snat_main_per_thread_data_t *tsm;
1315   snat_static_mapping_t *m;
1316   snat_interface_t *interface;
1317   int i;
1318   snat_address_t *addresses = twice_nat ? sm->twice_nat_addresses : sm->addresses;
1319
1320   /* Find SNAT address */
1321   for (i=0; i < vec_len (addresses); i++)
1322     {
1323       if (addresses[i].addr.as_u32 == addr.as_u32)
1324         {
1325           a = addresses + i;
1326           break;
1327         }
1328     }
1329   if (!a)
1330     return VNET_API_ERROR_NO_SUCH_ENTRY;
1331
1332   if (delete_sm)
1333     {
1334       pool_foreach (m, sm->static_mappings,
1335       ({
1336           if (m->external_addr.as_u32 == addr.as_u32)
1337             (void) snat_add_static_mapping (m->local_addr, m->external_addr,
1338                                             m->local_port, m->external_port,
1339                                             m->vrf_id, m->addr_only, ~0,
1340                                             m->proto, 0, m->twice_nat,
1341                                             m->out2in_only, m->tag);
1342       }));
1343     }
1344   else
1345     {
1346       /* Check if address is used in some static mapping */
1347       if (is_snat_address_used_in_static_mapping(sm, addr))
1348         {
1349           clib_warning ("address used in static mapping");
1350           return VNET_API_ERROR_UNSPECIFIED;
1351         }
1352     }
1353
1354   if (a->fib_index != ~0)
1355     fib_table_unlock(a->fib_index, FIB_PROTOCOL_IP4,
1356                      FIB_SOURCE_PLUGIN_HI);
1357
1358   /* Delete sessions using address */
1359   if (a->busy_tcp_ports || a->busy_udp_ports || a->busy_icmp_ports)
1360     {
1361       vec_foreach (tsm, sm->per_thread_data)
1362         {
1363           pool_foreach (ses, tsm->sessions, ({
1364             if (ses->out2in.addr.as_u32 == addr.as_u32)
1365               {
1366                 ses->outside_address_index = ~0;
1367                 nat_free_session_data (sm, ses, tsm - sm->per_thread_data);
1368                 clib_dlist_remove (tsm->list_pool, ses->per_user_index);
1369                 pool_put_index (tsm->list_pool, ses->per_user_index);
1370                 vec_add1 (ses_to_be_removed, ses - tsm->sessions);
1371                 user_key.addr = ses->in2out.addr;
1372                 user_key.fib_index = ses->in2out.fib_index;
1373                 kv.key = user_key.as_u64;
1374                 if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
1375                   {
1376                     u = pool_elt_at_index (tsm->users, value.value);
1377                     u->nsessions--;
1378                   }
1379               }
1380           }));
1381
1382           vec_foreach (ses_index, ses_to_be_removed)
1383             pool_put_index (tsm->sessions, ses_index[0]);
1384
1385           vec_free (ses_to_be_removed);
1386        }
1387     }
1388
1389   if (twice_nat)
1390     {
1391       vec_del1 (sm->twice_nat_addresses, i);
1392       return 0;
1393     }
1394   else
1395     vec_del1 (sm->addresses, i);
1396
1397   /* Delete external address from FIB */
1398   pool_foreach (interface, sm->interfaces,
1399   ({
1400     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1401       continue;
1402
1403     snat_add_del_addr_to_fib(&addr, 32, interface->sw_if_index, 0);
1404     break;
1405   }));
1406   pool_foreach (interface, sm->output_feature_interfaces,
1407   ({
1408     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1409       continue;
1410
1411     snat_add_del_addr_to_fib(&addr, 32, interface->sw_if_index, 0);
1412     break;
1413   }));
1414
1415   return 0;
1416 }
1417
1418 int snat_interface_add_del (u32 sw_if_index, u8 is_inside, int is_del)
1419 {
1420   snat_main_t *sm = &snat_main;
1421   snat_interface_t *i;
1422   const char * feature_name, *del_feature_name;
1423   snat_address_t * ap;
1424   snat_static_mapping_t * m;
1425   snat_det_map_t * dm;
1426
1427   if (sm->out2in_dpo && !is_inside)
1428     return VNET_API_ERROR_UNSUPPORTED;
1429
1430   if (sm->static_mapping_only && !(sm->static_mapping_connection_tracking))
1431     feature_name = is_inside ?  "nat44-in2out-fast" : "nat44-out2in-fast";
1432   else
1433     {
1434       if (sm->num_workers > 1 && !sm->deterministic)
1435         feature_name = is_inside ?  "nat44-in2out-worker-handoff" : "nat44-out2in-worker-handoff";
1436       else if (sm->deterministic)
1437         feature_name = is_inside ?  "nat44-det-in2out" : "nat44-det-out2in";
1438       else
1439         feature_name = is_inside ?  "nat44-in2out" : "nat44-out2in";
1440     }
1441
1442   if (sm->fq_in2out_index == ~0 && !sm->deterministic && sm->num_workers > 1)
1443     sm->fq_in2out_index = vlib_frame_queue_main_init (sm->in2out_node_index, 0);
1444
1445   if (sm->fq_out2in_index == ~0 && !sm->deterministic && sm->num_workers > 1)
1446     sm->fq_out2in_index = vlib_frame_queue_main_init (sm->out2in_node_index, 0);
1447
1448   pool_foreach (i, sm->interfaces,
1449   ({
1450     if (i->sw_if_index == sw_if_index)
1451       {
1452         if (is_del)
1453           {
1454             if (nat_interface_is_inside(i) && nat_interface_is_outside(i))
1455               {
1456                 if (is_inside)
1457                   i->flags &= ~NAT_INTERFACE_FLAG_IS_INSIDE;
1458                 else
1459                   i->flags &= ~NAT_INTERFACE_FLAG_IS_OUTSIDE;
1460
1461                 if (sm->num_workers > 1 && !sm->deterministic)
1462                   {
1463                     del_feature_name = "nat44-handoff-classify";
1464                     feature_name = !is_inside ?  "nat44-in2out-worker-handoff" :
1465                                                  "nat44-out2in-worker-handoff";
1466                   }
1467                 else if (sm->deterministic)
1468                   {
1469                     del_feature_name = "nat44-det-classify";
1470                     feature_name = !is_inside ?  "nat44-det-in2out" :
1471                                                  "nat44-det-out2in";
1472                   }
1473                 else
1474                   {
1475                     del_feature_name = "nat44-classify";
1476                     feature_name = !is_inside ?  "nat44-in2out" : "nat44-out2in";
1477                   }
1478
1479                 vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1480                                              sw_if_index, 0, 0, 0);
1481                 vnet_feature_enable_disable ("ip4-unicast", feature_name,
1482                                              sw_if_index, 1, 0, 0);
1483               }
1484             else
1485               {
1486                 vnet_feature_enable_disable ("ip4-unicast", feature_name,
1487                                              sw_if_index, 0, 0, 0);
1488                 pool_put (sm->interfaces, i);
1489               }
1490           }
1491         else
1492           {
1493             if ((nat_interface_is_inside(i) && is_inside) ||
1494                 (nat_interface_is_outside(i) && !is_inside))
1495               return 0;
1496
1497             if (sm->num_workers > 1 && !sm->deterministic)
1498               {
1499                 del_feature_name = !is_inside ?  "nat44-in2out-worker-handoff" :
1500                                                  "nat44-out2in-worker-handoff";
1501                 feature_name = "nat44-handoff-classify";
1502               }
1503             else if (sm->deterministic)
1504               {
1505                 del_feature_name = !is_inside ?  "nat44-det-in2out" :
1506                                                  "nat44-det-out2in";
1507                 feature_name = "nat44-det-classify";
1508               }
1509             else
1510               {
1511                 del_feature_name = !is_inside ?  "nat44-in2out" : "nat44-out2in";
1512                 feature_name = "nat44-classify";
1513               }
1514
1515             vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1516                                          sw_if_index, 0, 0, 0);
1517             vnet_feature_enable_disable ("ip4-unicast", feature_name,
1518                                          sw_if_index, 1, 0, 0);
1519             goto set_flags;
1520           }
1521
1522         goto fib;
1523       }
1524   }));
1525
1526   if (is_del)
1527     return VNET_API_ERROR_NO_SUCH_ENTRY;
1528
1529   pool_get (sm->interfaces, i);
1530   i->sw_if_index = sw_if_index;
1531   i->flags = 0;
1532   vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index, 1, 0, 0);
1533
1534 set_flags:
1535   if (is_inside)
1536     i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
1537   else
1538     i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
1539
1540   /* Add/delete external addresses to FIB */
1541 fib:
1542   if (is_inside && !sm->out2in_dpo)
1543     {
1544       vnet_feature_enable_disable ("ip4-local", "nat44-hairpinning",
1545                                    sw_if_index, !is_del, 0, 0);
1546       return 0;
1547     }
1548
1549   vec_foreach (ap, sm->addresses)
1550     snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, !is_del);
1551
1552   pool_foreach (m, sm->static_mappings,
1553   ({
1554     if (!(m->addr_only) || (m->local_addr.as_u32 == m->external_addr.as_u32))
1555       continue;
1556
1557     snat_add_del_addr_to_fib(&m->external_addr, 32, sw_if_index, !is_del);
1558   }));
1559
1560   pool_foreach (dm, sm->det_maps,
1561   ({
1562     snat_add_del_addr_to_fib(&dm->out_addr, dm->out_plen, sw_if_index, !is_del);
1563   }));
1564
1565   return 0;
1566 }
1567
1568 int snat_interface_add_del_output_feature (u32 sw_if_index,
1569                                            u8 is_inside,
1570                                            int is_del)
1571 {
1572   snat_main_t *sm = &snat_main;
1573   snat_interface_t *i;
1574   snat_address_t * ap;
1575   snat_static_mapping_t * m;
1576
1577   if (sm->deterministic ||
1578       (sm->static_mapping_only && !(sm->static_mapping_connection_tracking)))
1579     return VNET_API_ERROR_UNSUPPORTED;
1580
1581   if (is_inside)
1582     {
1583       vnet_feature_enable_disable ("ip4-unicast", "nat44-hairpin-dst",
1584                                    sw_if_index, !is_del, 0, 0);
1585       vnet_feature_enable_disable ("ip4-output", "nat44-hairpin-src",
1586                                    sw_if_index, !is_del, 0, 0);
1587       goto fq;
1588     }
1589
1590   if (sm->num_workers > 1)
1591     {
1592       vnet_feature_enable_disable ("ip4-unicast", "nat44-out2in-worker-handoff",
1593                                    sw_if_index, !is_del, 0, 0);
1594       vnet_feature_enable_disable ("ip4-output",
1595                                    "nat44-in2out-output-worker-handoff",
1596                                    sw_if_index, !is_del, 0, 0);
1597     }
1598   else
1599     {
1600       vnet_feature_enable_disable ("ip4-unicast", "nat44-out2in", sw_if_index,
1601                                    !is_del, 0, 0);
1602       vnet_feature_enable_disable ("ip4-output", "nat44-in2out-output",
1603                                    sw_if_index, !is_del, 0, 0);
1604     }
1605
1606 fq:
1607   if (sm->fq_in2out_output_index == ~0 && sm->num_workers > 1)
1608     sm->fq_in2out_output_index =
1609       vlib_frame_queue_main_init (sm->in2out_output_node_index, 0);
1610
1611   if (sm->fq_out2in_index == ~0 && sm->num_workers > 1)
1612     sm->fq_out2in_index = vlib_frame_queue_main_init (sm->out2in_node_index, 0);
1613
1614   pool_foreach (i, sm->output_feature_interfaces,
1615   ({
1616     if (i->sw_if_index == sw_if_index)
1617       {
1618         if (is_del)
1619           pool_put (sm->output_feature_interfaces, i);
1620         else
1621           return VNET_API_ERROR_VALUE_EXIST;
1622
1623         goto fib;
1624       }
1625   }));
1626
1627   if (is_del)
1628     return VNET_API_ERROR_NO_SUCH_ENTRY;
1629
1630   pool_get (sm->output_feature_interfaces, i);
1631   i->sw_if_index = sw_if_index;
1632   i->flags = 0;
1633   if (is_inside)
1634     i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
1635   else
1636     i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
1637
1638   /* Add/delete external addresses to FIB */
1639 fib:
1640   if (is_inside)
1641     return 0;
1642
1643   vec_foreach (ap, sm->addresses)
1644     snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, !is_del);
1645
1646   pool_foreach (m, sm->static_mappings,
1647   ({
1648     if (!(m->addr_only))
1649       continue;
1650
1651     snat_add_del_addr_to_fib(&m->external_addr, 32, sw_if_index, !is_del);
1652   }));
1653
1654   return 0;
1655 }
1656
1657 int snat_set_workers (uword * bitmap)
1658 {
1659   snat_main_t *sm = &snat_main;
1660   int i, j = 0;
1661
1662   if (sm->num_workers < 2)
1663     return VNET_API_ERROR_FEATURE_DISABLED;
1664
1665   if (clib_bitmap_last_set (bitmap) >= sm->num_workers)
1666     return VNET_API_ERROR_INVALID_WORKER;
1667
1668   vec_free (sm->workers);
1669   clib_bitmap_foreach (i, bitmap,
1670     ({
1671       vec_add1(sm->workers, i);
1672       sm->per_thread_data[sm->first_worker_index + i].snat_thread_index = j;
1673       j++;
1674     }));
1675
1676   sm->port_per_thread = (0xffff - 1024) / _vec_len (sm->workers);
1677   sm->num_snat_thread = _vec_len (sm->workers);
1678
1679   return 0;
1680 }
1681
1682
1683 static void
1684 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
1685                                        uword opaque,
1686                                        u32 sw_if_index,
1687                                        ip4_address_t * address,
1688                                        u32 address_length,
1689                                        u32 if_address_index,
1690                                        u32 is_delete);
1691
1692 static int
1693 nat_alloc_addr_and_port_default (snat_address_t * addresses,
1694                                  u32 fib_index,
1695                                  u32 thread_index,
1696                                  snat_session_key_t * k,
1697                                  u32 * address_indexp,
1698                                  u16 port_per_thread,
1699                                  u32 snat_thread_index);
1700
1701 static clib_error_t * snat_init (vlib_main_t * vm)
1702 {
1703   snat_main_t * sm = &snat_main;
1704   clib_error_t * error = 0;
1705   ip4_main_t * im = &ip4_main;
1706   ip_lookup_main_t * lm = &im->lookup_main;
1707   uword *p;
1708   vlib_thread_registration_t *tr;
1709   vlib_thread_main_t *tm = vlib_get_thread_main ();
1710   uword *bitmap = 0;
1711   u32 i;
1712   ip4_add_del_interface_address_callback_t cb4;
1713
1714   sm->vlib_main = vm;
1715   sm->vnet_main = vnet_get_main();
1716   sm->ip4_main = im;
1717   sm->ip4_lookup_main = lm;
1718   sm->api_main = &api_main;
1719   sm->first_worker_index = 0;
1720   sm->next_worker = 0;
1721   sm->num_workers = 0;
1722   sm->num_snat_thread = 1;
1723   sm->workers = 0;
1724   sm->port_per_thread = 0xffff - 1024;
1725   sm->fq_in2out_index = ~0;
1726   sm->fq_out2in_index = ~0;
1727   sm->udp_timeout = SNAT_UDP_TIMEOUT;
1728   sm->tcp_established_timeout = SNAT_TCP_ESTABLISHED_TIMEOUT;
1729   sm->tcp_transitory_timeout = SNAT_TCP_TRANSITORY_TIMEOUT;
1730   sm->icmp_timeout = SNAT_ICMP_TIMEOUT;
1731   sm->alloc_addr_and_port = nat_alloc_addr_and_port_default;
1732   sm->forwarding_enabled = 0;
1733
1734   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
1735   if (p)
1736     {
1737       tr = (vlib_thread_registration_t *) p[0];
1738       if (tr)
1739         {
1740           sm->num_workers = tr->count;
1741           sm->first_worker_index = tr->first_index;
1742         }
1743     }
1744
1745   vec_validate (sm->per_thread_data, tm->n_vlib_mains - 1);
1746
1747   /* Use all available workers by default */
1748   if (sm->num_workers > 1)
1749     {
1750       for (i=0; i < sm->num_workers; i++)
1751         bitmap = clib_bitmap_set (bitmap, i, 1);
1752       snat_set_workers(bitmap);
1753       clib_bitmap_free (bitmap);
1754     }
1755   else
1756     {
1757       sm->per_thread_data[0].snat_thread_index = 0;
1758     }
1759
1760   error = snat_api_init(vm, sm);
1761   if (error)
1762     return error;
1763
1764   /* Set up the interface address add/del callback */
1765   cb4.function = snat_ip4_add_del_interface_address_cb;
1766   cb4.function_opaque = 0;
1767
1768   vec_add1 (im->add_del_interface_address_callbacks, cb4);
1769
1770   nat_dpo_module_init ();
1771
1772   /* Init IPFIX logging */
1773   snat_ipfix_logging_init(vm);
1774
1775   /* Init NAT64 */
1776   error = nat64_init(vm);
1777   if (error)
1778     return error;
1779
1780   dslite_init(vm);
1781
1782   /* Init virtual fragmenentation reassembly */
1783   return nat_reass_init(vm);
1784 }
1785
1786 VLIB_INIT_FUNCTION (snat_init);
1787
1788 void snat_free_outside_address_and_port (snat_address_t * addresses,
1789                                          u32 thread_index,
1790                                          snat_session_key_t * k,
1791                                          u32 address_index)
1792 {
1793   snat_address_t *a;
1794   u16 port_host_byte_order = clib_net_to_host_u16 (k->port);
1795
1796   ASSERT (address_index < vec_len (addresses));
1797
1798   a = addresses + address_index;
1799
1800   switch (k->protocol)
1801     {
1802 #define _(N, i, n, s) \
1803     case SNAT_PROTOCOL_##N: \
1804       ASSERT (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, \
1805         port_host_byte_order) == 1); \
1806       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, \
1807         port_host_byte_order, 0); \
1808       a->busy_##n##_ports--; \
1809       a->busy_##n##_ports_per_thread[thread_index]--; \
1810       break;
1811       foreach_snat_protocol
1812 #undef _
1813     default:
1814       clib_warning("unknown_protocol");
1815       return;
1816     }
1817 }
1818
1819 /**
1820  * @brief Match NAT44 static mapping.
1821  *
1822  * @param sm          NAT main.
1823  * @param match       Address and port to match.
1824  * @param mapping     External or local address and port of the matched mapping.
1825  * @param by_external If 0 match by local address otherwise match by external
1826  *                    address.
1827  * @param is_addr_only If matched mapping is address only
1828  * @param twice_nat If matched mapping is twice NAT.
1829  *
1830  * @returns 0 if match found otherwise 1.
1831  */
1832 int snat_static_mapping_match (snat_main_t * sm,
1833                                snat_session_key_t match,
1834                                snat_session_key_t * mapping,
1835                                u8 by_external,
1836                                u8 *is_addr_only,
1837                                u8 *twice_nat)
1838 {
1839   clib_bihash_kv_8_8_t kv, value;
1840   snat_static_mapping_t *m;
1841   snat_session_key_t m_key;
1842   clib_bihash_8_8_t *mapping_hash = &sm->static_mapping_by_local;
1843   u32 rand, lo = 0, hi, mid;
1844
1845   if (by_external)
1846     mapping_hash = &sm->static_mapping_by_external;
1847
1848   m_key.addr = match.addr;
1849   m_key.port = clib_net_to_host_u16 (match.port);
1850   m_key.protocol = match.protocol;
1851   m_key.fib_index = match.fib_index;
1852
1853   kv.key = m_key.as_u64;
1854
1855   if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
1856     {
1857       /* Try address only mapping */
1858       m_key.port = 0;
1859       m_key.protocol = 0;
1860       kv.key = m_key.as_u64;
1861       if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
1862         return 1;
1863     }
1864
1865   m = pool_elt_at_index (sm->static_mappings, value.value);
1866
1867   if (by_external)
1868     {
1869       if (vec_len (m->locals))
1870         {
1871           hi = vec_len (m->locals) - 1;
1872           rand = 1 + (random_u32 (&sm->random_seed) % m->locals[hi].prefix);
1873           while (lo < hi)
1874             {
1875               mid = ((hi - lo) >> 1) + lo;
1876               (rand > m->locals[mid].prefix) ? (lo = mid + 1) : (hi = mid);
1877             }
1878           if (!(m->locals[lo].prefix >= rand))
1879             return 1;
1880           mapping->addr = m->locals[lo].addr;
1881           mapping->port = clib_host_to_net_u16 (m->locals[lo].port);
1882         }
1883       else
1884         {
1885           mapping->addr = m->local_addr;
1886           /* Address only mapping doesn't change port */
1887           mapping->port = m->addr_only ? match.port
1888             : clib_host_to_net_u16 (m->local_port);
1889         }
1890       mapping->fib_index = m->fib_index;
1891       mapping->protocol = m->proto;
1892     }
1893   else
1894     {
1895       mapping->addr = m->external_addr;
1896       /* Address only mapping doesn't change port */
1897       mapping->port = m->addr_only ? match.port
1898         : clib_host_to_net_u16 (m->external_port);
1899       mapping->fib_index = sm->outside_fib_index;
1900     }
1901
1902   if (PREDICT_FALSE(is_addr_only != 0))
1903     *is_addr_only = m->addr_only;
1904
1905   if (PREDICT_FALSE(twice_nat != 0))
1906     *twice_nat = m->twice_nat;
1907
1908   return 0;
1909 }
1910
1911 static_always_inline u16
1912 snat_random_port (u16 min, u16 max)
1913 {
1914   snat_main_t *sm = &snat_main;
1915   return min + random_u32 (&sm->random_seed) /
1916     (random_u32_max() / (max - min + 1) + 1);
1917 }
1918
1919 int
1920 snat_alloc_outside_address_and_port (snat_address_t * addresses,
1921                                      u32 fib_index,
1922                                      u32 thread_index,
1923                                      snat_session_key_t * k,
1924                                      u32 * address_indexp,
1925                                      u16 port_per_thread,
1926                                      u32 snat_thread_index)
1927 {
1928   snat_main_t *sm = &snat_main;
1929
1930   return sm->alloc_addr_and_port(addresses, fib_index, thread_index, k,
1931                                  address_indexp, port_per_thread,
1932                                  snat_thread_index);
1933 }
1934
1935 static int
1936 nat_alloc_addr_and_port_default (snat_address_t * addresses,
1937                                  u32 fib_index,
1938                                  u32 thread_index,
1939                                  snat_session_key_t * k,
1940                                  u32 * address_indexp,
1941                                  u16 port_per_thread,
1942                                  u32 snat_thread_index)
1943 {
1944   int i, gi = 0;
1945   snat_address_t *a, *ga = 0;
1946   u32 portnum;
1947
1948   for (i = 0; i < vec_len (addresses); i++)
1949     {
1950       a = addresses + i;
1951       switch (k->protocol)
1952         {
1953 #define _(N, j, n, s) \
1954         case SNAT_PROTOCOL_##N: \
1955           if (a->busy_##n##_ports_per_thread[thread_index] < port_per_thread) \
1956             { \
1957               if (a->fib_index == fib_index) \
1958                 { \
1959                   while (1) \
1960                     { \
1961                       portnum = (port_per_thread * \
1962                         snat_thread_index) + \
1963                         snat_random_port(1, port_per_thread) + 1024; \
1964                       if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, portnum)) \
1965                         continue; \
1966                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, portnum, 1); \
1967                       a->busy_##n##_ports_per_thread[thread_index]++; \
1968                       a->busy_##n##_ports++; \
1969                       k->addr = a->addr; \
1970                       k->port = clib_host_to_net_u16(portnum); \
1971                       *address_indexp = i; \
1972                       return 0; \
1973                     } \
1974                 } \
1975               else if (a->fib_index == ~0) \
1976                 { \
1977                   ga = a; \
1978                   gi = i; \
1979                 } \
1980             } \
1981           break;
1982           foreach_snat_protocol
1983 #undef _
1984         default:
1985           clib_warning("unknown protocol");
1986           return 1;
1987         }
1988
1989     }
1990
1991   if (ga)
1992     {
1993       a = ga;
1994       switch (k->protocol)
1995         {
1996 #define _(N, j, n, s) \
1997         case SNAT_PROTOCOL_##N: \
1998           while (1) \
1999             { \
2000               portnum = (port_per_thread * \
2001                 snat_thread_index) + \
2002                 snat_random_port(1, port_per_thread) + 1024; \
2003               if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, portnum)) \
2004                 continue; \
2005               clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, portnum, 1); \
2006               a->busy_##n##_ports_per_thread[thread_index]++; \
2007               a->busy_##n##_ports++; \
2008               k->addr = a->addr; \
2009               k->port = clib_host_to_net_u16(portnum); \
2010               *address_indexp = gi; \
2011               return 0; \
2012             }
2013           break;
2014           foreach_snat_protocol
2015 #undef _
2016         default:
2017           clib_warning ("unknown protocol");
2018           return 1;
2019         }
2020     }
2021
2022   /* Totally out of translations to use... */
2023   snat_ipfix_logging_addresses_exhausted(0);
2024   return 1;
2025 }
2026
2027 static int
2028 nat_alloc_addr_and_port_mape (snat_address_t * addresses,
2029                               u32 fib_index,
2030                               u32 thread_index,
2031                               snat_session_key_t * k,
2032                               u32 * address_indexp,
2033                               u16 port_per_thread,
2034                               u32 snat_thread_index)
2035 {
2036   snat_main_t *sm = &snat_main;
2037   snat_address_t *a = addresses;
2038   u16 m, ports, portnum, A, j;
2039   m = 16 - (sm->psid_offset + sm->psid_length);
2040   ports = (1 << (16 - sm->psid_length)) - (1 << m);
2041
2042   if (!vec_len (addresses))
2043     goto exhausted;
2044
2045   switch (k->protocol)
2046     {
2047 #define _(N, i, n, s) \
2048     case SNAT_PROTOCOL_##N: \
2049       if (a->busy_##n##_ports < ports) \
2050         { \
2051           while (1) \
2052             { \
2053               A = snat_random_port(1, pow2_mask(sm->psid_offset)); \
2054               j = snat_random_port(0, pow2_mask(m)); \
2055               portnum = A | (sm->psid << sm->psid_offset) | (j << (16 - m)); \
2056               if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, portnum)) \
2057                 continue; \
2058               clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, portnum, 1); \
2059               a->busy_##n##_ports++; \
2060               k->addr = a->addr; \
2061               k->port = clib_host_to_net_u16 (portnum); \
2062               *address_indexp = i; \
2063               return 0; \
2064             } \
2065         } \
2066       break;
2067       foreach_snat_protocol
2068 #undef _
2069     default:
2070       clib_warning("unknown protocol");
2071       return 1;
2072     }
2073
2074 exhausted:
2075   /* Totally out of translations to use... */
2076   snat_ipfix_logging_addresses_exhausted(0);
2077   return 1;
2078 }
2079
2080 void
2081 nat44_add_del_address_dpo (ip4_address_t addr, u8 is_add)
2082 {
2083   dpo_id_t dpo_v4 = DPO_INVALID;
2084   fib_prefix_t pfx = {
2085     .fp_proto = FIB_PROTOCOL_IP4,
2086     .fp_len = 32,
2087     .fp_addr.ip4.as_u32 = addr.as_u32,
2088   };
2089
2090   if (is_add)
2091     {
2092       nat_dpo_create (DPO_PROTO_IP4, 0, &dpo_v4);
2093       fib_table_entry_special_dpo_add (0, &pfx, FIB_SOURCE_PLUGIN_HI,
2094                                        FIB_ENTRY_FLAG_EXCLUSIVE, &dpo_v4);
2095       dpo_reset (&dpo_v4);
2096     }
2097   else
2098     {
2099       fib_table_entry_special_remove (0, &pfx, FIB_SOURCE_PLUGIN_HI);
2100     }
2101 }
2102
2103 uword
2104 unformat_snat_protocol (unformat_input_t * input, va_list * args)
2105 {
2106   u32 *r = va_arg (*args, u32 *);
2107
2108   if (0);
2109 #define _(N, i, n, s) else if (unformat (input, s)) *r = SNAT_PROTOCOL_##N;
2110   foreach_snat_protocol
2111 #undef _
2112   else
2113     return 0;
2114   return 1;
2115 }
2116
2117 u8 *
2118 format_snat_protocol (u8 * s, va_list * args)
2119 {
2120   u32 i = va_arg (*args, u32);
2121   u8 *t = 0;
2122
2123   switch (i)
2124     {
2125 #define _(N, j, n, str) case SNAT_PROTOCOL_##N: t = (u8 *) str; break;
2126       foreach_snat_protocol
2127 #undef _
2128     default:
2129       s = format (s, "unknown");
2130       return s;
2131     }
2132   s = format (s, "%s", t);
2133   return s;
2134 }
2135
2136 static u32
2137 snat_get_worker_in2out_cb (ip4_header_t * ip0, u32 rx_fib_index0)
2138 {
2139   snat_main_t *sm = &snat_main;
2140   u32 next_worker_index = 0;
2141   u32 hash;
2142
2143   next_worker_index = sm->first_worker_index;
2144   hash = ip0->src_address.as_u32 + (ip0->src_address.as_u32 >> 8) +
2145          (ip0->src_address.as_u32 >> 16) + (ip0->src_address.as_u32 >>24);
2146
2147   if (PREDICT_TRUE (is_pow2 (_vec_len (sm->workers))))
2148     next_worker_index += sm->workers[hash & (_vec_len (sm->workers) - 1)];
2149   else
2150     next_worker_index += sm->workers[hash % _vec_len (sm->workers)];
2151
2152   return next_worker_index;
2153 }
2154
2155 static u32
2156 snat_get_worker_out2in_cb (ip4_header_t * ip0, u32 rx_fib_index0)
2157 {
2158   snat_main_t *sm = &snat_main;
2159   udp_header_t *udp;
2160   u16 port;
2161   snat_session_key_t m_key;
2162   clib_bihash_kv_8_8_t kv, value;
2163   snat_static_mapping_t *m;
2164   nat_ed_ses_key_t key;
2165   clib_bihash_kv_16_8_t s_kv, s_value;
2166   snat_main_per_thread_data_t *tsm;
2167   snat_session_t *s;
2168   int i;
2169   u32 proto;
2170   u32 next_worker_index = 0;
2171
2172   /* first try static mappings without port */
2173   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
2174     {
2175       m_key.addr = ip0->dst_address;
2176       m_key.port = 0;
2177       m_key.protocol = 0;
2178       m_key.fib_index = rx_fib_index0;
2179       kv.key = m_key.as_u64;
2180       if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
2181         {
2182           m = pool_elt_at_index (sm->static_mappings, value.value);
2183           return m->worker_index;
2184         }
2185     }
2186
2187   proto = ip_proto_to_snat_proto (ip0->protocol);
2188   udp = ip4_next_header (ip0);
2189   port = udp->dst_port;
2190
2191   if (PREDICT_FALSE (ip4_is_fragment (ip0)))
2192     {
2193       if (PREDICT_FALSE (nat_reass_is_drop_frag (0)))
2194         return vlib_get_thread_index ();
2195
2196       if (PREDICT_TRUE (!ip4_is_first_fragment (ip0)))
2197         {
2198           nat_reass_ip4_t *reass;
2199
2200           reass = nat_ip4_reass_find (ip0->src_address, ip0->dst_address,
2201                                       ip0->fragment_id, ip0->protocol);
2202
2203           if (reass && (reass->thread_index != (u32) ~ 0))
2204             return reass->thread_index;
2205           else
2206             return vlib_get_thread_index ();
2207         }
2208     }
2209
2210   /* unknown protocol */
2211   if (PREDICT_FALSE (proto == ~0))
2212     {
2213       key.l_addr = ip0->dst_address;
2214       key.r_addr = ip0->src_address;
2215       key.fib_index = rx_fib_index0;
2216       key.proto = ip0->protocol;
2217       key.r_port = 0;
2218       key.l_port = 0;
2219       s_kv.key[0] = key.as_u64[0];
2220       s_kv.key[1] = key.as_u64[1];
2221
2222       if (!clib_bihash_search_16_8 (&sm->out2in_ed, &s_kv, &s_value))
2223         {
2224           for (i = 0; i < _vec_len (sm->per_thread_data); i++)
2225             {
2226               tsm = vec_elt_at_index (sm->per_thread_data, i);
2227               if (!pool_is_free_index(tsm->sessions, s_value.value))
2228                 {
2229                   s = pool_elt_at_index (tsm->sessions, s_value.value);
2230                   if (s->out2in.addr.as_u32 == ip0->dst_address.as_u32 &&
2231                       s->out2in.port == ip0->protocol &&
2232                       snat_is_unk_proto_session (s))
2233                     return i;
2234                 }
2235             }
2236          }
2237
2238       /* if no session use current thread */
2239       return vlib_get_thread_index ();
2240     }
2241
2242   if (PREDICT_FALSE (ip0->protocol == IP_PROTOCOL_ICMP))
2243     {
2244       icmp46_header_t * icmp = (icmp46_header_t *) udp;
2245       icmp_echo_header_t *echo = (icmp_echo_header_t *)(icmp + 1);
2246       if (!icmp_is_error_message (icmp))
2247         port = echo->identifier;
2248       else
2249         {
2250           ip4_header_t *inner_ip = (ip4_header_t *)(echo + 1);
2251           proto = ip_proto_to_snat_proto (inner_ip->protocol);
2252           void *l4_header = ip4_next_header (inner_ip);
2253           switch (proto)
2254             {
2255             case SNAT_PROTOCOL_ICMP:
2256               icmp = (icmp46_header_t*)l4_header;
2257               echo = (icmp_echo_header_t *)(icmp + 1);
2258               port = echo->identifier;
2259               break;
2260             case SNAT_PROTOCOL_UDP:
2261             case SNAT_PROTOCOL_TCP:
2262               port = ((tcp_udp_header_t*)l4_header)->src_port;
2263               break;
2264             default:
2265               return vlib_get_thread_index ();
2266             }
2267         }
2268     }
2269
2270   /* try static mappings with port */
2271   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
2272     {
2273       m_key.addr = ip0->dst_address;
2274       m_key.port = clib_net_to_host_u16 (port);
2275       m_key.protocol = proto;
2276       m_key.fib_index = rx_fib_index0;
2277       kv.key = m_key.as_u64;
2278       if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
2279         {
2280           m = pool_elt_at_index (sm->static_mappings, value.value);
2281           return m->worker_index;
2282         }
2283     }
2284
2285   /* worker by outside port */
2286   next_worker_index = sm->first_worker_index;
2287   next_worker_index +=
2288     sm->workers[(clib_net_to_host_u16 (port) - 1024) / sm->port_per_thread];
2289   return next_worker_index;
2290 }
2291
2292 static clib_error_t *
2293 snat_config (vlib_main_t * vm, unformat_input_t * input)
2294 {
2295   snat_main_t * sm = &snat_main;
2296   u32 translation_buckets = 1024;
2297   u32 translation_memory_size = 128<<20;
2298   u32 user_buckets = 128;
2299   u32 user_memory_size = 64<<20;
2300   u32 max_translations_per_user = 100;
2301   u32 outside_vrf_id = 0;
2302   u32 inside_vrf_id = 0;
2303   u32 static_mapping_buckets = 1024;
2304   u32 static_mapping_memory_size = 64<<20;
2305   u32 nat64_bib_buckets = 1024;
2306   u32 nat64_bib_memory_size = 128 << 20;
2307   u32 nat64_st_buckets = 2048;
2308   u32 nat64_st_memory_size = 256 << 20;
2309   u8 static_mapping_only = 0;
2310   u8 static_mapping_connection_tracking = 0;
2311   snat_main_per_thread_data_t *tsm;
2312   dslite_main_t * dm = &dslite_main;
2313
2314   sm->deterministic = 0;
2315   sm->out2in_dpo = 0;
2316
2317   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2318     {
2319       if (unformat (input, "translation hash buckets %d", &translation_buckets))
2320         ;
2321       else if (unformat (input, "translation hash memory %d",
2322                          &translation_memory_size));
2323       else if (unformat (input, "user hash buckets %d", &user_buckets))
2324         ;
2325       else if (unformat (input, "user hash memory %d",
2326                          &user_memory_size))
2327         ;
2328       else if (unformat (input, "max translations per user %d",
2329                          &max_translations_per_user))
2330         ;
2331       else if (unformat (input, "outside VRF id %d",
2332                          &outside_vrf_id))
2333         ;
2334       else if (unformat (input, "inside VRF id %d",
2335                          &inside_vrf_id))
2336         ;
2337       else if (unformat (input, "static mapping only"))
2338         {
2339           static_mapping_only = 1;
2340           if (unformat (input, "connection tracking"))
2341             static_mapping_connection_tracking = 1;
2342         }
2343       else if (unformat (input, "deterministic"))
2344         sm->deterministic = 1;
2345       else if (unformat (input, "nat64 bib hash buckets %d",
2346                          &nat64_bib_buckets))
2347         ;
2348       else if (unformat (input, "nat64 bib hash memory %d",
2349                          &nat64_bib_memory_size))
2350         ;
2351       else if (unformat (input, "nat64 st hash buckets %d", &nat64_st_buckets))
2352         ;
2353       else if (unformat (input, "nat64 st hash memory %d",
2354                          &nat64_st_memory_size))
2355         ;
2356       else if (unformat (input, "out2in dpo"))
2357         sm->out2in_dpo = 1;
2358       else if (unformat (input, "dslite ce"))
2359         dslite_set_ce(dm, 1);
2360       else
2361         return clib_error_return (0, "unknown input '%U'",
2362                                   format_unformat_error, input);
2363     }
2364
2365   /* for show commands, etc. */
2366   sm->translation_buckets = translation_buckets;
2367   sm->translation_memory_size = translation_memory_size;
2368   /* do not exceed load factor 10 */
2369   sm->max_translations = 10 * translation_buckets;
2370   sm->user_buckets = user_buckets;
2371   sm->user_memory_size = user_memory_size;
2372   sm->max_translations_per_user = max_translations_per_user;
2373   sm->outside_vrf_id = outside_vrf_id;
2374   sm->outside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
2375                                                              outside_vrf_id,
2376                                                              FIB_SOURCE_PLUGIN_HI);
2377   sm->inside_vrf_id = inside_vrf_id;
2378   sm->inside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
2379                                                             inside_vrf_id,
2380                                                             FIB_SOURCE_PLUGIN_HI);
2381   sm->static_mapping_only = static_mapping_only;
2382   sm->static_mapping_connection_tracking = static_mapping_connection_tracking;
2383
2384   nat64_set_hash(nat64_bib_buckets, nat64_bib_memory_size, nat64_st_buckets,
2385                  nat64_st_memory_size);
2386
2387   if (sm->deterministic)
2388     {
2389       sm->in2out_node_index = snat_det_in2out_node.index;
2390       sm->in2out_output_node_index = ~0;
2391       sm->out2in_node_index = snat_det_out2in_node.index;
2392       sm->icmp_match_in2out_cb = icmp_match_in2out_det;
2393       sm->icmp_match_out2in_cb = icmp_match_out2in_det;
2394     }
2395   else
2396     {
2397       sm->worker_in2out_cb = snat_get_worker_in2out_cb;
2398       sm->worker_out2in_cb = snat_get_worker_out2in_cb;
2399       sm->in2out_node_index = snat_in2out_node.index;
2400       sm->in2out_output_node_index = snat_in2out_output_node.index;
2401       sm->out2in_node_index = snat_out2in_node.index;
2402       if (!static_mapping_only ||
2403           (static_mapping_only && static_mapping_connection_tracking))
2404         {
2405           sm->icmp_match_in2out_cb = icmp_match_in2out_slow;
2406           sm->icmp_match_out2in_cb = icmp_match_out2in_slow;
2407
2408           vec_foreach (tsm, sm->per_thread_data)
2409             {
2410               clib_bihash_init_8_8 (&tsm->in2out, "in2out", translation_buckets,
2411                                     translation_memory_size);
2412
2413               clib_bihash_init_8_8 (&tsm->out2in, "out2in", translation_buckets,
2414                                     translation_memory_size);
2415
2416               clib_bihash_init_8_8 (&tsm->user_hash, "users", user_buckets,
2417                                     user_memory_size);
2418             }
2419
2420           clib_bihash_init_16_8 (&sm->in2out_ed, "in2out-ed",
2421                                  translation_buckets, translation_memory_size);
2422
2423           clib_bihash_init_16_8 (&sm->out2in_ed, "out2in-ed",
2424                                  translation_buckets, translation_memory_size);
2425         }
2426       else
2427         {
2428           sm->icmp_match_in2out_cb = icmp_match_in2out_fast;
2429           sm->icmp_match_out2in_cb = icmp_match_out2in_fast;
2430         }
2431       clib_bihash_init_8_8 (&sm->static_mapping_by_local,
2432                             "static_mapping_by_local", static_mapping_buckets,
2433                             static_mapping_memory_size);
2434
2435       clib_bihash_init_8_8 (&sm->static_mapping_by_external,
2436                             "static_mapping_by_external", static_mapping_buckets,
2437                             static_mapping_memory_size);
2438     }
2439
2440   return 0;
2441 }
2442
2443 VLIB_CONFIG_FUNCTION (snat_config, "nat");
2444
2445 u8 * format_snat_session_state (u8 * s, va_list * args)
2446 {
2447   u32 i = va_arg (*args, u32);
2448   u8 *t = 0;
2449
2450   switch (i)
2451     {
2452 #define _(v, N, str) case SNAT_SESSION_##N: t = (u8 *) str; break;
2453     foreach_snat_session_state
2454 #undef _
2455     default:
2456       t = format (t, "unknown");
2457     }
2458   s = format (s, "%s", t);
2459   return s;
2460 }
2461
2462 u8 * format_snat_key (u8 * s, va_list * args)
2463 {
2464   snat_session_key_t * key = va_arg (*args, snat_session_key_t *);
2465
2466   s = format (s, "%U proto %U port %d fib %d",
2467               format_ip4_address, &key->addr,
2468               format_snat_protocol, key->protocol,
2469               clib_net_to_host_u16 (key->port), key->fib_index);
2470   return s;
2471 }
2472
2473 u8 * format_snat_session (u8 * s, va_list * args)
2474 {
2475   snat_main_t * sm __attribute__((unused)) = va_arg (*args, snat_main_t *);
2476   snat_session_t * sess = va_arg (*args, snat_session_t *);
2477
2478   if (snat_is_unk_proto_session (sess))
2479     {
2480       s = format (s, "  i2o %U proto %u fib %u\n",
2481                   format_ip4_address, &sess->in2out.addr,
2482                   clib_net_to_host_u16 (sess->in2out.port),
2483                   sess->in2out.fib_index);
2484       s = format (s, "    o2i %U proto %u fib %u\n",
2485                   format_ip4_address, &sess->out2in.addr,
2486                   clib_net_to_host_u16 (sess->out2in.port),
2487                   sess->out2in.fib_index);
2488     }
2489   else
2490     {
2491       s = format (s, "  i2o %U\n", format_snat_key, &sess->in2out);
2492       s = format (s, "    o2i %U\n", format_snat_key, &sess->out2in);
2493     }
2494   if (is_twice_nat_session (sess))
2495     {
2496       s = format (s, "       external host o2i %U:%d i2o %U:%d\n",
2497                   format_ip4_address, &sess->ext_host_addr,
2498                   clib_net_to_host_u16 (sess->ext_host_port),
2499                   format_ip4_address, &sess->ext_host_nat_addr,
2500                   clib_net_to_host_u16 (sess->ext_host_nat_port));
2501     }
2502   else
2503     {
2504       if (sess->ext_host_addr.as_u32)
2505           s = format (s, "       external host %U\n",
2506                       format_ip4_address, &sess->ext_host_addr);
2507     }
2508   s = format (s, "       last heard %.2f\n", sess->last_heard);
2509   s = format (s, "       total pkts %d, total bytes %lld\n",
2510               sess->total_pkts, sess->total_bytes);
2511   if (snat_is_session_static (sess))
2512     s = format (s, "       static translation\n");
2513   else
2514     s = format (s, "       dynamic translation\n");
2515   if (sess->flags & SNAT_SESSION_FLAG_LOAD_BALANCING)
2516     s = format (s, "       load-balancing\n");
2517   if (is_twice_nat_session (sess))
2518     s = format (s, "       twice-nat\n");
2519
2520   return s;
2521 }
2522
2523 u8 * format_snat_user (u8 * s, va_list * args)
2524 {
2525   snat_main_per_thread_data_t * sm = va_arg (*args, snat_main_per_thread_data_t *);
2526   snat_user_t * u = va_arg (*args, snat_user_t *);
2527   int verbose = va_arg (*args, int);
2528   dlist_elt_t * head, * elt;
2529   u32 elt_index, head_index;
2530   u32 session_index;
2531   snat_session_t * sess;
2532
2533   s = format (s, "%U: %d dynamic translations, %d static translations\n",
2534               format_ip4_address, &u->addr, u->nsessions, u->nstaticsessions);
2535
2536   if (verbose == 0)
2537     return s;
2538
2539   if (u->nsessions || u->nstaticsessions)
2540     {
2541       head_index = u->sessions_per_user_list_head_index;
2542       head = pool_elt_at_index (sm->list_pool, head_index);
2543
2544       elt_index = head->next;
2545       elt = pool_elt_at_index (sm->list_pool, elt_index);
2546       session_index = elt->value;
2547
2548       while (session_index != ~0)
2549         {
2550           sess = pool_elt_at_index (sm->sessions, session_index);
2551
2552           s = format (s, "  %U\n", format_snat_session, sm, sess);
2553
2554           elt_index = elt->next;
2555           elt = pool_elt_at_index (sm->list_pool, elt_index);
2556           session_index = elt->value;
2557         }
2558     }
2559
2560   return s;
2561 }
2562
2563 u8 * format_snat_static_mapping (u8 * s, va_list * args)
2564 {
2565   snat_static_mapping_t *m = va_arg (*args, snat_static_mapping_t *);
2566   nat44_lb_addr_port_t *local;
2567
2568   if (m->addr_only)
2569       s = format (s, "local %U external %U vrf %d %s",
2570                   format_ip4_address, &m->local_addr,
2571                   format_ip4_address, &m->external_addr,
2572                   m->vrf_id, m->twice_nat ? "twice-nat" : "");
2573   else
2574    {
2575       if (vec_len (m->locals))
2576         {
2577           s = format (s, "%U vrf %d external %U:%d %s %s",
2578                       format_snat_protocol, m->proto,
2579                       m->vrf_id,
2580                       format_ip4_address, &m->external_addr, m->external_port,
2581                       m->twice_nat ? "twice-nat" : "",
2582                       m->out2in_only ? "out2in-only" : "");
2583           vec_foreach (local, m->locals)
2584             s = format (s, "\n  local %U:%d probability %d\%",
2585                         format_ip4_address, &local->addr, local->port,
2586                         local->probability);
2587         }
2588       else
2589         s = format (s, "%U local %U:%d external %U:%d vrf %d %s %s",
2590                     format_snat_protocol, m->proto,
2591                     format_ip4_address, &m->local_addr, m->local_port,
2592                     format_ip4_address, &m->external_addr, m->external_port,
2593                     m->vrf_id, m->twice_nat ? "twice-nat" : "",
2594                     m->out2in_only ? "out2in-only" : "");
2595    }
2596   return s;
2597 }
2598
2599 u8 * format_snat_static_map_to_resolve (u8 * s, va_list * args)
2600 {
2601   snat_static_map_resolve_t *m = va_arg (*args, snat_static_map_resolve_t *);
2602   vnet_main_t *vnm = vnet_get_main();
2603
2604   if (m->addr_only)
2605       s = format (s, "local %U external %U vrf %d",
2606                   format_ip4_address, &m->l_addr,
2607                   format_vnet_sw_if_index_name, vnm, m->sw_if_index,
2608                   m->vrf_id);
2609   else
2610       s = format (s, "%U local %U:%d external %U:%d vrf %d",
2611                   format_snat_protocol, m->proto,
2612                   format_ip4_address, &m->l_addr, m->l_port,
2613                   format_vnet_sw_if_index_name, vnm, m->sw_if_index,
2614                   m->e_port, m->vrf_id);
2615
2616   return s;
2617 }
2618
2619 u8 * format_det_map_ses (u8 * s, va_list * args)
2620 {
2621   snat_det_map_t * det_map = va_arg (*args, snat_det_map_t *);
2622   ip4_address_t in_addr, out_addr;
2623   u32 in_offset, out_offset;
2624   snat_det_session_t * ses = va_arg (*args, snat_det_session_t *);
2625   u32 * i = va_arg (*args, u32 *);
2626
2627   u32 user_index = *i / SNAT_DET_SES_PER_USER;
2628   in_addr.as_u32 = clib_host_to_net_u32 (
2629     clib_net_to_host_u32(det_map->in_addr.as_u32) + user_index);
2630   in_offset = clib_net_to_host_u32(in_addr.as_u32) -
2631     clib_net_to_host_u32(det_map->in_addr.as_u32);
2632   out_offset = in_offset / det_map->sharing_ratio;
2633   out_addr.as_u32 = clib_host_to_net_u32(
2634     clib_net_to_host_u32(det_map->out_addr.as_u32) + out_offset);
2635   s = format (s, "in %U:%d out %U:%d external host %U:%d state: %U expire: %d\n",
2636               format_ip4_address, &in_addr,
2637               clib_net_to_host_u16 (ses->in_port),
2638               format_ip4_address, &out_addr,
2639               clib_net_to_host_u16 (ses->out.out_port),
2640               format_ip4_address, &ses->out.ext_host_addr,
2641               clib_net_to_host_u16 (ses->out.ext_host_port),
2642               format_snat_session_state, ses->state,
2643               ses->expire);
2644
2645   return s;
2646 }
2647
2648 static void
2649 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
2650                                        uword opaque,
2651                                        u32 sw_if_index,
2652                                        ip4_address_t * address,
2653                                        u32 address_length,
2654                                        u32 if_address_index,
2655                                        u32 is_delete)
2656 {
2657   snat_main_t *sm = &snat_main;
2658   snat_static_map_resolve_t *rp;
2659   u32 *indices_to_delete = 0;
2660   ip4_address_t l_addr;
2661   int i, j;
2662   int rv;
2663   u8 twice_nat = 0;
2664   snat_address_t *addresses = sm->addresses;
2665
2666   for (i = 0; i < vec_len(sm->auto_add_sw_if_indices); i++)
2667     {
2668       if (sw_if_index == sm->auto_add_sw_if_indices[i])
2669           goto match;
2670     }
2671
2672   for (i = 0; i < vec_len(sm->auto_add_sw_if_indices_twice_nat); i++)
2673     {
2674       twice_nat = 1;
2675       addresses = sm->twice_nat_addresses;
2676       if (sw_if_index == sm->auto_add_sw_if_indices_twice_nat[i])
2677           goto match;
2678     }
2679
2680   return;
2681
2682 match:
2683   if (!is_delete)
2684     {
2685       /* Don't trip over lease renewal, static config */
2686       for (j = 0; j < vec_len(addresses); j++)
2687         if (addresses[j].addr.as_u32 == address->as_u32)
2688           return;
2689
2690       snat_add_address (sm, address, ~0, twice_nat);
2691       /* Scan static map resolution vector */
2692       for (j = 0; j < vec_len (sm->to_resolve); j++)
2693         {
2694           rp = sm->to_resolve + j;
2695           /* On this interface? */
2696           if (rp->sw_if_index == sw_if_index)
2697             {
2698               /* Indetity mapping? */
2699               if (rp->l_addr.as_u32 == 0)
2700                 l_addr.as_u32 = address[0].as_u32;
2701               else
2702                 l_addr.as_u32 = rp->l_addr.as_u32;
2703               /* Add the static mapping */
2704               rv = snat_add_static_mapping (l_addr,
2705                                             address[0],
2706                                             rp->l_port,
2707                                             rp->e_port,
2708                                             rp->vrf_id,
2709                                             rp->addr_only,
2710                                             ~0 /* sw_if_index */,
2711                                             rp->proto,
2712                                             rp->is_add,
2713                                             0, 0, rp->tag);
2714               if (rv)
2715                 clib_warning ("snat_add_static_mapping returned %d",
2716                               rv);
2717               vec_free (rp->tag);
2718               vec_add1 (indices_to_delete, j);
2719             }
2720         }
2721       /* If we resolved any of the outstanding static mappings */
2722       if (vec_len(indices_to_delete))
2723         {
2724           /* Delete them */
2725           for (j = vec_len(indices_to_delete)-1; j >= 0; j--)
2726             vec_delete(sm->to_resolve, 1, j);
2727           vec_free(indices_to_delete);
2728         }
2729       return;
2730     }
2731   else
2732     {
2733       (void) snat_del_address(sm, address[0], 1, twice_nat);
2734       return;
2735     }
2736 }
2737
2738
2739 int snat_add_interface_address (snat_main_t *sm, u32 sw_if_index, int is_del,
2740                                 u8 twice_nat)
2741 {
2742   ip4_main_t * ip4_main = sm->ip4_main;
2743   ip4_address_t * first_int_addr;
2744   snat_static_map_resolve_t *rp;
2745   u32 *indices_to_delete = 0;
2746   int i, j;
2747   u32 *auto_add_sw_if_indices =
2748     twice_nat ? sm->auto_add_sw_if_indices_twice_nat : sm->auto_add_sw_if_indices;
2749
2750   first_int_addr = ip4_interface_first_address (ip4_main, sw_if_index,
2751                                                 0 /* just want the address*/);
2752
2753   for (i = 0; i < vec_len(auto_add_sw_if_indices); i++)
2754     {
2755       if (auto_add_sw_if_indices[i] == sw_if_index)
2756         {
2757           if (is_del)
2758             {
2759               /* if have address remove it */
2760               if (first_int_addr)
2761                   (void) snat_del_address (sm, first_int_addr[0], 1, twice_nat);
2762               else
2763                 {
2764                   for (j = 0; j < vec_len (sm->to_resolve); j++)
2765                     {
2766                       rp = sm->to_resolve + j;
2767                       if (rp->sw_if_index == sw_if_index)
2768                         vec_add1 (indices_to_delete, j);
2769                     }
2770                   if (vec_len(indices_to_delete))
2771                     {
2772                       for (j = vec_len(indices_to_delete)-1; j >= 0; j--)
2773                         vec_del1(sm->to_resolve, j);
2774                       vec_free(indices_to_delete);
2775                     }
2776                 }
2777               if (twice_nat)
2778                 vec_del1(sm->auto_add_sw_if_indices_twice_nat, i);
2779               else
2780                 vec_del1(sm->auto_add_sw_if_indices, i);
2781             }
2782           else
2783             return VNET_API_ERROR_VALUE_EXIST;
2784
2785           return 0;
2786         }
2787     }
2788
2789   if (is_del)
2790     return VNET_API_ERROR_NO_SUCH_ENTRY;
2791
2792   /* add to the auto-address list */
2793   if (twice_nat)
2794     vec_add1(sm->auto_add_sw_if_indices_twice_nat, sw_if_index);
2795   else
2796     vec_add1(sm->auto_add_sw_if_indices, sw_if_index);
2797
2798   /* If the address is already bound - or static - add it now */
2799   if (first_int_addr)
2800       snat_add_address (sm, first_int_addr, ~0, twice_nat);
2801
2802   return 0;
2803 }
2804
2805 int
2806 nat44_del_session (snat_main_t *sm, ip4_address_t *addr, u16 port,
2807                    snat_protocol_t proto, u32 vrf_id, int is_in)
2808 {
2809   snat_main_per_thread_data_t *tsm;
2810   clib_bihash_kv_8_8_t kv, value;
2811   ip4_header_t ip;
2812   u32 fib_index = fib_table_find (FIB_PROTOCOL_IP4, vrf_id);
2813   snat_session_key_t key;
2814   snat_session_t *s;
2815   clib_bihash_8_8_t *t;
2816   snat_user_key_t u_key;
2817   snat_user_t *u;
2818
2819   ip.dst_address.as_u32 = ip.src_address.as_u32 = addr->as_u32;
2820   if (sm->num_workers)
2821     tsm =
2822       vec_elt_at_index (sm->per_thread_data,
2823                         sm->worker_in2out_cb (&ip, fib_index));
2824   else
2825     tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
2826
2827   key.addr.as_u32 = addr->as_u32;
2828   key.port = clib_host_to_net_u16 (port);
2829   key.protocol = proto;
2830   key.fib_index = fib_index;
2831   kv.key = key.as_u64;
2832   t = is_in ? &tsm->in2out : &tsm->out2in;
2833   if (!clib_bihash_search_8_8 (t, &kv, &value))
2834     {
2835       s = pool_elt_at_index (tsm->sessions, value.value);
2836       kv.key = s->in2out.as_u64;
2837       clib_bihash_add_del_8_8 (&tsm->in2out, &kv, 0);
2838       kv.key = s->out2in.as_u64;
2839       clib_bihash_add_del_8_8 (&tsm->out2in, &kv, 0);
2840       u_key.addr = s->in2out.addr;
2841       u_key.fib_index = s->in2out.fib_index;
2842       kv.key = u_key.as_u64;
2843       if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
2844         {
2845           u = pool_elt_at_index (tsm->users, value.value);
2846           u->nsessions--;
2847         }
2848       clib_dlist_remove (tsm->list_pool, s->per_user_index);
2849       pool_put (tsm->sessions, s);
2850       return 0;
2851     }
2852
2853   return VNET_API_ERROR_NO_SUCH_ENTRY;
2854 }
2855
2856 void
2857 nat_set_alloc_addr_and_port_mape (u16 psid, u16 psid_offset, u16 psid_length)
2858 {
2859   snat_main_t *sm = &snat_main;
2860
2861   sm->alloc_addr_and_port = nat_alloc_addr_and_port_mape;
2862   sm->psid = psid;
2863   sm->psid_offset = psid_offset;
2864   sm->psid_length = psid_length;
2865 }
2866
2867 void
2868 nat_set_alloc_addr_and_port_default (void)
2869 {
2870   snat_main_t *sm = &snat_main;
2871
2872   sm->alloc_addr_and_port = nat_alloc_addr_and_port_default;
2873 }
2874