fa62250cb1c83ebaa5495f757f1045b4e3a4988b
[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/nat_inlines.h>
28 #include <nat/nat44/inlines.h>
29 #include <nat/nat_affinity.h>
30 #include <nat/nat_syslog.h>
31 #include <nat/nat_ha.h>
32 #include <vnet/fib/fib_table.h>
33 #include <vnet/fib/ip4_fib.h>
34 #include <vnet/ip/reass/ip4_sv_reass.h>
35 #include <vppinfra/bihash_16_8.h>
36 #include <nat/nat44/ed_inlines.h>
37
38 #include <vpp/app/version.h>
39
40 snat_main_t snat_main;
41
42 fib_source_t nat_fib_src_hi;
43 fib_source_t nat_fib_src_low;
44
45 /* *INDENT-OFF* */
46 /* Hook up input features */
47 VNET_FEATURE_INIT (nat_pre_in2out, static) = {
48   .arc_name = "ip4-unicast",
49   .node_name = "nat-pre-in2out",
50   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
51                                "ip4-sv-reassembly-feature"),
52 };
53 VNET_FEATURE_INIT (nat_pre_out2in, static) = {
54   .arc_name = "ip4-unicast",
55   .node_name = "nat-pre-out2in",
56   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
57                                "ip4-dhcp-client-detect",
58                                "ip4-sv-reassembly-feature"),
59 };
60 VNET_FEATURE_INIT (snat_in2out_worker_handoff, static) = {
61   .arc_name = "ip4-unicast",
62   .node_name = "nat44-in2out-worker-handoff",
63   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa"),
64 };
65 VNET_FEATURE_INIT (snat_out2in_worker_handoff, static) = {
66   .arc_name = "ip4-unicast",
67   .node_name = "nat44-out2in-worker-handoff",
68   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
69                                "ip4-dhcp-client-detect"),
70 };
71 VNET_FEATURE_INIT (ip4_snat_in2out, static) = {
72   .arc_name = "ip4-unicast",
73   .node_name = "nat44-in2out",
74   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
75 };
76 VNET_FEATURE_INIT (ip4_snat_out2in, static) = {
77   .arc_name = "ip4-unicast",
78   .node_name = "nat44-out2in",
79   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature",
80                                "ip4-dhcp-client-detect"),
81 };
82 VNET_FEATURE_INIT (ip4_nat_classify, static) = {
83   .arc_name = "ip4-unicast",
84   .node_name = "nat44-classify",
85   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
86 };
87 VNET_FEATURE_INIT (ip4_snat_det_in2out, static) = {
88   .arc_name = "ip4-unicast",
89   .node_name = "nat44-det-in2out",
90   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
91 };
92 VNET_FEATURE_INIT (ip4_snat_det_out2in, static) = {
93   .arc_name = "ip4-unicast",
94   .node_name = "nat44-det-out2in",
95   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature",
96                                "ip4-dhcp-client-detect"),
97 };
98 VNET_FEATURE_INIT (ip4_nat_det_classify, static) = {
99   .arc_name = "ip4-unicast",
100   .node_name = "nat44-det-classify",
101   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
102 };
103 VNET_FEATURE_INIT (ip4_nat44_ed_in2out, static) = {
104   .arc_name = "ip4-unicast",
105   .node_name = "nat44-ed-in2out",
106   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
107 };
108 VNET_FEATURE_INIT (ip4_nat44_ed_out2in, static) = {
109   .arc_name = "ip4-unicast",
110   .node_name = "nat44-ed-out2in",
111   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature",
112                                "ip4-dhcp-client-detect"),
113 };
114 VNET_FEATURE_INIT (ip4_nat44_ed_classify, static) = {
115   .arc_name = "ip4-unicast",
116   .node_name = "nat44-ed-classify",
117   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
118 };
119 VNET_FEATURE_INIT (ip4_nat_handoff_classify, static) = {
120   .arc_name = "ip4-unicast",
121   .node_name = "nat44-handoff-classify",
122   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
123 };
124 VNET_FEATURE_INIT (ip4_snat_in2out_fast, static) = {
125   .arc_name = "ip4-unicast",
126   .node_name = "nat44-in2out-fast",
127   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
128 };
129 VNET_FEATURE_INIT (ip4_snat_out2in_fast, static) = {
130   .arc_name = "ip4-unicast",
131   .node_name = "nat44-out2in-fast",
132   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature",
133                                "ip4-dhcp-client-detect"),
134 };
135 VNET_FEATURE_INIT (ip4_snat_hairpin_dst, static) = {
136   .arc_name = "ip4-unicast",
137   .node_name = "nat44-hairpin-dst",
138   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
139 };
140 VNET_FEATURE_INIT (ip4_nat44_ed_hairpin_dst, static) = {
141   .arc_name = "ip4-unicast",
142   .node_name = "nat44-ed-hairpin-dst",
143   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
144 };
145
146 /* Hook up output features */
147 VNET_FEATURE_INIT (ip4_snat_in2out_output, static) = {
148   .arc_name = "ip4-output",
149   .node_name = "nat44-in2out-output",
150   .runs_after = VNET_FEATURES ("acl-plugin-out-ip4-fa","ip4-sv-reassembly-output-feature"),
151 };
152 VNET_FEATURE_INIT (ip4_snat_in2out_output_worker_handoff, static) = {
153   .arc_name = "ip4-output",
154   .node_name = "nat44-in2out-output-worker-handoff",
155   .runs_after = VNET_FEATURES ("acl-plugin-out-ip4-fa","ip4-sv-reassembly-output-feature"),
156 };
157 VNET_FEATURE_INIT (ip4_snat_hairpin_src, static) = {
158   .arc_name = "ip4-output",
159   .node_name = "nat44-hairpin-src",
160   .runs_after = VNET_FEATURES ("acl-plugin-out-ip4-fa","ip4-sv-reassembly-output-feature"),
161 };
162 VNET_FEATURE_INIT (ip4_nat44_ed_in2out_output, static) = {
163   .arc_name = "ip4-output",
164   .node_name = "nat44-ed-in2out-output",
165   .runs_after = VNET_FEATURES ("ip4-sv-reassembly-output-feature"),
166   .runs_before = VNET_FEATURES ("acl-plugin-out-ip4-fa"),
167 };
168 VNET_FEATURE_INIT (ip4_nat44_ed_hairpin_src, static) = {
169   .arc_name = "ip4-output",
170   .node_name = "nat44-ed-hairpin-src",
171   .runs_after = VNET_FEATURES ("ip4-sv-reassembly-output-feature"),
172   .runs_before = VNET_FEATURES ("acl-plugin-out-ip4-fa"),
173 };
174
175 /* Hook up ip4-local features */
176 VNET_FEATURE_INIT (ip4_nat_hairpinning, static) =
177 {
178   .arc_name = "ip4-local",
179   .node_name = "nat44-hairpinning",
180   .runs_before = VNET_FEATURES("ip4-local-end-of-arc"),
181 };
182 VNET_FEATURE_INIT (ip4_nat44_ed_hairpinning, static) =
183 {
184   .arc_name = "ip4-local",
185   .node_name = "nat44-ed-hairpinning",
186   .runs_before = VNET_FEATURES("ip4-local-end-of-arc"),
187 };
188
189
190 VLIB_PLUGIN_REGISTER () = {
191     .version = VPP_BUILD_VER,
192     .description = "Network Address Translation (NAT)",
193 };
194 /* *INDENT-ON* */
195
196 void
197 nat_free_session_data (snat_main_t * sm, snat_session_t * s, u32 thread_index,
198                        u8 is_ha)
199 {
200   clib_bihash_kv_8_8_t kv;
201   u8 proto;
202   u16 r_port, l_port;
203   ip4_address_t *l_addr, *r_addr;
204   u32 fib_index = 0;
205   clib_bihash_kv_16_8_t ed_kv;
206   snat_main_per_thread_data_t *tsm =
207     vec_elt_at_index (sm->per_thread_data, thread_index);
208
209   if (is_fwd_bypass_session (s))
210     {
211       if (snat_is_unk_proto_session (s))
212         {
213           init_ed_k (&ed_kv, s->in2out.addr, 0, s->ext_host_addr, 0, 0,
214                      s->in2out.port);
215         }
216       else
217         {
218           l_port = s->in2out.port;
219           r_port = s->ext_host_port;
220           l_addr = &s->in2out.addr;
221           r_addr = &s->ext_host_addr;
222           proto = nat_proto_to_ip_proto (s->nat_proto);
223           init_ed_k (&ed_kv, *l_addr, l_port, *r_addr, r_port, fib_index,
224                      proto);
225         }
226       if (clib_bihash_add_del_16_8 (&tsm->in2out_ed, &ed_kv, 0))
227         nat_elog_warn ("in2out_ed key del failed");
228       return;
229     }
230
231   /* session lookup tables */
232   if (is_ed_session (s))
233     {
234       if (is_affinity_sessions (s))
235         nat_affinity_unlock (s->ext_host_addr, s->out2in.addr,
236                              s->nat_proto, s->out2in.port);
237       l_addr = &s->out2in.addr;
238       r_addr = &s->ext_host_addr;
239       fib_index = s->out2in.fib_index;
240       if (snat_is_unk_proto_session (s))
241         {
242           proto = s->in2out.port;
243           r_port = 0;
244           l_port = 0;
245         }
246       else
247         {
248           proto = nat_proto_to_ip_proto (s->nat_proto);
249           l_port = s->out2in.port;
250           r_port = s->ext_host_port;
251         }
252       init_ed_k (&ed_kv, *l_addr, l_port, *r_addr, r_port, fib_index, proto);
253       if (clib_bihash_add_del_16_8 (&sm->out2in_ed, &ed_kv, 0))
254         nat_elog_warn ("out2in_ed key del failed");
255       l_addr = &s->in2out.addr;
256       fib_index = s->in2out.fib_index;
257       if (!snat_is_unk_proto_session (s))
258         l_port = s->in2out.port;
259       if (is_twice_nat_session (s))
260         {
261           r_addr = &s->ext_host_nat_addr;
262           r_port = s->ext_host_nat_port;
263         }
264       init_ed_k (&ed_kv, *l_addr, l_port, *r_addr, r_port, fib_index, proto);
265       if (clib_bihash_add_del_16_8 (&tsm->in2out_ed, &ed_kv, 0))
266         nat_elog_warn ("in2out_ed key del failed");
267
268       if (!is_ha)
269         nat_syslog_nat44_sdel (s->user_index, s->in2out.fib_index,
270                                &s->in2out.addr, s->in2out.port,
271                                &s->ext_host_nat_addr, s->ext_host_nat_port,
272                                &s->out2in.addr, s->out2in.port,
273                                &s->ext_host_addr, s->ext_host_port,
274                                s->nat_proto, is_twice_nat_session (s));
275     }
276   else
277     {
278       init_nat_i2o_k (&kv, s);
279       if (clib_bihash_add_del_8_8 (&tsm->in2out, &kv, 0))
280         nat_elog_warn ("in2out key del failed");
281       init_nat_o2i_k (&kv, s);
282       if (clib_bihash_add_del_8_8 (&tsm->out2in, &kv, 0))
283         nat_elog_warn ("out2in key del failed");
284
285       if (!is_ha)
286         nat_syslog_nat44_apmdel (s->user_index, s->in2out.fib_index,
287                                  &s->in2out.addr, s->in2out.port,
288                                  &s->out2in.addr, s->out2in.port,
289                                  s->nat_proto);
290     }
291
292   if (snat_is_unk_proto_session (s))
293     return;
294
295   if (!is_ha)
296     {
297       /* log NAT event */
298       snat_ipfix_logging_nat44_ses_delete (thread_index,
299                                            s->in2out.addr.as_u32,
300                                            s->out2in.addr.as_u32,
301                                            s->nat_proto,
302                                            s->in2out.port,
303                                            s->out2in.port,
304                                            s->in2out.fib_index);
305
306       nat_ha_sdel (&s->out2in.addr, s->out2in.port, &s->ext_host_addr,
307                    s->ext_host_port, s->nat_proto, s->out2in.fib_index,
308                    thread_index);
309     }
310
311   /* Twice NAT address and port for external host */
312   if (is_twice_nat_session (s))
313     {
314       snat_free_outside_address_and_port (sm->twice_nat_addresses,
315                                           thread_index,
316                                           &s->ext_host_nat_addr,
317                                           s->ext_host_nat_port, s->nat_proto);
318     }
319
320   if (snat_is_session_static (s))
321     return;
322
323   snat_free_outside_address_and_port (sm->addresses, thread_index,
324                                       &s->out2in.addr, s->out2in.port,
325                                       s->nat_proto);
326 }
327
328 int
329 nat44_set_session_limit (u32 session_limit, u32 vrf_id)
330 {
331   snat_main_t *sm = &snat_main;
332   u32 fib_index = fib_table_find (FIB_PROTOCOL_IP4, vrf_id);
333   u32 len = vec_len (sm->max_translations_per_fib);
334
335   if (len <= fib_index)
336     {
337       vec_validate (sm->max_translations_per_fib, fib_index + 1);
338
339       for (; len < vec_len (sm->max_translations_per_fib); len++)
340         sm->max_translations_per_fib[len] = sm->max_translations_per_thread;
341     }
342
343   sm->max_translations_per_fib[fib_index] = session_limit;
344   return 0;
345 }
346
347 void
348 nat44_free_session_data (snat_main_t * sm, snat_session_t * s,
349                          u32 thread_index, u8 is_ha)
350 {
351   u8 proto;
352   u16 r_port, l_port;
353   ip4_address_t *l_addr, *r_addr;
354   u32 fib_index;
355   clib_bihash_kv_16_8_t ed_kv;
356   snat_main_per_thread_data_t *tsm =
357     vec_elt_at_index (sm->per_thread_data, thread_index);
358
359   if (is_fwd_bypass_session (s))
360     {
361       if (snat_is_unk_proto_session (s))
362         {
363           proto = s->in2out.port;
364           r_port = 0;
365           l_port = 0;
366         }
367       else
368         {
369           proto = nat_proto_to_ip_proto (s->nat_proto);
370           l_port = s->in2out.port;
371           r_port = s->ext_host_port;
372         }
373
374       l_addr = &s->in2out.addr;
375       r_addr = &s->ext_host_addr;
376       fib_index = 0;
377       init_ed_k (&ed_kv, *l_addr, l_port, *r_addr, r_port, fib_index, proto);
378
379       if (PREDICT_FALSE
380           (clib_bihash_add_del_16_8 (&tsm->in2out_ed, &ed_kv, 0)))
381         nat_elog_warn ("in2out_ed key del failed");
382       return;
383     }
384
385   /* session lookup tables */
386   if (is_affinity_sessions (s))
387     nat_affinity_unlock (s->ext_host_addr, s->out2in.addr,
388                          s->nat_proto, s->out2in.port);
389   l_addr = &s->out2in.addr;
390   r_addr = &s->ext_host_addr;
391   fib_index = s->out2in.fib_index;
392   if (snat_is_unk_proto_session (s))
393     {
394       proto = s->in2out.port;
395       r_port = 0;
396       l_port = 0;
397     }
398   else
399     {
400       proto = nat_proto_to_ip_proto (s->nat_proto);
401       l_port = s->out2in.port;
402       r_port = s->ext_host_port;
403     }
404   init_ed_k (&ed_kv, *l_addr, l_port, *r_addr, r_port, fib_index, proto);
405
406   if (PREDICT_FALSE (clib_bihash_add_del_16_8 (&sm->out2in_ed, &ed_kv, 0)))
407     nat_elog_warn ("out2in_ed key del failed");
408
409   l_addr = &s->in2out.addr;
410   fib_index = s->in2out.fib_index;
411
412   if (!snat_is_unk_proto_session (s))
413     l_port = s->in2out.port;
414
415   if (is_twice_nat_session (s))
416     {
417       r_addr = &s->ext_host_nat_addr;
418       r_port = s->ext_host_nat_port;
419     }
420   init_ed_k (&ed_kv, *l_addr, l_port, *r_addr, r_port, fib_index, proto);
421
422   if (PREDICT_FALSE (clib_bihash_add_del_16_8 (&tsm->in2out_ed, &ed_kv, 0)))
423     nat_elog_warn ("in2out_ed key del failed");
424
425   if (!is_ha)
426     {
427       nat_syslog_nat44_sdel (s->user_index, s->in2out.fib_index,
428                              &s->in2out.addr, s->in2out.port,
429                              &s->ext_host_nat_addr, s->ext_host_nat_port,
430                              &s->out2in.addr, s->out2in.port,
431                              &s->ext_host_addr, s->ext_host_port,
432                              s->nat_proto, is_twice_nat_session (s));
433     }
434
435   if (snat_is_unk_proto_session (s))
436     return;
437
438   if (!is_ha)
439     {
440       snat_ipfix_logging_nat44_ses_delete (thread_index,
441                                            s->in2out.addr.as_u32,
442                                            s->out2in.addr.as_u32,
443                                            s->nat_proto,
444                                            s->in2out.port,
445                                            s->out2in.port,
446                                            s->in2out.fib_index);
447       nat_ha_sdel (&s->out2in.addr, s->out2in.port, &s->ext_host_addr,
448                    s->ext_host_port, s->nat_proto, s->out2in.fib_index,
449                    thread_index);
450     }
451
452   /* Twice NAT address and port for external host */
453   if (is_twice_nat_session (s))
454     {
455       snat_free_outside_address_and_port (sm->twice_nat_addresses,
456                                           thread_index,
457                                           &s->ext_host_nat_addr,
458                                           s->ext_host_nat_port, s->nat_proto);
459     }
460
461   if (snat_is_session_static (s))
462     return;
463
464   snat_free_outside_address_and_port (sm->addresses, thread_index,
465                                       &s->out2in.addr, s->out2in.port,
466                                       s->nat_proto);
467 }
468
469
470 snat_user_t *
471 nat_user_get_or_create (snat_main_t * sm, ip4_address_t * addr, u32 fib_index,
472                         u32 thread_index)
473 {
474   snat_user_t *u = 0;
475   snat_user_key_t user_key;
476   clib_bihash_kv_8_8_t kv, value;
477   snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
478   dlist_elt_t *per_user_list_head_elt;
479
480   user_key.addr.as_u32 = addr->as_u32;
481   user_key.fib_index = fib_index;
482   kv.key = user_key.as_u64;
483
484   /* Ever heard of the "user" = src ip4 address before? */
485   if (clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
486     {
487       if (pool_elts (tsm->users) >= sm->max_users_per_thread)
488         {
489           vlib_increment_simple_counter (&sm->user_limit_reached,
490                                          thread_index, 0, 1);
491           nat_elog_warn ("maximum user limit reached");
492           return NULL;
493         }
494       /* no, make a new one */
495       pool_get (tsm->users, u);
496       clib_memset (u, 0, sizeof (*u));
497
498       u->addr.as_u32 = addr->as_u32;
499       u->fib_index = fib_index;
500
501       pool_get (tsm->list_pool, per_user_list_head_elt);
502
503       u->sessions_per_user_list_head_index = per_user_list_head_elt -
504         tsm->list_pool;
505
506       clib_dlist_init (tsm->list_pool, u->sessions_per_user_list_head_index);
507
508       kv.value = u - tsm->users;
509
510       /* add user */
511       if (clib_bihash_add_del_8_8 (&tsm->user_hash, &kv, 1))
512         {
513           nat_elog_warn ("user_hash key add failed");
514           nat44_delete_user_with_no_session (sm, u, thread_index);
515           return NULL;
516         }
517
518       vlib_set_simple_counter (&sm->total_users, thread_index, 0,
519                                pool_elts (tsm->users));
520     }
521   else
522     {
523       u = pool_elt_at_index (tsm->users, value.value);
524     }
525
526   return u;
527 }
528
529 snat_session_t *
530 nat_session_alloc_or_recycle (snat_main_t * sm, snat_user_t * u,
531                               u32 thread_index, f64 now)
532 {
533   snat_session_t *s;
534   snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
535   u32 oldest_per_user_translation_list_index, session_index;
536   dlist_elt_t *oldest_per_user_translation_list_elt;
537   dlist_elt_t *per_user_translation_list_elt;
538
539   /* Over quota? Recycle the least recently used translation */
540   if ((u->nsessions + u->nstaticsessions) >= sm->max_translations_per_user)
541     {
542       oldest_per_user_translation_list_index =
543         clib_dlist_remove_head (tsm->list_pool,
544                                 u->sessions_per_user_list_head_index);
545
546       ASSERT (oldest_per_user_translation_list_index != ~0);
547
548       /* Add it back to the end of the LRU list */
549       clib_dlist_addtail (tsm->list_pool,
550                           u->sessions_per_user_list_head_index,
551                           oldest_per_user_translation_list_index);
552       /* Get the list element */
553       oldest_per_user_translation_list_elt =
554         pool_elt_at_index (tsm->list_pool,
555                            oldest_per_user_translation_list_index);
556
557       /* Get the session index from the list element */
558       session_index = oldest_per_user_translation_list_elt->value;
559
560       /* Get the session */
561       s = pool_elt_at_index (tsm->sessions, session_index);
562       nat_free_session_data (sm, s, thread_index, 0);
563       if (snat_is_session_static (s))
564         u->nstaticsessions--;
565       else
566         u->nsessions--;
567       s->flags = 0;
568       s->total_bytes = 0;
569       s->total_pkts = 0;
570       s->state = 0;
571       s->ext_host_addr.as_u32 = 0;
572       s->ext_host_port = 0;
573       s->ext_host_nat_addr.as_u32 = 0;
574       s->ext_host_nat_port = 0;
575     }
576   else
577     {
578       pool_get (tsm->sessions, s);
579       clib_memset (s, 0, sizeof (*s));
580
581       /* Create list elts */
582       pool_get (tsm->list_pool, per_user_translation_list_elt);
583       clib_dlist_init (tsm->list_pool,
584                        per_user_translation_list_elt - tsm->list_pool);
585
586       per_user_translation_list_elt->value = s - tsm->sessions;
587       s->per_user_index = per_user_translation_list_elt - tsm->list_pool;
588       s->per_user_list_head_index = u->sessions_per_user_list_head_index;
589
590       clib_dlist_addtail (tsm->list_pool,
591                           s->per_user_list_head_index,
592                           per_user_translation_list_elt - tsm->list_pool);
593
594       s->user_index = u - tsm->users;
595       vlib_set_simple_counter (&sm->total_sessions, thread_index, 0,
596                                pool_elts (tsm->sessions));
597     }
598
599   s->ha_last_refreshed = now;
600
601   return s;
602 }
603
604 void
605 snat_add_del_addr_to_fib (ip4_address_t * addr, u8 p_len, u32 sw_if_index,
606                           int is_add)
607 {
608   fib_prefix_t prefix = {
609     .fp_len = p_len,
610     .fp_proto = FIB_PROTOCOL_IP4,
611     .fp_addr = {
612                 .ip4.as_u32 = addr->as_u32,
613                 },
614   };
615   u32 fib_index = ip4_fib_table_get_index_for_sw_if_index (sw_if_index);
616
617   if (is_add)
618     fib_table_entry_update_one_path (fib_index,
619                                      &prefix,
620                                      nat_fib_src_low,
621                                      (FIB_ENTRY_FLAG_CONNECTED |
622                                       FIB_ENTRY_FLAG_LOCAL |
623                                       FIB_ENTRY_FLAG_EXCLUSIVE),
624                                      DPO_PROTO_IP4,
625                                      NULL,
626                                      sw_if_index,
627                                      ~0, 1, NULL, FIB_ROUTE_PATH_FLAG_NONE);
628   else
629     fib_table_entry_delete (fib_index, &prefix, nat_fib_src_low);
630 }
631
632 int
633 snat_add_address (snat_main_t * sm, ip4_address_t * addr, u32 vrf_id,
634                   u8 twice_nat)
635 {
636   snat_address_t *ap;
637   snat_interface_t *i;
638   vlib_thread_main_t *tm = vlib_get_thread_main ();
639
640   if (twice_nat && !sm->endpoint_dependent)
641     return VNET_API_ERROR_FEATURE_DISABLED;
642
643   /* Check if address already exists */
644   /* *INDENT-OFF* */
645   vec_foreach (ap, twice_nat ? sm->twice_nat_addresses : sm->addresses)
646     {
647       if (ap->addr.as_u32 == addr->as_u32)
648         return VNET_API_ERROR_VALUE_EXIST;
649     }
650   /* *INDENT-ON* */
651
652   if (twice_nat)
653     vec_add2 (sm->twice_nat_addresses, ap, 1);
654   else
655     vec_add2 (sm->addresses, ap, 1);
656
657   ap->addr = *addr;
658   if (vrf_id != ~0)
659     ap->fib_index =
660       fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, vrf_id,
661                                          nat_fib_src_low);
662   else
663     ap->fib_index = ~0;
664 #define _(N, i, n, s) \
665   clib_memset(ap->busy_##n##_port_refcounts, 0, sizeof(ap->busy_##n##_port_refcounts));\
666   ap->busy_##n##_ports = 0; \
667   ap->busy_##n##_ports_per_thread = 0;\
668   vec_validate_init_empty (ap->busy_##n##_ports_per_thread, tm->n_vlib_mains - 1, 0);
669   foreach_nat_protocol
670 #undef _
671     if (twice_nat)
672     return 0;
673
674   /* Add external address to FIB */
675   /* *INDENT-OFF* */
676   pool_foreach (i, sm->interfaces,
677   ({
678     if (nat_interface_is_inside(i) || sm->out2in_dpo)
679       continue;
680
681     snat_add_del_addr_to_fib(addr, 32, i->sw_if_index, 1);
682     break;
683   }));
684   pool_foreach (i, sm->output_feature_interfaces,
685   ({
686     if (nat_interface_is_inside(i) || sm->out2in_dpo)
687       continue;
688
689     snat_add_del_addr_to_fib(addr, 32, i->sw_if_index, 1);
690     break;
691   }));
692   /* *INDENT-ON* */
693
694   return 0;
695 }
696
697 static int
698 is_snat_address_used_in_static_mapping (snat_main_t * sm, ip4_address_t addr)
699 {
700   snat_static_mapping_t *m;
701   /* *INDENT-OFF* */
702   pool_foreach (m, sm->static_mappings,
703   ({
704       if (is_addr_only_static_mapping (m) ||
705           is_out2in_only_static_mapping (m) ||
706           is_identity_static_mapping (m))
707         continue;
708       if (m->external_addr.as_u32 == addr.as_u32)
709         return 1;
710   }));
711   /* *INDENT-ON* */
712
713   return 0;
714 }
715
716 static void
717 snat_add_static_mapping_when_resolved (snat_main_t * sm,
718                                        ip4_address_t l_addr,
719                                        u16 l_port,
720                                        u32 sw_if_index,
721                                        u16 e_port,
722                                        u32 vrf_id,
723                                        nat_protocol_t proto,
724                                        int addr_only, int is_add, u8 * tag,
725                                        int twice_nat, int out2in_only,
726                                        int identity_nat)
727 {
728   snat_static_map_resolve_t *rp;
729
730   vec_add2 (sm->to_resolve, rp, 1);
731   rp->l_addr.as_u32 = l_addr.as_u32;
732   rp->l_port = l_port;
733   rp->sw_if_index = sw_if_index;
734   rp->e_port = e_port;
735   rp->vrf_id = vrf_id;
736   rp->proto = proto;
737   rp->addr_only = addr_only;
738   rp->is_add = is_add;
739   rp->twice_nat = twice_nat;
740   rp->out2in_only = out2in_only;
741   rp->identity_nat = identity_nat;
742   rp->tag = vec_dup (tag);
743 }
744
745 static u32
746 get_thread_idx_by_port (u16 e_port)
747 {
748   snat_main_t *sm = &snat_main;
749   u32 thread_idx = sm->num_workers;
750   if (sm->num_workers > 1)
751     {
752       thread_idx =
753         sm->first_worker_index +
754         sm->workers[(e_port - 1024) / sm->port_per_thread];
755     }
756   return thread_idx;
757 }
758
759 void
760 snat_static_mapping_del_sessions (snat_main_t * sm,
761                                   snat_main_per_thread_data_t * tsm,
762                                   snat_user_key_t u_key, int addr_only,
763                                   ip4_address_t e_addr, u16 e_port)
764 {
765   clib_bihash_kv_8_8_t kv, value;
766   kv.key = u_key.as_u64;
767   u64 user_index;
768   dlist_elt_t *head, *elt;
769   snat_user_t *u;
770   snat_session_t *s;
771   u32 elt_index, head_index, ses_index;
772   if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
773     {
774       user_index = value.value;
775       u = pool_elt_at_index (tsm->users, user_index);
776       if (u->nstaticsessions)
777         {
778           head_index = u->sessions_per_user_list_head_index;
779           head = pool_elt_at_index (tsm->list_pool, head_index);
780           elt_index = head->next;
781           elt = pool_elt_at_index (tsm->list_pool, elt_index);
782           ses_index = elt->value;
783           while (ses_index != ~0)
784             {
785               s = pool_elt_at_index (tsm->sessions, ses_index);
786               elt = pool_elt_at_index (tsm->list_pool, elt->next);
787               ses_index = elt->value;
788
789               if (!addr_only)
790                 {
791                   if ((s->out2in.addr.as_u32 != e_addr.as_u32) ||
792                       (s->out2in.port != e_port))
793                     continue;
794                 }
795
796               if (is_lb_session (s))
797                 continue;
798
799               if (!snat_is_session_static (s))
800                 continue;
801
802               nat_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
803               nat44_delete_session (sm, s, tsm - sm->per_thread_data);
804
805               if (!addr_only)
806                 break;
807             }
808         }
809     }
810 }
811
812 void
813 snat_ed_static_mapping_del_sessions (snat_main_t * sm,
814                                      snat_main_per_thread_data_t * tsm,
815                                      ip4_address_t l_addr,
816                                      u16 l_port,
817                                      u8 protocol,
818                                      u32 fib_index, int addr_only,
819                                      ip4_address_t e_addr, u16 e_port)
820 {
821   snat_session_t *s;
822   u32 *indexes_to_free = NULL;
823   /* *INDENT-OFF* */
824   pool_foreach (s, tsm->sessions, {
825     if (s->in2out.fib_index != fib_index ||
826         s->in2out.addr.as_u32 != l_addr.as_u32)
827       {
828         continue;
829       }
830     if (!addr_only)
831       {
832         if ((s->out2in.addr.as_u32 != e_addr.as_u32) ||
833             s->out2in.port != e_port ||
834             s->in2out.port != l_port ||
835             s->nat_proto != protocol)
836           continue;
837       }
838
839     if (is_lb_session (s))
840       continue;
841     if (!snat_is_session_static (s))
842       continue;
843     nat_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
844     vec_add1 (indexes_to_free, s - tsm->sessions);
845     if (!addr_only)
846       break;
847   });
848   /* *INDENT-ON* */
849   u32 *ses_index;
850   vec_foreach (ses_index, indexes_to_free)
851   {
852     s = pool_elt_at_index (tsm->sessions, *ses_index);
853     nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
854   }
855   vec_free (indexes_to_free);
856 }
857
858 int
859 snat_add_static_mapping (ip4_address_t l_addr, ip4_address_t e_addr,
860                          u16 l_port, u16 e_port, u32 vrf_id, int addr_only,
861                          u32 sw_if_index, nat_protocol_t proto, int is_add,
862                          twice_nat_type_t twice_nat, u8 out2in_only, u8 * tag,
863                          u8 identity_nat)
864 {
865   snat_main_t *sm = &snat_main;
866   snat_static_mapping_t *m;
867   clib_bihash_kv_8_8_t kv, value;
868   snat_address_t *a = 0;
869   u32 fib_index = ~0;
870   snat_interface_t *interface;
871   int i;
872   snat_main_per_thread_data_t *tsm;
873   snat_user_key_t u_key;
874   snat_user_t *u;
875   dlist_elt_t *head, *elt;
876   u32 elt_index, head_index;
877   u32 ses_index;
878   u64 user_index;
879   snat_session_t *s;
880   snat_static_map_resolve_t *rp, *rp_match = 0;
881   nat44_lb_addr_port_t *local;
882   u32 find = ~0;
883
884   if (!sm->endpoint_dependent)
885     {
886       if (twice_nat || out2in_only)
887         return VNET_API_ERROR_FEATURE_DISABLED;
888     }
889
890   /* If the external address is a specific interface address */
891   if (sw_if_index != ~0)
892     {
893       ip4_address_t *first_int_addr;
894
895       for (i = 0; i < vec_len (sm->to_resolve); i++)
896         {
897           rp = sm->to_resolve + i;
898           if (rp->sw_if_index != sw_if_index ||
899               rp->l_addr.as_u32 != l_addr.as_u32 ||
900               rp->vrf_id != vrf_id || rp->addr_only != addr_only)
901             continue;
902
903           if (!addr_only)
904             {
905               if ((rp->l_port != l_port && rp->e_port != e_port)
906                   || rp->proto != proto)
907                 continue;
908             }
909
910           rp_match = rp;
911           break;
912         }
913
914       /* Might be already set... */
915       first_int_addr = ip4_interface_first_address
916         (sm->ip4_main, sw_if_index, 0 /* just want the address */ );
917
918       if (is_add)
919         {
920           if (rp_match)
921             return VNET_API_ERROR_VALUE_EXIST;
922
923           snat_add_static_mapping_when_resolved
924             (sm, l_addr, l_port, sw_if_index, e_port, vrf_id, proto,
925              addr_only, is_add, tag, twice_nat, out2in_only, identity_nat);
926
927           /* DHCP resolution required? */
928           if (first_int_addr == 0)
929             {
930               return 0;
931             }
932           else
933             {
934               e_addr.as_u32 = first_int_addr->as_u32;
935               /* Identity mapping? */
936               if (l_addr.as_u32 == 0)
937                 l_addr.as_u32 = e_addr.as_u32;
938             }
939         }
940       else
941         {
942           if (!rp_match)
943             return VNET_API_ERROR_NO_SUCH_ENTRY;
944
945           vec_del1 (sm->to_resolve, i);
946
947           if (first_int_addr)
948             {
949               e_addr.as_u32 = first_int_addr->as_u32;
950               /* Identity mapping? */
951               if (l_addr.as_u32 == 0)
952                 l_addr.as_u32 = e_addr.as_u32;
953             }
954           else
955             return 0;
956         }
957     }
958
959   init_nat_k (&kv, e_addr, addr_only ? 0 : e_port, 0, addr_only ? 0 : proto);
960   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
961     m = 0;
962   else
963     m = pool_elt_at_index (sm->static_mappings, value.value);
964
965   if (is_add)
966     {
967       if (m)
968         {
969           if (is_identity_static_mapping (m))
970             {
971               /* *INDENT-OFF* */
972               pool_foreach (local, m->locals,
973               ({
974                 if (local->vrf_id == vrf_id)
975                   return VNET_API_ERROR_VALUE_EXIST;
976               }));
977               /* *INDENT-ON* */
978               pool_get (m->locals, local);
979               local->vrf_id = vrf_id;
980               local->fib_index =
981                 fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, vrf_id,
982                                                    nat_fib_src_low);
983               init_nat_kv (&kv, m->local_addr, m->local_port,
984                            local->fib_index, m->proto,
985                            m - sm->static_mappings);
986               clib_bihash_add_del_8_8 (&sm->static_mapping_by_local, &kv, 1);
987               return 0;
988             }
989           else
990             return VNET_API_ERROR_VALUE_EXIST;
991         }
992
993       if (twice_nat && addr_only)
994         return VNET_API_ERROR_UNSUPPORTED;
995
996       /* Convert VRF id to FIB index */
997       if (vrf_id != ~0)
998         fib_index =
999           fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, vrf_id,
1000                                              nat_fib_src_low);
1001       /* If not specified use inside VRF id from SNAT plugin startup config */
1002       else
1003         {
1004           fib_index = sm->inside_fib_index;
1005           vrf_id = sm->inside_vrf_id;
1006           fib_table_lock (fib_index, FIB_PROTOCOL_IP4, nat_fib_src_low);
1007         }
1008
1009       if (!(out2in_only || identity_nat))
1010         {
1011           init_nat_k (&kv, l_addr, addr_only ? 0 : l_port, fib_index,
1012                       addr_only ? 0 : proto);
1013           if (!clib_bihash_search_8_8
1014               (&sm->static_mapping_by_local, &kv, &value))
1015             return VNET_API_ERROR_VALUE_EXIST;
1016         }
1017
1018       /* Find external address in allocated addresses and reserve port for
1019          address and port pair mapping when dynamic translations enabled */
1020       if (!(addr_only || sm->static_mapping_only || out2in_only))
1021         {
1022           for (i = 0; i < vec_len (sm->addresses); i++)
1023             {
1024               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1025                 {
1026                   a = sm->addresses + i;
1027                   /* External port must be unused */
1028                   switch (proto)
1029                     {
1030 #define _(N, j, n, s) \
1031                     case NAT_PROTOCOL_##N: \
1032                       if (a->busy_##n##_port_refcounts[e_port]) \
1033                         return VNET_API_ERROR_INVALID_VALUE; \
1034                       ++a->busy_##n##_port_refcounts[e_port]; \
1035                       if (e_port > 1024) \
1036                         { \
1037                           a->busy_##n##_ports++; \
1038                           a->busy_##n##_ports_per_thread[get_thread_idx_by_port(e_port)]++; \
1039                         } \
1040                       break;
1041                       foreach_nat_protocol
1042 #undef _
1043                     default:
1044                       nat_elog_info ("unknown protocol");
1045                       return VNET_API_ERROR_INVALID_VALUE_2;
1046                     }
1047                   break;
1048                 }
1049             }
1050           /* External address must be allocated */
1051           if (!a && (l_addr.as_u32 != e_addr.as_u32))
1052             {
1053               if (sw_if_index != ~0)
1054                 {
1055                   for (i = 0; i < vec_len (sm->to_resolve); i++)
1056                     {
1057                       rp = sm->to_resolve + i;
1058                       if (rp->addr_only)
1059                         continue;
1060                       if (rp->sw_if_index != sw_if_index &&
1061                           rp->l_addr.as_u32 != l_addr.as_u32 &&
1062                           rp->vrf_id != vrf_id && rp->l_port != l_port &&
1063                           rp->e_port != e_port && rp->proto != proto)
1064                         continue;
1065
1066                       vec_del1 (sm->to_resolve, i);
1067                       break;
1068                     }
1069                 }
1070               return VNET_API_ERROR_NO_SUCH_ENTRY;
1071             }
1072         }
1073
1074       pool_get (sm->static_mappings, m);
1075       clib_memset (m, 0, sizeof (*m));
1076       m->tag = vec_dup (tag);
1077       m->local_addr = l_addr;
1078       m->external_addr = e_addr;
1079       m->twice_nat = twice_nat;
1080       if (out2in_only)
1081         m->flags |= NAT_STATIC_MAPPING_FLAG_OUT2IN_ONLY;
1082       if (addr_only)
1083         m->flags |= NAT_STATIC_MAPPING_FLAG_ADDR_ONLY;
1084       if (identity_nat)
1085         {
1086           m->flags |= NAT_STATIC_MAPPING_FLAG_IDENTITY_NAT;
1087           pool_get (m->locals, local);
1088           local->vrf_id = vrf_id;
1089           local->fib_index = fib_index;
1090         }
1091       else
1092         {
1093           m->vrf_id = vrf_id;
1094           m->fib_index = fib_index;
1095         }
1096       if (!addr_only)
1097         {
1098           m->local_port = l_port;
1099           m->external_port = e_port;
1100           m->proto = proto;
1101         }
1102
1103       if (sm->num_workers > 1)
1104         {
1105           ip4_header_t ip = {
1106             .src_address = m->local_addr,
1107           };
1108           vec_add1 (m->workers, sm->worker_in2out_cb (&ip, m->fib_index, 0));
1109           tsm = vec_elt_at_index (sm->per_thread_data, m->workers[0]);
1110         }
1111       else
1112         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1113
1114       init_nat_kv (&kv, m->local_addr, m->local_port, fib_index, m->proto,
1115                    m - sm->static_mappings);
1116       if (!out2in_only)
1117         clib_bihash_add_del_8_8 (&sm->static_mapping_by_local, &kv, 1);
1118
1119       init_nat_kv (&kv, m->external_addr, m->external_port, 0, m->proto,
1120                    m - sm->static_mappings);
1121       clib_bihash_add_del_8_8 (&sm->static_mapping_by_external, &kv, 1);
1122
1123       /* Delete dynamic sessions matching local address (+ local port) */
1124       if (!(sm->static_mapping_only))
1125         {
1126           u_key.addr = m->local_addr;
1127           u_key.fib_index = m->fib_index;
1128           kv.key = u_key.as_u64;
1129           if (!clib_bihash_search_8_8 (&tsm->user_hash, &kv, &value))
1130             {
1131               user_index = value.value;
1132               u = pool_elt_at_index (tsm->users, user_index);
1133               if (u->nsessions)
1134                 {
1135                   head_index = u->sessions_per_user_list_head_index;
1136                   head = pool_elt_at_index (tsm->list_pool, head_index);
1137                   elt_index = head->next;
1138                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
1139                   ses_index = elt->value;
1140                   while (ses_index != ~0)
1141                     {
1142                       s = pool_elt_at_index (tsm->sessions, ses_index);
1143                       elt = pool_elt_at_index (tsm->list_pool, elt->next);
1144                       ses_index = elt->value;
1145
1146                       if (snat_is_session_static (s))
1147                         continue;
1148
1149                       if (!addr_only && s->in2out.port != m->local_port)
1150                         continue;
1151
1152                       nat_free_session_data (sm, s,
1153                                              tsm - sm->per_thread_data, 0);
1154                       nat44_delete_session (sm, s, tsm - sm->per_thread_data);
1155
1156                       if (!addr_only && !sm->endpoint_dependent)
1157                         break;
1158                     }
1159                 }
1160             }
1161         }
1162     }
1163   else
1164     {
1165       if (!m)
1166         {
1167           if (sw_if_index != ~0)
1168             return 0;
1169           else
1170             return VNET_API_ERROR_NO_SUCH_ENTRY;
1171         }
1172
1173       if (identity_nat)
1174         {
1175           if (vrf_id == ~0)
1176             vrf_id = sm->inside_vrf_id;
1177
1178           /* *INDENT-OFF* */
1179           pool_foreach (local, m->locals,
1180           ({
1181             if (local->vrf_id == vrf_id)
1182               find = local - m->locals;
1183           }));
1184           /* *INDENT-ON* */
1185           if (find == ~0)
1186             return VNET_API_ERROR_NO_SUCH_ENTRY;
1187
1188           local = pool_elt_at_index (m->locals, find);
1189           fib_index = local->fib_index;
1190           pool_put (m->locals, local);
1191         }
1192       else
1193         fib_index = m->fib_index;
1194
1195       /* Free external address port */
1196       if (!(addr_only || sm->static_mapping_only || out2in_only))
1197         {
1198           for (i = 0; i < vec_len (sm->addresses); i++)
1199             {
1200               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1201                 {
1202                   a = sm->addresses + i;
1203                   switch (proto)
1204                     {
1205 #define _(N, j, n, s) \
1206                     case NAT_PROTOCOL_##N: \
1207                       --a->busy_##n##_port_refcounts[e_port]; \
1208                       if (e_port > 1024) \
1209                         { \
1210                           a->busy_##n##_ports--; \
1211                           a->busy_##n##_ports_per_thread[get_thread_idx_by_port(e_port)]--; \
1212                         } \
1213                       break;
1214                       foreach_nat_protocol
1215 #undef _
1216                     default:
1217                       nat_elog_info ("unknown protocol");
1218                       return VNET_API_ERROR_INVALID_VALUE_2;
1219                     }
1220                   break;
1221                 }
1222             }
1223         }
1224
1225       if (sm->num_workers > 1)
1226         tsm = vec_elt_at_index (sm->per_thread_data, m->workers[0]);
1227       else
1228         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1229
1230       init_nat_k (&kv, m->local_addr, m->local_port, fib_index, m->proto);
1231       if (!out2in_only)
1232         clib_bihash_add_del_8_8 (&sm->static_mapping_by_local, &kv, 0);
1233
1234       /* Delete session(s) for static mapping if exist */
1235       if (!(sm->static_mapping_only) ||
1236           (sm->static_mapping_only && sm->static_mapping_connection_tracking))
1237         {
1238           if (sm->endpoint_dependent)
1239             {
1240               snat_ed_static_mapping_del_sessions (sm, tsm, m->local_addr,
1241                                                    m->local_port, m->proto,
1242                                                    fib_index, addr_only,
1243                                                    e_addr, e_port);
1244             }
1245           else
1246             {
1247               u_key.addr = m->local_addr;
1248               u_key.fib_index = fib_index;
1249               kv.key = u_key.as_u64;
1250               snat_static_mapping_del_sessions (sm, tsm, u_key, addr_only,
1251                                                 e_addr, e_port);
1252             }
1253         }
1254
1255       fib_table_unlock (fib_index, FIB_PROTOCOL_IP4, nat_fib_src_low);
1256       if (pool_elts (m->locals))
1257         return 0;
1258
1259       init_nat_k (&kv, m->external_addr, m->external_port, 0, m->proto);
1260       clib_bihash_add_del_8_8 (&sm->static_mapping_by_external, &kv, 0);
1261
1262       vec_free (m->tag);
1263       vec_free (m->workers);
1264       /* Delete static mapping from pool */
1265       pool_put (sm->static_mappings, m);
1266     }
1267
1268   if (!addr_only || (l_addr.as_u32 == e_addr.as_u32))
1269     return 0;
1270
1271   /* Add/delete external address to FIB */
1272   /* *INDENT-OFF* */
1273   pool_foreach (interface, sm->interfaces,
1274   ({
1275     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1276       continue;
1277
1278     snat_add_del_addr_to_fib(&e_addr, 32, interface->sw_if_index, is_add);
1279     break;
1280   }));
1281   pool_foreach (interface, sm->output_feature_interfaces,
1282   ({
1283     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1284       continue;
1285
1286     snat_add_del_addr_to_fib(&e_addr, 32, interface->sw_if_index, is_add);
1287     break;
1288   }));
1289   /* *INDENT-ON* */
1290
1291   return 0;
1292 }
1293
1294 int
1295 nat44_add_del_lb_static_mapping (ip4_address_t e_addr, u16 e_port,
1296                                  nat_protocol_t proto,
1297                                  nat44_lb_addr_port_t * locals, u8 is_add,
1298                                  twice_nat_type_t twice_nat, u8 out2in_only,
1299                                  u8 * tag, u32 affinity)
1300 {
1301   snat_main_t *sm = &snat_main;
1302   snat_static_mapping_t *m;
1303   clib_bihash_kv_8_8_t kv, value;
1304   snat_address_t *a = 0;
1305   int i;
1306   nat44_lb_addr_port_t *local;
1307   snat_main_per_thread_data_t *tsm;
1308   snat_session_t *s;
1309   uword *bitmap = 0;
1310
1311   if (!sm->endpoint_dependent)
1312     return VNET_API_ERROR_FEATURE_DISABLED;
1313
1314   init_nat_k (&kv, e_addr, e_port, 0, proto);
1315   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
1316     m = 0;
1317   else
1318     m = pool_elt_at_index (sm->static_mappings, value.value);
1319
1320   if (is_add)
1321     {
1322       if (m)
1323         return VNET_API_ERROR_VALUE_EXIST;
1324
1325       if (vec_len (locals) < 2)
1326         return VNET_API_ERROR_INVALID_VALUE;
1327
1328       /* Find external address in allocated addresses and reserve port for
1329          address and port pair mapping when dynamic translations enabled */
1330       if (!(sm->static_mapping_only || out2in_only))
1331         {
1332           for (i = 0; i < vec_len (sm->addresses); i++)
1333             {
1334               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1335                 {
1336                   a = sm->addresses + i;
1337                   /* External port must be unused */
1338                   switch (proto)
1339                     {
1340 #define _(N, j, n, s) \
1341                     case NAT_PROTOCOL_##N: \
1342                       if (a->busy_##n##_port_refcounts[e_port]) \
1343                         return VNET_API_ERROR_INVALID_VALUE; \
1344                       ++a->busy_##n##_port_refcounts[e_port]; \
1345                       if (e_port > 1024) \
1346                         { \
1347                           a->busy_##n##_ports++; \
1348                           a->busy_##n##_ports_per_thread[get_thread_idx_by_port(e_port)]++; \
1349                         } \
1350                       break;
1351                       foreach_nat_protocol
1352 #undef _
1353                     default:
1354                       nat_elog_info ("unknown protocol");
1355                       return VNET_API_ERROR_INVALID_VALUE_2;
1356                     }
1357                   break;
1358                 }
1359             }
1360           /* External address must be allocated */
1361           if (!a)
1362             return VNET_API_ERROR_NO_SUCH_ENTRY;
1363         }
1364
1365       pool_get (sm->static_mappings, m);
1366       clib_memset (m, 0, sizeof (*m));
1367       m->tag = vec_dup (tag);
1368       m->external_addr = e_addr;
1369       m->external_port = e_port;
1370       m->proto = proto;
1371       m->twice_nat = twice_nat;
1372       m->flags |= NAT_STATIC_MAPPING_FLAG_LB;
1373       if (out2in_only)
1374         m->flags |= NAT_STATIC_MAPPING_FLAG_OUT2IN_ONLY;
1375       m->affinity = affinity;
1376
1377       if (affinity)
1378         m->affinity_per_service_list_head_index =
1379           nat_affinity_get_per_service_list_head_index ();
1380       else
1381         m->affinity_per_service_list_head_index = ~0;
1382
1383       init_nat_kv (&kv, m->external_addr, m->external_port, 0, m->proto,
1384                    m - sm->static_mappings);
1385       if (clib_bihash_add_del_8_8 (&sm->static_mapping_by_external, &kv, 1))
1386         {
1387           nat_elog_err ("static_mapping_by_external key add failed");
1388           return VNET_API_ERROR_UNSPECIFIED;
1389         }
1390
1391       for (i = 0; i < vec_len (locals); i++)
1392         {
1393           locals[i].fib_index =
1394             fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
1395                                                locals[i].vrf_id,
1396                                                nat_fib_src_low);
1397           if (!out2in_only)
1398             {
1399               init_nat_kv (&kv, locals[i].addr, locals[i].port,
1400                            locals[i].fib_index, m->proto,
1401                            m - sm->static_mappings);
1402               clib_bihash_add_del_8_8 (&sm->static_mapping_by_local, &kv, 1);
1403             }
1404           locals[i].prefix = (i == 0) ? locals[i].probability :
1405             (locals[i - 1].prefix + locals[i].probability);
1406           pool_get (m->locals, local);
1407           *local = locals[i];
1408           if (sm->num_workers > 1)
1409             {
1410               ip4_header_t ip = {
1411                 .src_address = locals[i].addr,
1412               };
1413               bitmap =
1414                 clib_bitmap_set (bitmap,
1415                                  sm->worker_in2out_cb (&ip, m->fib_index, 0),
1416                                  1);
1417             }
1418         }
1419
1420       /* Assign workers */
1421       if (sm->num_workers > 1)
1422         {
1423           /* *INDENT-OFF* */
1424           clib_bitmap_foreach (i, bitmap,
1425             ({
1426                vec_add1(m->workers, i);
1427             }));
1428           /* *INDENT-ON* */
1429         }
1430     }
1431   else
1432     {
1433       if (!m)
1434         return VNET_API_ERROR_NO_SUCH_ENTRY;
1435
1436       if (!is_lb_static_mapping (m))
1437         return VNET_API_ERROR_INVALID_VALUE;
1438
1439       /* Free external address port */
1440       if (!(sm->static_mapping_only || out2in_only))
1441         {
1442           for (i = 0; i < vec_len (sm->addresses); i++)
1443             {
1444               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1445                 {
1446                   a = sm->addresses + i;
1447                   switch (proto)
1448                     {
1449 #define _(N, j, n, s) \
1450                     case NAT_PROTOCOL_##N: \
1451                       --a->busy_##n##_port_refcounts[e_port]; \
1452                       if (e_port > 1024) \
1453                         { \
1454                           a->busy_##n##_ports--; \
1455                           a->busy_##n##_ports_per_thread[get_thread_idx_by_port(e_port)]--; \
1456                         } \
1457                       break;
1458                       foreach_nat_protocol
1459 #undef _
1460                     default:
1461                       nat_elog_info ("unknown protocol");
1462                       return VNET_API_ERROR_INVALID_VALUE_2;
1463                     }
1464                   break;
1465                 }
1466             }
1467         }
1468
1469       init_nat_k (&kv, m->external_addr, m->external_port, 0, m->proto);
1470       if (clib_bihash_add_del_8_8 (&sm->static_mapping_by_external, &kv, 0))
1471         {
1472           nat_elog_err ("static_mapping_by_external key del failed");
1473           return VNET_API_ERROR_UNSPECIFIED;
1474         }
1475
1476       /* *INDENT-OFF* */
1477       pool_foreach (local, m->locals,
1478       ({
1479           fib_table_unlock (local->fib_index, FIB_PROTOCOL_IP4,
1480                             nat_fib_src_low);
1481           if (!out2in_only)
1482             {
1483 init_nat_k(&              kv, local->addr, local->port, local->fib_index, m->proto);
1484               if (clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 0))
1485                 {
1486                   nat_elog_err ("static_mapping_by_local key del failed");
1487                   return VNET_API_ERROR_UNSPECIFIED;
1488                 }
1489             }
1490
1491           if (sm->num_workers > 1)
1492             {
1493               ip4_header_t ip = {
1494                 .src_address = local->addr,
1495               };
1496               tsm = vec_elt_at_index (sm->per_thread_data,
1497                                       sm->worker_in2out_cb (&ip, m->fib_index, 0));
1498             }
1499           else
1500             tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1501
1502           /* Delete sessions */
1503           pool_foreach (s, tsm->sessions, {
1504             if (!(is_lb_session (s)))
1505               continue;
1506
1507             if ((s->in2out.addr.as_u32 != local->addr.as_u32) ||
1508                 s->in2out.port != local->port)
1509               continue;
1510
1511             nat_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
1512             nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
1513           });
1514       }));
1515       /* *INDENT-ON* */
1516       if (m->affinity)
1517         nat_affinity_flush_service (m->affinity_per_service_list_head_index);
1518       pool_free (m->locals);
1519       vec_free (m->tag);
1520       vec_free (m->workers);
1521
1522       pool_put (sm->static_mappings, m);
1523     }
1524
1525   return 0;
1526 }
1527
1528 int
1529 nat44_lb_static_mapping_add_del_local (ip4_address_t e_addr, u16 e_port,
1530                                        ip4_address_t l_addr, u16 l_port,
1531                                        nat_protocol_t proto, u32 vrf_id,
1532                                        u8 probability, u8 is_add)
1533 {
1534   snat_main_t *sm = &snat_main;
1535   snat_static_mapping_t *m = 0;
1536   clib_bihash_kv_8_8_t kv, value;
1537   nat44_lb_addr_port_t *local, *prev_local, *match_local = 0;
1538   snat_main_per_thread_data_t *tsm;
1539   snat_session_t *s;
1540   u32 *locals = 0;
1541   uword *bitmap = 0;
1542   int i;
1543
1544   if (!sm->endpoint_dependent)
1545     return VNET_API_ERROR_FEATURE_DISABLED;
1546
1547   init_nat_k (&kv, e_addr, e_port, 0, proto);
1548   if (!clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
1549     m = pool_elt_at_index (sm->static_mappings, value.value);
1550
1551   if (!m)
1552     return VNET_API_ERROR_NO_SUCH_ENTRY;
1553
1554   if (!is_lb_static_mapping (m))
1555     return VNET_API_ERROR_INVALID_VALUE;
1556
1557   /* *INDENT-OFF* */
1558   pool_foreach (local, m->locals,
1559   ({
1560     if ((local->addr.as_u32 == l_addr.as_u32) && (local->port == l_port) &&
1561         (local->vrf_id == vrf_id))
1562       {
1563         match_local = local;
1564         break;
1565       }
1566   }));
1567   /* *INDENT-ON* */
1568
1569   if (is_add)
1570     {
1571       if (match_local)
1572         return VNET_API_ERROR_VALUE_EXIST;
1573
1574       pool_get (m->locals, local);
1575       clib_memset (local, 0, sizeof (*local));
1576       local->addr.as_u32 = l_addr.as_u32;
1577       local->port = l_port;
1578       local->probability = probability;
1579       local->vrf_id = vrf_id;
1580       local->fib_index =
1581         fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, vrf_id,
1582                                            nat_fib_src_low);
1583
1584       if (!is_out2in_only_static_mapping (m))
1585         {
1586           init_nat_kv (&kv, l_addr, l_port, local->fib_index, proto,
1587                        m - sm->static_mappings);
1588           if (clib_bihash_add_del_8_8 (&sm->static_mapping_by_local, &kv, 1))
1589             nat_elog_err ("static_mapping_by_local key add failed");
1590         }
1591     }
1592   else
1593     {
1594       if (!match_local)
1595         return VNET_API_ERROR_NO_SUCH_ENTRY;
1596
1597       if (pool_elts (m->locals) < 3)
1598         return VNET_API_ERROR_UNSPECIFIED;
1599
1600       fib_table_unlock (match_local->fib_index, FIB_PROTOCOL_IP4,
1601                         nat_fib_src_low);
1602
1603       if (!is_out2in_only_static_mapping (m))
1604         {
1605           init_nat_k (&kv, l_addr, l_port, match_local->fib_index, proto);
1606           if (clib_bihash_add_del_8_8 (&sm->static_mapping_by_local, &kv, 0))
1607             nat_elog_err ("static_mapping_by_local key del failed");
1608         }
1609
1610       if (sm->num_workers > 1)
1611         {
1612           ip4_header_t ip = {
1613             .src_address = local->addr,
1614           };
1615           tsm = vec_elt_at_index (sm->per_thread_data,
1616                                   sm->worker_in2out_cb (&ip, m->fib_index,
1617                                                         0));
1618         }
1619       else
1620         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1621
1622       /* Delete sessions */
1623       /* *INDENT-OFF* */
1624       pool_foreach (s, tsm->sessions, {
1625         if (!(is_lb_session (s)))
1626           continue;
1627
1628         if ((s->in2out.addr.as_u32 != match_local->addr.as_u32) ||
1629             s->in2out.port != match_local->port)
1630           continue;
1631
1632         nat_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
1633         nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
1634       });
1635       /* *INDENT-ON* */
1636
1637       pool_put (m->locals, match_local);
1638     }
1639
1640   vec_free (m->workers);
1641
1642   /* *INDENT-OFF* */
1643   pool_foreach (local, m->locals,
1644   ({
1645     vec_add1 (locals, local - m->locals);
1646     if (sm->num_workers > 1)
1647       {
1648         ip4_header_t ip;
1649         ip.src_address.as_u32 = local->addr.as_u32,
1650         bitmap = clib_bitmap_set (bitmap,
1651                                   sm->worker_in2out_cb (&ip, local->fib_index, 0),
1652                                   1);
1653       }
1654   }));
1655   /* *INDENT-ON* */
1656
1657   ASSERT (vec_len (locals) > 1);
1658
1659   local = pool_elt_at_index (m->locals, locals[0]);
1660   local->prefix = local->probability;
1661   for (i = 1; i < vec_len (locals); i++)
1662     {
1663       local = pool_elt_at_index (m->locals, locals[i]);
1664       prev_local = pool_elt_at_index (m->locals, locals[i - 1]);
1665       local->prefix = local->probability + prev_local->prefix;
1666     }
1667
1668   /* Assign workers */
1669   if (sm->num_workers > 1)
1670     {
1671       /* *INDENT-OFF* */
1672       clib_bitmap_foreach (i, bitmap, ({ vec_add1(m->workers, i); }));
1673       /* *INDENT-ON* */
1674     }
1675
1676   return 0;
1677 }
1678
1679 int
1680 snat_del_address (snat_main_t * sm, ip4_address_t addr, u8 delete_sm,
1681                   u8 twice_nat)
1682 {
1683   snat_address_t *a = 0;
1684   snat_session_t *ses;
1685   u32 *ses_to_be_removed = 0, *ses_index;
1686   snat_main_per_thread_data_t *tsm;
1687   snat_static_mapping_t *m;
1688   snat_interface_t *interface;
1689   int i;
1690   snat_address_t *addresses =
1691     twice_nat ? sm->twice_nat_addresses : sm->addresses;
1692
1693   /* Find SNAT address */
1694   for (i = 0; i < vec_len (addresses); i++)
1695     {
1696       if (addresses[i].addr.as_u32 == addr.as_u32)
1697         {
1698           a = addresses + i;
1699           break;
1700         }
1701     }
1702   if (!a)
1703     return VNET_API_ERROR_NO_SUCH_ENTRY;
1704
1705   if (delete_sm)
1706     {
1707       /* *INDENT-OFF* */
1708       pool_foreach (m, sm->static_mappings,
1709       ({
1710           if (m->external_addr.as_u32 == addr.as_u32)
1711             (void) snat_add_static_mapping (m->local_addr, m->external_addr,
1712                                             m->local_port, m->external_port,
1713                                             m->vrf_id, is_addr_only_static_mapping(m), ~0,
1714                                             m->proto, 0, m->twice_nat,
1715                                             is_out2in_only_static_mapping(m), m->tag, is_identity_static_mapping(m));
1716       }));
1717       /* *INDENT-ON* */
1718     }
1719   else
1720     {
1721       /* Check if address is used in some static mapping */
1722       if (is_snat_address_used_in_static_mapping (sm, addr))
1723         {
1724           nat_elog_notice ("address used in static mapping");
1725           return VNET_API_ERROR_UNSPECIFIED;
1726         }
1727     }
1728
1729   if (a->fib_index != ~0)
1730     fib_table_unlock (a->fib_index, FIB_PROTOCOL_IP4, nat_fib_src_low);
1731
1732   /* Delete sessions using address */
1733   if (a->busy_tcp_ports || a->busy_udp_ports || a->busy_icmp_ports)
1734     {
1735       /* *INDENT-OFF* */
1736       vec_foreach (tsm, sm->per_thread_data)
1737         {
1738           pool_foreach (ses, tsm->sessions, ({
1739             if (ses->out2in.addr.as_u32 == addr.as_u32)
1740               {
1741                 nat_free_session_data (sm, ses, tsm - sm->per_thread_data, 0);
1742                 vec_add1 (ses_to_be_removed, ses - tsm->sessions);
1743               }
1744           }));
1745
1746           if (sm->endpoint_dependent){
1747               vec_foreach (ses_index, ses_to_be_removed)
1748                 {
1749                   ses = pool_elt_at_index (tsm->sessions, ses_index[0]);
1750                   nat_ed_session_delete (sm, ses, tsm - sm->per_thread_data, 1);
1751                 }
1752           }else{
1753               vec_foreach (ses_index, ses_to_be_removed)
1754                 {
1755                   ses = pool_elt_at_index (tsm->sessions, ses_index[0]);
1756                   nat44_delete_session (sm, ses, tsm - sm->per_thread_data);
1757                 }
1758           }
1759
1760           vec_free (ses_to_be_removed);
1761         }
1762       /* *INDENT-ON* */
1763     }
1764
1765 #define _(N, i, n, s) \
1766   vec_free (a->busy_##n##_ports_per_thread);
1767   foreach_nat_protocol
1768 #undef _
1769     if (twice_nat)
1770     {
1771       vec_del1 (sm->twice_nat_addresses, i);
1772       return 0;
1773     }
1774   else
1775     vec_del1 (sm->addresses, i);
1776
1777   /* Delete external address from FIB */
1778   /* *INDENT-OFF* */
1779   pool_foreach (interface, sm->interfaces,
1780   ({
1781     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1782       continue;
1783
1784     snat_add_del_addr_to_fib(&addr, 32, interface->sw_if_index, 0);
1785     break;
1786   }));
1787   pool_foreach (interface, sm->output_feature_interfaces,
1788   ({
1789     if (nat_interface_is_inside(interface) || sm->out2in_dpo)
1790       continue;
1791
1792     snat_add_del_addr_to_fib(&addr, 32, interface->sw_if_index, 0);
1793     break;
1794   }));
1795   /* *INDENT-ON* */
1796
1797   return 0;
1798 }
1799
1800 int
1801 snat_interface_add_del (u32 sw_if_index, u8 is_inside, int is_del)
1802 {
1803   snat_main_t *sm = &snat_main;
1804   snat_interface_t *i;
1805   const char *feature_name, *del_feature_name;
1806   snat_address_t *ap;
1807   snat_static_mapping_t *m;
1808   snat_det_map_t *dm;
1809   nat_outside_fib_t *outside_fib;
1810   u32 fib_index = fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4,
1811                                                        sw_if_index);
1812
1813   if (sm->out2in_dpo && !is_inside)
1814     return VNET_API_ERROR_UNSUPPORTED;
1815
1816   /* *INDENT-OFF* */
1817   pool_foreach (i, sm->output_feature_interfaces,
1818   ({
1819     if (i->sw_if_index == sw_if_index)
1820       return VNET_API_ERROR_VALUE_EXIST;
1821   }));
1822   /* *INDENT-ON* */
1823
1824   if (sm->static_mapping_only && !(sm->static_mapping_connection_tracking))
1825     feature_name = is_inside ? "nat44-in2out-fast" : "nat44-out2in-fast";
1826   else
1827     {
1828       if (sm->num_workers > 1 && !sm->deterministic)
1829         feature_name =
1830           is_inside ? "nat44-in2out-worker-handoff" :
1831           "nat44-out2in-worker-handoff";
1832       else if (sm->deterministic)
1833         feature_name = is_inside ? "nat44-det-in2out" : "nat44-det-out2in";
1834       else if (sm->endpoint_dependent)
1835         {
1836           feature_name = is_inside ? "nat-pre-in2out" : "nat-pre-out2in";
1837         }
1838       else
1839         feature_name = is_inside ? "nat44-in2out" : "nat44-out2in";
1840     }
1841
1842   if (sm->fq_in2out_index == ~0 && !sm->deterministic && sm->num_workers > 1)
1843     sm->fq_in2out_index =
1844       vlib_frame_queue_main_init (sm->in2out_node_index, NAT_FQ_NELTS);
1845
1846   if (sm->fq_out2in_index == ~0 && !sm->deterministic && sm->num_workers > 1)
1847     sm->fq_out2in_index =
1848       vlib_frame_queue_main_init (sm->out2in_node_index, NAT_FQ_NELTS);
1849
1850   if (!is_inside)
1851     {
1852       /* *INDENT-OFF* */
1853       vec_foreach (outside_fib, sm->outside_fibs)
1854         {
1855           if (outside_fib->fib_index == fib_index)
1856             {
1857               if (is_del)
1858                 {
1859                   outside_fib->refcount--;
1860                   if (!outside_fib->refcount)
1861                     vec_del1 (sm->outside_fibs, outside_fib - sm->outside_fibs);
1862                 }
1863               else
1864                 outside_fib->refcount++;
1865               goto feature_set;
1866             }
1867         }
1868       /* *INDENT-ON* */
1869       if (!is_del)
1870         {
1871           vec_add2 (sm->outside_fibs, outside_fib, 1);
1872           outside_fib->refcount = 1;
1873           outside_fib->fib_index = fib_index;
1874         }
1875     }
1876 feature_set:
1877   /* *INDENT-OFF* */
1878   pool_foreach (i, sm->interfaces,
1879   ({
1880     if (i->sw_if_index == sw_if_index)
1881       {
1882         if (is_del)
1883           {
1884             if (nat_interface_is_inside(i) && nat_interface_is_outside(i))
1885               {
1886                 if (is_inside)
1887                   i->flags &= ~NAT_INTERFACE_FLAG_IS_INSIDE;
1888                 else
1889                   i->flags &= ~NAT_INTERFACE_FLAG_IS_OUTSIDE;
1890
1891                 if (sm->num_workers > 1 && !sm->deterministic)
1892                   {
1893                     del_feature_name = "nat44-handoff-classify";
1894                     feature_name = !is_inside ?  "nat44-in2out-worker-handoff" :
1895                                                  "nat44-out2in-worker-handoff";
1896                   }
1897                 else if (sm->deterministic)
1898                   {
1899                     del_feature_name = "nat44-det-classify";
1900                     feature_name = !is_inside ?  "nat44-det-in2out" :
1901                                                  "nat44-det-out2in";
1902                   }
1903                 else if (sm->endpoint_dependent)
1904                   {
1905                     del_feature_name = "nat44-ed-classify";
1906                     feature_name = !is_inside ?  "nat-pre-in2out" :
1907                                                  "nat-pre-out2in";
1908                   }
1909                 else
1910                   {
1911                     del_feature_name = "nat44-classify";
1912                     feature_name = !is_inside ?  "nat44-in2out" : "nat44-out2in";
1913                   }
1914
1915                 int rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 0);
1916                 if (rv)
1917                   return rv;
1918                 vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1919                                              sw_if_index, 0, 0, 0);
1920                 vnet_feature_enable_disable ("ip4-unicast", feature_name,
1921                                              sw_if_index, 1, 0, 0);
1922                 if (!is_inside)
1923                   {
1924                     if (sm->endpoint_dependent)
1925                       vnet_feature_enable_disable ("ip4-local",
1926                                                    "nat44-ed-hairpinning",
1927                                                    sw_if_index, 1, 0, 0);
1928                     else if (!sm->deterministic)
1929                       vnet_feature_enable_disable ("ip4-local",
1930                                                    "nat44-hairpinning",
1931                                                    sw_if_index, 1, 0, 0);
1932                   }
1933               }
1934             else
1935               {
1936                 int rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 0);
1937                 if (rv)
1938                   return rv;
1939                 vnet_feature_enable_disable ("ip4-unicast", feature_name,
1940                                              sw_if_index, 0, 0, 0);
1941                 pool_put (sm->interfaces, i);
1942                 if (is_inside)
1943                   {
1944                     if (sm->endpoint_dependent)
1945                       vnet_feature_enable_disable ("ip4-local",
1946                                                    "nat44-ed-hairpinning",
1947                                                    sw_if_index, 0, 0, 0);
1948                     else if (!sm->deterministic)
1949                       vnet_feature_enable_disable ("ip4-local",
1950                                                    "nat44-hairpinning",
1951                                                    sw_if_index, 0, 0, 0);
1952                   }
1953               }
1954           }
1955         else
1956           {
1957             if ((nat_interface_is_inside(i) && is_inside) ||
1958                 (nat_interface_is_outside(i) && !is_inside))
1959               return 0;
1960
1961             if (sm->num_workers > 1 && !sm->deterministic)
1962               {
1963                 del_feature_name = !is_inside ?  "nat44-in2out-worker-handoff" :
1964                                                  "nat44-out2in-worker-handoff";
1965                 feature_name = "nat44-handoff-classify";
1966               }
1967             else if (sm->deterministic)
1968               {
1969                 del_feature_name = !is_inside ?  "nat44-det-in2out" :
1970                                                  "nat44-det-out2in";
1971                 feature_name = "nat44-det-classify";
1972               }
1973             else if (sm->endpoint_dependent)
1974               {
1975                 del_feature_name = !is_inside ?  "nat-pre-in2out" :
1976                                                  "nat-pre-out2in";
1977
1978                 feature_name = "nat44-ed-classify";
1979               }
1980             else
1981               {
1982                 del_feature_name = !is_inside ?  "nat44-in2out" : "nat44-out2in";
1983                 feature_name = "nat44-classify";
1984               }
1985
1986             int rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 1);
1987             if (rv)
1988               return rv;
1989             vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1990                                          sw_if_index, 0, 0, 0);
1991             vnet_feature_enable_disable ("ip4-unicast", feature_name,
1992                                          sw_if_index, 1, 0, 0);
1993             if (!is_inside)
1994               {
1995                 if (sm->endpoint_dependent)
1996                   vnet_feature_enable_disable ("ip4-local", "nat44-ed-hairpinning",
1997                                                sw_if_index, 0, 0, 0);
1998                 else if (!sm->deterministic)
1999                   vnet_feature_enable_disable ("ip4-local", "nat44-hairpinning",
2000                                                sw_if_index, 0, 0, 0);
2001               }
2002             goto set_flags;
2003           }
2004
2005         goto fib;
2006       }
2007   }));
2008   /* *INDENT-ON* */
2009
2010   if (is_del)
2011     return VNET_API_ERROR_NO_SUCH_ENTRY;
2012
2013   pool_get (sm->interfaces, i);
2014   i->sw_if_index = sw_if_index;
2015   i->flags = 0;
2016   vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index, 1, 0,
2017                                0);
2018
2019   int rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 1);
2020   if (rv)
2021     return rv;
2022
2023   if (is_inside && !sm->out2in_dpo)
2024     {
2025       if (sm->endpoint_dependent)
2026         vnet_feature_enable_disable ("ip4-local", "nat44-ed-hairpinning",
2027                                      sw_if_index, 1, 0, 0);
2028       else if (!sm->deterministic)
2029         vnet_feature_enable_disable ("ip4-local", "nat44-hairpinning",
2030                                      sw_if_index, 1, 0, 0);
2031     }
2032
2033 set_flags:
2034   if (is_inside)
2035     {
2036       i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
2037       return 0;
2038     }
2039   else
2040     i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
2041
2042   /* Add/delete external addresses to FIB */
2043 fib:
2044   /* *INDENT-OFF* */
2045   vec_foreach (ap, sm->addresses)
2046     snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, !is_del);
2047
2048   pool_foreach (m, sm->static_mappings,
2049   ({
2050     if (!(is_addr_only_static_mapping(m)) || (m->local_addr.as_u32 == m->external_addr.as_u32))
2051       continue;
2052
2053     snat_add_del_addr_to_fib(&m->external_addr, 32, sw_if_index, !is_del);
2054   }));
2055
2056   pool_foreach (dm, sm->det_maps,
2057   ({
2058     snat_add_del_addr_to_fib(&dm->out_addr, dm->out_plen, sw_if_index, !is_del);
2059   }));
2060   /* *INDENT-ON* */
2061
2062   return 0;
2063 }
2064
2065 int
2066 snat_interface_add_del_output_feature (u32 sw_if_index,
2067                                        u8 is_inside, int is_del)
2068 {
2069   snat_main_t *sm = &snat_main;
2070   snat_interface_t *i;
2071   snat_address_t *ap;
2072   snat_static_mapping_t *m;
2073   nat_outside_fib_t *outside_fib;
2074   u32 fib_index = fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4,
2075                                                        sw_if_index);
2076
2077
2078   if (sm->deterministic ||
2079       (sm->static_mapping_only && !(sm->static_mapping_connection_tracking)))
2080     return VNET_API_ERROR_UNSUPPORTED;
2081
2082   /* *INDENT-OFF* */
2083   pool_foreach (i, sm->interfaces,
2084   ({
2085     if (i->sw_if_index == sw_if_index)
2086       return VNET_API_ERROR_VALUE_EXIST;
2087   }));
2088   /* *INDENT-ON* */
2089
2090   if (!is_inside)
2091     {
2092       /* *INDENT-OFF* */
2093       vec_foreach (outside_fib, sm->outside_fibs)
2094         {
2095           if (outside_fib->fib_index == fib_index)
2096             {
2097               if (is_del)
2098                 {
2099                   outside_fib->refcount--;
2100                   if (!outside_fib->refcount)
2101                     vec_del1 (sm->outside_fibs, outside_fib - sm->outside_fibs);
2102                 }
2103               else
2104                 outside_fib->refcount++;
2105               goto feature_set;
2106             }
2107         }
2108       /* *INDENT-ON* */
2109       if (!is_del)
2110         {
2111           vec_add2 (sm->outside_fibs, outside_fib, 1);
2112           outside_fib->refcount = 1;
2113           outside_fib->fib_index = fib_index;
2114         }
2115     }
2116
2117 feature_set:
2118   if (is_inside)
2119     {
2120       if (sm->endpoint_dependent)
2121         {
2122           int rv =
2123             ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, !is_del);
2124           if (rv)
2125             return rv;
2126           rv =
2127             ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index,
2128                                                             !is_del);
2129           if (rv)
2130             return rv;
2131           vnet_feature_enable_disable ("ip4-unicast", "nat44-ed-hairpin-dst",
2132                                        sw_if_index, !is_del, 0, 0);
2133           vnet_feature_enable_disable ("ip4-output", "nat44-ed-hairpin-src",
2134                                        sw_if_index, !is_del, 0, 0);
2135         }
2136       else
2137         {
2138           int rv =
2139             ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, !is_del);
2140           if (rv)
2141             return rv;
2142           rv =
2143             ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index,
2144                                                             !is_del);
2145           if (rv)
2146             return rv;
2147           vnet_feature_enable_disable ("ip4-unicast", "nat44-hairpin-dst",
2148                                        sw_if_index, !is_del, 0, 0);
2149           vnet_feature_enable_disable ("ip4-output", "nat44-hairpin-src",
2150                                        sw_if_index, !is_del, 0, 0);
2151         }
2152       goto fq;
2153     }
2154
2155   if (sm->num_workers > 1)
2156     {
2157       int rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, !is_del);
2158       if (rv)
2159         return rv;
2160       rv =
2161         ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index, !is_del);
2162       if (rv)
2163         return rv;
2164       vnet_feature_enable_disable ("ip4-unicast",
2165                                    "nat44-out2in-worker-handoff",
2166                                    sw_if_index, !is_del, 0, 0);
2167       vnet_feature_enable_disable ("ip4-output",
2168                                    "nat44-in2out-output-worker-handoff",
2169                                    sw_if_index, !is_del, 0, 0);
2170     }
2171   else
2172     {
2173       if (sm->endpoint_dependent)
2174         {
2175           int rv =
2176             ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, !is_del);
2177           if (rv)
2178             return rv;
2179           rv =
2180             ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index,
2181                                                             !is_del);
2182           if (rv)
2183             return rv;
2184           vnet_feature_enable_disable ("ip4-unicast", "nat-pre-out2in",
2185                                        sw_if_index, !is_del, 0, 0);
2186           vnet_feature_enable_disable ("ip4-output", "nat44-ed-in2out-output",
2187                                        sw_if_index, !is_del, 0, 0);
2188         }
2189       else
2190         {
2191           int rv =
2192             ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, !is_del);
2193           if (rv)
2194             return rv;
2195           rv =
2196             ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index,
2197                                                             !is_del);
2198           if (rv)
2199             return rv;
2200           vnet_feature_enable_disable ("ip4-unicast", "nat44-out2in",
2201                                        sw_if_index, !is_del, 0, 0);
2202           vnet_feature_enable_disable ("ip4-output", "nat44-in2out-output",
2203                                        sw_if_index, !is_del, 0, 0);
2204         }
2205     }
2206
2207 fq:
2208   if (sm->fq_in2out_output_index == ~0 && sm->num_workers > 1)
2209     sm->fq_in2out_output_index =
2210       vlib_frame_queue_main_init (sm->in2out_output_node_index, 0);
2211
2212   if (sm->fq_out2in_index == ~0 && sm->num_workers > 1)
2213     sm->fq_out2in_index =
2214       vlib_frame_queue_main_init (sm->out2in_node_index, 0);
2215
2216   /* *INDENT-OFF* */
2217   pool_foreach (i, sm->output_feature_interfaces,
2218   ({
2219     if (i->sw_if_index == sw_if_index)
2220       {
2221         if (is_del)
2222           pool_put (sm->output_feature_interfaces, i);
2223         else
2224           return VNET_API_ERROR_VALUE_EXIST;
2225
2226         goto fib;
2227       }
2228   }));
2229   /* *INDENT-ON* */
2230
2231   if (is_del)
2232     return VNET_API_ERROR_NO_SUCH_ENTRY;
2233
2234   pool_get (sm->output_feature_interfaces, i);
2235   i->sw_if_index = sw_if_index;
2236   i->flags = 0;
2237   if (is_inside)
2238     i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
2239   else
2240     i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
2241
2242   /* Add/delete external addresses to FIB */
2243 fib:
2244   if (is_inside)
2245     return 0;
2246
2247   /* *INDENT-OFF* */
2248   vec_foreach (ap, sm->addresses)
2249     snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, !is_del);
2250
2251   pool_foreach (m, sm->static_mappings,
2252   ({
2253     if (!((is_addr_only_static_mapping(m)))  || (m->local_addr.as_u32 == m->external_addr.as_u32))
2254       continue;
2255
2256     snat_add_del_addr_to_fib(&m->external_addr, 32, sw_if_index, !is_del);
2257   }));
2258   /* *INDENT-ON* */
2259
2260   return 0;
2261 }
2262
2263 int
2264 snat_set_workers (uword * bitmap)
2265 {
2266   snat_main_t *sm = &snat_main;
2267   int i, j = 0;
2268
2269   if (sm->num_workers < 2)
2270     return VNET_API_ERROR_FEATURE_DISABLED;
2271
2272   if (clib_bitmap_last_set (bitmap) >= sm->num_workers)
2273     return VNET_API_ERROR_INVALID_WORKER;
2274
2275   vec_free (sm->workers);
2276   /* *INDENT-OFF* */
2277   clib_bitmap_foreach (i, bitmap,
2278     ({
2279       vec_add1(sm->workers, i);
2280       sm->per_thread_data[sm->first_worker_index + i].snat_thread_index = j;
2281       sm->per_thread_data[sm->first_worker_index + i].thread_index = i;
2282       j++;
2283     }));
2284   /* *INDENT-ON* */
2285
2286   sm->port_per_thread = (0xffff - 1024) / _vec_len (sm->workers);
2287
2288   return 0;
2289 }
2290
2291 static void
2292 snat_update_outside_fib (u32 sw_if_index, u32 new_fib_index,
2293                          u32 old_fib_index)
2294 {
2295   snat_main_t *sm = &snat_main;
2296   nat_outside_fib_t *outside_fib;
2297   snat_interface_t *i;
2298   u8 is_add = 1;
2299   u8 match = 0;
2300
2301   if (new_fib_index == old_fib_index)
2302     return;
2303
2304   if (!vec_len (sm->outside_fibs))
2305     return;
2306
2307   /* *INDENT-OFF* */
2308   pool_foreach (i, sm->interfaces,
2309     ({
2310       if (i->sw_if_index == sw_if_index)
2311         {
2312           if (!(nat_interface_is_outside (i)))
2313             return;
2314           match = 1;
2315         }
2316     }));
2317
2318   pool_foreach (i, sm->output_feature_interfaces,
2319     ({
2320       if (i->sw_if_index == sw_if_index)
2321         {
2322           if (!(nat_interface_is_outside (i)))
2323             return;
2324           match = 1;
2325         }
2326     }));
2327   /* *INDENT-ON* */
2328
2329   if (!match)
2330     return;
2331
2332   vec_foreach (outside_fib, sm->outside_fibs)
2333   {
2334     if (outside_fib->fib_index == old_fib_index)
2335       {
2336         outside_fib->refcount--;
2337         if (!outside_fib->refcount)
2338           vec_del1 (sm->outside_fibs, outside_fib - sm->outside_fibs);
2339         break;
2340       }
2341   }
2342
2343   vec_foreach (outside_fib, sm->outside_fibs)
2344   {
2345     if (outside_fib->fib_index == new_fib_index)
2346       {
2347         outside_fib->refcount++;
2348         is_add = 0;
2349         break;
2350       }
2351   }
2352
2353   if (is_add)
2354     {
2355       vec_add2 (sm->outside_fibs, outside_fib, 1);
2356       outside_fib->refcount = 1;
2357       outside_fib->fib_index = new_fib_index;
2358     }
2359 }
2360
2361 static void
2362 snat_ip4_table_bind (ip4_main_t * im,
2363                      uword opaque,
2364                      u32 sw_if_index, u32 new_fib_index, u32 old_fib_index)
2365 {
2366   snat_update_outside_fib (sw_if_index, new_fib_index, old_fib_index);
2367 }
2368
2369 static void
2370 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
2371                                        uword opaque,
2372                                        u32 sw_if_index,
2373                                        ip4_address_t * address,
2374                                        u32 address_length,
2375                                        u32 if_address_index, u32 is_delete);
2376
2377 static void
2378 nat_ip4_add_del_addr_only_sm_cb (ip4_main_t * im,
2379                                  uword opaque,
2380                                  u32 sw_if_index,
2381                                  ip4_address_t * address,
2382                                  u32 address_length,
2383                                  u32 if_address_index, u32 is_delete);
2384
2385 static int
2386 nat_alloc_addr_and_port_default (snat_address_t * addresses, u32 fib_index,
2387                                  u32 thread_index, nat_protocol_t proto,
2388                                  ip4_address_t * addr, u16 * port,
2389                                  u16 port_per_thread, u32 snat_thread_index);
2390
2391 void
2392 test_key_calc_split ()
2393 {
2394   ip4_address_t l_addr;
2395   l_addr.as_u8[0] = 1;
2396   l_addr.as_u8[1] = 1;
2397   l_addr.as_u8[2] = 1;
2398   l_addr.as_u8[3] = 1;
2399   ip4_address_t r_addr;
2400   r_addr.as_u8[0] = 2;
2401   r_addr.as_u8[1] = 2;
2402   r_addr.as_u8[2] = 2;
2403   r_addr.as_u8[3] = 2;
2404   u16 l_port = 40001;
2405   u16 r_port = 40301;
2406   u8 proto = 9;
2407   u32 fib_index = 9000001;
2408   u32 thread_index = 3000000001;
2409   u32 session_index = 3000000221;
2410   clib_bihash_kv_16_8_t kv;
2411   init_ed_kv (&kv, l_addr, l_port, r_addr, r_port, fib_index, proto,
2412               thread_index, session_index);
2413   ip4_address_t l_addr2;
2414   ip4_address_t r_addr2;
2415   clib_memset (&l_addr2, 0, sizeof (l_addr2));
2416   clib_memset (&r_addr2, 0, sizeof (r_addr2));
2417   u16 l_port2 = 0;
2418   u16 r_port2 = 0;
2419   u8 proto2 = 0;
2420   u32 fib_index2 = 0;
2421   split_ed_kv (&kv, &l_addr2, &r_addr2, &proto2, &fib_index2, &l_port2,
2422                &r_port2);
2423   ASSERT (l_addr.as_u32 == l_addr2.as_u32);
2424   ASSERT (r_addr.as_u32 == r_addr2.as_u32);
2425   ASSERT (l_port == l_port2);
2426   ASSERT (r_port == r_port2);
2427   ASSERT (proto == proto2);
2428   ASSERT (fib_index == fib_index2);
2429   ASSERT (thread_index == ed_value_get_thread_index (&kv));
2430   ASSERT (session_index == ed_value_get_session_index (&kv));
2431
2432   fib_index = 7001;
2433   proto = 5;
2434   nat_protocol_t proto3 = ~0;
2435   u64 key = calc_nat_key (l_addr, l_port, fib_index, proto);
2436   split_nat_key (key, &l_addr2, &l_port2, &fib_index2, &proto3);
2437   ASSERT (l_addr.as_u32 == l_addr2.as_u32);
2438   ASSERT (l_port == l_port2);
2439   ASSERT (proto == proto3);
2440   ASSERT (fib_index == fib_index2);
2441 }
2442
2443 static clib_error_t *
2444 snat_init (vlib_main_t * vm)
2445 {
2446   snat_main_t *sm = &snat_main;
2447   clib_error_t *error = 0;
2448   ip4_main_t *im = &ip4_main;
2449   ip_lookup_main_t *lm = &im->lookup_main;
2450   uword *p;
2451   vlib_thread_registration_t *tr;
2452   vlib_thread_main_t *tm = vlib_get_thread_main ();
2453   uword *bitmap = 0;
2454   u32 i;
2455   ip4_add_del_interface_address_callback_t cb4;
2456   vlib_node_t *node;
2457
2458   sm->vnet_main = vnet_get_main ();
2459   sm->ip4_main = im;
2460   sm->ip4_lookup_main = lm;
2461   sm->api_main = vlibapi_get_main ();
2462   sm->first_worker_index = 0;
2463   sm->num_workers = 0;
2464   sm->workers = 0;
2465   sm->port_per_thread = 0xffff - 1024;
2466   sm->fq_in2out_index = ~0;
2467   sm->fq_in2out_output_index = ~0;
2468   sm->fq_out2in_index = ~0;
2469
2470   sm->alloc_addr_and_port = nat_alloc_addr_and_port_default;
2471   sm->addr_and_port_alloc_alg = NAT_ADDR_AND_PORT_ALLOC_ALG_DEFAULT;
2472   sm->forwarding_enabled = 0;
2473   sm->log_class = vlib_log_register_class ("nat", 0);
2474   sm->log_level = SNAT_LOG_ERROR;
2475   sm->mss_clamping = 0;
2476
2477   node = vlib_get_node_by_name (vm, (u8 *) "error-drop");
2478   sm->error_node_index = node->index;
2479
2480   node = vlib_get_node_by_name (vm, (u8 *) "nat-pre-in2out");
2481   sm->pre_in2out_node_index = node->index;
2482   node = vlib_get_node_by_name (vm, (u8 *) "nat-pre-out2in");
2483   sm->pre_out2in_node_index = node->index;
2484
2485   node = vlib_get_node_by_name (vm, (u8 *) "nat-pre-in2out");
2486   sm->pre_in2out_node_index = node->index;
2487
2488   node = vlib_get_node_by_name (vm, (u8 *) "nat-pre-out2in");
2489   sm->pre_out2in_node_index = node->index;
2490
2491   node = vlib_get_node_by_name (vm, (u8 *) "nat44-in2out");
2492   sm->in2out_node_index = node->index;
2493   node = vlib_get_node_by_name (vm, (u8 *) "nat44-in2out-output");
2494   sm->in2out_output_node_index = node->index;
2495   node = vlib_get_node_by_name (vm, (u8 *) "nat44-in2out-fast");
2496   sm->in2out_fast_node_index = node->index;
2497   node = vlib_get_node_by_name (vm, (u8 *) "nat44-in2out-slowpath");
2498   sm->in2out_slowpath_node_index = node->index;
2499   node = vlib_get_node_by_name (vm, (u8 *) "nat44-in2out-output-slowpath");
2500   sm->in2out_slowpath_output_node_index = node->index;
2501
2502   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-in2out");
2503   sm->ed_in2out_node_index = node->index;
2504   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-in2out-slowpath");
2505   sm->ed_in2out_slowpath_node_index = node->index;
2506
2507   node = vlib_get_node_by_name (vm, (u8 *) "nat44-out2in");
2508   sm->out2in_node_index = node->index;
2509   node = vlib_get_node_by_name (vm, (u8 *) "nat44-out2in-fast");
2510   sm->out2in_fast_node_index = node->index;
2511
2512   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-out2in");
2513   sm->ed_out2in_node_index = node->index;
2514   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-out2in-slowpath");
2515   sm->ed_out2in_slowpath_node_index = node->index;
2516
2517   node = vlib_get_node_by_name (vm, (u8 *) "nat44-det-in2out");
2518   sm->det_in2out_node_index = node->index;
2519   node = vlib_get_node_by_name (vm, (u8 *) "nat44-det-out2in");
2520   sm->det_out2in_node_index = node->index;
2521
2522   node = vlib_get_node_by_name (vm, (u8 *) "nat44-hairpinning");
2523   sm->hairpinning_node_index = node->index;
2524   node = vlib_get_node_by_name (vm, (u8 *) "nat44-hairpin-dst");
2525   sm->hairpin_dst_node_index = node->index;
2526   node = vlib_get_node_by_name (vm, (u8 *) "nat44-hairpin-src");
2527   sm->hairpin_src_node_index = node->index;
2528   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-hairpinning");
2529   sm->ed_hairpinning_node_index = node->index;
2530   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-hairpin-dst");
2531   sm->ed_hairpin_dst_node_index = node->index;
2532   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-hairpin-src");
2533   sm->ed_hairpin_src_node_index = node->index;
2534
2535   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
2536   if (p)
2537     {
2538       tr = (vlib_thread_registration_t *) p[0];
2539       if (tr)
2540         {
2541           sm->num_workers = tr->count;
2542           sm->first_worker_index = tr->first_index;
2543         }
2544     }
2545
2546   vec_validate (sm->per_thread_data, tm->n_vlib_mains - 1);
2547
2548   /* Use all available workers by default */
2549   if (sm->num_workers > 1)
2550     {
2551       for (i = 0; i < sm->num_workers; i++)
2552         bitmap = clib_bitmap_set (bitmap, i, 1);
2553       snat_set_workers (bitmap);
2554       clib_bitmap_free (bitmap);
2555     }
2556   else
2557     {
2558       sm->per_thread_data[0].snat_thread_index = 0;
2559     }
2560
2561   error = snat_api_init (vm, sm);
2562   if (error)
2563     return error;
2564
2565   /* Set up the interface address add/del callback */
2566   cb4.function = snat_ip4_add_del_interface_address_cb;
2567   cb4.function_opaque = 0;
2568
2569   vec_add1 (im->add_del_interface_address_callbacks, cb4);
2570
2571   cb4.function = nat_ip4_add_del_addr_only_sm_cb;
2572   cb4.function_opaque = 0;
2573
2574   vec_add1 (im->add_del_interface_address_callbacks, cb4);
2575
2576   nat_dpo_module_init ();
2577
2578   /* Init counters */
2579   sm->total_users.name = "total-users";
2580   sm->total_users.stat_segment_name = "/nat44/total-users";
2581   vlib_validate_simple_counter (&sm->total_users, 0);
2582   vlib_zero_simple_counter (&sm->total_users, 0);
2583   sm->total_sessions.name = "total-sessions";
2584   sm->total_sessions.stat_segment_name = "/nat44/total-sessions";
2585   vlib_validate_simple_counter (&sm->total_sessions, 0);
2586   vlib_zero_simple_counter (&sm->total_sessions, 0);
2587   sm->user_limit_reached.name = "user-limit-reached";
2588   sm->user_limit_reached.stat_segment_name = "/nat44/user-limit-reached";
2589   vlib_validate_simple_counter (&sm->user_limit_reached, 0);
2590   vlib_zero_simple_counter (&sm->user_limit_reached, 0);
2591
2592   /* Init IPFIX logging */
2593   snat_ipfix_logging_init (vm);
2594
2595   /* Init NAT64 */
2596   error = nat64_init (vm);
2597   if (error)
2598     return error;
2599
2600   ip4_table_bind_callback_t cbt4 = {
2601     .function = snat_ip4_table_bind,
2602   };
2603   vec_add1 (ip4_main.table_bind_callbacks, cbt4);
2604
2605   nat_fib_src_hi = fib_source_allocate ("nat-hi",
2606                                         FIB_SOURCE_PRIORITY_HI,
2607                                         FIB_SOURCE_BH_SIMPLE);
2608   nat_fib_src_low = fib_source_allocate ("nat-low",
2609                                          FIB_SOURCE_PRIORITY_LOW,
2610                                          FIB_SOURCE_BH_SIMPLE);
2611
2612   test_key_calc_split ();
2613   return error;
2614 }
2615
2616 VLIB_INIT_FUNCTION (snat_init);
2617
2618 void
2619 snat_free_outside_address_and_port (snat_address_t * addresses,
2620                                     u32 thread_index,
2621                                     ip4_address_t * addr,
2622                                     u16 port, nat_protocol_t protocol)
2623 {
2624   snat_address_t *a;
2625   u32 address_index;
2626   u16 port_host_byte_order = clib_net_to_host_u16 (port);
2627
2628   for (address_index = 0; address_index < vec_len (addresses);
2629        address_index++)
2630     {
2631       if (addresses[address_index].addr.as_u32 == addr->as_u32)
2632         break;
2633     }
2634
2635   ASSERT (address_index < vec_len (addresses));
2636
2637   a = addresses + address_index;
2638
2639   switch (protocol)
2640     {
2641 #define _(N, i, n, s) \
2642     case NAT_PROTOCOL_##N: \
2643       ASSERT (a->busy_##n##_port_refcounts[port_host_byte_order] >= 1); \
2644       --a->busy_##n##_port_refcounts[port_host_byte_order]; \
2645       a->busy_##n##_ports--; \
2646       a->busy_##n##_ports_per_thread[thread_index]--; \
2647       break;
2648       foreach_nat_protocol
2649 #undef _
2650     default:
2651       nat_elog_info ("unknown protocol");
2652       return;
2653     }
2654 }
2655
2656 static int
2657 nat_set_outside_address_and_port (snat_address_t * addresses,
2658                                   u32 thread_index, ip4_address_t addr,
2659                                   u16 port, nat_protocol_t protocol)
2660 {
2661   snat_address_t *a = 0;
2662   u32 address_index;
2663   u16 port_host_byte_order = clib_net_to_host_u16 (port);
2664
2665   for (address_index = 0; address_index < vec_len (addresses);
2666        address_index++)
2667     {
2668       if (addresses[address_index].addr.as_u32 != addr.as_u32)
2669         continue;
2670
2671       a = addresses + address_index;
2672       switch (protocol)
2673         {
2674 #define _(N, j, n, s) \
2675         case NAT_PROTOCOL_##N: \
2676           if (a->busy_##n##_port_refcounts[port_host_byte_order]) \
2677             return VNET_API_ERROR_INSTANCE_IN_USE; \
2678           ++a->busy_##n##_port_refcounts[port_host_byte_order]; \
2679           a->busy_##n##_ports_per_thread[thread_index]++; \
2680           a->busy_##n##_ports++; \
2681           return 0;
2682           foreach_nat_protocol
2683 #undef _
2684         default:
2685           nat_elog_info ("unknown protocol");
2686           return 1;
2687         }
2688     }
2689
2690   return VNET_API_ERROR_NO_SUCH_ENTRY;
2691 }
2692
2693 int
2694 snat_static_mapping_match (snat_main_t * sm,
2695                            ip4_address_t match_addr,
2696                            u16 match_port,
2697                            u32 match_fib_index,
2698                            nat_protocol_t match_protocol,
2699                            ip4_address_t * mapping_addr,
2700                            u16 * mapping_port,
2701                            u32 * mapping_fib_index,
2702                            u8 by_external,
2703                            u8 * is_addr_only,
2704                            twice_nat_type_t * twice_nat,
2705                            lb_nat_type_t * lb, ip4_address_t * ext_host_addr,
2706                            u8 * is_identity_nat)
2707 {
2708   clib_bihash_kv_8_8_t kv, value;
2709   snat_static_mapping_t *m;
2710   clib_bihash_8_8_t *mapping_hash = &sm->static_mapping_by_local;
2711   u32 rand, lo = 0, hi, mid, *tmp = 0, i;
2712   u8 backend_index;
2713   nat44_lb_addr_port_t *local;
2714
2715   if (by_external)
2716     {
2717       mapping_hash = &sm->static_mapping_by_external;
2718       init_nat_k (&kv, match_addr, match_port, 0, match_protocol);
2719       if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
2720         {
2721           /* Try address only mapping */
2722           init_nat_k (&kv, match_addr, 0, 0, 0);
2723           if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
2724             return 1;
2725         }
2726
2727     }
2728   else
2729     {
2730       init_nat_k (&kv, match_addr, match_port, match_fib_index,
2731                   match_protocol);
2732       if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
2733         {
2734           /* Try address only mapping */
2735           init_nat_k (&kv, match_addr, 0, match_fib_index, 0);
2736           if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
2737             return 1;
2738         }
2739
2740     }
2741
2742   m = pool_elt_at_index (sm->static_mappings, value.value);
2743
2744   if (by_external)
2745     {
2746       if (is_lb_static_mapping (m))
2747         {
2748           if (PREDICT_FALSE (lb != 0))
2749             *lb = m->affinity ? AFFINITY_LB_NAT : LB_NAT;
2750           if (m->affinity && !nat_affinity_find_and_lock (ext_host_addr[0],
2751                                                           match_addr,
2752                                                           match_protocol,
2753                                                           match_port,
2754                                                           &backend_index))
2755             {
2756               local = pool_elt_at_index (m->locals, backend_index);
2757               *mapping_addr = local->addr;
2758               *mapping_port = local->port;
2759               *mapping_fib_index = local->fib_index;
2760               goto end;
2761             }
2762           // pick locals matching this worker
2763           if (PREDICT_FALSE (sm->num_workers > 1))
2764             {
2765               u32 thread_index = vlib_get_thread_index ();
2766               /* *INDENT-OFF* */
2767               pool_foreach_index (i, m->locals,
2768               ({
2769                 local = pool_elt_at_index (m->locals, i);
2770
2771                 ip4_header_t ip = {
2772                   .src_address = local->addr,
2773                 };
2774
2775                 if (sm->worker_in2out_cb (&ip, m->fib_index, 0) ==
2776                     thread_index)
2777                   {
2778                     vec_add1 (tmp, i);
2779                   }
2780               }));
2781               /* *INDENT-ON* */
2782               ASSERT (vec_len (tmp) != 0);
2783             }
2784           else
2785             {
2786               /* *INDENT-OFF* */
2787               pool_foreach_index (i, m->locals,
2788               ({
2789                 vec_add1 (tmp, i);
2790               }));
2791               /* *INDENT-ON* */
2792             }
2793           hi = vec_len (tmp) - 1;
2794           local = pool_elt_at_index (m->locals, tmp[hi]);
2795           rand = 1 + (random_u32 (&sm->random_seed) % local->prefix);
2796           while (lo < hi)
2797             {
2798               mid = ((hi - lo) >> 1) + lo;
2799               local = pool_elt_at_index (m->locals, tmp[mid]);
2800               (rand > local->prefix) ? (lo = mid + 1) : (hi = mid);
2801             }
2802           local = pool_elt_at_index (m->locals, tmp[lo]);
2803           if (!(local->prefix >= rand))
2804             return 1;
2805           *mapping_addr = local->addr;
2806           *mapping_port = local->port;
2807           *mapping_fib_index = local->fib_index;
2808           if (m->affinity)
2809             {
2810               if (nat_affinity_create_and_lock (ext_host_addr[0], match_addr,
2811                                                 match_protocol, match_port,
2812                                                 tmp[lo], m->affinity,
2813                                                 m->affinity_per_service_list_head_index))
2814                 nat_elog_info ("create affinity record failed");
2815             }
2816           vec_free (tmp);
2817         }
2818       else
2819         {
2820           if (PREDICT_FALSE (lb != 0))
2821             *lb = NO_LB_NAT;
2822           *mapping_fib_index = m->fib_index;
2823           *mapping_addr = m->local_addr;
2824           /* Address only mapping doesn't change port */
2825           *mapping_port = is_addr_only_static_mapping (m) ? match_port
2826             : m->local_port;
2827         }
2828     }
2829   else
2830     {
2831       *mapping_addr = m->external_addr;
2832       /* Address only mapping doesn't change port */
2833       *mapping_port = is_addr_only_static_mapping (m) ? match_port
2834         : m->external_port;
2835       *mapping_fib_index = sm->outside_fib_index;
2836     }
2837
2838 end:
2839   if (PREDICT_FALSE (is_addr_only != 0))
2840     *is_addr_only = is_addr_only_static_mapping (m);
2841
2842   if (PREDICT_FALSE (twice_nat != 0))
2843     *twice_nat = m->twice_nat;
2844
2845   if (PREDICT_FALSE (is_identity_nat != 0))
2846     *is_identity_nat = is_identity_static_mapping (m);
2847
2848   return 0;
2849 }
2850
2851 int
2852 snat_alloc_outside_address_and_port (snat_address_t * addresses,
2853                                      u32 fib_index,
2854                                      u32 thread_index,
2855                                      nat_protocol_t proto,
2856                                      ip4_address_t * addr,
2857                                      u16 * port,
2858                                      u16 port_per_thread,
2859                                      u32 snat_thread_index)
2860 {
2861   snat_main_t *sm = &snat_main;
2862
2863   return sm->alloc_addr_and_port (addresses, fib_index, thread_index, proto,
2864                                   addr, port, port_per_thread,
2865                                   snat_thread_index);
2866 }
2867
2868 static int
2869 nat_alloc_addr_and_port_default (snat_address_t * addresses,
2870                                  u32 fib_index,
2871                                  u32 thread_index,
2872                                  nat_protocol_t proto,
2873                                  ip4_address_t * addr,
2874                                  u16 * port,
2875                                  u16 port_per_thread, u32 snat_thread_index)
2876 {
2877   int i;
2878   snat_address_t *a, *ga = 0;
2879   u32 portnum;
2880
2881   for (i = 0; i < vec_len (addresses); i++)
2882     {
2883       a = addresses + i;
2884       switch (proto)
2885         {
2886 #define _(N, j, n, s) \
2887         case NAT_PROTOCOL_##N: \
2888           if (a->busy_##n##_ports_per_thread[thread_index] < port_per_thread) \
2889             { \
2890               if (a->fib_index == fib_index) \
2891                 { \
2892                   while (1) \
2893                     { \
2894                       portnum = (port_per_thread * \
2895                         snat_thread_index) + \
2896                         snat_random_port(0, port_per_thread - 1) + 1024; \
2897                       if (a->busy_##n##_port_refcounts[portnum]) \
2898                         continue; \
2899                       --a->busy_##n##_port_refcounts[portnum]; \
2900                       a->busy_##n##_ports_per_thread[thread_index]++; \
2901                       a->busy_##n##_ports++; \
2902                       *addr = a->addr; \
2903                       *port = clib_host_to_net_u16(portnum); \
2904                       return 0; \
2905                     } \
2906                 } \
2907               else if (a->fib_index == ~0) \
2908                 { \
2909                   ga = a; \
2910                 } \
2911             } \
2912           break;
2913           foreach_nat_protocol
2914 #undef _
2915         default:
2916           nat_elog_info ("unknown protocol");
2917           return 1;
2918         }
2919
2920     }
2921
2922   if (ga)
2923     {
2924       a = ga;
2925       switch (proto)
2926         {
2927 #define _(N, j, n, s) \
2928         case NAT_PROTOCOL_##N: \
2929           while (1) \
2930             { \
2931               portnum = (port_per_thread * \
2932                 snat_thread_index) + \
2933                 snat_random_port(0, port_per_thread - 1) + 1024; \
2934               if (a->busy_##n##_port_refcounts[portnum]) \
2935                 continue; \
2936               ++a->busy_##n##_port_refcounts[portnum]; \
2937               a->busy_##n##_ports_per_thread[thread_index]++; \
2938               a->busy_##n##_ports++; \
2939               *addr = a->addr; \
2940               *port = clib_host_to_net_u16(portnum); \
2941               return 0; \
2942             }
2943           break;
2944           foreach_nat_protocol
2945 #undef _
2946         default:
2947           nat_elog_info ("unknown protocol");
2948           return 1;
2949         }
2950     }
2951
2952   /* Totally out of translations to use... */
2953   snat_ipfix_logging_addresses_exhausted (thread_index, 0);
2954   return 1;
2955 }
2956
2957 static int
2958 nat_alloc_addr_and_port_mape (snat_address_t * addresses, u32 fib_index,
2959                               u32 thread_index, nat_protocol_t proto,
2960                               ip4_address_t * addr, u16 * port,
2961                               u16 port_per_thread, u32 snat_thread_index)
2962 {
2963   snat_main_t *sm = &snat_main;
2964   snat_address_t *a = addresses;
2965   u16 m, ports, portnum, A, j;
2966   m = 16 - (sm->psid_offset + sm->psid_length);
2967   ports = (1 << (16 - sm->psid_length)) - (1 << m);
2968
2969   if (!vec_len (addresses))
2970     goto exhausted;
2971
2972   switch (proto)
2973     {
2974 #define _(N, i, n, s) \
2975     case NAT_PROTOCOL_##N: \
2976       if (a->busy_##n##_ports < ports) \
2977         { \
2978           while (1) \
2979             { \
2980               A = snat_random_port(1, pow2_mask(sm->psid_offset)); \
2981               j = snat_random_port(0, pow2_mask(m)); \
2982               portnum = A | (sm->psid << sm->psid_offset) | (j << (16 - m)); \
2983               if (a->busy_##n##_port_refcounts[portnum]) \
2984                 continue; \
2985               ++a->busy_##n##_port_refcounts[portnum]; \
2986               a->busy_##n##_ports++; \
2987               *addr = a->addr; \
2988               *port = clib_host_to_net_u16 (portnum); \
2989               return 0; \
2990             } \
2991         } \
2992       break;
2993       foreach_nat_protocol
2994 #undef _
2995     default:
2996       nat_elog_info ("unknown protocol");
2997       return 1;
2998     }
2999
3000 exhausted:
3001   /* Totally out of translations to use... */
3002   snat_ipfix_logging_addresses_exhausted (thread_index, 0);
3003   return 1;
3004 }
3005
3006 static int
3007 nat_alloc_addr_and_port_range (snat_address_t * addresses, u32 fib_index,
3008                                u32 thread_index, nat_protocol_t proto,
3009                                ip4_address_t * addr, u16 * port,
3010                                u16 port_per_thread, u32 snat_thread_index)
3011 {
3012   snat_main_t *sm = &snat_main;
3013   snat_address_t *a = addresses;
3014   u16 portnum, ports;
3015
3016   ports = sm->end_port - sm->start_port + 1;
3017
3018   if (!vec_len (addresses))
3019     goto exhausted;
3020
3021   switch (proto)
3022     {
3023 #define _(N, i, n, s) \
3024     case NAT_PROTOCOL_##N: \
3025       if (a->busy_##n##_ports < ports) \
3026         { \
3027           while (1) \
3028             { \
3029               portnum = snat_random_port(sm->start_port, sm->end_port); \
3030               if (a->busy_##n##_port_refcounts[portnum]) \
3031                 continue; \
3032               ++a->busy_##n##_port_refcounts[portnum]; \
3033               a->busy_##n##_ports++; \
3034               *addr = a->addr; \
3035               *port = clib_host_to_net_u16 (portnum); \
3036               return 0; \
3037             } \
3038         } \
3039       break;
3040       foreach_nat_protocol
3041 #undef _
3042     default:
3043       nat_elog_info ("unknown protocol");
3044       return 1;
3045     }
3046
3047 exhausted:
3048   /* Totally out of translations to use... */
3049   snat_ipfix_logging_addresses_exhausted (thread_index, 0);
3050   return 1;
3051 }
3052
3053 void
3054 nat44_add_del_address_dpo (ip4_address_t addr, u8 is_add)
3055 {
3056   dpo_id_t dpo_v4 = DPO_INVALID;
3057   fib_prefix_t pfx = {
3058     .fp_proto = FIB_PROTOCOL_IP4,
3059     .fp_len = 32,
3060     .fp_addr.ip4.as_u32 = addr.as_u32,
3061   };
3062
3063   if (is_add)
3064     {
3065       nat_dpo_create (DPO_PROTO_IP4, 0, &dpo_v4);
3066       fib_table_entry_special_dpo_add (0, &pfx, nat_fib_src_hi,
3067                                        FIB_ENTRY_FLAG_EXCLUSIVE, &dpo_v4);
3068       dpo_reset (&dpo_v4);
3069     }
3070   else
3071     {
3072       fib_table_entry_special_remove (0, &pfx, nat_fib_src_hi);
3073     }
3074 }
3075
3076 u8 *
3077 format_session_kvp (u8 * s, va_list * args)
3078 {
3079   clib_bihash_kv_8_8_t *v = va_arg (*args, clib_bihash_kv_8_8_t *);
3080
3081   s = format (s, "%U session-index %llu", format_snat_key, v->key, v->value);
3082
3083   return s;
3084 }
3085
3086 u8 *
3087 format_static_mapping_kvp (u8 * s, va_list * args)
3088 {
3089   clib_bihash_kv_8_8_t *v = va_arg (*args, clib_bihash_kv_8_8_t *);
3090
3091   s = format (s, "%U static-mapping-index %llu",
3092               format_snat_key, v->key, v->value);
3093
3094   return s;
3095 }
3096
3097 u8 *
3098 format_user_kvp (u8 * s, va_list * args)
3099 {
3100   clib_bihash_kv_8_8_t *v = va_arg (*args, clib_bihash_kv_8_8_t *);
3101   snat_user_key_t k;
3102
3103   k.as_u64 = v->key;
3104
3105   s = format (s, "%U fib %d user-index %llu", format_ip4_address, &k.addr,
3106               k.fib_index, v->value);
3107
3108   return s;
3109 }
3110
3111 u8 *
3112 format_ed_session_kvp (u8 * s, va_list * args)
3113 {
3114   clib_bihash_kv_16_8_t *v = va_arg (*args, clib_bihash_kv_16_8_t *);
3115
3116   u8 proto;
3117   u16 r_port, l_port;
3118   ip4_address_t l_addr, r_addr;
3119   u32 fib_index;
3120
3121   split_ed_kv (v, &l_addr, &r_addr, &proto, &fib_index, &l_port, &r_port);
3122   s =
3123     format (s,
3124             "local %U:%d remote %U:%d proto %U fib %d thread-index %u session-index %u",
3125             format_ip4_address, &l_addr, clib_net_to_host_u16 (l_port),
3126             format_ip4_address, &r_addr, clib_net_to_host_u16 (r_port),
3127             format_ip_protocol, proto, fib_index,
3128             ed_value_get_session_index (v), ed_value_get_thread_index (v));
3129
3130   return s;
3131 }
3132
3133 static u32
3134 snat_get_worker_in2out_cb (ip4_header_t * ip0, u32 rx_fib_index0,
3135                            u8 is_output)
3136 {
3137   snat_main_t *sm = &snat_main;
3138   u32 next_worker_index = 0;
3139   u32 hash;
3140
3141   next_worker_index = sm->first_worker_index;
3142   hash = ip0->src_address.as_u32 + (ip0->src_address.as_u32 >> 8) +
3143     (ip0->src_address.as_u32 >> 16) + (ip0->src_address.as_u32 >> 24);
3144
3145   if (PREDICT_TRUE (is_pow2 (_vec_len (sm->workers))))
3146     next_worker_index += sm->workers[hash & (_vec_len (sm->workers) - 1)];
3147   else
3148     next_worker_index += sm->workers[hash % _vec_len (sm->workers)];
3149
3150   return next_worker_index;
3151 }
3152
3153 static u32
3154 snat_get_worker_out2in_cb (vlib_buffer_t * b, ip4_header_t * ip0,
3155                            u32 rx_fib_index0, u8 is_output)
3156 {
3157   snat_main_t *sm = &snat_main;
3158   udp_header_t *udp;
3159   u16 port;
3160   clib_bihash_kv_8_8_t kv, value;
3161   snat_static_mapping_t *m;
3162   u32 proto;
3163   u32 next_worker_index = 0;
3164
3165   /* first try static mappings without port */
3166   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
3167     {
3168       init_nat_k (&kv, ip0->dst_address, 0, rx_fib_index0, 0);
3169       if (!clib_bihash_search_8_8
3170           (&sm->static_mapping_by_external, &kv, &value))
3171         {
3172           m = pool_elt_at_index (sm->static_mappings, value.value);
3173           return m->workers[0];
3174         }
3175     }
3176
3177   proto = ip_proto_to_nat_proto (ip0->protocol);
3178   udp = ip4_next_header (ip0);
3179   port = udp->dst_port;
3180
3181   /* unknown protocol */
3182   if (PREDICT_FALSE (proto == NAT_PROTOCOL_OTHER))
3183     {
3184       /* use current thread */
3185       return vlib_get_thread_index ();
3186     }
3187
3188   if (PREDICT_FALSE (ip0->protocol == IP_PROTOCOL_ICMP))
3189     {
3190       icmp46_header_t *icmp = (icmp46_header_t *) udp;
3191       icmp_echo_header_t *echo = (icmp_echo_header_t *) (icmp + 1);
3192       if (!icmp_type_is_error_message
3193           (vnet_buffer (b)->ip.reass.icmp_type_or_tcp_flags))
3194         port = vnet_buffer (b)->ip.reass.l4_src_port;
3195       else
3196         {
3197           /* if error message, then it's not fragmented and we can access it */
3198           ip4_header_t *inner_ip = (ip4_header_t *) (echo + 1);
3199           proto = ip_proto_to_nat_proto (inner_ip->protocol);
3200           void *l4_header = ip4_next_header (inner_ip);
3201           switch (proto)
3202             {
3203             case NAT_PROTOCOL_ICMP:
3204               icmp = (icmp46_header_t *) l4_header;
3205               echo = (icmp_echo_header_t *) (icmp + 1);
3206               port = echo->identifier;
3207               break;
3208             case NAT_PROTOCOL_UDP:
3209             case NAT_PROTOCOL_TCP:
3210               port = ((tcp_udp_header_t *) l4_header)->src_port;
3211               break;
3212             default:
3213               return vlib_get_thread_index ();
3214             }
3215         }
3216     }
3217
3218   /* try static mappings with port */
3219   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
3220     {
3221       init_nat_k (&kv, ip0->dst_address, port, rx_fib_index0, proto);
3222       if (!clib_bihash_search_8_8
3223           (&sm->static_mapping_by_external, &kv, &value))
3224         {
3225           m = pool_elt_at_index (sm->static_mappings, value.value);
3226           return m->workers[0];
3227         }
3228     }
3229
3230   /* worker by outside port */
3231   next_worker_index = sm->first_worker_index;
3232   next_worker_index +=
3233     sm->workers[(clib_net_to_host_u16 (port) - 1024) / sm->port_per_thread];
3234   return next_worker_index;
3235 }
3236
3237 static u32
3238 nat44_ed_get_worker_in2out_cb (ip4_header_t * ip, u32 rx_fib_index,
3239                                u8 is_output)
3240 {
3241   snat_main_t *sm = &snat_main;
3242   u32 next_worker_index = sm->first_worker_index;
3243   u32 hash;
3244
3245   clib_bihash_kv_16_8_t kv16, value16;
3246   snat_main_per_thread_data_t *tsm;
3247   udp_header_t *udp;
3248
3249   if (PREDICT_FALSE (is_output))
3250     {
3251       u32 fib_index = sm->outside_fib_index;
3252       nat_outside_fib_t *outside_fib;
3253       fib_node_index_t fei = FIB_NODE_INDEX_INVALID;
3254       fib_prefix_t pfx = {
3255         .fp_proto = FIB_PROTOCOL_IP4,
3256         .fp_len = 32,
3257         .fp_addr = {
3258                     .ip4.as_u32 = ip->dst_address.as_u32,
3259                     }
3260         ,
3261       };
3262
3263       udp = ip4_next_header (ip);
3264
3265       switch (vec_len (sm->outside_fibs))
3266         {
3267         case 0:
3268           fib_index = sm->outside_fib_index;
3269           break;
3270         case 1:
3271           fib_index = sm->outside_fibs[0].fib_index;
3272           break;
3273         default:
3274             /* *INDENT-OFF* */
3275             vec_foreach (outside_fib, sm->outside_fibs)
3276               {
3277                 fei = fib_table_lookup (outside_fib->fib_index, &pfx);
3278                 if (FIB_NODE_INDEX_INVALID != fei)
3279                   {
3280                     if (fib_entry_get_resolving_interface (fei) != ~0)
3281                       {
3282                         fib_index = outside_fib->fib_index;
3283                         break;
3284                       }
3285                   }
3286               }
3287             /* *INDENT-ON* */
3288           break;
3289         }
3290
3291       init_ed_k (&kv16, ip->src_address, udp->src_port, ip->dst_address,
3292                  udp->dst_port, fib_index, ip->protocol);
3293
3294       if (PREDICT_TRUE (!clib_bihash_search_16_8 (&sm->out2in_ed,
3295                                                   &kv16, &value16)))
3296         {
3297           tsm =
3298             vec_elt_at_index (sm->per_thread_data,
3299                               ed_value_get_thread_index (&value16));
3300           next_worker_index += tsm->thread_index;
3301
3302           nat_elog_debug_handoff ("HANDOFF IN2OUT-OUTPUT-FEATURE (session)",
3303                                   next_worker_index, fib_index,
3304                                   clib_net_to_host_u32 (ip->
3305                                                         src_address.as_u32),
3306                                   clib_net_to_host_u32 (ip->
3307                                                         dst_address.as_u32));
3308
3309           return next_worker_index;
3310         }
3311     }
3312
3313   hash = ip->src_address.as_u32 + (ip->src_address.as_u32 >> 8) +
3314     (ip->src_address.as_u32 >> 16) + (ip->src_address.as_u32 >> 24);
3315
3316   if (PREDICT_TRUE (is_pow2 (_vec_len (sm->workers))))
3317     next_worker_index += sm->workers[hash & (_vec_len (sm->workers) - 1)];
3318   else
3319     next_worker_index += sm->workers[hash % _vec_len (sm->workers)];
3320
3321   if (PREDICT_TRUE (!is_output))
3322     {
3323       nat_elog_debug_handoff ("HANDOFF IN2OUT",
3324                               next_worker_index, rx_fib_index,
3325                               clib_net_to_host_u32 (ip->src_address.as_u32),
3326                               clib_net_to_host_u32 (ip->dst_address.as_u32));
3327     }
3328   else
3329     {
3330       nat_elog_debug_handoff ("HANDOFF IN2OUT-OUTPUT-FEATURE",
3331                               next_worker_index, rx_fib_index,
3332                               clib_net_to_host_u32 (ip->src_address.as_u32),
3333                               clib_net_to_host_u32 (ip->dst_address.as_u32));
3334     }
3335
3336   return next_worker_index;
3337 }
3338
3339 static u32
3340 nat44_ed_get_worker_out2in_cb (vlib_buffer_t * b, ip4_header_t * ip,
3341                                u32 rx_fib_index, u8 is_output)
3342 {
3343   snat_main_t *sm = &snat_main;
3344   clib_bihash_kv_8_8_t kv, value;
3345   clib_bihash_kv_16_8_t kv16, value16;
3346   snat_main_per_thread_data_t *tsm;
3347
3348   u32 proto, next_worker_index = 0;
3349   udp_header_t *udp;
3350   u16 port;
3351   snat_static_mapping_t *m;
3352   u32 hash;
3353
3354   proto = ip_proto_to_nat_proto (ip->protocol);
3355
3356   if (PREDICT_TRUE (proto == NAT_PROTOCOL_UDP || proto == NAT_PROTOCOL_TCP))
3357     {
3358       udp = ip4_next_header (ip);
3359
3360       init_ed_k (&kv16, ip->dst_address, udp->dst_port, ip->src_address,
3361                  udp->src_port, rx_fib_index, ip->protocol);
3362
3363       if (PREDICT_TRUE (!clib_bihash_search_16_8 (&sm->out2in_ed,
3364                                                   &kv16, &value16)))
3365         {
3366           tsm =
3367             vec_elt_at_index (sm->per_thread_data,
3368                               ed_value_get_thread_index (&value16));
3369           vnet_buffer2 (b)->nat.ed_out2in_nat_session_index =
3370             ed_value_get_session_index (&value16);
3371           next_worker_index = sm->first_worker_index + tsm->thread_index;
3372           nat_elog_debug_handoff ("HANDOFF OUT2IN (session)",
3373                                   next_worker_index, rx_fib_index,
3374                                   clib_net_to_host_u32 (ip->
3375                                                         src_address.as_u32),
3376                                   clib_net_to_host_u32 (ip->
3377                                                         dst_address.as_u32));
3378           return next_worker_index;
3379         }
3380     }
3381   else if (proto == NAT_PROTOCOL_ICMP)
3382     {
3383       if (!get_icmp_o2i_ed_key (b, ip, rx_fib_index, ~0, ~0, 0, 0, 0, &kv16))
3384         {
3385           if (PREDICT_TRUE (!clib_bihash_search_16_8 (&sm->out2in_ed,
3386                                                       &kv16, &value16)))
3387             {
3388               tsm =
3389                 vec_elt_at_index (sm->per_thread_data,
3390                                   ed_value_get_thread_index (&value16));
3391               next_worker_index = sm->first_worker_index + tsm->thread_index;
3392               nat_elog_debug_handoff ("HANDOFF OUT2IN (session)",
3393                                       next_worker_index, rx_fib_index,
3394                                       clib_net_to_host_u32 (ip->
3395                                                             src_address.as_u32),
3396                                       clib_net_to_host_u32 (ip->
3397                                                             dst_address.as_u32));
3398               return next_worker_index;
3399             }
3400         }
3401     }
3402
3403   /* first try static mappings without port */
3404   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
3405     {
3406       init_nat_k (&kv, ip->dst_address, 0, 0, 0);
3407       if (!clib_bihash_search_8_8
3408           (&sm->static_mapping_by_external, &kv, &value))
3409         {
3410           m = pool_elt_at_index (sm->static_mappings, value.value);
3411           next_worker_index = m->workers[0];
3412           goto done;
3413         }
3414     }
3415
3416   /* unknown protocol */
3417   if (PREDICT_FALSE (proto == NAT_PROTOCOL_OTHER))
3418     {
3419       /* use current thread */
3420       next_worker_index = vlib_get_thread_index ();
3421       goto done;
3422     }
3423
3424   udp = ip4_next_header (ip);
3425   port = udp->dst_port;
3426
3427   if (PREDICT_FALSE (ip->protocol == IP_PROTOCOL_ICMP))
3428     {
3429       icmp46_header_t *icmp = (icmp46_header_t *) udp;
3430       icmp_echo_header_t *echo = (icmp_echo_header_t *) (icmp + 1);
3431       if (!icmp_type_is_error_message
3432           (vnet_buffer (b)->ip.reass.icmp_type_or_tcp_flags))
3433         port = vnet_buffer (b)->ip.reass.l4_src_port;
3434       else
3435         {
3436           /* if error message, then it's not fragmented and we can access it */
3437           ip4_header_t *inner_ip = (ip4_header_t *) (echo + 1);
3438           proto = ip_proto_to_nat_proto (inner_ip->protocol);
3439           void *l4_header = ip4_next_header (inner_ip);
3440           switch (proto)
3441             {
3442             case NAT_PROTOCOL_ICMP:
3443               icmp = (icmp46_header_t *) l4_header;
3444               echo = (icmp_echo_header_t *) (icmp + 1);
3445               port = echo->identifier;
3446               break;
3447             case NAT_PROTOCOL_UDP:
3448             case NAT_PROTOCOL_TCP:
3449               port = ((tcp_udp_header_t *) l4_header)->src_port;
3450               break;
3451             default:
3452               next_worker_index = vlib_get_thread_index ();
3453               goto done;
3454             }
3455         }
3456     }
3457
3458   /* try static mappings with port */
3459   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
3460     {
3461       init_nat_k (&kv, ip->dst_address, proto, 0, port);
3462       if (!clib_bihash_search_8_8
3463           (&sm->static_mapping_by_external, &kv, &value))
3464         {
3465           m = pool_elt_at_index (sm->static_mappings, value.value);
3466           if (!is_lb_static_mapping (m))
3467             {
3468               next_worker_index = m->workers[0];
3469               goto done;
3470             }
3471
3472           hash = ip->src_address.as_u32 + (ip->src_address.as_u32 >> 8) +
3473             (ip->src_address.as_u32 >> 16) + (ip->src_address.as_u32 >> 24);
3474
3475           if (PREDICT_TRUE (is_pow2 (_vec_len (m->workers))))
3476             next_worker_index =
3477               m->workers[hash & (_vec_len (m->workers) - 1)];
3478           else
3479             next_worker_index = m->workers[hash % _vec_len (m->workers)];
3480           goto done;
3481         }
3482     }
3483
3484   /* worker by outside port */
3485   next_worker_index = sm->first_worker_index;
3486   next_worker_index +=
3487     sm->workers[(clib_net_to_host_u16 (port) - 1024) / sm->port_per_thread];
3488
3489 done:
3490   nat_elog_debug_handoff ("HANDOFF OUT2IN", next_worker_index, rx_fib_index,
3491                           clib_net_to_host_u32 (ip->src_address.as_u32),
3492                           clib_net_to_host_u32 (ip->dst_address.as_u32));
3493   return next_worker_index;
3494 }
3495
3496 void
3497 nat_ha_sadd_cb (ip4_address_t * in_addr, u16 in_port,
3498                 ip4_address_t * out_addr, u16 out_port,
3499                 ip4_address_t * eh_addr, u16 eh_port,
3500                 ip4_address_t * ehn_addr, u16 ehn_port, u8 proto,
3501                 u32 fib_index, u16 flags, u32 thread_index)
3502 {
3503   snat_main_t *sm = &snat_main;
3504   snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
3505   snat_user_t *u;
3506   snat_session_t *s;
3507   clib_bihash_kv_8_8_t kv;
3508   vlib_main_t *vm = vlib_get_main ();
3509   f64 now = vlib_time_now (vm);
3510   nat_outside_fib_t *outside_fib;
3511   fib_node_index_t fei = FIB_NODE_INDEX_INVALID;
3512   fib_prefix_t pfx = {
3513     .fp_proto = FIB_PROTOCOL_IP4,
3514     .fp_len = 32,
3515     .fp_addr = {
3516                 .ip4.as_u32 = eh_addr->as_u32,
3517                 },
3518   };
3519
3520   if (!(flags & SNAT_SESSION_FLAG_STATIC_MAPPING))
3521     {
3522       if (nat_set_outside_address_and_port
3523           (sm->addresses, thread_index, *out_addr, out_port, proto))
3524         return;
3525     }
3526
3527   u = nat_user_get_or_create (sm, in_addr, fib_index, thread_index);
3528   if (!u)
3529     return;
3530
3531   s = nat_session_alloc_or_recycle (sm, u, thread_index, now);
3532   if (!s)
3533     return;
3534
3535   if (sm->endpoint_dependent)
3536     {
3537       nat_ed_lru_insert (tsm, s, now, nat_proto_to_ip_proto (proto));
3538     }
3539
3540   s->out2in.addr.as_u32 = out_addr->as_u32;
3541   s->out2in.port = out_port;
3542   s->nat_proto = proto;
3543   s->last_heard = now;
3544   s->flags = flags;
3545   s->ext_host_addr.as_u32 = eh_addr->as_u32;
3546   s->ext_host_port = eh_port;
3547   user_session_increment (sm, u, snat_is_session_static (s));
3548   switch (vec_len (sm->outside_fibs))
3549     {
3550     case 0:
3551       s->out2in.fib_index = sm->outside_fib_index;
3552       break;
3553     case 1:
3554       s->out2in.fib_index = sm->outside_fibs[0].fib_index;
3555       break;
3556     default:
3557       /* *INDENT-OFF* */
3558       vec_foreach (outside_fib, sm->outside_fibs)
3559         {
3560           fei = fib_table_lookup (outside_fib->fib_index, &pfx);
3561           if (FIB_NODE_INDEX_INVALID != fei)
3562             {
3563               if (fib_entry_get_resolving_interface (fei) != ~0)
3564                 {
3565                   s->out2in.fib_index = outside_fib->fib_index;
3566                   break;
3567                 }
3568             }
3569         }
3570       /* *INDENT-ON* */
3571       break;
3572     }
3573   init_nat_o2i_kv (&kv, s, s - tsm->sessions);
3574   if (clib_bihash_add_del_8_8 (&tsm->out2in, &kv, 1))
3575     nat_elog_warn ("out2in key add failed");
3576
3577   s->in2out.addr.as_u32 = in_addr->as_u32;
3578   s->in2out.port = in_port;
3579   s->in2out.fib_index = fib_index;
3580   init_nat_i2o_kv (&kv, s, s - tsm->sessions);
3581   if (clib_bihash_add_del_8_8 (&tsm->in2out, &kv, 1))
3582     nat_elog_warn ("in2out key add failed");
3583 }
3584
3585 void
3586 nat_ha_sdel_cb (ip4_address_t * out_addr, u16 out_port,
3587                 ip4_address_t * eh_addr, u16 eh_port, u8 proto, u32 fib_index,
3588                 u32 ti)
3589 {
3590   snat_main_t *sm = &snat_main;
3591   clib_bihash_kv_8_8_t kv, value;
3592   u32 thread_index;
3593   snat_session_t *s;
3594   snat_main_per_thread_data_t *tsm;
3595
3596   if (sm->num_workers > 1)
3597     thread_index =
3598       sm->first_worker_index +
3599       (sm->workers[(clib_net_to_host_u16 (out_port) -
3600                     1024) / sm->port_per_thread]);
3601   else
3602     thread_index = sm->num_workers;
3603   tsm = vec_elt_at_index (sm->per_thread_data, thread_index);
3604
3605   init_nat_k (&kv, *out_addr, out_port, fib_index, proto);
3606   if (clib_bihash_search_8_8 (&tsm->out2in, &kv, &value))
3607     return;
3608
3609   s = pool_elt_at_index (tsm->sessions, value.value);
3610   nat_free_session_data (sm, s, thread_index, 1);
3611   nat44_delete_session (sm, s, thread_index);
3612 }
3613
3614 void
3615 nat_ha_sref_cb (ip4_address_t * out_addr, u16 out_port,
3616                 ip4_address_t * eh_addr, u16 eh_port, u8 proto, u32 fib_index,
3617                 u32 total_pkts, u64 total_bytes, u32 thread_index)
3618 {
3619   snat_main_t *sm = &snat_main;
3620   clib_bihash_kv_8_8_t kv, value;
3621   snat_session_t *s;
3622   snat_main_per_thread_data_t *tsm;
3623
3624   tsm = vec_elt_at_index (sm->per_thread_data, thread_index);
3625
3626   init_nat_k (&kv, *out_addr, out_port, fib_index, proto);
3627   if (clib_bihash_search_8_8 (&tsm->out2in, &kv, &value))
3628     return;
3629
3630   s = pool_elt_at_index (tsm->sessions, value.value);
3631   s->total_pkts = total_pkts;
3632   s->total_bytes = total_bytes;
3633 }
3634
3635 void
3636 nat_ha_sadd_ed_cb (ip4_address_t * in_addr, u16 in_port,
3637                    ip4_address_t * out_addr, u16 out_port,
3638                    ip4_address_t * eh_addr, u16 eh_port,
3639                    ip4_address_t * ehn_addr, u16 ehn_port, u8 proto,
3640                    u32 fib_index, u16 flags, u32 thread_index)
3641 {
3642   snat_main_t *sm = &snat_main;
3643   snat_main_per_thread_data_t *tsm = &sm->per_thread_data[thread_index];
3644   snat_session_t *s;
3645   clib_bihash_kv_16_8_t kv;
3646   vlib_main_t *vm = vlib_get_main ();
3647   f64 now = vlib_time_now (vm);
3648   nat_outside_fib_t *outside_fib;
3649   fib_node_index_t fei = FIB_NODE_INDEX_INVALID;
3650   fib_prefix_t pfx = {
3651     .fp_proto = FIB_PROTOCOL_IP4,
3652     .fp_len = 32,
3653     .fp_addr = {
3654                 .ip4.as_u32 = eh_addr->as_u32,
3655                 },
3656   };
3657
3658
3659   if (!(flags & SNAT_SESSION_FLAG_STATIC_MAPPING))
3660     {
3661       if (nat_set_outside_address_and_port
3662           (sm->addresses, thread_index, *out_addr, out_port, proto))
3663         return;
3664     }
3665
3666   if (flags & SNAT_SESSION_FLAG_TWICE_NAT)
3667     {
3668       if (nat_set_outside_address_and_port
3669           (sm->addresses, thread_index, *ehn_addr, ehn_port, proto))
3670         return;
3671     }
3672
3673   s = nat_ed_session_alloc (sm, thread_index, now, proto);
3674   if (!s)
3675     return;
3676
3677   s->last_heard = now;
3678   s->flags = flags;
3679   s->ext_host_nat_addr.as_u32 = s->ext_host_addr.as_u32 = eh_addr->as_u32;
3680   s->ext_host_nat_port = s->ext_host_port = eh_port;
3681   if (is_twice_nat_session (s))
3682     {
3683       s->ext_host_nat_addr.as_u32 = ehn_addr->as_u32;
3684       s->ext_host_nat_port = ehn_port;
3685     }
3686   switch (vec_len (sm->outside_fibs))
3687     {
3688     case 0:
3689       s->out2in.fib_index = sm->outside_fib_index;
3690       break;
3691     case 1:
3692       s->out2in.fib_index = sm->outside_fibs[0].fib_index;
3693       break;
3694     default:
3695       /* *INDENT-OFF* */
3696       vec_foreach (outside_fib, sm->outside_fibs)
3697         {
3698           fei = fib_table_lookup (outside_fib->fib_index, &pfx);
3699           if (FIB_NODE_INDEX_INVALID != fei)
3700             {
3701               if (fib_entry_get_resolving_interface (fei) != ~0)
3702                 {
3703                   s->out2in.fib_index = outside_fib->fib_index;
3704                   break;
3705                 }
3706             }
3707         }
3708       /* *INDENT-ON* */
3709       break;
3710     }
3711   s->nat_proto = proto;
3712   s->out2in.addr.as_u32 = out_addr->as_u32;
3713   s->out2in.port = out_port;
3714
3715   s->in2out.addr.as_u32 = in_addr->as_u32;
3716   s->in2out.port = in_port;
3717   s->in2out.fib_index = fib_index;
3718
3719   init_ed_kv (&kv, *in_addr, in_port, s->ext_host_nat_addr,
3720               s->ext_host_nat_port, fib_index, nat_proto_to_ip_proto (proto),
3721               thread_index, s - tsm->sessions);
3722   if (clib_bihash_add_del_16_8 (&tsm->in2out_ed, &kv, 1))
3723     nat_elog_warn ("in2out key add failed");
3724
3725   init_ed_kv (&kv, *out_addr, out_port, *eh_addr, eh_port,
3726               s->out2in.fib_index, nat_proto_to_ip_proto (proto),
3727               thread_index, s - tsm->sessions);
3728   if (clib_bihash_add_del_16_8 (&sm->out2in_ed, &kv, 1))
3729     nat_elog_warn ("out2in key add failed");
3730 }
3731
3732 void
3733 nat_ha_sdel_ed_cb (ip4_address_t * out_addr, u16 out_port,
3734                    ip4_address_t * eh_addr, u16 eh_port, u8 proto,
3735                    u32 fib_index, u32 ti)
3736 {
3737   snat_main_t *sm = &snat_main;
3738   clib_bihash_kv_16_8_t kv, value;
3739   u32 thread_index;
3740   snat_session_t *s;
3741   snat_main_per_thread_data_t *tsm;
3742
3743   if (sm->num_workers > 1)
3744     thread_index =
3745       sm->first_worker_index +
3746       (sm->workers[(clib_net_to_host_u16 (out_port) -
3747                     1024) / sm->port_per_thread]);
3748   else
3749     thread_index = sm->num_workers;
3750   tsm = vec_elt_at_index (sm->per_thread_data, thread_index);
3751
3752   init_ed_k (&kv, *out_addr, out_port, *eh_addr, eh_port, fib_index, proto);
3753   if (clib_bihash_search_16_8 (&sm->out2in_ed, &kv, &value))
3754     return;
3755
3756   s = pool_elt_at_index (tsm->sessions, ed_value_get_session_index (&value));
3757   nat_free_session_data (sm, s, thread_index, 1);
3758   nat44_delete_session (sm, s, thread_index);
3759 }
3760
3761 void
3762 nat_ha_sref_ed_cb (ip4_address_t * out_addr, u16 out_port,
3763                    ip4_address_t * eh_addr, u16 eh_port, u8 proto,
3764                    u32 fib_index, u32 total_pkts, u64 total_bytes,
3765                    u32 thread_index)
3766 {
3767   snat_main_t *sm = &snat_main;
3768   clib_bihash_kv_16_8_t kv, value;
3769   snat_session_t *s;
3770   snat_main_per_thread_data_t *tsm;
3771
3772   tsm = vec_elt_at_index (sm->per_thread_data, thread_index);
3773
3774   init_ed_k (&kv, *out_addr, out_port, *eh_addr, eh_port, fib_index, proto);
3775   if (clib_bihash_search_16_8 (&sm->out2in_ed, &kv, &value))
3776     return;
3777
3778   s = pool_elt_at_index (tsm->sessions, ed_value_get_session_index (&value));
3779   s->total_pkts = total_pkts;
3780   s->total_bytes = total_bytes;
3781 }
3782
3783 static u32
3784 nat_calc_bihash_buckets (u32 n_elts)
3785 {
3786   return 1 << (max_log2 (n_elts >> 1) + 1);
3787 }
3788
3789 static u32
3790 nat_calc_bihash_memory (u32 n_buckets, uword kv_size)
3791 {
3792   return n_buckets * (8 + kv_size * 4);
3793 }
3794
3795 void
3796 nat44_db_init (snat_main_per_thread_data_t * tsm)
3797 {
3798   snat_main_t *sm = &snat_main;
3799
3800   pool_alloc (tsm->sessions, sm->max_translations_per_thread);
3801   pool_alloc (tsm->lru_pool, sm->max_translations_per_thread);
3802
3803   dlist_elt_t *head;
3804
3805   pool_get (tsm->lru_pool, head);
3806   tsm->tcp_trans_lru_head_index = head - tsm->lru_pool;
3807   clib_dlist_init (tsm->lru_pool, tsm->tcp_trans_lru_head_index);
3808
3809   pool_get (tsm->lru_pool, head);
3810   tsm->tcp_estab_lru_head_index = head - tsm->lru_pool;
3811   clib_dlist_init (tsm->lru_pool, tsm->tcp_estab_lru_head_index);
3812
3813   pool_get (tsm->lru_pool, head);
3814   tsm->udp_lru_head_index = head - tsm->lru_pool;
3815   clib_dlist_init (tsm->lru_pool, tsm->udp_lru_head_index);
3816
3817   pool_get (tsm->lru_pool, head);
3818   tsm->icmp_lru_head_index = head - tsm->lru_pool;
3819   clib_dlist_init (tsm->lru_pool, tsm->icmp_lru_head_index);
3820
3821   pool_get (tsm->lru_pool, head);
3822   tsm->unk_proto_lru_head_index = head - tsm->lru_pool;
3823   clib_dlist_init (tsm->lru_pool, tsm->unk_proto_lru_head_index);
3824
3825   if (sm->endpoint_dependent)
3826     {
3827       clib_bihash_init_16_8 (&tsm->in2out_ed, "in2out-ed",
3828                              sm->translation_buckets,
3829                              sm->translation_memory_size);
3830       clib_bihash_set_kvp_format_fn_16_8 (&tsm->in2out_ed,
3831                                           format_ed_session_kvp);
3832     }
3833   else
3834     {
3835       clib_bihash_init_8_8 (&tsm->in2out, "in2out",
3836                             sm->translation_buckets,
3837                             sm->translation_memory_size);
3838       clib_bihash_set_kvp_format_fn_8_8 (&tsm->in2out, format_session_kvp);
3839       clib_bihash_init_8_8 (&tsm->out2in, "out2in",
3840                             sm->translation_buckets,
3841                             sm->translation_memory_size);
3842       clib_bihash_set_kvp_format_fn_8_8 (&tsm->out2in, format_session_kvp);
3843     }
3844
3845   // TODO: resolve static mappings (put only to !ED)
3846   pool_alloc (tsm->list_pool, sm->max_translations_per_thread);
3847   clib_bihash_init_8_8 (&tsm->user_hash, "users", sm->user_buckets,
3848                         sm->user_memory_size);
3849   clib_bihash_set_kvp_format_fn_8_8 (&tsm->user_hash, format_user_kvp);
3850 }
3851
3852 void
3853 nat44_db_free (snat_main_per_thread_data_t * tsm)
3854 {
3855   snat_main_t *sm = &snat_main;
3856
3857   pool_free (tsm->sessions);
3858   pool_free (tsm->lru_pool);
3859
3860   if (sm->endpoint_dependent)
3861     {
3862       clib_bihash_free_16_8 (&tsm->in2out_ed);
3863     }
3864   else
3865     {
3866       clib_bihash_free_8_8 (&tsm->in2out);
3867       clib_bihash_free_8_8 (&tsm->out2in);
3868     }
3869
3870   // TODO: resolve static mappings (put only to !ED)
3871   pool_free (tsm->users);
3872   pool_free (tsm->list_pool);
3873   clib_bihash_free_8_8 (&tsm->user_hash);
3874 }
3875
3876 void
3877 nat44_sessions_clear ()
3878 {
3879   snat_main_t *sm = &snat_main;
3880   snat_main_per_thread_data_t *tsm;
3881
3882   if (sm->endpoint_dependent)
3883     {
3884       clib_bihash_free_16_8 (&sm->out2in_ed);
3885       clib_bihash_init_16_8 (&sm->out2in_ed, "out2in-ed",
3886                              clib_max (1, sm->num_workers) *
3887                              sm->translation_buckets,
3888                              clib_max (1, sm->num_workers) *
3889                              sm->translation_memory_size);
3890       clib_bihash_set_kvp_format_fn_16_8 (&sm->out2in_ed,
3891                                           format_ed_session_kvp);
3892     }
3893
3894   /* *INDENT-OFF* */
3895   vec_foreach (tsm, sm->per_thread_data)
3896     {
3897       u32 ti;
3898
3899       nat44_db_free (tsm);
3900       nat44_db_init (tsm);
3901
3902       ti = tsm->snat_thread_index;
3903       vlib_set_simple_counter (&sm->total_users, ti, 0, 0);
3904       vlib_set_simple_counter (&sm->total_sessions, ti, 0, 0);
3905     }
3906   /* *INDENT-ON* */
3907 }
3908
3909 static clib_error_t *
3910 snat_config (vlib_main_t * vm, unformat_input_t * input)
3911 {
3912   snat_main_t *sm = &snat_main;
3913   snat_main_per_thread_data_t *tsm;
3914
3915   u32 static_mapping_buckets = 1024;
3916   uword static_mapping_memory_size = 64 << 20;
3917
3918   u32 nat64_bib_buckets = 1024;
3919   u32 nat64_bib_memory_size = 128 << 20;
3920
3921   u32 nat64_st_buckets = 2048;
3922   uword nat64_st_memory_size = 256 << 20;
3923
3924   u32 max_users_per_thread = 0;
3925   u32 user_memory_size = 0;
3926   u32 max_translations_per_thread = 0;
3927   u32 translation_memory_size = 0;
3928
3929   u32 max_translations_per_user = ~0;
3930
3931   u32 outside_vrf_id = 0;
3932   u32 outside_ip6_vrf_id = 0;
3933   u32 inside_vrf_id = 0;
3934   u8 static_mapping_only = 0;
3935   u8 static_mapping_connection_tracking = 0;
3936
3937   u32 udp_timeout = SNAT_UDP_TIMEOUT;
3938   u32 icmp_timeout = SNAT_ICMP_TIMEOUT;
3939   u32 tcp_transitory_timeout = SNAT_TCP_TRANSITORY_TIMEOUT;
3940   u32 tcp_established_timeout = SNAT_TCP_ESTABLISHED_TIMEOUT;
3941
3942   sm->deterministic = 0;
3943   sm->out2in_dpo = 0;
3944   sm->endpoint_dependent = 0;
3945
3946   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
3947     {
3948       if (unformat
3949           (input, "max translations per thread %d",
3950            &max_translations_per_thread))
3951         ;
3952       else if (unformat (input, "udp timeout %d", &udp_timeout))
3953         ;
3954       else if (unformat (input, "icmp timeout %d", &icmp_timeout))
3955         ;
3956       else if (unformat (input, "tcp transitory timeout %d",
3957                          &tcp_transitory_timeout));
3958       else if (unformat (input, "tcp established timeout %d",
3959                          &tcp_established_timeout));
3960       else if (unformat (input, "translation hash memory %d",
3961                          &translation_memory_size));
3962       else
3963         if (unformat
3964             (input, "max users per thread %d", &max_users_per_thread))
3965         ;
3966       else if (unformat (input, "user hash memory %d", &user_memory_size))
3967         ;
3968       else if (unformat (input, "max translations per user %d",
3969                          &max_translations_per_user))
3970         ;
3971       else if (unformat (input, "outside VRF id %d", &outside_vrf_id))
3972         ;
3973       else if (unformat (input, "outside ip6 VRF id %d", &outside_ip6_vrf_id))
3974         ;
3975       else if (unformat (input, "inside VRF id %d", &inside_vrf_id))
3976         ;
3977       else if (unformat (input, "static mapping only"))
3978         {
3979           static_mapping_only = 1;
3980           if (unformat (input, "connection tracking"))
3981             static_mapping_connection_tracking = 1;
3982         }
3983       else if (unformat (input, "deterministic"))
3984         sm->deterministic = 1;
3985       else if (unformat (input, "nat64 bib hash buckets %d",
3986                          &nat64_bib_buckets))
3987         ;
3988       else if (unformat (input, "nat64 bib hash memory %d",
3989                          &nat64_bib_memory_size))
3990         ;
3991       else
3992         if (unformat (input, "nat64 st hash buckets %d", &nat64_st_buckets))
3993         ;
3994       else if (unformat (input, "nat64 st hash memory %d",
3995                          &nat64_st_memory_size))
3996         ;
3997       else if (unformat (input, "out2in dpo"))
3998         sm->out2in_dpo = 1;
3999       else if (unformat (input, "endpoint-dependent"))
4000         sm->endpoint_dependent = 1;
4001       else
4002         return clib_error_return (0, "unknown input '%U'",
4003                                   format_unformat_error, input);
4004     }
4005
4006   if (sm->deterministic && sm->endpoint_dependent)
4007     return clib_error_return (0,
4008                               "deterministic and endpoint-dependent modes are mutually exclusive");
4009
4010   if (static_mapping_only && (sm->deterministic || sm->endpoint_dependent))
4011     return clib_error_return (0,
4012                               "static mapping only mode available only for simple nat");
4013
4014   if (sm->out2in_dpo && (sm->deterministic || sm->endpoint_dependent))
4015     return clib_error_return (0,
4016                               "out2in dpo mode available only for simple nat");
4017   if (sm->endpoint_dependent && max_users_per_thread > 0)
4018     {
4019       return clib_error_return (0,
4020                                 "setting 'max users' in endpoint-dependent mode is not supported");
4021     }
4022
4023   if (sm->endpoint_dependent && max_translations_per_user != ~0)
4024     {
4025       return clib_error_return (0,
4026                                 "setting 'max translations per user' in endpoint-dependent mode is not supported");
4027     }
4028
4029   /* optionally configurable timeouts for testing purposes */
4030   sm->udp_timeout = udp_timeout;
4031   sm->tcp_transitory_timeout = tcp_transitory_timeout;
4032   sm->tcp_established_timeout = tcp_established_timeout;
4033   sm->icmp_timeout = icmp_timeout;
4034
4035   if (0 == max_users_per_thread)
4036     {
4037       max_users_per_thread = 1024;
4038     }
4039   sm->max_users_per_thread = max_users_per_thread;
4040   sm->user_buckets = nat_calc_bihash_buckets (sm->max_users_per_thread);
4041
4042   if (0 == max_translations_per_thread)
4043     {
4044       // default value based on legacy setting of load factor 10 * default
4045       // translation buckets 1024
4046       max_translations_per_thread = 10 * 1024;
4047     }
4048   sm->max_translations_per_thread = max_translations_per_thread;
4049   sm->translation_buckets =
4050     nat_calc_bihash_buckets (sm->max_translations_per_thread);
4051   if (0 == translation_memory_size)
4052     {
4053       translation_memory_size =
4054         nat_calc_bihash_memory (sm->translation_buckets,
4055                                 sizeof (clib_bihash_16_8_t));
4056     }
4057   sm->translation_memory_size = translation_memory_size;
4058   if (0 == user_memory_size)
4059     {
4060       user_memory_size =
4061         nat_calc_bihash_memory (sm->max_users_per_thread,
4062                                 sizeof (clib_bihash_8_8_t));
4063     }
4064   sm->user_memory_size = user_memory_size;
4065   vec_add1 (sm->max_translations_per_fib, sm->max_translations_per_thread);
4066
4067   sm->max_translations_per_user = max_translations_per_user == ~0 ?
4068     sm->max_translations_per_thread : max_translations_per_user;
4069
4070   sm->outside_vrf_id = outside_vrf_id;
4071   sm->outside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
4072                                                              outside_vrf_id,
4073                                                              nat_fib_src_hi);
4074   sm->inside_vrf_id = inside_vrf_id;
4075   sm->inside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
4076                                                             inside_vrf_id,
4077                                                             nat_fib_src_hi);
4078   sm->static_mapping_only = static_mapping_only;
4079   sm->static_mapping_connection_tracking = static_mapping_connection_tracking;
4080
4081   nat64_set_hash (nat64_bib_buckets, nat64_bib_memory_size, nat64_st_buckets,
4082                   nat64_st_memory_size);
4083
4084   if (sm->deterministic)
4085     {
4086       sm->in2out_node_index = snat_det_in2out_node.index;
4087       sm->in2out_output_node_index = ~0;
4088       sm->out2in_node_index = snat_det_out2in_node.index;
4089       sm->icmp_match_in2out_cb = icmp_match_in2out_det;
4090       sm->icmp_match_out2in_cb = icmp_match_out2in_det;
4091     }
4092   else
4093     {
4094       if (sm->endpoint_dependent)
4095         {
4096           sm->worker_in2out_cb = nat44_ed_get_worker_in2out_cb;
4097           sm->worker_out2in_cb = nat44_ed_get_worker_out2in_cb;
4098
4099           sm->in2out_node_index = nat44_ed_in2out_node.index;
4100           sm->in2out_output_node_index = nat44_ed_in2out_output_node.index;
4101           sm->out2in_node_index = nat44_ed_out2in_node.index;
4102
4103           sm->icmp_match_in2out_cb = icmp_match_in2out_ed;
4104           sm->icmp_match_out2in_cb = icmp_match_out2in_ed;
4105           nat_affinity_init (vm);
4106           nat_ha_init (vm, nat_ha_sadd_ed_cb, nat_ha_sdel_ed_cb,
4107                        nat_ha_sref_ed_cb);
4108           clib_bihash_init_16_8 (&sm->out2in_ed, "out2in-ed",
4109                                  clib_max (1, sm->num_workers) *
4110                                  sm->translation_buckets,
4111                                  clib_max (1, sm->num_workers) *
4112                                  sm->translation_memory_size);
4113           clib_bihash_set_kvp_format_fn_16_8 (&sm->out2in_ed,
4114                                               format_ed_session_kvp);
4115         }
4116       else
4117         {
4118           sm->worker_in2out_cb = snat_get_worker_in2out_cb;
4119           sm->worker_out2in_cb = snat_get_worker_out2in_cb;
4120
4121           sm->in2out_node_index = snat_in2out_node.index;
4122           sm->in2out_output_node_index = snat_in2out_output_node.index;
4123           sm->out2in_node_index = snat_out2in_node.index;
4124
4125           sm->icmp_match_in2out_cb = icmp_match_in2out_slow;
4126           sm->icmp_match_out2in_cb = icmp_match_out2in_slow;
4127           nat_ha_init (vm, nat_ha_sadd_cb, nat_ha_sdel_cb, nat_ha_sref_cb);
4128         }
4129       if (!static_mapping_only ||
4130           (static_mapping_only && static_mapping_connection_tracking))
4131         {
4132           /* *INDENT-OFF* */
4133           vec_foreach (tsm, sm->per_thread_data)
4134             {
4135               nat44_db_init (tsm);
4136             }
4137           /* *INDENT-ON* */
4138         }
4139       else
4140         {
4141           sm->icmp_match_in2out_cb = icmp_match_in2out_fast;
4142           sm->icmp_match_out2in_cb = icmp_match_out2in_fast;
4143         }
4144       clib_bihash_init_8_8 (&sm->static_mapping_by_local,
4145                             "static_mapping_by_local", static_mapping_buckets,
4146                             static_mapping_memory_size);
4147       clib_bihash_set_kvp_format_fn_8_8 (&sm->static_mapping_by_local,
4148                                          format_static_mapping_kvp);
4149
4150       clib_bihash_init_8_8 (&sm->static_mapping_by_external,
4151                             "static_mapping_by_external",
4152                             static_mapping_buckets,
4153                             static_mapping_memory_size);
4154       clib_bihash_set_kvp_format_fn_8_8 (&sm->static_mapping_by_external,
4155                                          format_static_mapping_kvp);
4156     }
4157
4158   return 0;
4159 }
4160
4161 VLIB_CONFIG_FUNCTION (snat_config, "nat");
4162
4163 static void
4164 nat_ip4_add_del_addr_only_sm_cb (ip4_main_t * im,
4165                                  uword opaque,
4166                                  u32 sw_if_index,
4167                                  ip4_address_t * address,
4168                                  u32 address_length,
4169                                  u32 if_address_index, u32 is_delete)
4170 {
4171   snat_main_t *sm = &snat_main;
4172   snat_static_map_resolve_t *rp;
4173   snat_static_mapping_t *m;
4174   clib_bihash_kv_8_8_t kv, value;
4175   int i, rv;
4176   ip4_address_t l_addr;
4177
4178   for (i = 0; i < vec_len (sm->to_resolve); i++)
4179     {
4180       rp = sm->to_resolve + i;
4181       if (rp->addr_only == 0)
4182         continue;
4183       if (rp->sw_if_index == sw_if_index)
4184         goto match;
4185     }
4186
4187   return;
4188
4189 match:
4190   init_nat_k (&kv, *address, rp->addr_only ? 0 : rp->e_port,
4191               sm->outside_fib_index, rp->addr_only ? 0 : rp->proto);
4192   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
4193     m = 0;
4194   else
4195     m = pool_elt_at_index (sm->static_mappings, value.value);
4196
4197   if (!is_delete)
4198     {
4199       /* Don't trip over lease renewal, static config */
4200       if (m)
4201         return;
4202     }
4203   else
4204     {
4205       if (!m)
4206         return;
4207     }
4208
4209   /* Indetity mapping? */
4210   if (rp->l_addr.as_u32 == 0)
4211     l_addr.as_u32 = address[0].as_u32;
4212   else
4213     l_addr.as_u32 = rp->l_addr.as_u32;
4214   /* Add the static mapping */
4215   rv = snat_add_static_mapping (l_addr,
4216                                 address[0],
4217                                 rp->l_port,
4218                                 rp->e_port,
4219                                 rp->vrf_id,
4220                                 rp->addr_only, ~0 /* sw_if_index */ ,
4221                                 rp->proto, !is_delete, rp->twice_nat,
4222                                 rp->out2in_only, rp->tag, rp->identity_nat);
4223   if (rv)
4224     nat_elog_notice_X1 ("snat_add_static_mapping returned %d", "i4", rv);
4225 }
4226
4227 static void
4228 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
4229                                        uword opaque,
4230                                        u32 sw_if_index,
4231                                        ip4_address_t * address,
4232                                        u32 address_length,
4233                                        u32 if_address_index, u32 is_delete)
4234 {
4235   snat_main_t *sm = &snat_main;
4236   snat_static_map_resolve_t *rp;
4237   ip4_address_t l_addr;
4238   int i, j;
4239   int rv;
4240   u8 twice_nat = 0;
4241   snat_address_t *addresses = sm->addresses;
4242
4243   for (i = 0; i < vec_len (sm->auto_add_sw_if_indices); i++)
4244     {
4245       if (sw_if_index == sm->auto_add_sw_if_indices[i])
4246         goto match;
4247     }
4248
4249   for (i = 0; i < vec_len (sm->auto_add_sw_if_indices_twice_nat); i++)
4250     {
4251       twice_nat = 1;
4252       addresses = sm->twice_nat_addresses;
4253       if (sw_if_index == sm->auto_add_sw_if_indices_twice_nat[i])
4254         goto match;
4255     }
4256
4257   return;
4258
4259 match:
4260   if (!is_delete)
4261     {
4262       /* Don't trip over lease renewal, static config */
4263       for (j = 0; j < vec_len (addresses); j++)
4264         if (addresses[j].addr.as_u32 == address->as_u32)
4265           return;
4266
4267       (void) snat_add_address (sm, address, ~0, twice_nat);
4268       /* Scan static map resolution vector */
4269       for (j = 0; j < vec_len (sm->to_resolve); j++)
4270         {
4271           rp = sm->to_resolve + j;
4272           if (rp->addr_only)
4273             continue;
4274           /* On this interface? */
4275           if (rp->sw_if_index == sw_if_index)
4276             {
4277               /* Indetity mapping? */
4278               if (rp->l_addr.as_u32 == 0)
4279                 l_addr.as_u32 = address[0].as_u32;
4280               else
4281                 l_addr.as_u32 = rp->l_addr.as_u32;
4282               /* Add the static mapping */
4283               rv = snat_add_static_mapping (l_addr,
4284                                             address[0],
4285                                             rp->l_port,
4286                                             rp->e_port,
4287                                             rp->vrf_id,
4288                                             rp->addr_only,
4289                                             ~0 /* sw_if_index */ ,
4290                                             rp->proto,
4291                                             rp->is_add, rp->twice_nat,
4292                                             rp->out2in_only, rp->tag,
4293                                             rp->identity_nat);
4294               if (rv)
4295                 nat_elog_notice_X1 ("snat_add_static_mapping returned %d",
4296                                     "i4", rv);
4297             }
4298         }
4299       return;
4300     }
4301   else
4302     {
4303       (void) snat_del_address (sm, address[0], 1, twice_nat);
4304       return;
4305     }
4306 }
4307
4308
4309 int
4310 snat_add_interface_address (snat_main_t * sm, u32 sw_if_index, int is_del,
4311                             u8 twice_nat)
4312 {
4313   ip4_main_t *ip4_main = sm->ip4_main;
4314   ip4_address_t *first_int_addr;
4315   snat_static_map_resolve_t *rp;
4316   u32 *indices_to_delete = 0;
4317   int i, j;
4318   u32 *auto_add_sw_if_indices =
4319     twice_nat ? sm->
4320     auto_add_sw_if_indices_twice_nat : sm->auto_add_sw_if_indices;
4321
4322   first_int_addr = ip4_interface_first_address (ip4_main, sw_if_index, 0        /* just want the address */
4323     );
4324
4325   for (i = 0; i < vec_len (auto_add_sw_if_indices); i++)
4326     {
4327       if (auto_add_sw_if_indices[i] == sw_if_index)
4328         {
4329           if (is_del)
4330             {
4331               /* if have address remove it */
4332               if (first_int_addr)
4333                 (void) snat_del_address (sm, first_int_addr[0], 1, twice_nat);
4334               else
4335                 {
4336                   for (j = 0; j < vec_len (sm->to_resolve); j++)
4337                     {
4338                       rp = sm->to_resolve + j;
4339                       if (rp->sw_if_index == sw_if_index)
4340                         vec_add1 (indices_to_delete, j);
4341                     }
4342                   if (vec_len (indices_to_delete))
4343                     {
4344                       for (j = vec_len (indices_to_delete) - 1; j >= 0; j--)
4345                         vec_del1 (sm->to_resolve, j);
4346                       vec_free (indices_to_delete);
4347                     }
4348                 }
4349               if (twice_nat)
4350                 vec_del1 (sm->auto_add_sw_if_indices_twice_nat, i);
4351               else
4352                 vec_del1 (sm->auto_add_sw_if_indices, i);
4353             }
4354           else
4355             return VNET_API_ERROR_VALUE_EXIST;
4356
4357           return 0;
4358         }
4359     }
4360
4361   if (is_del)
4362     return VNET_API_ERROR_NO_SUCH_ENTRY;
4363
4364   /* add to the auto-address list */
4365   if (twice_nat)
4366     vec_add1 (sm->auto_add_sw_if_indices_twice_nat, sw_if_index);
4367   else
4368     vec_add1 (sm->auto_add_sw_if_indices, sw_if_index);
4369
4370   /* If the address is already bound - or static - add it now */
4371   if (first_int_addr)
4372     (void) snat_add_address (sm, first_int_addr, ~0, twice_nat);
4373
4374   return 0;
4375 }
4376
4377 int
4378 nat44_del_session (snat_main_t * sm, ip4_address_t * addr, u16 port,
4379                    nat_protocol_t proto, u32 vrf_id, int is_in)
4380 {
4381   snat_main_per_thread_data_t *tsm;
4382   clib_bihash_kv_8_8_t kv, value;
4383   ip4_header_t ip;
4384   u32 fib_index = fib_table_find (FIB_PROTOCOL_IP4, vrf_id);
4385   snat_session_t *s;
4386   clib_bihash_8_8_t *t;
4387
4388   if (sm->endpoint_dependent)
4389     return VNET_API_ERROR_UNSUPPORTED;
4390
4391   ip.dst_address.as_u32 = ip.src_address.as_u32 = addr->as_u32;
4392   if (sm->num_workers > 1)
4393     tsm =
4394       vec_elt_at_index (sm->per_thread_data,
4395                         sm->worker_in2out_cb (&ip, fib_index, 0));
4396   else
4397     tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
4398
4399   init_nat_k (&kv, *addr, port, fib_index, proto);
4400   t = is_in ? &tsm->in2out : &tsm->out2in;
4401   if (!clib_bihash_search_8_8 (t, &kv, &value))
4402     {
4403       if (pool_is_free_index (tsm->sessions, value.value))
4404         return VNET_API_ERROR_UNSPECIFIED;
4405
4406       s = pool_elt_at_index (tsm->sessions, value.value);
4407       nat_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
4408       nat44_delete_session (sm, s, tsm - sm->per_thread_data);
4409       return 0;
4410     }
4411
4412   return VNET_API_ERROR_NO_SUCH_ENTRY;
4413 }
4414
4415 int
4416 nat44_del_ed_session (snat_main_t * sm, ip4_address_t * addr, u16 port,
4417                       ip4_address_t * eh_addr, u16 eh_port, u8 proto,
4418                       u32 vrf_id, int is_in)
4419 {
4420   ip4_header_t ip;
4421   clib_bihash_16_8_t *t;
4422   clib_bihash_kv_16_8_t kv, value;
4423   u32 fib_index = fib_table_find (FIB_PROTOCOL_IP4, vrf_id);
4424   snat_session_t *s;
4425   snat_main_per_thread_data_t *tsm;
4426
4427   if (!sm->endpoint_dependent)
4428     return VNET_API_ERROR_FEATURE_DISABLED;
4429
4430   ip.dst_address.as_u32 = ip.src_address.as_u32 = addr->as_u32;
4431   if (sm->num_workers > 1)
4432     tsm =
4433       vec_elt_at_index (sm->per_thread_data,
4434                         sm->worker_in2out_cb (&ip, fib_index, 0));
4435   else
4436     tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
4437
4438   t = is_in ? &tsm->in2out_ed : &sm->out2in_ed;
4439   init_ed_k (&kv, *addr, port, *eh_addr, eh_port, fib_index, proto);
4440   if (clib_bihash_search_16_8 (t, &kv, &value))
4441     {
4442       return VNET_API_ERROR_NO_SUCH_ENTRY;
4443     }
4444
4445   if (pool_is_free_index (tsm->sessions, value.value))
4446     return VNET_API_ERROR_UNSPECIFIED;
4447   s = pool_elt_at_index (tsm->sessions, value.value);
4448   nat_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
4449   nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
4450   return 0;
4451 }
4452
4453 void
4454 nat_set_alloc_addr_and_port_mape (u16 psid, u16 psid_offset, u16 psid_length)
4455 {
4456   snat_main_t *sm = &snat_main;
4457
4458   sm->addr_and_port_alloc_alg = NAT_ADDR_AND_PORT_ALLOC_ALG_MAPE;
4459   sm->alloc_addr_and_port = nat_alloc_addr_and_port_mape;
4460   sm->psid = psid;
4461   sm->psid_offset = psid_offset;
4462   sm->psid_length = psid_length;
4463 }
4464
4465 void
4466 nat_set_alloc_addr_and_port_range (u16 start_port, u16 end_port)
4467 {
4468   snat_main_t *sm = &snat_main;
4469
4470   sm->addr_and_port_alloc_alg = NAT_ADDR_AND_PORT_ALLOC_ALG_RANGE;
4471   sm->alloc_addr_and_port = nat_alloc_addr_and_port_range;
4472   sm->start_port = start_port;
4473   sm->end_port = end_port;
4474 }
4475
4476 void
4477 nat_set_alloc_addr_and_port_default (void)
4478 {
4479   snat_main_t *sm = &snat_main;
4480
4481   sm->addr_and_port_alloc_alg = NAT_ADDR_AND_PORT_ALLOC_ALG_DEFAULT;
4482   sm->alloc_addr_and_port = nat_alloc_addr_and_port_default;
4483 }
4484
4485 VLIB_NODE_FN (nat_default_node) (vlib_main_t * vm,
4486                                  vlib_node_runtime_t * node,
4487                                  vlib_frame_t * frame)
4488 {
4489   return 0;
4490 }
4491
4492 /* *INDENT-OFF* */
4493 VLIB_REGISTER_NODE (nat_default_node) = {
4494   .name = "nat-default",
4495   .vector_size = sizeof (u32),
4496   .format_trace = 0,
4497   .type = VLIB_NODE_TYPE_INTERNAL,
4498   .n_errors = 0,
4499   .n_next_nodes = NAT_N_NEXT,
4500   .next_nodes = {
4501     [NAT_NEXT_DROP] = "error-drop",
4502     [NAT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
4503     [NAT_NEXT_IN2OUT_ED_FAST_PATH] = "nat44-ed-in2out",
4504     [NAT_NEXT_IN2OUT_ED_SLOW_PATH] = "nat44-ed-in2out-slowpath",
4505     [NAT_NEXT_IN2OUT_ED_OUTPUT_SLOW_PATH] = "nat44-ed-in2out-output-slowpath",
4506     [NAT_NEXT_OUT2IN_ED_FAST_PATH] = "nat44-ed-out2in",
4507     [NAT_NEXT_OUT2IN_ED_SLOW_PATH] = "nat44-ed-out2in-slowpath",
4508     [NAT_NEXT_IN2OUT_CLASSIFY] = "nat44-in2out-worker-handoff",
4509     [NAT_NEXT_OUT2IN_CLASSIFY] = "nat44-out2in-worker-handoff",
4510   },
4511 };
4512 /* *INDENT-ON* */
4513
4514 /*
4515  * fd.io coding-style-patch-verification: ON
4516  *
4517  * Local Variables:
4518  * eval: (c-set-style "gnu")
4519  * End:
4520  */