nat: nat44-ei/ed nat objects cleanup improvements
[vpp.git] / src / plugins / nat / nat44-ed / nat44_ed.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 <vpp/app/version.h>
19
20 #include <vnet/vnet.h>
21 #include <vnet/ip/ip.h>
22 #include <vnet/ip/ip4.h>
23 #include <vnet/ip/ip_table.h>
24 #include <vnet/ip/reass/ip4_sv_reass.h>
25 #include <vnet/fib/fib_table.h>
26 #include <vnet/fib/ip4_fib.h>
27 #include <vnet/plugin/plugin.h>
28 #include <vppinfra/bihash_16_8.h>
29
30 #include <nat/lib/log.h>
31 #include <nat/lib/nat_inlines.h>
32 #include <nat/lib/ipfix_logging.h>
33 #include <vnet/syslog/syslog.h>
34 #include <nat/lib/nat_syslog_constants.h>
35 #include <nat/lib/nat_syslog.h>
36
37 #include <nat/nat44-ed/nat44_ed.h>
38 #include <nat/nat44-ed/nat44_ed_affinity.h>
39 #include <nat/nat44-ed/nat44_ed_inlines.h>
40
41 #include <vpp/stats/stat_segment.h>
42
43 snat_main_t snat_main;
44
45 static_always_inline void nat_validate_interface_counters (snat_main_t *sm,
46                                                            u32 sw_if_index);
47
48 #define skip_if_disabled()                                                    \
49   do                                                                          \
50     {                                                                         \
51       snat_main_t *sm = &snat_main;                                           \
52       if (PREDICT_FALSE (!sm->enabled))                                       \
53         return;                                                               \
54     }                                                                         \
55   while (0)
56
57 #define fail_if_enabled()                                                     \
58   do                                                                          \
59     {                                                                         \
60       snat_main_t *sm = &snat_main;                                           \
61       if (PREDICT_FALSE (sm->enabled))                                        \
62         {                                                                     \
63           nat_log_err ("plugin enabled");                                     \
64           return 1;                                                           \
65         }                                                                     \
66     }                                                                         \
67   while (0)
68
69 #define fail_if_disabled()                                                    \
70   do                                                                          \
71     {                                                                         \
72       snat_main_t *sm = &snat_main;                                           \
73       if (PREDICT_FALSE (!sm->enabled))                                       \
74         {                                                                     \
75           nat_log_err ("plugin disabled");                                    \
76           return 1;                                                           \
77         }                                                                     \
78     }                                                                         \
79   while (0)
80
81 /* Hook up input features */
82 VNET_FEATURE_INIT (nat_pre_in2out, static) = {
83   .arc_name = "ip4-unicast",
84   .node_name = "nat-pre-in2out",
85   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
86                                "ip4-sv-reassembly-feature"),
87 };
88 VNET_FEATURE_INIT (nat_pre_out2in, static) = {
89   .arc_name = "ip4-unicast",
90   .node_name = "nat-pre-out2in",
91   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
92                                "ip4-dhcp-client-detect",
93                                "ip4-sv-reassembly-feature"),
94 };
95 VNET_FEATURE_INIT (snat_in2out_worker_handoff, static) = {
96   .arc_name = "ip4-unicast",
97   .node_name = "nat44-in2out-worker-handoff",
98   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa"),
99 };
100 VNET_FEATURE_INIT (snat_out2in_worker_handoff, static) = {
101   .arc_name = "ip4-unicast",
102   .node_name = "nat44-out2in-worker-handoff",
103   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa",
104                                "ip4-dhcp-client-detect"),
105 };
106 VNET_FEATURE_INIT (ip4_snat_in2out, static) = {
107   .arc_name = "ip4-unicast",
108   .node_name = "nat44-in2out",
109   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
110 };
111 VNET_FEATURE_INIT (ip4_snat_out2in, static) = {
112   .arc_name = "ip4-unicast",
113   .node_name = "nat44-out2in",
114   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature",
115                                "ip4-dhcp-client-detect"),
116 };
117 VNET_FEATURE_INIT (ip4_nat44_ed_in2out, static) = {
118   .arc_name = "ip4-unicast",
119   .node_name = "nat44-ed-in2out",
120   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
121 };
122 VNET_FEATURE_INIT (ip4_nat44_ed_out2in, static) = {
123   .arc_name = "ip4-unicast",
124   .node_name = "nat44-ed-out2in",
125   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature",
126                                "ip4-dhcp-client-detect"),
127 };
128 VNET_FEATURE_INIT (ip4_nat44_ed_classify, static) = {
129   .arc_name = "ip4-unicast",
130   .node_name = "nat44-ed-classify",
131   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
132 };
133 VNET_FEATURE_INIT (ip4_nat_handoff_classify, static) = {
134   .arc_name = "ip4-unicast",
135   .node_name = "nat44-handoff-classify",
136   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
137 };
138 VNET_FEATURE_INIT (ip4_snat_in2out_fast, static) = {
139   .arc_name = "ip4-unicast",
140   .node_name = "nat44-in2out-fast",
141   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature"),
142 };
143 VNET_FEATURE_INIT (ip4_snat_out2in_fast, static) = {
144   .arc_name = "ip4-unicast",
145   .node_name = "nat44-out2in-fast",
146   .runs_after = VNET_FEATURES ("acl-plugin-in-ip4-fa","ip4-sv-reassembly-feature",
147                                "ip4-dhcp-client-detect"),
148 };
149
150 /* Hook up output features */
151 VNET_FEATURE_INIT (ip4_snat_in2out_output, static) = {
152   .arc_name = "ip4-output",
153   .node_name = "nat44-in2out-output",
154   .runs_after = VNET_FEATURES ("ip4-sv-reassembly-output-feature"),
155   .runs_before = VNET_FEATURES ("acl-plugin-out-ip4-fa"),
156 };
157 VNET_FEATURE_INIT (ip4_snat_in2out_output_worker_handoff, static) = {
158   .arc_name = "ip4-output",
159   .node_name = "nat44-in2out-output-worker-handoff",
160   .runs_after = VNET_FEATURES ("ip4-sv-reassembly-output-feature"),
161   .runs_before = VNET_FEATURES ("acl-plugin-out-ip4-fa"),
162 };
163 VNET_FEATURE_INIT (nat_pre_in2out_output, static) = {
164   .arc_name = "ip4-output",
165   .node_name = "nat-pre-in2out-output",
166   .runs_after = VNET_FEATURES ("ip4-sv-reassembly-output-feature"),
167   .runs_before = VNET_FEATURES ("acl-plugin-out-ip4-fa"),
168 };
169 VNET_FEATURE_INIT (ip4_nat44_ed_in2out_output, static) = {
170   .arc_name = "ip4-output",
171   .node_name = "nat44-ed-in2out-output",
172   .runs_after = VNET_FEATURES ("ip4-sv-reassembly-output-feature"),
173   .runs_before = VNET_FEATURES ("acl-plugin-out-ip4-fa"),
174 };
175
176 VLIB_PLUGIN_REGISTER () = {
177     .version = VPP_BUILD_VER,
178     .description = "Network Address Translation (NAT)",
179 };
180
181 static void nat44_ed_db_init (u32 translations, u32 translation_buckets);
182 static void nat44_ed_worker_db_free (snat_main_per_thread_data_t *tsm);
183
184 static int nat44_ed_add_static_mapping_internal (
185   ip4_address_t l_addr, ip4_address_t e_addr, u16 l_port, u16 e_port,
186   ip_protocol_t proto, u32 vrf_id, u32 sw_if_index, u32 flags,
187   ip4_address_t pool_addr, u8 *tag);
188 static int nat44_ed_del_static_mapping_internal (
189   ip4_address_t l_addr, ip4_address_t e_addr, u16 l_port, u16 e_port,
190   ip_protocol_t proto, u32 vrf_id, u32 sw_if_index, u32 flags);
191
192 u32 nat_calc_bihash_buckets (u32 n_elts);
193
194 u8 *
195 format_ed_session_kvp (u8 * s, va_list * args)
196 {
197   clib_bihash_kv_16_8_t *v = va_arg (*args, clib_bihash_kv_16_8_t *);
198
199   u8 proto;
200   u16 r_port, l_port;
201   ip4_address_t l_addr, r_addr;
202   u32 fib_index;
203
204   split_ed_kv (v, &l_addr, &r_addr, &proto, &fib_index, &l_port, &r_port);
205   s = format (s,
206               "local %U:%d remote %U:%d proto %U fib %d thread-index %u "
207               "session-index %u",
208               format_ip4_address, &l_addr, clib_net_to_host_u16 (l_port),
209               format_ip4_address, &r_addr, clib_net_to_host_u16 (r_port),
210               format_ip_protocol, proto, fib_index,
211               ed_value_get_thread_index (v), ed_value_get_session_index (v));
212
213   return s;
214 }
215
216 static_always_inline int
217 nat44_ed_sm_i2o_add (snat_main_t *sm, snat_static_mapping_t *m,
218                      ip4_address_t addr, u16 port, u32 fib_index, u8 proto)
219 {
220   ASSERT (!pool_is_free (sm->static_mappings, m));
221   clib_bihash_kv_16_8_t kv;
222   nat44_ed_sm_init_i2o_kv (&kv, addr.as_u32, port, fib_index, proto,
223                            m - sm->static_mappings);
224   return clib_bihash_add_del_16_8 (&sm->flow_hash, &kv, 1 /*is_add*/);
225 }
226
227 static_always_inline int
228 nat44_ed_sm_i2o_del (snat_main_t *sm, ip4_address_t addr, u16 port,
229                      u32 fib_index, u8 proto)
230 {
231   clib_bihash_kv_16_8_t kv;
232   nat44_ed_sm_init_i2o_k (&kv, addr.as_u32, port, fib_index, proto);
233   return clib_bihash_add_del_16_8 (&sm->flow_hash, &kv, 0 /*is_add*/);
234 }
235
236 static_always_inline int
237 nat44_ed_sm_o2i_add (snat_main_t *sm, snat_static_mapping_t *m,
238                      ip4_address_t addr, u16 port, u32 fib_index, u8 proto)
239 {
240   ASSERT (!pool_is_free (sm->static_mappings, m));
241   clib_bihash_kv_16_8_t kv;
242   nat44_ed_sm_init_o2i_kv (&kv, addr.as_u32, port, fib_index, proto,
243                            m - sm->static_mappings);
244   return clib_bihash_add_del_16_8 (&sm->flow_hash, &kv, 1 /*is_add*/);
245 }
246
247 static_always_inline int
248 nat44_ed_sm_o2i_del (snat_main_t *sm, ip4_address_t addr, u16 port,
249                      u32 fib_index, u8 proto)
250 {
251   clib_bihash_kv_16_8_t kv;
252   nat44_ed_sm_init_o2i_k (&kv, addr.as_u32, port, fib_index, proto);
253   return clib_bihash_add_del_16_8 (&sm->flow_hash, &kv, 0 /*is_add*/);
254 }
255
256 void
257 nat44_ed_free_session_data (snat_main_t *sm, snat_session_t *s,
258                             u32 thread_index, u8 is_ha)
259 {
260   per_vrf_sessions_unregister_session (s, thread_index);
261
262   if (nat_ed_ses_i2o_flow_hash_add_del (sm, thread_index, s, 0))
263     nat_elog_warn (sm, "flow hash del failed");
264
265   if (nat_ed_ses_o2i_flow_hash_add_del (sm, thread_index, s, 0))
266     nat_elog_warn (sm, "flow hash del failed");
267
268   if (na44_ed_is_fwd_bypass_session (s))
269     {
270       return;
271     }
272
273   if (nat44_ed_is_affinity_session (s))
274     nat_affinity_unlock (s->ext_host_addr, s->out2in.addr, s->proto,
275                          s->out2in.port);
276
277   if (!is_ha)
278     nat_syslog_nat44_sdel (0, s->in2out.fib_index, &s->in2out.addr,
279                            s->in2out.port, &s->ext_host_nat_addr,
280                            s->ext_host_nat_port, &s->out2in.addr,
281                            s->out2in.port, &s->ext_host_addr, s->ext_host_port,
282                            s->proto, nat44_ed_is_twice_nat_session (s));
283
284   if (!is_ha)
285     {
286       /* log NAT event */
287       nat_ipfix_logging_nat44_ses_delete (
288         thread_index, s->in2out.addr.as_u32, s->out2in.addr.as_u32, s->proto,
289         s->in2out.port, s->out2in.port, s->in2out.fib_index);
290     }
291 }
292
293 static int
294 is_snat_address_used_in_static_mapping (snat_main_t *sm, ip4_address_t addr)
295 {
296   snat_static_mapping_t *m;
297   pool_foreach (m, sm->static_mappings)
298     {
299       if (is_sm_addr_only (m->flags) || is_sm_out2in_only (m->flags) ||
300           is_sm_identity_nat (m->flags))
301         {
302           continue;
303         }
304       if (m->external_addr.as_u32 == addr.as_u32)
305         {
306           return 1;
307         }
308     }
309   return 0;
310 }
311
312 static void
313 nat44_ed_add_del_addr_to_fib (ip4_address_t *addr, u8 p_len, u32 sw_if_index,
314                               int is_add)
315 {
316   // Add the external NAT address to the FIB as receive entries. This ensures
317   // that VPP will reply to ARP for this address and we don't need to enable
318   // proxy ARP on the outside interface.
319
320   snat_main_t *sm = &snat_main;
321   fib_prefix_t prefix = {
322     .fp_len = p_len,
323     .fp_proto = FIB_PROTOCOL_IP4,
324     .fp_addr = {
325                 .ip4.as_u32 = addr->as_u32,
326                 },
327   };
328   u32 fib_index = ip4_fib_table_get_index_for_sw_if_index (sw_if_index);
329
330   if (is_add)
331     {
332       fib_table_entry_update_one_path (fib_index, &prefix, sm->fib_src_low,
333                                        (FIB_ENTRY_FLAG_CONNECTED |
334                                         FIB_ENTRY_FLAG_LOCAL |
335                                         FIB_ENTRY_FLAG_EXCLUSIVE),
336                                        DPO_PROTO_IP4, NULL, sw_if_index, ~0, 1,
337                                        NULL, FIB_ROUTE_PATH_FLAG_NONE);
338     }
339   else
340     {
341       fib_table_entry_delete (fib_index, &prefix, sm->fib_src_low);
342     }
343 }
344
345 static void
346 nat44_ed_add_del_addr_to_fib_foreach_out_if (ip4_address_t *addr, u8 is_add)
347 {
348   snat_main_t *sm = &snat_main;
349   snat_interface_t *i;
350
351   pool_foreach (i, sm->interfaces)
352     {
353       if (nat44_ed_is_interface_outside (i))
354         {
355           nat44_ed_add_del_addr_to_fib (addr, 32, i->sw_if_index, is_add);
356         }
357     }
358   pool_foreach (i, sm->output_feature_interfaces)
359     {
360       if (nat44_ed_is_interface_outside (i))
361         {
362           nat44_ed_add_del_addr_to_fib (addr, 32, i->sw_if_index, is_add);
363         }
364     }
365 }
366
367 static_always_inline void
368 nat44_ed_add_del_addr_to_fib_foreach_addr (u32 sw_if_index, u8 is_add)
369 {
370   snat_main_t *sm = &snat_main;
371   snat_address_t *ap;
372
373   vec_foreach (ap, sm->addresses)
374     {
375       nat44_ed_add_del_addr_to_fib (&ap->addr, 32, sw_if_index, is_add);
376     }
377 }
378
379 static_always_inline void
380 nat44_ed_add_del_addr_to_fib_foreach_addr_only_sm (u32 sw_if_index, u8 is_add)
381 {
382   snat_main_t *sm = &snat_main;
383   snat_static_mapping_t *m;
384
385   pool_foreach (m, sm->static_mappings)
386     {
387       if (is_sm_addr_only (m->flags) && !is_sm_identity_nat (m->flags))
388         {
389           nat44_ed_add_del_addr_to_fib (&m->external_addr, 32, sw_if_index,
390                                         is_add);
391         }
392     }
393 }
394
395 int
396 nat44_ed_add_address (ip4_address_t *addr, u32 vrf_id, u8 twice_nat)
397 {
398   snat_main_t *sm = &snat_main;
399   snat_address_t *ap, *addresses;
400
401   addresses = twice_nat ? sm->twice_nat_addresses : sm->addresses;
402
403   if (!sm->enabled)
404     {
405       return VNET_API_ERROR_UNSUPPORTED;
406     }
407
408   // check if address already exists
409   vec_foreach (ap, addresses)
410     {
411       if (ap->addr.as_u32 == addr->as_u32)
412         {
413           nat_log_err ("address exist");
414           return VNET_API_ERROR_VALUE_EXIST;
415         }
416     }
417
418   if (twice_nat)
419     {
420       vec_add2 (sm->twice_nat_addresses, ap, 1);
421     }
422   else
423     {
424       vec_add2 (sm->addresses, ap, 1);
425     }
426
427   ap->fib_index = ~0;
428   ap->addr = *addr;
429
430   if (vrf_id != ~0)
431     {
432       ap->fib_index = fib_table_find_or_create_and_lock (
433         FIB_PROTOCOL_IP4, vrf_id, sm->fib_src_low);
434     }
435
436     if (!twice_nat)
437   {
438     // if we don't have enabled interface we don't add address
439     // to fib
440     nat44_ed_add_del_addr_to_fib_foreach_out_if (addr, 1);
441   }
442   return 0;
443 }
444
445 int
446 nat44_ed_del_address (ip4_address_t addr, u8 delete_sm, u8 twice_nat)
447 {
448   snat_main_t *sm = &snat_main;
449   snat_address_t *a = 0, *addresses;
450   snat_session_t *ses;
451   u32 *ses_to_be_removed = 0, *ses_index;
452   snat_main_per_thread_data_t *tsm;
453   snat_static_mapping_t *m;
454   int j;
455
456   addresses = twice_nat ? sm->twice_nat_addresses : sm->addresses;
457
458   for (j = 0; j < vec_len (addresses); j++)
459     {
460       if (addresses[j].addr.as_u32 == addr.as_u32)
461         {
462           a = addresses + j;
463           break;
464         }
465     }
466   if (!a)
467     {
468       nat_log_err ("no such address");
469       return VNET_API_ERROR_NO_SUCH_ENTRY;
470     }
471
472   if (delete_sm)
473     {
474       pool_foreach (m, sm->static_mappings)
475         {
476           if (m->external_addr.as_u32 == addr.as_u32)
477             {
478               nat44_ed_del_static_mapping_internal (
479                 m->local_addr, m->external_addr, m->local_port,
480                 m->external_port, ip_proto_to_nat_proto (m->proto), m->vrf_id,
481                 ~0, m->flags);
482             }
483         }
484     }
485   else
486     {
487       if (is_snat_address_used_in_static_mapping (sm, addr))
488         {
489           nat_log_err ("address used in static mapping");
490           return VNET_API_ERROR_UNSPECIFIED;
491         }
492     }
493
494   // delete sessions using address
495   vec_foreach (tsm, sm->per_thread_data)
496     {
497       pool_foreach (ses, tsm->sessions)
498         {
499           if (ses->out2in.addr.as_u32 == addr.as_u32)
500             {
501               nat44_ed_free_session_data (sm, ses, tsm - sm->per_thread_data,
502                                           0);
503               vec_add1 (ses_to_be_removed, ses - tsm->sessions);
504             }
505         }
506       vec_foreach (ses_index, ses_to_be_removed)
507         {
508           ses = pool_elt_at_index (tsm->sessions, ses_index[0]);
509           nat_ed_session_delete (sm, ses, tsm - sm->per_thread_data, 1);
510         }
511       vec_free (ses_to_be_removed);
512     }
513
514   if (!twice_nat)
515     {
516       nat44_ed_add_del_addr_to_fib_foreach_out_if (&addr, 0);
517     }
518
519   if (a->fib_index != ~0)
520     {
521       fib_table_unlock (a->fib_index, FIB_PROTOCOL_IP4, sm->fib_src_low);
522     }
523
524   if (!twice_nat)
525     {
526       vec_del1 (sm->addresses, j);
527     }
528   else
529     {
530       vec_del1 (sm->twice_nat_addresses, j);
531     }
532
533   return 0;
534 }
535
536 u32
537 get_thread_idx_by_port (u16 e_port)
538 {
539   snat_main_t *sm = &snat_main;
540   u32 thread_idx = sm->num_workers;
541   if (sm->num_workers > 1)
542     {
543       thread_idx =
544         sm->first_worker_index +
545         sm->workers[(e_port - 1024) / sm->port_per_thread];
546     }
547   return thread_idx;
548 }
549
550 void
551 nat_ed_static_mapping_del_sessions (snat_main_t * sm,
552                                     snat_main_per_thread_data_t * tsm,
553                                     ip4_address_t l_addr,
554                                     u16 l_port,
555                                     u8 protocol,
556                                     u32 fib_index, int addr_only,
557                                     ip4_address_t e_addr, u16 e_port)
558 {
559   snat_session_t *s;
560   u32 *indexes_to_free = NULL;
561   pool_foreach (s, tsm->sessions) {
562     if (s->in2out.fib_index != fib_index ||
563         s->in2out.addr.as_u32 != l_addr.as_u32)
564       {
565         continue;
566       }
567     if (!addr_only)
568       {
569         if ((s->out2in.addr.as_u32 != e_addr.as_u32) ||
570             s->out2in.port != e_port || s->in2out.port != l_port ||
571             s->proto != protocol)
572           continue;
573       }
574
575     if (nat44_ed_is_lb_session (s))
576       continue;
577     if (!nat44_ed_is_session_static (s))
578       continue;
579     nat44_ed_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
580     vec_add1 (indexes_to_free, s - tsm->sessions);
581     if (!addr_only)
582       break;
583   }
584   u32 *ses_index;
585   vec_foreach (ses_index, indexes_to_free)
586   {
587     s = pool_elt_at_index (tsm->sessions, *ses_index);
588     nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
589   }
590   vec_free (indexes_to_free);
591 }
592
593 static_always_inline snat_static_mapping_t *
594 nat44_ed_sm_lookup (snat_main_t *sm, clib_bihash_kv_16_8_t *kv)
595 {
596   clib_bihash_kv_16_8_t v;
597   int rc = clib_bihash_search_16_8 (&sm->flow_hash, kv, &v);
598   if (!rc)
599     {
600       ASSERT (0 == ed_value_get_thread_index (&v));
601       return pool_elt_at_index (sm->static_mappings,
602                                 ed_value_get_session_index (&v));
603     }
604   return NULL;
605 }
606
607 snat_static_mapping_t *
608 nat44_ed_sm_o2i_lookup (snat_main_t *sm, ip4_address_t addr, u16 port,
609                         u32 fib_index, u8 proto)
610 {
611   clib_bihash_kv_16_8_t kv;
612   nat44_ed_sm_init_o2i_k (&kv, addr.as_u32, port, fib_index, proto);
613   return nat44_ed_sm_lookup (sm, &kv);
614 }
615
616 snat_static_mapping_t *
617 nat44_ed_sm_i2o_lookup (snat_main_t *sm, ip4_address_t addr, u16 port,
618                         u32 fib_index, u8 proto)
619 {
620   clib_bihash_kv_16_8_t kv;
621   nat44_ed_sm_init_i2o_k (&kv, addr.as_u32, port, fib_index, proto);
622   return nat44_ed_sm_lookup (sm, &kv);
623 }
624
625 void
626 nat44_ed_add_resolve_record (ip4_address_t l_addr, u16 l_port, u16 e_port,
627                              ip_protocol_t proto, u32 vrf_id, u32 sw_if_index,
628                              u32 flags, ip4_address_t pool_addr, u8 *tag)
629 {
630   snat_static_map_resolve_t *rp;
631   snat_main_t *sm = &snat_main;
632
633   vec_add2 (sm->to_resolve, rp, 1);
634   rp->l_addr.as_u32 = l_addr.as_u32;
635   rp->l_port = l_port;
636   rp->e_port = e_port;
637   rp->sw_if_index = sw_if_index;
638   rp->vrf_id = vrf_id;
639   rp->proto = proto;
640   rp->flags = flags;
641   rp->pool_addr = pool_addr;
642   rp->tag = vec_dup (tag);
643 }
644
645 int
646 nat44_ed_get_resolve_record (ip4_address_t l_addr, u16 l_port, u16 e_port,
647                              ip_protocol_t proto, u32 vrf_id, u32 sw_if_index,
648                              u32 flags, int *out)
649 {
650   snat_static_map_resolve_t *rp;
651   snat_main_t *sm = &snat_main;
652   int i;
653
654   for (i = 0; i < vec_len (sm->to_resolve); i++)
655     {
656       rp = sm->to_resolve + i;
657
658       if (rp->sw_if_index == sw_if_index && rp->vrf_id == vrf_id)
659         {
660           if (is_sm_identity_nat (rp->flags) && is_sm_identity_nat (flags))
661             {
662               if (!(is_sm_addr_only (rp->flags) && is_sm_addr_only (flags)))
663                 {
664                   if (rp->e_port != e_port || rp->proto != proto)
665                     {
666                       continue;
667                     }
668                 }
669             }
670           else if (rp->l_addr.as_u32 == l_addr.as_u32)
671             {
672               if (!(is_sm_addr_only (rp->flags) && is_sm_addr_only (flags)))
673                 {
674                   if (rp->l_port != l_port || rp->e_port != e_port ||
675                       rp->proto != proto)
676                     {
677                       continue;
678                     }
679                 }
680             }
681           else
682             {
683               continue;
684             }
685           if (out)
686             {
687               *out = i;
688             }
689           return 0;
690         }
691     }
692   return 1;
693 }
694
695 int
696 nat44_ed_del_resolve_record (ip4_address_t l_addr, u16 l_port, u16 e_port,
697                              ip_protocol_t proto, u32 vrf_id, u32 sw_if_index,
698                              u32 flags)
699 {
700   snat_main_t *sm = &snat_main;
701   int i;
702   if (!nat44_ed_get_resolve_record (l_addr, l_port, e_port, proto, vrf_id,
703                                     sw_if_index, flags, &i))
704     {
705       vec_del1 (sm->to_resolve, i);
706       return 0;
707     }
708   return 1;
709 }
710
711 static_always_inline int
712 nat44_ed_validate_sm_input (u32 flags)
713 {
714   // identity nat can be initiated only from inside interface
715   if (is_sm_identity_nat (flags) && is_sm_out2in_only (flags))
716     {
717       return VNET_API_ERROR_UNSUPPORTED;
718     }
719
720   if (is_sm_twice_nat (flags) || is_sm_self_twice_nat (flags))
721     {
722       if (is_sm_addr_only (flags) || is_sm_identity_nat (flags))
723         {
724           return VNET_API_ERROR_UNSUPPORTED;
725         }
726     }
727   return 0;
728 }
729
730 snat_address_t *
731 nat44_ed_addr_lookup (snat_main_t *sm, u32 addr)
732 {
733   for (int i = 0; i < vec_len (sm->addresses); ++i)
734     {
735       if (sm->addresses[i].addr.as_u32 == addr)
736         return &sm->addresses[i];
737     }
738   return NULL;
739 }
740
741 int
742 nat44_ed_add_static_mapping (ip4_address_t l_addr, ip4_address_t e_addr,
743                              u16 l_port, u16 e_port, ip_protocol_t proto,
744                              u32 vrf_id, u32 sw_if_index, u32 flags,
745                              ip4_address_t pool_addr, u8 *tag)
746 {
747   snat_main_t *sm = &snat_main;
748
749   // interface bound mapping
750   if (is_sm_switch_address (flags))
751     {
752       if (!nat44_ed_get_resolve_record (l_addr, l_port, e_port, proto, vrf_id,
753                                         sw_if_index, flags, 0))
754         {
755           return VNET_API_ERROR_VALUE_EXIST;
756         }
757
758       nat44_ed_add_resolve_record (l_addr, l_port, e_port, proto, vrf_id,
759                                    sw_if_index, flags, pool_addr, tag);
760       ip4_address_t *first_int_addr =
761         ip4_interface_first_address (sm->ip4_main, sw_if_index, 0);
762       if (!first_int_addr)
763         {
764           // dhcp resolution required
765           return 0;
766         }
767
768       e_addr.as_u32 = first_int_addr->as_u32;
769     }
770
771   return nat44_ed_add_static_mapping_internal (l_addr, e_addr, l_port, e_port,
772                                                proto, vrf_id, sw_if_index,
773                                                flags, pool_addr, tag);
774 }
775
776 int
777 nat44_ed_del_static_mapping (ip4_address_t l_addr, ip4_address_t e_addr,
778                              u16 l_port, u16 e_port, ip_protocol_t proto,
779                              u32 vrf_id, u32 sw_if_index, u32 flags)
780 {
781
782   snat_main_t *sm = &snat_main;
783
784   // interface bound mapping
785   if (is_sm_switch_address (flags))
786     {
787       if (nat44_ed_del_resolve_record (l_addr, l_port, e_port, proto, vrf_id,
788                                        sw_if_index, flags))
789         {
790           return VNET_API_ERROR_NO_SUCH_ENTRY;
791         }
792
793       ip4_address_t *first_int_addr =
794         ip4_interface_first_address (sm->ip4_main, sw_if_index, 0);
795       if (!first_int_addr)
796         {
797           // dhcp resolution required
798           return 0;
799         }
800
801       e_addr.as_u32 = first_int_addr->as_u32;
802     }
803
804   return nat44_ed_del_static_mapping_internal (
805     l_addr, e_addr, l_port, e_port, proto, vrf_id, sw_if_index, flags);
806 }
807
808 static int
809 nat44_ed_add_static_mapping_internal (ip4_address_t l_addr,
810                                       ip4_address_t e_addr, u16 l_port,
811                                       u16 e_port, ip_protocol_t proto,
812                                       u32 vrf_id, u32 sw_if_index, u32 flags,
813                                       ip4_address_t pool_addr, u8 *tag)
814 {
815   snat_main_t *sm = &snat_main;
816   nat44_lb_addr_port_t *local;
817   snat_static_mapping_t *m;
818   u32 fib_index = ~0;
819   int rv;
820
821   if (!sm->enabled)
822     {
823       return VNET_API_ERROR_UNSUPPORTED;
824     }
825
826   rv = nat44_ed_validate_sm_input (flags);
827   if (rv != 0)
828     {
829       return rv;
830     }
831
832   if (is_sm_addr_only (flags))
833     {
834       e_port = l_port = proto = 0;
835     }
836
837   if (is_sm_identity_nat (flags))
838     {
839       l_port = e_port;
840       l_addr.as_u32 = e_addr.as_u32;
841     }
842
843   m = nat44_ed_sm_o2i_lookup (sm, e_addr, e_port, 0, proto);
844   if (m)
845     {
846       if (!is_sm_identity_nat (m->flags))
847         {
848           return VNET_API_ERROR_VALUE_EXIST;
849         }
850
851       // case:
852       // adding local identity nat record for different vrf table
853       pool_foreach (local, m->locals)
854         {
855           if (local->vrf_id == vrf_id)
856             {
857               return VNET_API_ERROR_VALUE_EXIST;
858             }
859         }
860
861       pool_get (m->locals, local);
862
863       local->vrf_id = vrf_id;
864       local->fib_index = fib_table_find_or_create_and_lock (
865         FIB_PROTOCOL_IP4, vrf_id, sm->fib_src_low);
866
867       nat44_ed_sm_i2o_add (sm, m, m->local_addr, m->local_port,
868                            local->fib_index, m->proto);
869
870       return 0;
871     }
872
873   if (vrf_id != ~0)
874     {
875       fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, vrf_id,
876                                                      sm->fib_src_low);
877     }
878   else
879     {
880       // fallback to default vrf
881       vrf_id = sm->inside_vrf_id;
882       fib_index = sm->inside_fib_index;
883       fib_table_lock (fib_index, FIB_PROTOCOL_IP4, sm->fib_src_low);
884     }
885
886   // test if local mapping record doesn't exist
887   // identity nat supports multiple records in local mapping
888   if (!(is_sm_out2in_only (flags) || is_sm_identity_nat (flags)))
889     {
890       if (nat44_ed_sm_i2o_lookup (sm, l_addr, l_port, fib_index, proto))
891         {
892           return VNET_API_ERROR_VALUE_EXIST;
893         }
894     }
895
896   if (!(is_sm_out2in_only (flags) || is_sm_addr_only (flags) ||
897         sm->static_mapping_only))
898     {
899       if (!nat44_ed_addr_lookup (sm, e_addr.as_u32))
900         {
901           // remove resolve record
902           if (is_sm_switch_address (flags) && !is_sm_identity_nat (flags))
903             {
904               nat44_ed_del_resolve_record (l_addr, l_port, e_port, proto,
905                                            vrf_id, sw_if_index, flags);
906             }
907           return VNET_API_ERROR_NO_SUCH_ENTRY;
908         }
909     }
910
911   pool_get (sm->static_mappings, m);
912   clib_memset (m, 0, sizeof (*m));
913
914   m->flags = flags;
915   m->local_addr = l_addr;
916   m->external_addr = e_addr;
917
918   m->tag = vec_dup (tag);
919
920   if (is_sm_exact_address (flags) && is_sm_twice_nat (flags))
921     {
922       m->pool_addr = pool_addr;
923     }
924
925   if (!is_sm_addr_only (flags))
926     {
927       m->local_port = l_port;
928       m->external_port = e_port;
929       m->proto = proto;
930     }
931
932   if (is_sm_identity_nat (flags))
933     {
934       pool_get (m->locals, local);
935
936       local->vrf_id = vrf_id;
937       local->fib_index = fib_index;
938     }
939   else
940     {
941       m->vrf_id = vrf_id;
942       m->fib_index = fib_index;
943
944       // not identity && addr only
945       if (is_sm_addr_only (flags))
946         {
947           nat44_ed_add_del_addr_to_fib_foreach_out_if (&e_addr, 1);
948         }
949     }
950
951   if (!is_sm_out2in_only (flags))
952     {
953       nat44_ed_sm_i2o_add (sm, m, m->local_addr, m->local_port, fib_index,
954                            m->proto);
955     }
956
957   nat44_ed_sm_o2i_add (sm, m, m->external_addr, m->external_port, 0, m->proto);
958
959   if (sm->num_workers > 1)
960     {
961       // store worker index for this record
962       ip4_header_t ip = {
963         .src_address = m->local_addr,
964       };
965       u32 worker_index;
966       worker_index =
967         nat44_ed_get_in2out_worker_index (0, &ip, m->fib_index, 0);
968       vec_add1 (m->workers, worker_index);
969     }
970
971   return 0;
972 }
973
974 static int
975 nat44_ed_del_static_mapping_internal (ip4_address_t l_addr,
976                                       ip4_address_t e_addr, u16 l_port,
977                                       u16 e_port, ip_protocol_t proto,
978                                       u32 vrf_id, u32 sw_if_index, u32 flags)
979 {
980   snat_main_per_thread_data_t *tsm;
981   snat_main_t *sm = &snat_main;
982
983   nat44_lb_addr_port_t *local;
984   snat_static_mapping_t *m;
985   u32 fib_index = ~0;
986   int rv;
987
988   if (!sm->enabled)
989     {
990       return VNET_API_ERROR_UNSUPPORTED;
991     }
992
993   rv = nat44_ed_validate_sm_input (flags);
994   if (rv != 0)
995     {
996       return rv;
997     }
998
999   if (is_sm_addr_only (flags))
1000     {
1001       e_port = l_port = proto = 0;
1002     }
1003
1004   if (is_sm_identity_nat (flags))
1005     {
1006       l_port = e_port;
1007       l_addr.as_u32 = e_addr.as_u32;
1008     }
1009
1010   // fib index 0
1011   m = nat44_ed_sm_o2i_lookup (sm, e_addr, e_port, 0, proto);
1012
1013   if (!m)
1014     {
1015       if (is_sm_switch_address (flags))
1016         {
1017           return 0;
1018         }
1019       return VNET_API_ERROR_NO_SUCH_ENTRY;
1020     }
1021
1022   if (is_sm_identity_nat (flags))
1023     {
1024       u8 found = 0;
1025
1026       if (vrf_id == ~0)
1027         {
1028           vrf_id = sm->inside_vrf_id;
1029         }
1030
1031       pool_foreach (local, m->locals)
1032         {
1033           if (local->vrf_id == vrf_id)
1034             {
1035               local = pool_elt_at_index (m->locals, local - m->locals);
1036               fib_index = local->fib_index;
1037               pool_put (m->locals, local);
1038               found = 1;
1039             }
1040         }
1041
1042       if (!found)
1043         {
1044           return VNET_API_ERROR_NO_SUCH_ENTRY;
1045         }
1046     }
1047   else
1048     {
1049       fib_index = m->fib_index;
1050     }
1051
1052   if (!(is_sm_out2in_only (flags) || is_sm_addr_only (flags) ||
1053         sm->static_mapping_only))
1054     {
1055       if (!nat44_ed_addr_lookup (sm, e_addr.as_u32))
1056         {
1057           return VNET_API_ERROR_INVALID_VALUE;
1058         }
1059     }
1060
1061   if (!is_sm_out2in_only (flags))
1062     {
1063       nat44_ed_sm_i2o_del (sm, l_addr, l_port, fib_index, proto);
1064     }
1065
1066   if (!sm->static_mapping_only || sm->static_mapping_connection_tracking)
1067     {
1068       // delete sessions for static mapping
1069       if (sm->num_workers > 1)
1070         tsm = vec_elt_at_index (sm->per_thread_data, m->workers[0]);
1071       else
1072         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1073
1074       nat_ed_static_mapping_del_sessions (
1075         sm, tsm, m->local_addr, m->local_port, m->proto, fib_index,
1076         is_sm_addr_only (flags), e_addr, e_port);
1077     }
1078
1079   fib_table_unlock (fib_index, FIB_PROTOCOL_IP4, sm->fib_src_low);
1080
1081   if (!pool_elts (m->locals))
1082     {
1083       // this is last record remove all required stuff
1084       // fib_index 0
1085       nat44_ed_sm_o2i_del (sm, e_addr, e_port, 0, proto);
1086
1087       vec_free (m->tag);
1088       vec_free (m->workers);
1089       pool_put (sm->static_mappings, m);
1090
1091       if (is_sm_addr_only (flags) && !is_sm_identity_nat (flags))
1092         {
1093           nat44_ed_add_del_addr_to_fib_foreach_out_if (&e_addr, 0);
1094         }
1095     }
1096
1097   return 0;
1098 }
1099
1100 int
1101 nat44_ed_add_lb_static_mapping (ip4_address_t e_addr, u16 e_port,
1102                                 ip_protocol_t proto,
1103                                 nat44_lb_addr_port_t *locals, u32 flags,
1104                                 u8 *tag, u32 affinity)
1105 {
1106   snat_main_t *sm = &snat_main;
1107   snat_static_mapping_t *m;
1108   snat_address_t *a = 0;
1109
1110   nat44_lb_addr_port_t *local;
1111   uword *bitmap = 0;
1112   int rc = 0;
1113
1114   int i;
1115
1116   if (!sm->enabled)
1117     {
1118       return VNET_API_ERROR_UNSUPPORTED;
1119     }
1120
1121   m = nat44_ed_sm_o2i_lookup (sm, e_addr, e_port, 0, proto);
1122
1123   if (m)
1124     {
1125       return VNET_API_ERROR_VALUE_EXIST;
1126     }
1127
1128   if (vec_len (locals) < 2)
1129     {
1130       return VNET_API_ERROR_INVALID_VALUE;
1131     }
1132
1133   if (!(sm->static_mapping_only || is_sm_out2in_only (flags)))
1134     {
1135       /* Find external address in allocated addresses and reserve port for
1136          address and port pair mapping when dynamic translations enabled */
1137       for (i = 0; i < vec_len (sm->addresses); i++)
1138         {
1139           if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
1140             {
1141               /* External port must be unused */
1142               a = sm->addresses + i;
1143               if (nat44_ed_sm_o2i_lookup (sm, a->addr, e_port, 0, proto))
1144                 {
1145                   return VNET_API_ERROR_VALUE_EXIST;
1146                 }
1147               break;
1148             }
1149         }
1150       // external address must be allocated
1151       if (!a)
1152         {
1153           return VNET_API_ERROR_NO_SUCH_ENTRY;
1154         }
1155     }
1156
1157   pool_get (sm->static_mappings, m);
1158   clib_memset (m, 0, sizeof (*m));
1159   m->tag = vec_dup (tag);
1160   m->external_addr = e_addr;
1161   m->external_port = e_port;
1162   m->affinity = affinity;
1163   m->proto = proto;
1164
1165   m->flags = flags;
1166   m->flags |= NAT_SM_FLAG_LB;
1167
1168   if (affinity)
1169     m->affinity_per_service_list_head_index =
1170       nat_affinity_get_per_service_list_head_index ();
1171   else
1172     m->affinity_per_service_list_head_index = ~0;
1173
1174   if (nat44_ed_sm_o2i_add (sm, m, m->external_addr, m->external_port, 0,
1175                            m->proto))
1176     {
1177       nat_elog_err (sm, "sm o2i key add failed");
1178       return VNET_API_ERROR_UNSPECIFIED;
1179     }
1180
1181   for (i = 0; i < vec_len (locals); i++)
1182     {
1183       locals[i].fib_index = fib_table_find_or_create_and_lock (
1184         FIB_PROTOCOL_IP4, locals[i].vrf_id, sm->fib_src_low);
1185       if (!is_sm_out2in_only (flags))
1186         {
1187           if (nat44_ed_sm_o2i_add (sm, m, e_addr, e_port, 0, proto))
1188             {
1189               nat_elog_err (sm, "sm o2i key add failed");
1190               rc = VNET_API_ERROR_UNSPECIFIED;
1191               // here we continue with add operation so that it can be safely
1192               // reversed in delete path - otherwise we'd have to track what
1193               // we've done and deal with partial cleanups and since bihash
1194               // adds are (extremely improbable) the only points of failure,
1195               // it's easier to just do it this way
1196             }
1197         }
1198       locals[i].prefix = (i == 0) ?
1199                            locals[i].probability :
1200                            (locals[i - 1].prefix + locals[i].probability);
1201       pool_get (m->locals, local);
1202       *local = locals[i];
1203       if (sm->num_workers > 1)
1204         {
1205           ip4_header_t ip = {
1206             .src_address = locals[i].addr,
1207           };
1208           bitmap = clib_bitmap_set (
1209             bitmap, nat44_ed_get_in2out_worker_index (0, &ip, m->fib_index, 0),
1210             1);
1211         }
1212     }
1213
1214   /* Assign workers */
1215   if (sm->num_workers > 1)
1216     {
1217       clib_bitmap_foreach (i, bitmap)
1218         {
1219           vec_add1 (m->workers, i);
1220         }
1221     }
1222
1223   return rc;
1224 }
1225
1226 int
1227 nat44_ed_del_lb_static_mapping (ip4_address_t e_addr, u16 e_port,
1228                                 ip_protocol_t proto, u32 flags)
1229 {
1230   snat_main_t *sm = &snat_main;
1231   snat_static_mapping_t *m;
1232
1233   nat44_lb_addr_port_t *local;
1234   snat_main_per_thread_data_t *tsm;
1235   snat_session_t *s;
1236
1237   if (!sm->enabled)
1238     {
1239       return VNET_API_ERROR_UNSUPPORTED;
1240     }
1241
1242   m = nat44_ed_sm_o2i_lookup (sm, e_addr, e_port, 0, proto);
1243   if (!m)
1244     return VNET_API_ERROR_NO_SUCH_ENTRY;
1245
1246   if (!is_sm_lb (m->flags))
1247     return VNET_API_ERROR_INVALID_VALUE;
1248
1249   if (nat44_ed_sm_o2i_del (sm, m->external_addr, m->external_port, 0,
1250                            m->proto))
1251     {
1252       nat_elog_err (sm, "sm o2i key del failed");
1253       return VNET_API_ERROR_UNSPECIFIED;
1254     }
1255
1256   pool_foreach (local, m->locals)
1257     {
1258       fib_table_unlock (local->fib_index, FIB_PROTOCOL_IP4, sm->fib_src_low);
1259       if (!is_sm_out2in_only (flags))
1260         {
1261           if (nat44_ed_sm_i2o_del (sm, local->addr, local->port,
1262                                    local->fib_index, m->proto))
1263             {
1264               nat_elog_err (sm, "sm i2o key del failed");
1265               return VNET_API_ERROR_UNSPECIFIED;
1266             }
1267         }
1268
1269       if (sm->num_workers > 1)
1270         {
1271           ip4_header_t ip = {
1272             .src_address = local->addr,
1273           };
1274           tsm = vec_elt_at_index (
1275             sm->per_thread_data,
1276             nat44_ed_get_in2out_worker_index (0, &ip, m->fib_index, 0));
1277         }
1278       else
1279         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1280
1281       /* Delete sessions */
1282       pool_foreach (s, tsm->sessions)
1283         {
1284           if (!(nat44_ed_is_lb_session (s)))
1285             continue;
1286
1287           if ((s->in2out.addr.as_u32 != local->addr.as_u32) ||
1288               s->in2out.port != local->port)
1289             continue;
1290
1291           nat44_ed_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
1292           nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
1293         }
1294     }
1295
1296   if (m->affinity)
1297     {
1298       nat_affinity_flush_service (m->affinity_per_service_list_head_index);
1299     }
1300
1301   pool_free (m->locals);
1302   vec_free (m->tag);
1303   vec_free (m->workers);
1304   pool_put (sm->static_mappings, m);
1305
1306   return 0;
1307 }
1308
1309 int
1310 nat44_ed_add_del_lb_static_mapping_local (ip4_address_t e_addr, u16 e_port,
1311                                           ip4_address_t l_addr, u16 l_port,
1312                                           ip_protocol_t proto, u32 vrf_id,
1313                                           u8 probability, u8 is_add)
1314 {
1315   snat_main_t *sm = &snat_main;
1316   snat_static_mapping_t *m = 0;
1317   nat44_lb_addr_port_t *local, *prev_local, *match_local = 0;
1318   snat_main_per_thread_data_t *tsm;
1319   snat_session_t *s;
1320   u32 *locals = 0;
1321   uword *bitmap = 0;
1322   int i;
1323
1324   if (!sm->enabled)
1325     {
1326       return VNET_API_ERROR_UNSUPPORTED;
1327     }
1328
1329   m = nat44_ed_sm_o2i_lookup (sm, e_addr, e_port, 0, proto);
1330
1331   if (!m)
1332     {
1333       return VNET_API_ERROR_NO_SUCH_ENTRY;
1334     }
1335
1336   if (!is_sm_lb (m->flags))
1337     {
1338       return VNET_API_ERROR_INVALID_VALUE;
1339     }
1340
1341   pool_foreach (local, m->locals)
1342    {
1343     if ((local->addr.as_u32 == l_addr.as_u32) && (local->port == l_port) &&
1344         (local->vrf_id == vrf_id))
1345       {
1346         match_local = local;
1347         break;
1348       }
1349   }
1350
1351   if (is_add)
1352     {
1353       if (match_local)
1354         {
1355           return VNET_API_ERROR_VALUE_EXIST;
1356         }
1357
1358       pool_get (m->locals, local);
1359       clib_memset (local, 0, sizeof (*local));
1360       local->addr.as_u32 = l_addr.as_u32;
1361       local->port = l_port;
1362       local->probability = probability;
1363       local->vrf_id = vrf_id;
1364       local->fib_index =
1365         fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4, vrf_id,
1366                                            sm->fib_src_low);
1367
1368       if (!is_sm_out2in_only (m->flags))
1369         {
1370           if (nat44_ed_sm_i2o_add (sm, m, l_addr, l_port, local->fib_index,
1371                                    proto))
1372             {
1373               nat_elog_err (sm, "sm i2o key add failed");
1374               pool_put (m->locals, local);
1375               return VNET_API_ERROR_UNSPECIFIED;
1376             }
1377         }
1378     }
1379   else
1380     {
1381       if (!match_local)
1382         return VNET_API_ERROR_NO_SUCH_ENTRY;
1383
1384       if (pool_elts (m->locals) < 3)
1385         return VNET_API_ERROR_UNSPECIFIED;
1386
1387       fib_table_unlock (match_local->fib_index, FIB_PROTOCOL_IP4,
1388                         sm->fib_src_low);
1389
1390       if (!is_sm_out2in_only (m->flags))
1391         {
1392           if (nat44_ed_sm_i2o_del (sm, l_addr, l_port, match_local->fib_index,
1393                                    proto))
1394             nat_elog_err (sm, "sm i2o key del failed");
1395         }
1396
1397       if (sm->num_workers > 1)
1398         {
1399           ip4_header_t ip = {
1400             .src_address = local->addr,
1401           };
1402           tsm = vec_elt_at_index (
1403             sm->per_thread_data,
1404             nat44_ed_get_in2out_worker_index (0, &ip, m->fib_index, 0));
1405         }
1406       else
1407         tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1408
1409       /* Delete sessions */
1410       pool_foreach (s, tsm->sessions) {
1411           if (!(nat44_ed_is_lb_session (s)))
1412             continue;
1413
1414           if ((s->in2out.addr.as_u32 != match_local->addr.as_u32) ||
1415               s->in2out.port != match_local->port)
1416             continue;
1417
1418           nat44_ed_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
1419           nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
1420       }
1421
1422       pool_put (m->locals, match_local);
1423     }
1424
1425   vec_free (m->workers);
1426
1427   pool_foreach (local, m->locals)
1428    {
1429     vec_add1 (locals, local - m->locals);
1430     if (sm->num_workers > 1)
1431       {
1432         ip4_header_t ip;
1433         ip.src_address.as_u32 = local->addr.as_u32,
1434         bitmap = clib_bitmap_set (
1435           bitmap,
1436           nat44_ed_get_in2out_worker_index (0, &ip, local->fib_index, 0), 1);
1437       }
1438   }
1439
1440   ASSERT (vec_len (locals) > 1);
1441
1442   local = pool_elt_at_index (m->locals, locals[0]);
1443   local->prefix = local->probability;
1444   for (i = 1; i < vec_len (locals); i++)
1445     {
1446       local = pool_elt_at_index (m->locals, locals[i]);
1447       prev_local = pool_elt_at_index (m->locals, locals[i - 1]);
1448       local->prefix = local->probability + prev_local->prefix;
1449     }
1450
1451   /* Assign workers */
1452   if (sm->num_workers > 1)
1453     {
1454       clib_bitmap_foreach (i, bitmap)  { vec_add1(m->workers, i); }
1455     }
1456
1457   return 0;
1458 }
1459
1460 void
1461 expire_per_vrf_sessions (u32 fib_index)
1462 {
1463   per_vrf_sessions_t *per_vrf_sessions;
1464   snat_main_per_thread_data_t *tsm;
1465   snat_main_t *sm = &snat_main;
1466
1467   vec_foreach (tsm, sm->per_thread_data)
1468     {
1469       vec_foreach (per_vrf_sessions, tsm->per_vrf_sessions_vec)
1470         {
1471           if ((per_vrf_sessions->rx_fib_index == fib_index) ||
1472               (per_vrf_sessions->tx_fib_index == fib_index))
1473             {
1474               per_vrf_sessions->expired = 1;
1475             }
1476         }
1477     }
1478 }
1479
1480 void
1481 update_per_vrf_sessions_vec (u32 fib_index, int is_del)
1482 {
1483   snat_main_t *sm = &snat_main;
1484   nat_fib_t *fib;
1485
1486   // we don't care if it is outside/inside fib
1487   // we just care about their ref_count
1488   // if it reaches 0 sessions should expire
1489   // because the fib isn't valid for NAT anymore
1490
1491   vec_foreach (fib, sm->fibs)
1492   {
1493     if (fib->fib_index == fib_index)
1494       {
1495         if (is_del)
1496           {
1497             fib->ref_count--;
1498             if (!fib->ref_count)
1499               {
1500                 vec_del1 (sm->fibs, fib - sm->fibs);
1501                 expire_per_vrf_sessions (fib_index);
1502               }
1503             return;
1504           }
1505         else
1506           fib->ref_count++;
1507       }
1508   }
1509   if (!is_del)
1510     {
1511       vec_add2 (sm->fibs, fib, 1);
1512       fib->ref_count = 1;
1513       fib->fib_index = fib_index;
1514     }
1515 }
1516
1517 static_always_inline nat_outside_fib_t *
1518 nat44_ed_get_outside_fib (nat_outside_fib_t *outside_fibs, u32 fib_index)
1519 {
1520   nat_outside_fib_t *f;
1521   vec_foreach (f, outside_fibs)
1522     {
1523       if (f->fib_index == fib_index)
1524         {
1525           return f;
1526         }
1527     }
1528   return 0;
1529 }
1530
1531 static_always_inline snat_interface_t *
1532 nat44_ed_get_interface (snat_interface_t *interfaces, u32 sw_if_index)
1533 {
1534   snat_interface_t *i;
1535   pool_foreach (i, interfaces)
1536     {
1537       if (i->sw_if_index == sw_if_index)
1538         {
1539           return i;
1540         }
1541     }
1542   return 0;
1543 }
1544
1545 int
1546 nat44_ed_add_interface (u32 sw_if_index, u8 is_inside)
1547 {
1548   const char *del_feature_name, *feature_name;
1549   snat_main_t *sm = &snat_main;
1550
1551   nat_outside_fib_t *outside_fib;
1552   snat_interface_t *i;
1553   u32 fib_index;
1554   int rv;
1555
1556   if (!sm->enabled)
1557     {
1558       nat_log_err ("nat44 is disabled");
1559       return VNET_API_ERROR_UNSUPPORTED;
1560     }
1561
1562   if (nat44_ed_get_interface (sm->output_feature_interfaces, sw_if_index))
1563     {
1564       nat_log_err ("error interface already configured");
1565       return VNET_API_ERROR_VALUE_EXIST;
1566     }
1567
1568   i = nat44_ed_get_interface (sm->interfaces, sw_if_index);
1569   if (i)
1570     {
1571       if ((nat44_ed_is_interface_inside (i) && is_inside) ||
1572           (nat44_ed_is_interface_outside (i) && !is_inside))
1573         {
1574           return 0;
1575         }
1576       if (sm->num_workers > 1)
1577         {
1578           del_feature_name = !is_inside ? "nat44-in2out-worker-handoff" :
1579                                           "nat44-out2in-worker-handoff";
1580           feature_name = "nat44-handoff-classify";
1581         }
1582       else
1583         {
1584           del_feature_name = !is_inside ? "nat-pre-in2out" : "nat-pre-out2in";
1585
1586           feature_name = "nat44-ed-classify";
1587         }
1588
1589       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 1);
1590       if (rv)
1591         return rv;
1592       vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1593                                    sw_if_index, 0, 0, 0);
1594       vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index, 1,
1595                                    0, 0);
1596     }
1597   else
1598     {
1599       if (sm->num_workers > 1)
1600         {
1601           feature_name = is_inside ? "nat44-in2out-worker-handoff" :
1602                                      "nat44-out2in-worker-handoff";
1603         }
1604       else
1605         {
1606           feature_name = is_inside ? "nat-pre-in2out" : "nat-pre-out2in";
1607         }
1608
1609       nat_validate_interface_counters (sm, sw_if_index);
1610       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 1);
1611       if (rv)
1612         return rv;
1613       vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index, 1,
1614                                    0, 0);
1615
1616       pool_get (sm->interfaces, i);
1617       i->sw_if_index = sw_if_index;
1618       i->flags = 0;
1619     }
1620
1621   fib_index =
1622     fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4, sw_if_index);
1623
1624   update_per_vrf_sessions_vec (fib_index, 0 /*is_del*/);
1625
1626   if (!is_inside)
1627     {
1628       i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
1629
1630       outside_fib = nat44_ed_get_outside_fib (sm->outside_fibs, fib_index);
1631       if (outside_fib)
1632         {
1633           outside_fib->refcount++;
1634         }
1635       else
1636         {
1637           vec_add2 (sm->outside_fibs, outside_fib, 1);
1638           outside_fib->fib_index = fib_index;
1639           outside_fib->refcount = 1;
1640         }
1641
1642       nat44_ed_add_del_addr_to_fib_foreach_addr (sw_if_index, 1);
1643       nat44_ed_add_del_addr_to_fib_foreach_addr_only_sm (sw_if_index, 1);
1644     }
1645   else
1646     {
1647       i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
1648     }
1649
1650   return 0;
1651 }
1652
1653 int
1654 nat44_ed_del_interface (u32 sw_if_index, u8 is_inside)
1655 {
1656   const char *del_feature_name, *feature_name;
1657   snat_main_t *sm = &snat_main;
1658
1659   nat_outside_fib_t *outside_fib;
1660   snat_interface_t *i;
1661   u32 fib_index;
1662   int rv;
1663
1664   if (!sm->enabled)
1665     {
1666       nat_log_err ("nat44 is disabled");
1667       return VNET_API_ERROR_UNSUPPORTED;
1668     }
1669
1670   i = nat44_ed_get_interface (sm->interfaces, sw_if_index);
1671   if (i == 0)
1672     {
1673       nat_log_err ("error interface couldn't be found");
1674       return VNET_API_ERROR_NO_SUCH_ENTRY;
1675     }
1676
1677   if (nat44_ed_is_interface_inside (i) && nat44_ed_is_interface_outside (i))
1678     {
1679       if (sm->num_workers > 1)
1680         {
1681           del_feature_name = "nat44-handoff-classify";
1682           feature_name = !is_inside ? "nat44-in2out-worker-handoff" :
1683                                       "nat44-out2in-worker-handoff";
1684         }
1685       else
1686         {
1687           del_feature_name = "nat44-ed-classify";
1688           feature_name = !is_inside ? "nat-pre-in2out" : "nat-pre-out2in";
1689         }
1690
1691       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 0);
1692       if (rv)
1693         {
1694           return rv;
1695         }
1696       vnet_feature_enable_disable ("ip4-unicast", del_feature_name,
1697                                    sw_if_index, 0, 0, 0);
1698       vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index, 1,
1699                                    0, 0);
1700
1701       if (is_inside)
1702         {
1703           i->flags &= ~NAT_INTERFACE_FLAG_IS_INSIDE;
1704         }
1705       else
1706         {
1707           i->flags &= ~NAT_INTERFACE_FLAG_IS_OUTSIDE;
1708         }
1709     }
1710   else
1711     {
1712       if (sm->num_workers > 1)
1713         {
1714           feature_name = is_inside ? "nat44-in2out-worker-handoff" :
1715                                      "nat44-out2in-worker-handoff";
1716         }
1717       else
1718         {
1719           feature_name = is_inside ? "nat-pre-in2out" : "nat-pre-out2in";
1720         }
1721
1722       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 0);
1723       if (rv)
1724         {
1725           return rv;
1726         }
1727       vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index, 0,
1728                                    0, 0);
1729
1730       // remove interface
1731       pool_put (sm->interfaces, i);
1732     }
1733
1734   fib_index =
1735     fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4, sw_if_index);
1736
1737   update_per_vrf_sessions_vec (fib_index, 1 /*is_del*/);
1738
1739   if (!is_inside)
1740     {
1741       outside_fib = nat44_ed_get_outside_fib (sm->outside_fibs, fib_index);
1742       if (outside_fib)
1743         {
1744           outside_fib->refcount--;
1745           if (!outside_fib->refcount)
1746             {
1747               vec_del1 (sm->outside_fibs, outside_fib - sm->outside_fibs);
1748             }
1749         }
1750
1751       nat44_ed_add_del_addr_to_fib_foreach_addr (sw_if_index, 0);
1752       nat44_ed_add_del_addr_to_fib_foreach_addr_only_sm (sw_if_index, 0);
1753     }
1754
1755   return 0;
1756 }
1757
1758 int
1759 nat44_ed_add_output_interface (u32 sw_if_index)
1760 {
1761   snat_main_t *sm = &snat_main;
1762
1763   nat_outside_fib_t *outside_fib;
1764   snat_interface_t *i;
1765   u32 fib_index;
1766   int rv;
1767
1768   if (!sm->enabled)
1769     {
1770       nat_log_err ("nat44 is disabled");
1771       return VNET_API_ERROR_UNSUPPORTED;
1772     }
1773
1774   if (nat44_ed_get_interface (sm->interfaces, sw_if_index))
1775     {
1776       nat_log_err ("error interface already configured");
1777       return VNET_API_ERROR_VALUE_EXIST;
1778     }
1779
1780   if (nat44_ed_get_interface (sm->output_feature_interfaces, sw_if_index))
1781     {
1782       nat_log_err ("error interface already configured");
1783       return VNET_API_ERROR_VALUE_EXIST;
1784     }
1785
1786   if (sm->num_workers > 1)
1787     {
1788       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 1);
1789       if (rv)
1790         {
1791           return rv;
1792         }
1793
1794       rv = ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index, 1);
1795       if (rv)
1796         {
1797           return rv;
1798         }
1799
1800       vnet_feature_enable_disable (
1801         "ip4-unicast", "nat44-out2in-worker-handoff", sw_if_index, 1, 0, 0);
1802       vnet_feature_enable_disable ("ip4-output",
1803                                    "nat44-in2out-output-worker-handoff",
1804                                    sw_if_index, 1, 0, 0);
1805     }
1806   else
1807     {
1808       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 1);
1809       if (rv)
1810         {
1811           return rv;
1812         }
1813
1814       rv = ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index, 1);
1815       if (rv)
1816         {
1817           return rv;
1818         }
1819
1820       vnet_feature_enable_disable ("ip4-unicast", "nat-pre-out2in",
1821                                    sw_if_index, 1, 0, 0);
1822       vnet_feature_enable_disable ("ip4-output", "nat-pre-in2out-output",
1823                                    sw_if_index, 1, 0, 0);
1824     }
1825
1826   nat_validate_interface_counters (sm, sw_if_index);
1827
1828   pool_get (sm->output_feature_interfaces, i);
1829   i->sw_if_index = sw_if_index;
1830   i->flags = 0;
1831   i->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
1832   i->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
1833
1834   fib_index =
1835     fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4, sw_if_index);
1836   update_per_vrf_sessions_vec (fib_index, 0 /*is_del*/);
1837
1838   outside_fib = nat44_ed_get_outside_fib (sm->outside_fibs, fib_index);
1839   if (outside_fib)
1840     {
1841       outside_fib->refcount++;
1842     }
1843   else
1844     {
1845       vec_add2 (sm->outside_fibs, outside_fib, 1);
1846       outside_fib->fib_index = fib_index;
1847       outside_fib->refcount = 1;
1848     }
1849
1850   nat44_ed_add_del_addr_to_fib_foreach_addr (sw_if_index, 1);
1851   nat44_ed_add_del_addr_to_fib_foreach_addr_only_sm (sw_if_index, 1);
1852
1853   return 0;
1854 }
1855
1856 int
1857 nat44_ed_del_output_interface (u32 sw_if_index)
1858 {
1859   snat_main_t *sm = &snat_main;
1860
1861   nat_outside_fib_t *outside_fib;
1862   snat_interface_t *i;
1863   u32 fib_index;
1864   int rv;
1865
1866   if (!sm->enabled)
1867     {
1868       nat_log_err ("nat44 is disabled");
1869       return VNET_API_ERROR_UNSUPPORTED;
1870     }
1871
1872   i = nat44_ed_get_interface (sm->output_feature_interfaces, sw_if_index);
1873   if (!i)
1874     {
1875       nat_log_err ("error interface couldn't be found");
1876       return VNET_API_ERROR_NO_SUCH_ENTRY;
1877     }
1878
1879   if (sm->num_workers > 1)
1880     {
1881       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 0);
1882       if (rv)
1883         {
1884           return rv;
1885         }
1886
1887       rv = ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index, 0);
1888       if (rv)
1889         {
1890           return rv;
1891         }
1892
1893       vnet_feature_enable_disable (
1894         "ip4-unicast", "nat44-out2in-worker-handoff", sw_if_index, 0, 0, 0);
1895       vnet_feature_enable_disable ("ip4-output",
1896                                    "nat44-in2out-output-worker-handoff",
1897                                    sw_if_index, 0, 0, 0);
1898     }
1899   else
1900     {
1901       rv = ip4_sv_reass_enable_disable_with_refcnt (sw_if_index, 0);
1902       if (rv)
1903         {
1904           return rv;
1905         }
1906
1907       rv = ip4_sv_reass_output_enable_disable_with_refcnt (sw_if_index, 0);
1908       if (rv)
1909         {
1910           return rv;
1911         }
1912
1913       vnet_feature_enable_disable ("ip4-unicast", "nat-pre-out2in",
1914                                    sw_if_index, 0, 0, 0);
1915       vnet_feature_enable_disable ("ip4-output", "nat-pre-in2out-output",
1916                                    sw_if_index, 0, 0, 0);
1917     }
1918
1919   // remove interface
1920   pool_put (sm->output_feature_interfaces, i);
1921
1922   fib_index =
1923     fib_table_get_index_for_sw_if_index (FIB_PROTOCOL_IP4, sw_if_index);
1924   update_per_vrf_sessions_vec (fib_index, 1 /*is_del*/);
1925
1926   outside_fib = nat44_ed_get_outside_fib (sm->outside_fibs, fib_index);
1927   if (outside_fib)
1928     {
1929       outside_fib->refcount--;
1930       if (!outside_fib->refcount)
1931         {
1932           vec_del1 (sm->outside_fibs, outside_fib - sm->outside_fibs);
1933         }
1934     }
1935
1936   nat44_ed_add_del_addr_to_fib_foreach_addr (sw_if_index, 0);
1937   nat44_ed_add_del_addr_to_fib_foreach_addr_only_sm (sw_if_index, 0);
1938
1939   return 0;
1940 }
1941
1942 int
1943 snat_set_workers (uword * bitmap)
1944 {
1945   snat_main_t *sm = &snat_main;
1946   int i, j = 0;
1947
1948   if (sm->num_workers < 2)
1949     return VNET_API_ERROR_FEATURE_DISABLED;
1950
1951   if (clib_bitmap_last_set (bitmap) >= sm->num_workers)
1952     return VNET_API_ERROR_INVALID_WORKER;
1953
1954   vec_free (sm->workers);
1955   clib_bitmap_foreach (i, bitmap)
1956     {
1957       vec_add1(sm->workers, i);
1958       sm->per_thread_data[sm->first_worker_index + i].snat_thread_index = j;
1959       sm->per_thread_data[sm->first_worker_index + i].thread_index = i;
1960       j++;
1961     }
1962
1963   sm->port_per_thread = (0xffff - 1024) / _vec_len (sm->workers);
1964
1965   return 0;
1966 }
1967
1968 int
1969 nat44_ed_set_frame_queue_nelts (u32 frame_queue_nelts)
1970 {
1971   fail_if_enabled ();
1972   snat_main_t *sm = &snat_main;
1973   sm->frame_queue_nelts = frame_queue_nelts;
1974   return 0;
1975 }
1976
1977 static void
1978 nat44_ed_update_outside_fib_cb (ip4_main_t *im, uword opaque, u32 sw_if_index,
1979                                 u32 new_fib_index, u32 old_fib_index)
1980 {
1981   snat_main_t *sm = &snat_main;
1982   nat_outside_fib_t *outside_fib;
1983   snat_interface_t *i;
1984   u8 is_add = 1;
1985   u8 match = 0;
1986
1987   if (!sm->enabled || (new_fib_index == old_fib_index)
1988       || (!vec_len (sm->outside_fibs)))
1989     {
1990       return;
1991     }
1992
1993   pool_foreach (i, sm->interfaces)
1994      {
1995       if (i->sw_if_index == sw_if_index)
1996         {
1997           if (!(nat44_ed_is_interface_outside (i)))
1998             return;
1999           match = 1;
2000         }
2001     }
2002
2003   pool_foreach (i, sm->output_feature_interfaces)
2004      {
2005       if (i->sw_if_index == sw_if_index)
2006         {
2007           if (!(nat44_ed_is_interface_outside (i)))
2008             return;
2009           match = 1;
2010         }
2011     }
2012
2013   if (!match)
2014     return;
2015
2016   vec_foreach (outside_fib, sm->outside_fibs)
2017   {
2018     if (outside_fib->fib_index == old_fib_index)
2019       {
2020         outside_fib->refcount--;
2021         if (!outside_fib->refcount)
2022           vec_del1 (sm->outside_fibs, outside_fib - sm->outside_fibs);
2023         break;
2024       }
2025   }
2026
2027   vec_foreach (outside_fib, sm->outside_fibs)
2028   {
2029     if (outside_fib->fib_index == new_fib_index)
2030       {
2031         outside_fib->refcount++;
2032         is_add = 0;
2033         break;
2034       }
2035   }
2036
2037   if (is_add)
2038     {
2039       vec_add2 (sm->outside_fibs, outside_fib, 1);
2040       outside_fib->refcount = 1;
2041       outside_fib->fib_index = new_fib_index;
2042     }
2043 }
2044
2045 static void nat44_ed_update_outside_fib_cb (ip4_main_t *im, uword opaque,
2046                                             u32 sw_if_index, u32 new_fib_index,
2047                                             u32 old_fib_index);
2048
2049 static void nat44_ed_add_del_interface_address_cb (
2050   ip4_main_t *im, uword opaque, u32 sw_if_index, ip4_address_t *address,
2051   u32 address_length, u32 if_address_index, u32 is_delete);
2052
2053 static void nat44_ed_add_del_static_mapping_addr_only_cb (
2054   ip4_main_t *im, uword opaque, u32 sw_if_index, ip4_address_t *address,
2055   u32 address_length, u32 if_address_index, u32 is_delete);
2056
2057 void
2058 test_key_calc_split ()
2059 {
2060   ip4_address_t l_addr;
2061   l_addr.as_u8[0] = 1;
2062   l_addr.as_u8[1] = 1;
2063   l_addr.as_u8[2] = 1;
2064   l_addr.as_u8[3] = 1;
2065   ip4_address_t r_addr;
2066   r_addr.as_u8[0] = 2;
2067   r_addr.as_u8[1] = 2;
2068   r_addr.as_u8[2] = 2;
2069   r_addr.as_u8[3] = 2;
2070   u16 l_port = 40001;
2071   u16 r_port = 40301;
2072   u8 proto = 9;
2073   u32 fib_index = 9000001;
2074   u32 thread_index = 3000000001;
2075   u32 session_index = 3000000221;
2076   clib_bihash_kv_16_8_t kv;
2077   init_ed_kv (&kv, l_addr.as_u32, l_port, r_addr.as_u32, r_port, fib_index,
2078               proto, thread_index, session_index);
2079   ip4_address_t l_addr2;
2080   ip4_address_t r_addr2;
2081   clib_memset (&l_addr2, 0, sizeof (l_addr2));
2082   clib_memset (&r_addr2, 0, sizeof (r_addr2));
2083   u16 l_port2 = 0;
2084   u16 r_port2 = 0;
2085   u8 proto2 = 0;
2086   u32 fib_index2 = 0;
2087   split_ed_kv (&kv, &l_addr2, &r_addr2, &proto2, &fib_index2, &l_port2,
2088                &r_port2);
2089   ASSERT (l_addr.as_u32 == l_addr2.as_u32);
2090   ASSERT (r_addr.as_u32 == r_addr2.as_u32);
2091   ASSERT (l_port == l_port2);
2092   ASSERT (r_port == r_port2);
2093   ASSERT (proto == proto2);
2094   ASSERT (fib_index == fib_index2);
2095   ASSERT (thread_index == ed_value_get_thread_index (&kv));
2096   ASSERT (session_index == ed_value_get_session_index (&kv));
2097 }
2098
2099 static clib_error_t *
2100 nat_ip_table_add_del (vnet_main_t * vnm, u32 table_id, u32 is_add)
2101 {
2102   u32 fib_index;
2103   if (!is_add)
2104     {
2105       fib_index = ip4_fib_index_from_table_id (table_id);
2106       if (fib_index != ~0)
2107         {
2108           expire_per_vrf_sessions (fib_index);
2109         }
2110     }
2111   return 0;
2112 }
2113
2114 VNET_IP_TABLE_ADD_DEL_FUNCTION (nat_ip_table_add_del);
2115
2116 void
2117 nat44_set_node_indexes (snat_main_t * sm, vlib_main_t * vm)
2118 {
2119   vlib_node_t *node;
2120
2121   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-out2in");
2122   sm->out2in_node_index = node->index;
2123
2124   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-in2out");
2125   sm->in2out_node_index = node->index;
2126
2127   node = vlib_get_node_by_name (vm, (u8 *) "nat44-ed-in2out-output");
2128   sm->in2out_output_node_index = node->index;
2129 }
2130
2131 #define nat_validate_simple_counter(c, i)                                     \
2132   do                                                                          \
2133     {                                                                         \
2134       vlib_validate_simple_counter (&c, i);                                   \
2135       vlib_zero_simple_counter (&c, i);                                       \
2136     }                                                                         \
2137   while (0);
2138
2139 #define nat_init_simple_counter(c, n, sn)                                     \
2140   do                                                                          \
2141     {                                                                         \
2142       c.name = n;                                                             \
2143       c.stat_segment_name = sn;                                               \
2144       nat_validate_simple_counter (c, 0);                                     \
2145     }                                                                         \
2146   while (0);
2147
2148 static_always_inline void
2149 nat_validate_interface_counters (snat_main_t *sm, u32 sw_if_index)
2150 {
2151 #define _(x)                                                                  \
2152   nat_validate_simple_counter (sm->counters.fastpath.in2out.x, sw_if_index);  \
2153   nat_validate_simple_counter (sm->counters.fastpath.out2in.x, sw_if_index);  \
2154   nat_validate_simple_counter (sm->counters.slowpath.in2out.x, sw_if_index);  \
2155   nat_validate_simple_counter (sm->counters.slowpath.out2in.x, sw_if_index);
2156   foreach_nat_counter;
2157 #undef _
2158   nat_validate_simple_counter (sm->counters.hairpinning, sw_if_index);
2159 }
2160
2161 static clib_error_t *
2162 nat_init (vlib_main_t * vm)
2163 {
2164   snat_main_t *sm = &snat_main;
2165   vlib_thread_main_t *tm = vlib_get_thread_main ();
2166   vlib_thread_registration_t *tr;
2167   ip4_add_del_interface_address_callback_t cbi = { 0 };
2168   ip4_table_bind_callback_t cbt = { 0 };
2169   u32 i, num_threads = 0;
2170   uword *p, *bitmap = 0;
2171
2172   clib_memset (sm, 0, sizeof (*sm));
2173
2174   // required
2175   sm->vnet_main = vnet_get_main ();
2176   // convenience
2177   sm->ip4_main = &ip4_main;
2178   sm->api_main = vlibapi_get_main ();
2179   sm->ip4_lookup_main = &ip4_main.lookup_main;
2180
2181   // frame queue indices used for handoff
2182   sm->fq_out2in_index = ~0;
2183   sm->fq_in2out_index = ~0;
2184   sm->fq_in2out_output_index = ~0;
2185
2186   sm->log_level = NAT_LOG_ERROR;
2187
2188   nat44_set_node_indexes (sm, vm);
2189
2190   sm->log_class = vlib_log_register_class ("nat", 0);
2191   nat_ipfix_logging_init (vm);
2192
2193   nat_init_simple_counter (sm->total_sessions, "total-sessions",
2194                            "/nat44-ed/total-sessions");
2195   sm->max_cfg_sessions_gauge = stat_segment_new_entry (
2196     (u8 *) "/nat44-ed/max-cfg-sessions", STAT_DIR_TYPE_SCALAR_INDEX);
2197
2198 #define _(x)                                                                  \
2199   nat_init_simple_counter (sm->counters.fastpath.in2out.x, #x,                \
2200                            "/nat44-ed/in2out/fastpath/" #x);                  \
2201   nat_init_simple_counter (sm->counters.fastpath.out2in.x, #x,                \
2202                            "/nat44-ed/out2in/fastpath/" #x);                  \
2203   nat_init_simple_counter (sm->counters.slowpath.in2out.x, #x,                \
2204                            "/nat44-ed/in2out/slowpath/" #x);                  \
2205   nat_init_simple_counter (sm->counters.slowpath.out2in.x, #x,                \
2206                            "/nat44-ed/out2in/slowpath/" #x);
2207   foreach_nat_counter;
2208 #undef _
2209   nat_init_simple_counter (sm->counters.hairpinning, "hairpinning",
2210                            "/nat44-ed/hairpinning");
2211
2212   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
2213   if (p)
2214     {
2215       tr = (vlib_thread_registration_t *) p[0];
2216       if (tr)
2217         {
2218           sm->num_workers = tr->count;
2219           sm->first_worker_index = tr->first_index;
2220         }
2221     }
2222   num_threads = tm->n_vlib_mains - 1;
2223   sm->port_per_thread = 0xffff - 1024;
2224   vec_validate (sm->per_thread_data, num_threads);
2225
2226   /* Use all available workers by default */
2227   if (sm->num_workers > 1)
2228     {
2229       for (i = 0; i < sm->num_workers; i++)
2230         bitmap = clib_bitmap_set (bitmap, i, 1);
2231       snat_set_workers (bitmap);
2232       clib_bitmap_free (bitmap);
2233     }
2234   else
2235     {
2236       sm->per_thread_data[0].snat_thread_index = 0;
2237     }
2238
2239   /* callbacks to call when interface address changes. */
2240   cbi.function = nat44_ed_add_del_interface_address_cb;
2241   vec_add1 (sm->ip4_main->add_del_interface_address_callbacks, cbi);
2242   cbi.function = nat44_ed_add_del_static_mapping_addr_only_cb;
2243   vec_add1 (sm->ip4_main->add_del_interface_address_callbacks, cbi);
2244
2245   /* callbacks to call when interface to table biding changes */
2246   cbt.function = nat44_ed_update_outside_fib_cb;
2247   vec_add1 (sm->ip4_main->table_bind_callbacks, cbt);
2248
2249   sm->fib_src_low =
2250     fib_source_allocate ("nat-low", FIB_SOURCE_PRIORITY_LOW,
2251                          FIB_SOURCE_BH_SIMPLE);
2252   sm->fib_src_hi =
2253     fib_source_allocate ("nat-hi", FIB_SOURCE_PRIORITY_HI,
2254                          FIB_SOURCE_BH_SIMPLE);
2255
2256   nat_affinity_init (vm);
2257   test_key_calc_split ();
2258
2259   return nat44_api_hookup (vm);
2260 }
2261
2262 VLIB_INIT_FUNCTION (nat_init);
2263
2264 int
2265 nat44_plugin_enable (nat44_config_t c)
2266 {
2267   snat_main_t *sm = &snat_main;
2268
2269   fail_if_enabled ();
2270
2271   if (c.static_mapping_only && !c.connection_tracking)
2272     {
2273       nat_log_err ("unsupported combination of configuration");
2274       return 1;
2275     }
2276
2277   sm->static_mapping_only = c.static_mapping_only;
2278   sm->static_mapping_connection_tracking = c.connection_tracking;
2279
2280   sm->forwarding_enabled = 0;
2281   sm->mss_clamping = 0;
2282   sm->pat = (!c.static_mapping_only ||
2283              (c.static_mapping_only && c.connection_tracking));
2284
2285   if (!c.sessions)
2286     c.sessions = 63 * 1024;
2287
2288   sm->max_translations_per_thread = c.sessions;
2289   stat_segment_set_state_counter (sm->max_cfg_sessions_gauge,
2290                                   sm->max_translations_per_thread);
2291   sm->translation_buckets = nat_calc_bihash_buckets (c.sessions);
2292
2293   vec_add1 (sm->max_translations_per_fib, sm->max_translations_per_thread);
2294
2295   sm->inside_vrf_id = c.inside_vrf;
2296   sm->inside_fib_index =
2297     fib_table_find_or_create_and_lock
2298     (FIB_PROTOCOL_IP4, c.inside_vrf, sm->fib_src_hi);
2299
2300   sm->outside_vrf_id = c.outside_vrf;
2301   sm->outside_fib_index = fib_table_find_or_create_and_lock (
2302     FIB_PROTOCOL_IP4, c.outside_vrf, sm->fib_src_hi);
2303
2304   nat44_ed_db_init (sm->max_translations_per_thread, sm->translation_buckets);
2305
2306   nat_affinity_enable ();
2307
2308   nat_reset_timeouts (&sm->timeouts);
2309
2310   vlib_zero_simple_counter (&sm->total_sessions, 0);
2311
2312   if (!sm->frame_queue_nelts)
2313     {
2314       sm->frame_queue_nelts = NAT_FQ_NELTS_DEFAULT;
2315     }
2316
2317   if (sm->num_workers > 1)
2318     {
2319       if (sm->fq_in2out_index == ~0)
2320         {
2321           sm->fq_in2out_index = vlib_frame_queue_main_init (
2322             sm->in2out_node_index, sm->frame_queue_nelts);
2323         }
2324       if (sm->fq_out2in_index == ~0)
2325         {
2326           sm->fq_out2in_index = vlib_frame_queue_main_init (
2327             sm->out2in_node_index, sm->frame_queue_nelts);
2328         }
2329       if (sm->fq_in2out_output_index == ~0)
2330         {
2331           sm->fq_in2out_output_index = vlib_frame_queue_main_init (
2332             sm->in2out_output_node_index, sm->frame_queue_nelts);
2333         }
2334     }
2335
2336   sm->enabled = 1;
2337   sm->rconfig = c;
2338
2339   return 0;
2340 }
2341
2342 int
2343 nat44_ed_del_addresses ()
2344 {
2345   snat_main_t *sm = &snat_main;
2346   snat_address_t *a, *vec;
2347   int error = 0;
2348
2349   vec = vec_dup (sm->addresses);
2350   vec_foreach (a, vec)
2351     {
2352       error = nat44_ed_del_address (a->addr, 0, 0);
2353       if (error)
2354         {
2355           nat_log_err ("error occurred while removing adderess");
2356         }
2357     }
2358   vec_free (vec);
2359   vec_free (sm->addresses);
2360   sm->addresses = 0;
2361
2362   vec = vec_dup (sm->twice_nat_addresses);
2363   vec_foreach (a, vec)
2364     {
2365       error = nat44_ed_del_address (a->addr, 0, 1);
2366       if (error)
2367         {
2368           nat_log_err ("error occurred while removing adderess");
2369         }
2370     }
2371   vec_free (vec);
2372   vec_free (sm->twice_nat_addresses);
2373   sm->twice_nat_addresses = 0;
2374
2375   vec_free (sm->auto_add_sw_if_indices_twice_nat);
2376   sm->auto_add_sw_if_indices_twice_nat = 0;
2377
2378   vec_free (sm->auto_add_sw_if_indices);
2379   sm->auto_add_sw_if_indices = 0;
2380
2381   return error;
2382 }
2383
2384 int
2385 nat44_ed_del_interfaces ()
2386 {
2387   snat_main_t *sm = &snat_main;
2388   snat_interface_t *i, *pool;
2389   int error = 0;
2390
2391   pool = pool_dup (sm->interfaces);
2392   pool_foreach (i, pool)
2393     {
2394       if (nat44_ed_is_interface_inside (i))
2395         {
2396           error = nat44_ed_del_interface (i->sw_if_index, 1);
2397         }
2398       if (nat44_ed_is_interface_outside (i))
2399         {
2400           error = nat44_ed_del_interface (i->sw_if_index, 0);
2401         }
2402
2403       if (error)
2404         {
2405           nat_log_err ("error occurred while removing interface");
2406         }
2407     }
2408   pool_free (pool);
2409   pool_free (sm->interfaces);
2410   sm->interfaces = 0;
2411   return error;
2412 }
2413
2414 int
2415 nat44_ed_del_output_interfaces ()
2416 {
2417   snat_main_t *sm = &snat_main;
2418   snat_interface_t *i, *pool;
2419   int error = 0;
2420
2421   pool = pool_dup (sm->output_feature_interfaces);
2422   pool_foreach (i, pool)
2423     {
2424       error = nat44_ed_del_output_interface (i->sw_if_index);
2425       if (error)
2426         {
2427           nat_log_err ("error occurred while removing output interface");
2428         }
2429     }
2430   pool_free (pool);
2431   pool_free (sm->output_feature_interfaces);
2432   sm->output_feature_interfaces = 0;
2433   return error;
2434 }
2435
2436 int
2437 nat44_ed_del_static_mappings ()
2438 {
2439   snat_main_t *sm = &snat_main;
2440   snat_static_mapping_t *m, *pool;
2441   int error = 0;
2442
2443   pool = pool_dup (sm->static_mappings);
2444   pool_foreach (m, pool)
2445     {
2446       error = nat44_ed_del_static_mapping_internal (
2447         m->local_addr, m->external_addr, m->local_port, m->external_port,
2448         m->proto, m->vrf_id, ~0, m->flags);
2449       if (error)
2450         {
2451           nat_log_err ("error occurred while removing mapping");
2452         }
2453     }
2454   pool_free (pool);
2455   pool_free (sm->static_mappings);
2456   sm->static_mappings = 0;
2457
2458   vec_free (sm->to_resolve);
2459   sm->to_resolve = 0;
2460
2461   return error;
2462 }
2463
2464 int
2465 nat44_plugin_disable ()
2466 {
2467   snat_main_per_thread_data_t *tsm;
2468   snat_main_t *sm = &snat_main;
2469   int rc, error = 0;
2470
2471   fail_if_disabled ();
2472
2473   rc = nat44_ed_del_static_mappings ();
2474   if (rc)
2475     error = 1;
2476
2477   rc = nat44_ed_del_addresses ();
2478   if (rc)
2479     error = 1;
2480
2481   rc = nat44_ed_del_interfaces ();
2482   if (rc)
2483     error = 1;
2484
2485   rc = nat44_ed_del_output_interfaces ();
2486   if (rc)
2487     error = 1;
2488
2489   vec_free (sm->max_translations_per_fib);
2490   sm->max_translations_per_fib = 0;
2491
2492   clib_bihash_free_16_8 (&sm->flow_hash);
2493
2494   if (sm->pat)
2495     {
2496       vec_foreach (tsm, sm->per_thread_data)
2497         {
2498           nat44_ed_worker_db_free (tsm);
2499         }
2500     }
2501
2502   clib_memset (&sm->rconfig, 0, sizeof (sm->rconfig));
2503
2504   sm->forwarding_enabled = 0;
2505   sm->enabled = 0;
2506
2507   return error;
2508 }
2509
2510 void
2511 nat44_ed_forwarding_enable_disable (u8 is_enable)
2512 {
2513   snat_main_per_thread_data_t *tsm;
2514   snat_main_t *sm = &snat_main;
2515   snat_session_t *s;
2516
2517   u32 *ses_to_be_removed = 0, *ses_index;
2518
2519   sm->forwarding_enabled = is_enable != 0;
2520
2521   if (!sm->enabled || is_enable)
2522     {
2523       return;
2524     }
2525
2526   vec_foreach (tsm, sm->per_thread_data)
2527     {
2528       pool_foreach (s, tsm->sessions)
2529         {
2530           if (na44_ed_is_fwd_bypass_session (s))
2531             {
2532               vec_add1 (ses_to_be_removed, s - tsm->sessions);
2533             }
2534         }
2535       vec_foreach (ses_index, ses_to_be_removed)
2536         {
2537           s = pool_elt_at_index (tsm->sessions, ses_index[0]);
2538           nat44_ed_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
2539           nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
2540         }
2541
2542       vec_free (ses_to_be_removed);
2543     }
2544 }
2545
2546 static_always_inline snat_static_mapping_t *
2547 nat44_ed_sm_match (snat_main_t *sm, ip4_address_t match_addr, u16 match_port,
2548                    u32 match_fib_index, ip_protocol_t match_protocol,
2549                    int by_external)
2550 {
2551   snat_static_mapping_t *m;
2552   if (!by_external)
2553     {
2554       m = nat44_ed_sm_i2o_lookup (sm, match_addr, match_port, match_fib_index,
2555                                   match_protocol);
2556       if (m)
2557         return m;
2558
2559       /* Try address only mapping */
2560       m = nat44_ed_sm_i2o_lookup (sm, match_addr, 0, match_fib_index, 0);
2561       if (m)
2562         return m;
2563
2564       if (sm->inside_fib_index != match_fib_index)
2565         {
2566           m = nat44_ed_sm_i2o_lookup (sm, match_addr, match_port,
2567                                       sm->inside_fib_index, match_protocol);
2568           if (m)
2569             return m;
2570
2571           /* Try address only mapping */
2572           m = nat44_ed_sm_i2o_lookup (sm, match_addr, 0, sm->inside_fib_index,
2573                                       0);
2574           if (m)
2575             return m;
2576         }
2577       if (sm->outside_fib_index != match_fib_index)
2578         {
2579           m = nat44_ed_sm_i2o_lookup (sm, match_addr, match_port,
2580                                       sm->outside_fib_index, match_protocol);
2581           if (m)
2582             return m;
2583
2584           /* Try address only mapping */
2585           m = nat44_ed_sm_i2o_lookup (sm, match_addr, 0, sm->outside_fib_index,
2586                                       0);
2587           if (m)
2588             return m;
2589         }
2590     }
2591   else
2592     {
2593       m =
2594         nat44_ed_sm_o2i_lookup (sm, match_addr, match_port, 0, match_protocol);
2595       if (m)
2596         return m;
2597
2598       /* Try address only mapping */
2599       m = nat44_ed_sm_o2i_lookup (sm, match_addr, 0, 0, 0);
2600       if (m)
2601         return m;
2602     }
2603   return 0;
2604 }
2605
2606 int
2607 snat_static_mapping_match (vlib_main_t *vm, snat_main_t *sm,
2608                            ip4_address_t match_addr, u16 match_port,
2609                            u32 match_fib_index, ip_protocol_t match_protocol,
2610                            ip4_address_t *mapping_addr, u16 *mapping_port,
2611                            u32 *mapping_fib_index, int by_external,
2612                            u8 *is_addr_only, twice_nat_type_t *twice_nat,
2613                            lb_nat_type_t *lb, ip4_address_t *ext_host_addr,
2614                            u8 *is_identity_nat, snat_static_mapping_t **out)
2615 {
2616   snat_static_mapping_t *m;
2617   u32 rand, lo = 0, hi, mid, *tmp = 0, i;
2618   nat44_lb_addr_port_t *local;
2619   u8 backend_index;
2620
2621   m = nat44_ed_sm_match (sm, match_addr, match_port, match_fib_index,
2622                          match_protocol, by_external);
2623   if (!m)
2624     {
2625       return 1;
2626     }
2627
2628   if (by_external)
2629     {
2630       if (is_sm_lb (m->flags))
2631         {
2632           if (PREDICT_FALSE (lb != 0))
2633             *lb = m->affinity ? AFFINITY_LB_NAT : LB_NAT;
2634           if (m->affinity && !nat_affinity_find_and_lock (
2635                                vm, ext_host_addr[0], match_addr,
2636                                match_protocol, match_port, &backend_index))
2637             {
2638               local = pool_elt_at_index (m->locals, backend_index);
2639               *mapping_addr = local->addr;
2640               *mapping_port = local->port;
2641               *mapping_fib_index = local->fib_index;
2642               goto end;
2643             }
2644           // pick locals matching this worker
2645           if (PREDICT_FALSE (sm->num_workers > 1))
2646             {
2647               u32 thread_index = vlib_get_thread_index ();
2648               pool_foreach_index (i, m->locals)
2649                {
2650                 local = pool_elt_at_index (m->locals, i);
2651
2652                 ip4_header_t ip = {
2653                   .src_address = local->addr,
2654                 };
2655
2656                 if (nat44_ed_get_in2out_worker_index (0, &ip, m->fib_index,
2657                                                       0) == thread_index)
2658                   {
2659                     vec_add1 (tmp, i);
2660                   }
2661                }
2662               ASSERT (vec_len (tmp) != 0);
2663             }
2664           else
2665             {
2666               pool_foreach_index (i, m->locals)
2667                {
2668                 vec_add1 (tmp, i);
2669               }
2670             }
2671           hi = vec_len (tmp) - 1;
2672           local = pool_elt_at_index (m->locals, tmp[hi]);
2673           rand = 1 + (random_u32 (&sm->random_seed) % local->prefix);
2674           while (lo < hi)
2675             {
2676               mid = ((hi - lo) >> 1) + lo;
2677               local = pool_elt_at_index (m->locals, tmp[mid]);
2678               (rand > local->prefix) ? (lo = mid + 1) : (hi = mid);
2679             }
2680           local = pool_elt_at_index (m->locals, tmp[lo]);
2681           if (!(local->prefix >= rand))
2682             return 1;
2683           *mapping_addr = local->addr;
2684           *mapping_port = local->port;
2685           *mapping_fib_index = local->fib_index;
2686           if (m->affinity)
2687             {
2688               if (nat_affinity_create_and_lock (ext_host_addr[0], match_addr,
2689                                                 match_protocol, match_port,
2690                                                 tmp[lo], m->affinity,
2691                                                 m->affinity_per_service_list_head_index))
2692                 nat_elog_info (sm, "create affinity record failed");
2693             }
2694           vec_free (tmp);
2695         }
2696       else
2697         {
2698           if (PREDICT_FALSE (lb != 0))
2699             *lb = NO_LB_NAT;
2700           *mapping_fib_index = m->fib_index;
2701           *mapping_addr = m->local_addr;
2702           /* Address only mapping doesn't change port */
2703           *mapping_port =
2704             is_sm_addr_only (m->flags) ? match_port : m->local_port;
2705         }
2706     }
2707   else
2708     {
2709       *mapping_addr = m->external_addr;
2710       /* Address only mapping doesn't change port */
2711       *mapping_port =
2712         is_sm_addr_only (m->flags) ? match_port : m->external_port;
2713       *mapping_fib_index = sm->outside_fib_index;
2714     }
2715
2716 end:
2717   if (PREDICT_FALSE (is_addr_only != 0))
2718     *is_addr_only = is_sm_addr_only (m->flags);
2719
2720   if (PREDICT_FALSE (twice_nat != 0))
2721     {
2722       *twice_nat = TWICE_NAT_DISABLED;
2723
2724       if (is_sm_twice_nat (m->flags))
2725         {
2726           *twice_nat = TWICE_NAT;
2727         }
2728       else if (is_sm_self_twice_nat (m->flags))
2729         {
2730           *twice_nat = TWICE_NAT_SELF;
2731         }
2732     }
2733
2734   if (PREDICT_FALSE (is_identity_nat != 0))
2735     *is_identity_nat = is_sm_identity_nat (m->flags);
2736
2737   if (out != 0)
2738     *out = m;
2739
2740   return 0;
2741 }
2742
2743 u32
2744 nat44_ed_get_in2out_worker_index (vlib_buffer_t *b, ip4_header_t *ip,
2745                                   u32 rx_fib_index, u8 is_output)
2746 {
2747   snat_main_t *sm = &snat_main;
2748   u32 next_worker_index = sm->first_worker_index;
2749   u32 hash;
2750
2751   clib_bihash_kv_16_8_t kv16, value16;
2752
2753   u32 fib_index = rx_fib_index;
2754   if (b)
2755     {
2756       if (PREDICT_FALSE (is_output))
2757         {
2758           fib_index = sm->outside_fib_index;
2759           nat_outside_fib_t *outside_fib;
2760           fib_node_index_t fei = FIB_NODE_INDEX_INVALID;
2761           fib_prefix_t pfx = {
2762                   .fp_proto = FIB_PROTOCOL_IP4,
2763                   .fp_len = 32,
2764                   .fp_addr = {
2765                           .ip4.as_u32 = ip->dst_address.as_u32,
2766                   } ,
2767           };
2768
2769           switch (vec_len (sm->outside_fibs))
2770             {
2771             case 0:
2772               fib_index = sm->outside_fib_index;
2773               break;
2774             case 1:
2775               fib_index = sm->outside_fibs[0].fib_index;
2776               break;
2777             default:
2778               vec_foreach (outside_fib, sm->outside_fibs)
2779                 {
2780                   fei = fib_table_lookup (outside_fib->fib_index, &pfx);
2781                   if (FIB_NODE_INDEX_INVALID != fei)
2782                     {
2783                       if (fib_entry_get_resolving_interface (fei) != ~0)
2784                         {
2785                           fib_index = outside_fib->fib_index;
2786                           break;
2787                         }
2788                     }
2789                 }
2790               break;
2791             }
2792         }
2793
2794       if (PREDICT_FALSE (ip->protocol == IP_PROTOCOL_ICMP))
2795         {
2796           ip4_address_t lookup_saddr, lookup_daddr;
2797           u16 lookup_sport, lookup_dport;
2798           u8 lookup_protocol;
2799
2800           if (!nat_get_icmp_session_lookup_values (
2801                 b, ip, &lookup_saddr, &lookup_sport, &lookup_daddr,
2802                 &lookup_dport, &lookup_protocol))
2803             {
2804               init_ed_k (&kv16, lookup_saddr.as_u32, lookup_sport,
2805                          lookup_daddr.as_u32, lookup_dport, rx_fib_index,
2806                          lookup_protocol);
2807               if (!clib_bihash_search_16_8 (&sm->flow_hash, &kv16, &value16))
2808                 {
2809                   next_worker_index = ed_value_get_thread_index (&value16);
2810                   vnet_buffer2 (b)->nat.cached_session_index =
2811                     ed_value_get_session_index (&value16);
2812                   goto out;
2813                 }
2814             }
2815         }
2816
2817       init_ed_k (&kv16, ip->src_address.as_u32,
2818                  vnet_buffer (b)->ip.reass.l4_src_port, ip->dst_address.as_u32,
2819                  vnet_buffer (b)->ip.reass.l4_dst_port, fib_index,
2820                  ip->protocol);
2821
2822       if (!clib_bihash_search_16_8 (&sm->flow_hash, &kv16, &value16))
2823         {
2824           next_worker_index = ed_value_get_thread_index (&value16);
2825           vnet_buffer2 (b)->nat.cached_session_index =
2826             ed_value_get_session_index (&value16);
2827           goto out;
2828         }
2829
2830       // dst NAT
2831       init_ed_k (&kv16, ip->dst_address.as_u32,
2832                  vnet_buffer (b)->ip.reass.l4_dst_port, ip->src_address.as_u32,
2833                  vnet_buffer (b)->ip.reass.l4_src_port, rx_fib_index,
2834                  ip->protocol);
2835       if (!clib_bihash_search_16_8 (&sm->flow_hash, &kv16, &value16))
2836         {
2837           next_worker_index = ed_value_get_thread_index (&value16);
2838           vnet_buffer2 (b)->nat.cached_dst_nat_session_index =
2839             ed_value_get_session_index (&value16);
2840           goto out;
2841         }
2842     }
2843
2844   hash = ip->src_address.as_u32 + (ip->src_address.as_u32 >> 8) +
2845     (ip->src_address.as_u32 >> 16) + (ip->src_address.as_u32 >> 24);
2846
2847   if (PREDICT_TRUE (is_pow2 (_vec_len (sm->workers))))
2848     next_worker_index += sm->workers[hash & (_vec_len (sm->workers) - 1)];
2849   else
2850     next_worker_index += sm->workers[hash % _vec_len (sm->workers)];
2851
2852 out:
2853   if (PREDICT_TRUE (!is_output))
2854     {
2855       nat_elog_debug_handoff (sm, "HANDOFF IN2OUT", next_worker_index,
2856                               rx_fib_index,
2857                               clib_net_to_host_u32 (ip->src_address.as_u32),
2858                               clib_net_to_host_u32 (ip->dst_address.as_u32));
2859     }
2860   else
2861     {
2862       nat_elog_debug_handoff (sm, "HANDOFF IN2OUT-OUTPUT-FEATURE",
2863                               next_worker_index, rx_fib_index,
2864                               clib_net_to_host_u32 (ip->src_address.as_u32),
2865                               clib_net_to_host_u32 (ip->dst_address.as_u32));
2866     }
2867
2868   return next_worker_index;
2869 }
2870
2871 u32
2872 nat44_ed_get_out2in_worker_index (vlib_buffer_t *b, ip4_header_t *ip,
2873                                   u32 rx_fib_index, u8 is_output)
2874 {
2875   snat_main_t *sm = &snat_main;
2876   clib_bihash_kv_16_8_t kv16, value16;
2877
2878   u8 proto, next_worker_index = 0;
2879   u16 port;
2880   snat_static_mapping_t *m;
2881   u32 hash;
2882
2883   proto = ip->protocol;
2884
2885   if (PREDICT_FALSE (IP_PROTOCOL_ICMP == proto))
2886     {
2887       ip4_address_t lookup_saddr, lookup_daddr;
2888       u16 lookup_sport, lookup_dport;
2889       u8 lookup_protocol;
2890       if (!nat_get_icmp_session_lookup_values (
2891             b, ip, &lookup_saddr, &lookup_sport, &lookup_daddr, &lookup_dport,
2892             &lookup_protocol))
2893         {
2894           init_ed_k (&kv16, lookup_saddr.as_u32, lookup_sport,
2895                      lookup_daddr.as_u32, lookup_dport, rx_fib_index,
2896                      lookup_protocol);
2897           if (PREDICT_TRUE (
2898                 !clib_bihash_search_16_8 (&sm->flow_hash, &kv16, &value16)))
2899             {
2900               next_worker_index = ed_value_get_thread_index (&value16);
2901               nat_elog_debug_handoff (
2902                 sm, "HANDOFF OUT2IN (session)", next_worker_index,
2903                 rx_fib_index, clib_net_to_host_u32 (ip->src_address.as_u32),
2904                 clib_net_to_host_u32 (ip->dst_address.as_u32));
2905               return next_worker_index;
2906             }
2907         }
2908     }
2909
2910   init_ed_k (&kv16, ip->src_address.as_u32,
2911              vnet_buffer (b)->ip.reass.l4_src_port, ip->dst_address.as_u32,
2912              vnet_buffer (b)->ip.reass.l4_dst_port, rx_fib_index,
2913              ip->protocol);
2914
2915   if (PREDICT_TRUE (
2916         !clib_bihash_search_16_8 (&sm->flow_hash, &kv16, &value16)))
2917     {
2918       vnet_buffer2 (b)->nat.cached_session_index =
2919         ed_value_get_session_index (&value16);
2920       next_worker_index = ed_value_get_thread_index (&value16);
2921       nat_elog_debug_handoff (sm, "HANDOFF OUT2IN (session)",
2922                               next_worker_index, rx_fib_index,
2923                               clib_net_to_host_u32 (ip->src_address.as_u32),
2924                               clib_net_to_host_u32 (ip->dst_address.as_u32));
2925       return next_worker_index;
2926     }
2927
2928   /* first try static mappings without port */
2929   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
2930     {
2931       m = nat44_ed_sm_o2i_lookup (sm, ip->dst_address, 0, 0, proto);
2932       if (m)
2933         {
2934           {
2935             next_worker_index = m->workers[0];
2936             goto done;
2937           }
2938         }
2939     }
2940
2941   /* unknown protocol */
2942   if (PREDICT_FALSE (nat44_ed_is_unk_proto (proto)))
2943     {
2944       /* use current thread */
2945       next_worker_index = vlib_get_thread_index ();
2946       goto done;
2947     }
2948
2949   port = vnet_buffer (b)->ip.reass.l4_dst_port;
2950
2951   if (PREDICT_FALSE (ip->protocol == IP_PROTOCOL_ICMP))
2952     {
2953       udp_header_t *udp = ip4_next_header (ip);
2954       icmp46_header_t *icmp = (icmp46_header_t *) udp;
2955       icmp_echo_header_t *echo = (icmp_echo_header_t *) (icmp + 1);
2956       if (!icmp_type_is_error_message
2957           (vnet_buffer (b)->ip.reass.icmp_type_or_tcp_flags))
2958         port = vnet_buffer (b)->ip.reass.l4_src_port;
2959       else
2960         {
2961           /* if error message, then it's not fragmented and we can access it */
2962           ip4_header_t *inner_ip = (ip4_header_t *) (echo + 1);
2963           proto = inner_ip->protocol;
2964           void *l4_header = ip4_next_header (inner_ip);
2965           switch (proto)
2966             {
2967             case IP_PROTOCOL_ICMP:
2968               icmp = (icmp46_header_t *) l4_header;
2969               echo = (icmp_echo_header_t *) (icmp + 1);
2970               port = echo->identifier;
2971               break;
2972             case IP_PROTOCOL_UDP:
2973               /* breakthrough */
2974             case IP_PROTOCOL_TCP:
2975               port = ((tcp_udp_header_t *) l4_header)->src_port;
2976               break;
2977             default:
2978               next_worker_index = vlib_get_thread_index ();
2979               goto done;
2980             }
2981         }
2982     }
2983
2984   /* try static mappings with port */
2985   if (PREDICT_FALSE (pool_elts (sm->static_mappings)))
2986     {
2987       m = nat44_ed_sm_o2i_lookup (sm, ip->dst_address, port, 0, proto);
2988       if (m)
2989         {
2990           if (!is_sm_lb (m->flags))
2991             {
2992               next_worker_index = m->workers[0];
2993               goto done;
2994             }
2995
2996           hash = ip->src_address.as_u32 + (ip->src_address.as_u32 >> 8) +
2997             (ip->src_address.as_u32 >> 16) + (ip->src_address.as_u32 >> 24);
2998
2999           if (PREDICT_TRUE (is_pow2 (_vec_len (m->workers))))
3000             next_worker_index =
3001               m->workers[hash & (_vec_len (m->workers) - 1)];
3002           else
3003             next_worker_index = m->workers[hash % _vec_len (m->workers)];
3004           goto done;
3005         }
3006     }
3007
3008   /* worker by outside port */
3009   next_worker_index = sm->first_worker_index;
3010   next_worker_index +=
3011     sm->workers[(clib_net_to_host_u16 (port) - 1024) / sm->port_per_thread];
3012
3013 done:
3014   nat_elog_debug_handoff (sm, "HANDOFF OUT2IN", next_worker_index,
3015                           rx_fib_index,
3016                           clib_net_to_host_u32 (ip->src_address.as_u32),
3017                           clib_net_to_host_u32 (ip->dst_address.as_u32));
3018   return next_worker_index;
3019 }
3020
3021 u32
3022 nat44_get_max_session_limit ()
3023 {
3024   snat_main_t *sm = &snat_main;
3025   u32 max_limit = 0, len = 0;
3026
3027   for (; len < vec_len (sm->max_translations_per_fib); len++)
3028     {
3029       if (max_limit < sm->max_translations_per_fib[len])
3030         max_limit = sm->max_translations_per_fib[len];
3031     }
3032   return max_limit;
3033 }
3034
3035 int
3036 nat44_set_session_limit (u32 session_limit, u32 vrf_id)
3037 {
3038   snat_main_t *sm = &snat_main;
3039   u32 fib_index = fib_table_find (FIB_PROTOCOL_IP4, vrf_id);
3040   u32 len = vec_len (sm->max_translations_per_fib);
3041
3042   if (len <= fib_index)
3043     {
3044       vec_validate (sm->max_translations_per_fib, fib_index + 1);
3045
3046       for (; len < vec_len (sm->max_translations_per_fib); len++)
3047         sm->max_translations_per_fib[len] = sm->max_translations_per_thread;
3048     }
3049
3050   sm->max_translations_per_fib[fib_index] = session_limit;
3051   return 0;
3052 }
3053
3054 int
3055 nat44_update_session_limit (u32 session_limit, u32 vrf_id)
3056 {
3057   snat_main_t *sm = &snat_main;
3058
3059   if (nat44_set_session_limit (session_limit, vrf_id))
3060     return 1;
3061   sm->max_translations_per_thread = nat44_get_max_session_limit ();
3062
3063   stat_segment_set_state_counter (sm->max_cfg_sessions_gauge,
3064                                   sm->max_translations_per_thread);
3065
3066   sm->translation_buckets =
3067     nat_calc_bihash_buckets (sm->max_translations_per_thread);
3068
3069   nat44_ed_sessions_clear ();
3070   return 0;
3071 }
3072
3073 static void
3074 nat44_ed_worker_db_init (snat_main_per_thread_data_t *tsm, u32 translations,
3075                          u32 translation_buckets)
3076 {
3077   dlist_elt_t *head;
3078
3079   pool_alloc (tsm->sessions, translations);
3080   pool_alloc (tsm->lru_pool, translations);
3081
3082   pool_get (tsm->lru_pool, head);
3083   tsm->tcp_trans_lru_head_index = head - tsm->lru_pool;
3084   clib_dlist_init (tsm->lru_pool, tsm->tcp_trans_lru_head_index);
3085
3086   pool_get (tsm->lru_pool, head);
3087   tsm->tcp_estab_lru_head_index = head - tsm->lru_pool;
3088   clib_dlist_init (tsm->lru_pool, tsm->tcp_estab_lru_head_index);
3089
3090   pool_get (tsm->lru_pool, head);
3091   tsm->udp_lru_head_index = head - tsm->lru_pool;
3092   clib_dlist_init (tsm->lru_pool, tsm->udp_lru_head_index);
3093
3094   pool_get (tsm->lru_pool, head);
3095   tsm->icmp_lru_head_index = head - tsm->lru_pool;
3096   clib_dlist_init (tsm->lru_pool, tsm->icmp_lru_head_index);
3097
3098   pool_get (tsm->lru_pool, head);
3099   tsm->unk_proto_lru_head_index = head - tsm->lru_pool;
3100   clib_dlist_init (tsm->lru_pool, tsm->unk_proto_lru_head_index);
3101 }
3102
3103 static void
3104 reinit_ed_flow_hash ()
3105 {
3106   snat_main_t *sm = &snat_main;
3107   // we expect 2 flows per session, so multiply translation_buckets by 2
3108   clib_bihash_init_16_8 (
3109     &sm->flow_hash, "ed-flow-hash",
3110     clib_max (1, sm->num_workers) * 2 * sm->translation_buckets, 0);
3111   clib_bihash_set_kvp_format_fn_16_8 (&sm->flow_hash, format_ed_session_kvp);
3112 }
3113
3114 static void
3115 nat44_ed_db_init (u32 translations, u32 translation_buckets)
3116 {
3117   snat_main_t *sm = &snat_main;
3118   snat_main_per_thread_data_t *tsm;
3119
3120   reinit_ed_flow_hash ();
3121
3122   if (sm->pat)
3123     {
3124       vec_foreach (tsm, sm->per_thread_data)
3125         {
3126           nat44_ed_worker_db_init (tsm, sm->max_translations_per_thread,
3127                                    sm->translation_buckets);
3128         }
3129     }
3130 }
3131
3132 static void
3133 nat44_ed_worker_db_free (snat_main_per_thread_data_t *tsm)
3134 {
3135   pool_free (tsm->lru_pool);
3136   pool_free (tsm->sessions);
3137   vec_free (tsm->per_vrf_sessions_vec);
3138 }
3139
3140 void
3141 nat44_ed_sessions_clear ()
3142 {
3143   snat_main_t *sm = &snat_main;
3144   snat_main_per_thread_data_t *tsm;
3145
3146   reinit_ed_flow_hash ();
3147
3148   if (sm->pat)
3149     {
3150       vec_foreach (tsm, sm->per_thread_data)
3151         {
3152
3153           nat44_ed_worker_db_free (tsm);
3154           nat44_ed_worker_db_init (tsm, sm->max_translations_per_thread,
3155                                    sm->translation_buckets);
3156         }
3157     }
3158   vlib_zero_simple_counter (&sm->total_sessions, 0);
3159 }
3160
3161 static void
3162 nat44_ed_add_del_static_mapping_addr_only_cb (
3163   ip4_main_t *im, uword opaque, u32 sw_if_index, ip4_address_t *address,
3164   u32 address_length, u32 if_address_index, u32 is_delete)
3165 {
3166   snat_static_map_resolve_t *rp;
3167   snat_main_t *sm = &snat_main;
3168   snat_static_mapping_t *m;
3169   int i, rv = 0, match = 0;
3170
3171   if (!sm->enabled)
3172     {
3173       return;
3174     }
3175
3176   // find first addr_only resolve record by sw_if_index
3177   for (i = 0; i < vec_len (sm->to_resolve); i++)
3178     {
3179       rp = sm->to_resolve + i;
3180       if (is_sm_addr_only (rp->flags) && rp->sw_if_index == sw_if_index)
3181         {
3182           match = 1;
3183           break;
3184         }
3185     }
3186   if (!match)
3187     {
3188       return;
3189     }
3190
3191   m = nat44_ed_sm_o2i_lookup (
3192     sm, *address, is_sm_addr_only (rp->flags) ? 0 : rp->e_port, 0, rp->proto);
3193
3194   if (is_delete)
3195     {
3196       if (m)
3197         {
3198           rv = nat44_ed_del_static_mapping_internal (
3199             rp->l_addr, address[0], rp->l_port, rp->e_port, rp->proto,
3200             rp->vrf_id, ~0, rp->flags);
3201         }
3202       if (rv)
3203         {
3204           nat_elog_notice_X1 (sm, "nat44_ed_del_static_mapping returned %d",
3205                               "i4", rv);
3206         }
3207     }
3208   else
3209     {
3210       if (!m)
3211         {
3212           rv = nat44_ed_add_static_mapping_internal (
3213             rp->l_addr, address[0], rp->l_port, rp->e_port, rp->proto,
3214             rp->vrf_id, ~0, rp->flags, rp->pool_addr, rp->tag);
3215         }
3216       // else: don't trip over lease renewal, static config
3217       if (rv)
3218         {
3219           nat_elog_notice_X1 (sm, "nat44_ed_add_static_mapping returned %d",
3220                               "i4", rv);
3221         }
3222     }
3223 }
3224
3225 static_always_inline int
3226 is_sw_if_index_reg_for_auto_resolve (u32 *sw_if_indices, u32 sw_if_index)
3227 {
3228   u32 *i;
3229   vec_foreach (i, sw_if_indices)
3230     {
3231       if (*i == sw_if_index)
3232         {
3233           return 1;
3234         }
3235     }
3236   return 0;
3237 }
3238
3239 static void
3240 nat44_ed_add_del_interface_address_cb (ip4_main_t *im, uword opaque,
3241                                        u32 sw_if_index, ip4_address_t *address,
3242                                        u32 address_length,
3243                                        u32 if_address_index, u32 is_delete)
3244 {
3245   snat_main_t *sm = &snat_main;
3246   snat_static_map_resolve_t *rp;
3247   snat_address_t *addresses = sm->addresses;
3248   u8 twice_nat = 0;
3249   int rv, i;
3250
3251   if (!sm->enabled)
3252     {
3253       return;
3254     }
3255
3256   if (!is_sw_if_index_reg_for_auto_resolve (sm->auto_add_sw_if_indices,
3257                                             sw_if_index))
3258     {
3259       if (!is_sw_if_index_reg_for_auto_resolve (
3260             sm->auto_add_sw_if_indices_twice_nat, sw_if_index))
3261         {
3262           return;
3263         }
3264       else
3265         {
3266           addresses = sm->twice_nat_addresses;
3267           twice_nat = 1;
3268         }
3269     }
3270
3271   if (!is_delete)
3272     {
3273       // don't trip over lease renewal, static config
3274       for (i = 0; i < vec_len (addresses); i++)
3275         {
3276           if (addresses[i].addr.as_u32 == address->as_u32)
3277             {
3278               return;
3279             }
3280         }
3281
3282       (void) nat44_ed_add_address (address, ~0, twice_nat);
3283
3284       // scan static mapping switch address resolution record vector
3285       for (i = 0; i < vec_len (sm->to_resolve); i++)
3286         {
3287           rp = sm->to_resolve + i;
3288           if (is_sm_addr_only (rp->flags))
3289             {
3290               continue;
3291             }
3292           if (rp->sw_if_index == sw_if_index)
3293             {
3294               rv = nat44_ed_add_static_mapping_internal (
3295                 rp->l_addr, address[0], rp->l_port, rp->e_port, rp->proto,
3296                 rp->vrf_id, sw_if_index, rp->flags, rp->pool_addr, rp->tag);
3297               if (rv)
3298                 {
3299                   nat_elog_notice_X1 (
3300                     sm, "add_static_mapping_internal returned %d", "i4", rv);
3301                 }
3302             }
3303         }
3304     }
3305   else
3306     {
3307       // remove all static mapping records
3308       (void) nat44_ed_del_address (address[0], 1, twice_nat);
3309     }
3310 }
3311
3312 int
3313 nat44_ed_add_interface_address (u32 sw_if_index, u8 twice_nat)
3314 {
3315   snat_main_t *sm = &snat_main;
3316   ip4_main_t *ip4_main = sm->ip4_main;
3317   ip4_address_t *first_int_addr;
3318   u32 *auto_add_sw_if_indices = twice_nat ?
3319                                   sm->auto_add_sw_if_indices_twice_nat :
3320                                   sm->auto_add_sw_if_indices;
3321   int i;
3322
3323   for (i = 0; i < vec_len (auto_add_sw_if_indices); i++)
3324     {
3325       if (auto_add_sw_if_indices[i] == sw_if_index)
3326         {
3327           return VNET_API_ERROR_VALUE_EXIST;
3328         }
3329     }
3330
3331   // add to the auto-address list
3332   if (twice_nat)
3333     {
3334       vec_add1 (sm->auto_add_sw_if_indices_twice_nat, sw_if_index);
3335     }
3336   else
3337     {
3338       vec_add1 (sm->auto_add_sw_if_indices, sw_if_index);
3339     }
3340
3341   // if the address is already bound - or static - add it now
3342   first_int_addr = ip4_interface_first_address (ip4_main, sw_if_index, 0);
3343   if (first_int_addr)
3344     {
3345       (void) nat44_ed_add_address (first_int_addr, ~0, twice_nat);
3346     }
3347
3348   return 0;
3349 }
3350
3351 int
3352 nat44_ed_del_interface_address (u32 sw_if_index, u8 twice_nat)
3353 {
3354   snat_main_t *sm = &snat_main;
3355   ip4_main_t *ip4_main = sm->ip4_main;
3356   ip4_address_t *first_int_addr;
3357   snat_static_map_resolve_t *rp;
3358   u32 *indices_to_delete = 0;
3359   int i, j;
3360   u32 *auto_add_sw_if_indices;
3361
3362   if (!sm->enabled)
3363     {
3364       return VNET_API_ERROR_UNSUPPORTED;
3365     }
3366
3367   auto_add_sw_if_indices = twice_nat ? sm->auto_add_sw_if_indices_twice_nat :
3368                                        sm->auto_add_sw_if_indices;
3369
3370   for (i = 0; i < vec_len (auto_add_sw_if_indices); i++)
3371     {
3372       if (auto_add_sw_if_indices[i] == sw_if_index)
3373         {
3374           first_int_addr =
3375             ip4_interface_first_address (ip4_main, sw_if_index, 0);
3376           if (first_int_addr)
3377             {
3378               // remove all static mapping records
3379               (void) nat44_ed_del_address (first_int_addr[0], 1, twice_nat);
3380             }
3381           else
3382             {
3383               for (j = 0; j < vec_len (sm->to_resolve); j++)
3384                 {
3385                   rp = sm->to_resolve + j;
3386                   if (rp->sw_if_index == sw_if_index)
3387                     {
3388                       vec_add1 (indices_to_delete, j);
3389                     }
3390                 }
3391               if (vec_len (indices_to_delete))
3392                 {
3393                   for (j = vec_len (indices_to_delete) - 1; j >= 0; j--)
3394                     {
3395                       vec_del1 (sm->to_resolve, j);
3396                     }
3397                   vec_free (indices_to_delete);
3398                 }
3399             }
3400
3401           if (twice_nat)
3402             {
3403               vec_del1 (sm->auto_add_sw_if_indices_twice_nat, i);
3404             }
3405           else
3406             {
3407               vec_del1 (sm->auto_add_sw_if_indices, i);
3408             }
3409           return 0;
3410         }
3411     }
3412   return VNET_API_ERROR_NO_SUCH_ENTRY;
3413 }
3414
3415 int
3416 nat44_ed_del_session (snat_main_t *sm, ip4_address_t *addr, u16 port,
3417                       ip4_address_t *eh_addr, u16 eh_port, u8 proto,
3418                       u32 vrf_id, int is_in)
3419 {
3420   ip4_header_t ip;
3421   clib_bihash_kv_16_8_t kv, value;
3422   u32 fib_index;
3423   snat_session_t *s;
3424   snat_main_per_thread_data_t *tsm;
3425
3426   if (!sm->enabled)
3427     {
3428       return VNET_API_ERROR_UNSUPPORTED;
3429     }
3430
3431   fib_index = fib_table_find (FIB_PROTOCOL_IP4, vrf_id);
3432   ip.dst_address.as_u32 = ip.src_address.as_u32 = addr->as_u32;
3433   if (sm->num_workers > 1)
3434     tsm = vec_elt_at_index (
3435       sm->per_thread_data,
3436       nat44_ed_get_in2out_worker_index (0, &ip, fib_index, 0));
3437   else
3438     tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
3439
3440   init_ed_k (&kv, addr->as_u32, port, eh_addr->as_u32, eh_port, fib_index,
3441              proto);
3442   if (clib_bihash_search_16_8 (&sm->flow_hash, &kv, &value))
3443     {
3444       return VNET_API_ERROR_NO_SUCH_ENTRY;
3445     }
3446
3447   if (pool_is_free_index (tsm->sessions, ed_value_get_session_index (&value)))
3448     return VNET_API_ERROR_UNSPECIFIED;
3449   s = pool_elt_at_index (tsm->sessions, ed_value_get_session_index (&value));
3450   nat44_ed_free_session_data (sm, s, tsm - sm->per_thread_data, 0);
3451   nat_ed_session_delete (sm, s, tsm - sm->per_thread_data, 1);
3452   return 0;
3453 }
3454
3455 VLIB_NODE_FN (nat_default_node) (vlib_main_t * vm,
3456                                  vlib_node_runtime_t * node,
3457                                  vlib_frame_t * frame)
3458 {
3459   return 0;
3460 }
3461
3462 VLIB_REGISTER_NODE (nat_default_node) = {
3463   .name = "nat-default",
3464   .vector_size = sizeof (u32),
3465   .format_trace = 0,
3466   .type = VLIB_NODE_TYPE_INTERNAL,
3467   .n_errors = 0,
3468   .n_next_nodes = NAT_N_NEXT,
3469   .next_nodes = {
3470     [NAT_NEXT_DROP] = "error-drop",
3471     [NAT_NEXT_ICMP_ERROR] = "ip4-icmp-error",
3472     [NAT_NEXT_IN2OUT_ED_FAST_PATH] = "nat44-ed-in2out",
3473     [NAT_NEXT_IN2OUT_ED_SLOW_PATH] = "nat44-ed-in2out-slowpath",
3474     [NAT_NEXT_IN2OUT_ED_OUTPUT_FAST_PATH] = "nat44-ed-in2out-output",
3475     [NAT_NEXT_IN2OUT_ED_OUTPUT_SLOW_PATH] = "nat44-ed-in2out-output-slowpath",
3476     [NAT_NEXT_OUT2IN_ED_FAST_PATH] = "nat44-ed-out2in",
3477     [NAT_NEXT_OUT2IN_ED_SLOW_PATH] = "nat44-ed-out2in-slowpath",
3478     [NAT_NEXT_IN2OUT_CLASSIFY] = "nat44-in2out-worker-handoff",
3479     [NAT_NEXT_OUT2IN_CLASSIFY] = "nat44-out2in-worker-handoff",
3480   },
3481 };
3482
3483 void
3484 nat_6t_l3_l4_csum_calc (nat_6t_flow_t *f)
3485 {
3486   f->l3_csum_delta = 0;
3487   f->l4_csum_delta = 0;
3488   if (f->ops & NAT_FLOW_OP_SADDR_REWRITE &&
3489       f->rewrite.saddr.as_u32 != f->match.saddr.as_u32)
3490     {
3491       f->l3_csum_delta =
3492         ip_csum_add_even (f->l3_csum_delta, f->rewrite.saddr.as_u32);
3493       f->l3_csum_delta =
3494         ip_csum_sub_even (f->l3_csum_delta, f->match.saddr.as_u32);
3495     }
3496   else
3497     {
3498       f->rewrite.saddr.as_u32 = f->match.saddr.as_u32;
3499     }
3500   if (f->ops & NAT_FLOW_OP_DADDR_REWRITE &&
3501       f->rewrite.daddr.as_u32 != f->match.daddr.as_u32)
3502     {
3503       f->l3_csum_delta =
3504         ip_csum_add_even (f->l3_csum_delta, f->rewrite.daddr.as_u32);
3505       f->l3_csum_delta =
3506         ip_csum_sub_even (f->l3_csum_delta, f->match.daddr.as_u32);
3507     }
3508   else
3509     {
3510       f->rewrite.daddr.as_u32 = f->match.daddr.as_u32;
3511     }
3512   if (f->ops & NAT_FLOW_OP_SPORT_REWRITE && f->rewrite.sport != f->match.sport)
3513     {
3514       f->l4_csum_delta = ip_csum_add_even (f->l4_csum_delta, f->rewrite.sport);
3515       f->l4_csum_delta = ip_csum_sub_even (f->l4_csum_delta, f->match.sport);
3516     }
3517   else
3518     {
3519       f->rewrite.sport = f->match.sport;
3520     }
3521   if (f->ops & NAT_FLOW_OP_DPORT_REWRITE && f->rewrite.dport != f->match.dport)
3522     {
3523       f->l4_csum_delta = ip_csum_add_even (f->l4_csum_delta, f->rewrite.dport);
3524       f->l4_csum_delta = ip_csum_sub_even (f->l4_csum_delta, f->match.dport);
3525     }
3526   else
3527     {
3528       f->rewrite.dport = f->match.dport;
3529     }
3530   if (f->ops & NAT_FLOW_OP_ICMP_ID_REWRITE &&
3531       f->rewrite.icmp_id != f->match.sport)
3532     {
3533       f->l4_csum_delta =
3534         ip_csum_add_even (f->l4_csum_delta, f->rewrite.icmp_id);
3535       f->l4_csum_delta = ip_csum_sub_even (f->l4_csum_delta, f->match.sport);
3536     }
3537   else
3538     {
3539       f->rewrite.icmp_id = f->match.sport;
3540     }
3541   if (f->ops & NAT_FLOW_OP_TXFIB_REWRITE)
3542     {
3543     }
3544   else
3545     {
3546       f->rewrite.fib_index = f->match.fib_index;
3547     }
3548 }
3549
3550 static_always_inline int
3551 nat_6t_flow_icmp_translate (vlib_main_t *vm, snat_main_t *sm, vlib_buffer_t *b,
3552                             ip4_header_t *ip, nat_6t_flow_t *f);
3553
3554 static_always_inline void
3555 nat_6t_flow_ip4_translate (snat_main_t *sm, vlib_buffer_t *b, ip4_header_t *ip,
3556                            nat_6t_flow_t *f, ip_protocol_t proto,
3557                            int is_icmp_inner_ip4, int skip_saddr_rewrite)
3558 {
3559   udp_header_t *udp = ip4_next_header (ip);
3560   tcp_header_t *tcp = (tcp_header_t *) udp;
3561
3562   if ((IP_PROTOCOL_TCP == proto || IP_PROTOCOL_UDP == proto) &&
3563       !vnet_buffer (b)->ip.reass.is_non_first_fragment)
3564     {
3565       if (!is_icmp_inner_ip4)
3566         { // regular case
3567           ip->src_address = f->rewrite.saddr;
3568           ip->dst_address = f->rewrite.daddr;
3569           udp->src_port = f->rewrite.sport;
3570           udp->dst_port = f->rewrite.dport;
3571         }
3572       else
3573         { // icmp inner ip4 - reversed saddr/daddr
3574           ip->src_address = f->rewrite.daddr;
3575           ip->dst_address = f->rewrite.saddr;
3576           udp->src_port = f->rewrite.dport;
3577           udp->dst_port = f->rewrite.sport;
3578         }
3579
3580       if (IP_PROTOCOL_TCP == proto)
3581         {
3582           ip_csum_t tcp_sum = tcp->checksum;
3583           tcp_sum = ip_csum_sub_even (tcp_sum, f->l3_csum_delta);
3584           tcp_sum = ip_csum_sub_even (tcp_sum, f->l4_csum_delta);
3585           mss_clamping (sm->mss_clamping, tcp, &tcp_sum);
3586           tcp->checksum = ip_csum_fold (tcp_sum);
3587         }
3588       else if (IP_PROTOCOL_UDP == proto && udp->checksum)
3589         {
3590           ip_csum_t udp_sum = udp->checksum;
3591           udp_sum = ip_csum_sub_even (udp_sum, f->l3_csum_delta);
3592           udp_sum = ip_csum_sub_even (udp_sum, f->l4_csum_delta);
3593           udp->checksum = ip_csum_fold (udp_sum);
3594         }
3595     }
3596   else
3597     {
3598       if (!is_icmp_inner_ip4)
3599         { // regular case
3600           if (!skip_saddr_rewrite)
3601             {
3602               ip->src_address = f->rewrite.saddr;
3603             }
3604           ip->dst_address = f->rewrite.daddr;
3605         }
3606       else
3607         { // icmp inner ip4 - reversed saddr/daddr
3608           ip->src_address = f->rewrite.daddr;
3609           ip->dst_address = f->rewrite.saddr;
3610         }
3611     }
3612
3613   if (skip_saddr_rewrite)
3614     {
3615       ip->checksum = ip4_header_checksum (ip);
3616     }
3617   else
3618     {
3619       ip_csum_t ip_sum = ip->checksum;
3620       ip_sum = ip_csum_sub_even (ip_sum, f->l3_csum_delta);
3621       ip->checksum = ip_csum_fold (ip_sum);
3622     }
3623   if (0xffff == ip->checksum)
3624     ip->checksum = 0;
3625   ASSERT (ip4_header_checksum_is_valid (ip));
3626 }
3627
3628 static_always_inline int
3629 it_fits (vlib_main_t *vm, vlib_buffer_t *b, void *object, size_t size)
3630 {
3631   int result = ((u8 *) object + size <=
3632                 (u8 *) vlib_buffer_get_current (b) + b->current_length) &&
3633                vlib_object_within_buffer_data (vm, b, object, size);
3634   return result;
3635 }
3636
3637 static_always_inline int
3638 nat_6t_flow_icmp_translate (vlib_main_t *vm, snat_main_t *sm, vlib_buffer_t *b,
3639                             ip4_header_t *ip, nat_6t_flow_t *f)
3640 {
3641   if (IP_PROTOCOL_ICMP != ip->protocol)
3642     return NAT_ED_TRNSL_ERR_TRANSLATION_FAILED;
3643
3644   icmp46_header_t *icmp = ip4_next_header (ip);
3645   icmp_echo_header_t *echo = (icmp_echo_header_t *) (icmp + 1);
3646
3647   if ((!vnet_buffer (b)->ip.reass.is_non_first_fragment))
3648     {
3649       if (!it_fits (vm, b, icmp, sizeof (*icmp)))
3650         {
3651           return NAT_ED_TRNSL_ERR_PACKET_TRUNCATED;
3652         }
3653
3654       if (!icmp_type_is_error_message (icmp->type))
3655         {
3656           if ((f->ops & NAT_FLOW_OP_ICMP_ID_REWRITE) &&
3657               (f->rewrite.icmp_id != echo->identifier))
3658             {
3659               ip_csum_t sum = icmp->checksum;
3660               sum = ip_csum_update (sum, echo->identifier, f->rewrite.icmp_id,
3661                                     icmp_echo_header_t,
3662                                     identifier /* changed member */);
3663               echo->identifier = f->rewrite.icmp_id;
3664               icmp->checksum = ip_csum_fold (sum);
3665             }
3666         }
3667       else
3668         {
3669           ip_csum_t sum = ip_incremental_checksum (
3670             0, icmp,
3671             clib_net_to_host_u16 (ip->length) - ip4_header_bytes (ip));
3672           sum = (u16) ~ip_csum_fold (sum);
3673           if (sum != 0)
3674             {
3675               return NAT_ED_TRNSL_ERR_INVALID_CSUM;
3676             }
3677
3678           // errors are not fragmented
3679           ip4_header_t *inner_ip = (ip4_header_t *) (echo + 1);
3680
3681           if (!ip4_header_checksum_is_valid (inner_ip))
3682             {
3683               return NAT_ED_TRNSL_ERR_INNER_IP_CORRUPT;
3684             }
3685
3686           ip_protocol_t inner_proto = inner_ip->protocol;
3687
3688           ip_csum_t old_icmp_sum = icmp->checksum;
3689           ip_csum_t old_inner_ip_sum = inner_ip->checksum;
3690           ip_csum_t old_udp_sum;
3691           ip_csum_t old_tcp_sum;
3692           ip_csum_t new_icmp_sum;
3693           udp_header_t *udp;
3694           tcp_header_t *tcp;
3695
3696           switch (inner_proto)
3697             {
3698             case IP_PROTOCOL_UDP:
3699               udp = (udp_header_t *) (inner_ip + 1);
3700               if (!it_fits (vm, b, udp, sizeof (*udp)))
3701                 {
3702                   return NAT_ED_TRNSL_ERR_PACKET_TRUNCATED;
3703                 }
3704               old_udp_sum = udp->checksum;
3705               nat_6t_flow_ip4_translate (sm, b, inner_ip, f, inner_proto,
3706                                          1 /* is_icmp_inner_ip4 */,
3707                                          0 /* skip_saddr_rewrite */);
3708               new_icmp_sum = ip_csum_sub_even (old_icmp_sum, f->l3_csum_delta);
3709               new_icmp_sum = ip_csum_sub_even (new_icmp_sum, f->l4_csum_delta);
3710               new_icmp_sum =
3711                 ip_csum_update (new_icmp_sum, old_inner_ip_sum,
3712                                 inner_ip->checksum, ip4_header_t, checksum);
3713               new_icmp_sum =
3714                 ip_csum_update (new_icmp_sum, old_udp_sum, udp->checksum,
3715                                 udp_header_t, checksum);
3716               new_icmp_sum = ip_csum_fold (new_icmp_sum);
3717               icmp->checksum = new_icmp_sum;
3718               break;
3719             case IP_PROTOCOL_TCP:
3720               tcp = (tcp_header_t *) (inner_ip + 1);
3721               if (!it_fits (vm, b, tcp, sizeof (*tcp)))
3722                 {
3723                   return NAT_ED_TRNSL_ERR_PACKET_TRUNCATED;
3724                 }
3725               old_tcp_sum = tcp->checksum;
3726               nat_6t_flow_ip4_translate (sm, b, inner_ip, f, inner_proto,
3727                                          1 /* is_icmp_inner_ip4 */,
3728                                          0 /* skip_saddr_rewrite */);
3729               new_icmp_sum = ip_csum_sub_even (old_icmp_sum, f->l3_csum_delta);
3730               new_icmp_sum = ip_csum_sub_even (new_icmp_sum, f->l4_csum_delta);
3731               new_icmp_sum =
3732                 ip_csum_update (new_icmp_sum, old_inner_ip_sum,
3733                                 inner_ip->checksum, ip4_header_t, checksum);
3734               new_icmp_sum =
3735                 ip_csum_update (new_icmp_sum, old_tcp_sum, tcp->checksum,
3736                                 tcp_header_t, checksum);
3737               new_icmp_sum = ip_csum_fold (new_icmp_sum);
3738               icmp->checksum = new_icmp_sum;
3739               break;
3740             case IP_PROTOCOL_ICMP:
3741               if (f->ops & NAT_FLOW_OP_ICMP_ID_REWRITE)
3742                 {
3743                   icmp46_header_t *inner_icmp = ip4_next_header (inner_ip);
3744                   if (!it_fits (vm, b, inner_icmp, sizeof (*inner_icmp)))
3745                     {
3746                       return NAT_ED_TRNSL_ERR_PACKET_TRUNCATED;
3747                     }
3748                   icmp_echo_header_t *inner_echo =
3749                     (icmp_echo_header_t *) (inner_icmp + 1);
3750                   if (f->rewrite.icmp_id != inner_echo->identifier)
3751                     {
3752                       ip_csum_t sum = icmp->checksum;
3753                       sum = ip_csum_update (
3754                         sum, inner_echo->identifier, f->rewrite.icmp_id,
3755                         icmp_echo_header_t, identifier /* changed member */);
3756                       icmp->checksum = ip_csum_fold (sum);
3757                       ip_csum_t inner_sum = inner_icmp->checksum;
3758                       inner_sum = ip_csum_update (
3759                         sum, inner_echo->identifier, f->rewrite.icmp_id,
3760                         icmp_echo_header_t, identifier /* changed member */);
3761                       inner_icmp->checksum = ip_csum_fold (inner_sum);
3762                       inner_echo->identifier = f->rewrite.icmp_id;
3763                     }
3764                 }
3765               break;
3766             default:
3767               clib_warning ("unexpected NAT protocol value `%d'", inner_proto);
3768               return NAT_ED_TRNSL_ERR_TRANSLATION_FAILED;
3769             }
3770         }
3771     }
3772
3773   return NAT_ED_TRNSL_ERR_SUCCESS;
3774 }
3775
3776 static_always_inline nat_translation_error_e
3777 nat_6t_flow_buf_translate (vlib_main_t *vm, snat_main_t *sm, vlib_buffer_t *b,
3778                            ip4_header_t *ip, nat_6t_flow_t *f,
3779                            ip_protocol_t proto, int is_output_feature,
3780                            int is_i2o)
3781 {
3782   if (!is_output_feature && f->ops & NAT_FLOW_OP_TXFIB_REWRITE)
3783     {
3784       vnet_buffer (b)->sw_if_index[VLIB_TX] = f->rewrite.fib_index;
3785     }
3786
3787   if (IP_PROTOCOL_ICMP == proto)
3788     {
3789       if (ip->src_address.as_u32 != f->rewrite.saddr.as_u32)
3790         {
3791           // packet is returned from a router, not from destination
3792           // skip source address rewrite if in o2i path
3793           nat_6t_flow_ip4_translate (sm, b, ip, f, proto,
3794                                      0 /* is_icmp_inner_ip4 */,
3795                                      !is_i2o /* skip_saddr_rewrite */);
3796         }
3797       else
3798         {
3799           nat_6t_flow_ip4_translate (sm, b, ip, f, proto,
3800                                      0 /* is_icmp_inner_ip4 */,
3801                                      0 /* skip_saddr_rewrite */);
3802         }
3803       return nat_6t_flow_icmp_translate (vm, sm, b, ip, f);
3804     }
3805
3806   nat_6t_flow_ip4_translate (sm, b, ip, f, proto, 0 /* is_icmp_inner_ip4 */,
3807                              0 /* skip_saddr_rewrite */);
3808
3809   return NAT_ED_TRNSL_ERR_SUCCESS;
3810 }
3811
3812 nat_translation_error_e
3813 nat_6t_flow_buf_translate_i2o (vlib_main_t *vm, snat_main_t *sm,
3814                                vlib_buffer_t *b, ip4_header_t *ip,
3815                                nat_6t_flow_t *f, ip_protocol_t proto,
3816                                int is_output_feature)
3817 {
3818   return nat_6t_flow_buf_translate (vm, sm, b, ip, f, proto, is_output_feature,
3819                                     1 /* is_i2o */);
3820 }
3821
3822 nat_translation_error_e
3823 nat_6t_flow_buf_translate_o2i (vlib_main_t *vm, snat_main_t *sm,
3824                                vlib_buffer_t *b, ip4_header_t *ip,
3825                                nat_6t_flow_t *f, ip_protocol_t proto,
3826                                int is_output_feature)
3827 {
3828   return nat_6t_flow_buf_translate (vm, sm, b, ip, f, proto, is_output_feature,
3829                                     0 /* is_i2o */);
3830 }
3831
3832 u8 *
3833 format_nat_6t (u8 *s, va_list *args)
3834 {
3835   nat_6t_t *t = va_arg (*args, nat_6t_t *);
3836
3837   s = format (s, "saddr %U sport %u daddr %U dport %u proto %U fib_idx %u",
3838               format_ip4_address, t->saddr.as_u8,
3839               clib_net_to_host_u16 (t->sport), format_ip4_address,
3840               t->daddr.as_u8, clib_net_to_host_u16 (t->dport),
3841               format_ip_protocol, t->proto, t->fib_index);
3842   return s;
3843 }
3844
3845 u8 *
3846 format_nat_ed_translation_error (u8 *s, va_list *args)
3847 {
3848   nat_translation_error_e e = va_arg (*args, nat_translation_error_e);
3849
3850   switch (e)
3851     {
3852     case NAT_ED_TRNSL_ERR_SUCCESS:
3853       s = format (s, "success");
3854       break;
3855     case NAT_ED_TRNSL_ERR_TRANSLATION_FAILED:
3856       s = format (s, "translation-failed");
3857       break;
3858     case NAT_ED_TRNSL_ERR_FLOW_MISMATCH:
3859       s = format (s, "flow-mismatch");
3860       break;
3861     case NAT_ED_TRNSL_ERR_PACKET_TRUNCATED:
3862       s = format (s, "packet-truncated");
3863       break;
3864     case NAT_ED_TRNSL_ERR_INNER_IP_CORRUPT:
3865       s = format (s, "inner-ip-corrupted");
3866       break;
3867     case NAT_ED_TRNSL_ERR_INVALID_CSUM:
3868       s = format (s, "invalid-checksum");
3869       break;
3870     }
3871   return s;
3872 }
3873
3874 u8 *
3875 format_nat_6t_flow (u8 *s, va_list *args)
3876 {
3877   nat_6t_flow_t *f = va_arg (*args, nat_6t_flow_t *);
3878
3879   s = format (s, "match: %U ", format_nat_6t, &f->match);
3880   int r = 0;
3881   if (f->ops & NAT_FLOW_OP_SADDR_REWRITE)
3882     {
3883       s = format (s, "rewrite: saddr %U ", format_ip4_address,
3884                   f->rewrite.saddr.as_u8);
3885       r = 1;
3886     }
3887   if (f->ops & NAT_FLOW_OP_SPORT_REWRITE)
3888     {
3889       if (!r)
3890         {
3891           s = format (s, "rewrite: ");
3892           r = 1;
3893         }
3894       s = format (s, "sport %u ", clib_net_to_host_u16 (f->rewrite.sport));
3895     }
3896   if (f->ops & NAT_FLOW_OP_DADDR_REWRITE)
3897     {
3898       if (!r)
3899         {
3900           s = format (s, "rewrite: ");
3901           r = 1;
3902         }
3903       s = format (s, "daddr %U ", format_ip4_address, f->rewrite.daddr.as_u8);
3904     }
3905   if (f->ops & NAT_FLOW_OP_DPORT_REWRITE)
3906     {
3907       if (!r)
3908         {
3909           s = format (s, "rewrite: ");
3910           r = 1;
3911         }
3912       s = format (s, "dport %u ", clib_net_to_host_u16 (f->rewrite.dport));
3913     }
3914   if (f->ops & NAT_FLOW_OP_ICMP_ID_REWRITE)
3915     {
3916       if (!r)
3917         {
3918           s = format (s, "rewrite: ");
3919           r = 1;
3920         }
3921       s = format (s, "icmp-id %u ", clib_net_to_host_u16 (f->rewrite.icmp_id));
3922     }
3923   if (f->ops & NAT_FLOW_OP_TXFIB_REWRITE)
3924     {
3925       if (!r)
3926         {
3927           s = format (s, "rewrite: ");
3928           r = 1;
3929         }
3930       s = format (s, "txfib %u ", f->rewrite.fib_index);
3931     }
3932   return s;
3933 }
3934
3935 static inline void
3936 nat_syslog_nat44_sess (u32 ssubix, u32 sfibix, ip4_address_t *isaddr,
3937                        u16 isport, ip4_address_t *xsaddr, u16 xsport,
3938                        ip4_address_t *idaddr, u16 idport,
3939                        ip4_address_t *xdaddr, u16 xdport, u8 proto, u8 is_add,
3940                        u8 is_twicenat)
3941 {
3942   syslog_msg_t syslog_msg;
3943   fib_table_t *fib;
3944
3945   if (!syslog_is_enabled ())
3946     return;
3947
3948   if (syslog_severity_filter_block (SADD_SDEL_SEVERITY))
3949     return;
3950
3951   fib = fib_table_get (sfibix, FIB_PROTOCOL_IP4);
3952
3953   syslog_msg_init (&syslog_msg, NAT_FACILITY, SADD_SDEL_SEVERITY, NAT_APPNAME,
3954                    is_add ? SADD_MSGID : SDEL_MSGID);
3955
3956   syslog_msg_sd_init (&syslog_msg, NSESS_SDID);
3957   syslog_msg_add_sd_param (&syslog_msg, SSUBIX_SDPARAM_NAME, "%d", ssubix);
3958   syslog_msg_add_sd_param (&syslog_msg, SVLAN_SDPARAM_NAME, "%d",
3959                            fib->ft_table_id);
3960   syslog_msg_add_sd_param (&syslog_msg, IATYP_SDPARAM_NAME, IATYP_IPV4);
3961   syslog_msg_add_sd_param (&syslog_msg, ISADDR_SDPARAM_NAME, "%U",
3962                            format_ip4_address, isaddr);
3963   syslog_msg_add_sd_param (&syslog_msg, ISPORT_SDPARAM_NAME, "%d",
3964                            clib_net_to_host_u16 (isport));
3965   syslog_msg_add_sd_param (&syslog_msg, XATYP_SDPARAM_NAME, IATYP_IPV4);
3966   syslog_msg_add_sd_param (&syslog_msg, XSADDR_SDPARAM_NAME, "%U",
3967                            format_ip4_address, xsaddr);
3968   syslog_msg_add_sd_param (&syslog_msg, XSPORT_SDPARAM_NAME, "%d",
3969                            clib_net_to_host_u16 (xsport));
3970   syslog_msg_add_sd_param (&syslog_msg, PROTO_SDPARAM_NAME, "%d", proto);
3971   syslog_msg_add_sd_param (&syslog_msg, XDADDR_SDPARAM_NAME, "%U",
3972                            format_ip4_address, xdaddr);
3973   syslog_msg_add_sd_param (&syslog_msg, XDPORT_SDPARAM_NAME, "%d",
3974                            clib_net_to_host_u16 (xdport));
3975   if (is_twicenat)
3976     {
3977       syslog_msg_add_sd_param (&syslog_msg, IDADDR_SDPARAM_NAME, "%U",
3978                                format_ip4_address, idaddr);
3979       syslog_msg_add_sd_param (&syslog_msg, IDPORT_SDPARAM_NAME, "%d",
3980                                clib_net_to_host_u16 (idport));
3981     }
3982
3983   syslog_msg_send (&syslog_msg);
3984 }
3985
3986 void
3987 nat_syslog_nat44_sadd (u32 ssubix, u32 sfibix, ip4_address_t *isaddr,
3988                        u16 isport, ip4_address_t *idaddr, u16 idport,
3989                        ip4_address_t *xsaddr, u16 xsport,
3990                        ip4_address_t *xdaddr, u16 xdport, u8 proto,
3991                        u8 is_twicenat)
3992 {
3993   nat_syslog_nat44_sess (ssubix, sfibix, isaddr, isport, xsaddr, xsport,
3994                          idaddr, idport, xdaddr, xdport, proto, 1,
3995                          is_twicenat);
3996 }
3997
3998 void
3999 nat_syslog_nat44_sdel (u32 ssubix, u32 sfibix, ip4_address_t *isaddr,
4000                        u16 isport, ip4_address_t *idaddr, u16 idport,
4001                        ip4_address_t *xsaddr, u16 xsport,
4002                        ip4_address_t *xdaddr, u16 xdport, u8 proto,
4003                        u8 is_twicenat)
4004 {
4005   nat_syslog_nat44_sess (ssubix, sfibix, isaddr, isport, xsaddr, xsport,
4006                          idaddr, idport, xdaddr, xdport, proto, 0,
4007                          is_twicenat);
4008 }
4009
4010 /*
4011  * fd.io coding-style-patch-verification: ON
4012  *
4013  * Local Variables:
4014  * eval: (c-set-style "gnu")
4015  * End:
4016  */