c6783e47b6de0769a80c0051f274fe0e2caedfe4
[vpp.git] / src / plugins / snat / snat.c
1 /*
2  * snat.c - simple nat plugin
3  *
4  * Copyright (c) 2016 Cisco and/or its affiliates.
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <vnet/vnet.h>
19 #include <vnet/ip/ip.h>
20 #include <vnet/ip/ip4.h>
21 #include <vnet/plugin/plugin.h>
22 #include <snat/snat.h>
23 #include <snat/snat_ipfix_logging.h>
24 #include <snat/snat_det.h>
25 #include <vnet/fib/fib_table.h>
26 #include <vnet/fib/ip4_fib.h>
27
28 #include <vlibapi/api.h>
29 #include <vlibmemory/api.h>
30 #include <vlibsocket/api.h>
31 #include <vpp/app/version.h>
32
33 snat_main_t snat_main;
34
35 /* define message IDs */
36 #include <snat/snat_msg_enum.h>
37
38 /* define message structures */
39 #define vl_typedefs
40 #include <snat/snat_all_api_h.h> 
41 #undef vl_typedefs
42
43 /* define generated endian-swappers */
44 #define vl_endianfun
45 #include <snat/snat_all_api_h.h> 
46 #undef vl_endianfun
47
48 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
49
50 #define REPLY_MSG_ID_BASE sm->msg_id_base
51 #include <vlibapi/api_helper_macros.h>
52
53 /* Get the API version number */
54 #define vl_api_version(n,v) static u32 api_version=(v);
55 #include <snat/snat_all_api_h.h>
56 #undef vl_api_version
57
58 /* Macro to finish up custom dump fns */
59 #define FINISH                                  \
60     vec_add1 (s, 0);                            \
61     vl_print (handle, (char *)s);               \
62     vec_free (s);                               \
63     return handle;
64
65 /* Hook up input features */
66 VNET_FEATURE_INIT (ip4_snat_in2out, static) = {
67   .arc_name = "ip4-unicast",
68   .node_name = "snat-in2out",
69   .runs_before = VNET_FEATURES ("snat-out2in"),
70 };
71 VNET_FEATURE_INIT (ip4_snat_out2in, static) = {
72   .arc_name = "ip4-unicast",
73   .node_name = "snat-out2in",
74   .runs_before = VNET_FEATURES ("ip4-lookup"),
75 };
76 VNET_FEATURE_INIT (ip4_snat_det_in2out, static) = {
77   .arc_name = "ip4-unicast",
78   .node_name = "snat-det-in2out",
79   .runs_before = VNET_FEATURES ("snat-det-out2in"),
80 };
81 VNET_FEATURE_INIT (ip4_snat_det_out2in, static) = {
82   .arc_name = "ip4-unicast",
83   .node_name = "snat-det-out2in",
84   .runs_before = VNET_FEATURES ("ip4-lookup"),
85 };
86 VNET_FEATURE_INIT (ip4_snat_in2out_worker_handoff, static) = {
87   .arc_name = "ip4-unicast",
88   .node_name = "snat-in2out-worker-handoff",
89   .runs_before = VNET_FEATURES ("snat-out2in-worker-handoff"),
90 };
91 VNET_FEATURE_INIT (ip4_snat_out2in_worker_handoff, static) = {
92   .arc_name = "ip4-unicast",
93   .node_name = "snat-out2in-worker-handoff",
94   .runs_before = VNET_FEATURES ("ip4-lookup"),
95 };
96 VNET_FEATURE_INIT (ip4_snat_in2out_fast, static) = {
97   .arc_name = "ip4-unicast",
98   .node_name = "snat-in2out-fast",
99   .runs_before = VNET_FEATURES ("snat-out2in-fast"),
100 };
101 VNET_FEATURE_INIT (ip4_snat_out2in_fast, static) = {
102   .arc_name = "ip4-unicast",
103   .node_name = "snat-out2in-fast",
104   .runs_before = VNET_FEATURES ("ip4-lookup"),
105 };
106
107 /* *INDENT-OFF* */
108 VLIB_PLUGIN_REGISTER () = {
109     .version = VPP_BUILD_VER,
110     .description = "Network Address Translation",
111 };
112 /* *INDENT-ON* */
113
114 /**
115  * @brief Add/del NAT address to FIB.
116  *
117  * Add the external NAT address to the FIB as receive entries. This ensures
118  * that VPP will reply to ARP for this address and we don't need to enable
119  * proxy ARP on the outside interface.
120  *
121  * @param addr IPv4 address.
122  * @param plen address prefix length
123  * @param sw_if_index Interface.
124  * @param is_add If 0 delete, otherwise add.
125  */
126 void
127 snat_add_del_addr_to_fib (ip4_address_t * addr, u8 p_len, u32 sw_if_index,
128                           int is_add)
129 {
130   fib_prefix_t prefix = {
131     .fp_len = p_len,
132     .fp_proto = FIB_PROTOCOL_IP4,
133     .fp_addr = {
134         .ip4.as_u32 = addr->as_u32,
135     },
136   };
137   u32 fib_index = ip4_fib_table_get_index_for_sw_if_index(sw_if_index);
138
139   if (is_add)
140     fib_table_entry_update_one_path(fib_index,
141                                     &prefix,
142                                     FIB_SOURCE_PLUGIN_HI,
143                                     (FIB_ENTRY_FLAG_CONNECTED |
144                                      FIB_ENTRY_FLAG_LOCAL |
145                                      FIB_ENTRY_FLAG_EXCLUSIVE),
146                                     FIB_PROTOCOL_IP4,
147                                     NULL,
148                                     sw_if_index,
149                                     ~0,
150                                     1,
151                                     NULL,
152                                     FIB_ROUTE_PATH_FLAG_NONE);
153   else
154     fib_table_entry_delete(fib_index,
155                            &prefix,
156                            FIB_SOURCE_PLUGIN_HI);
157 }
158
159 void snat_add_address (snat_main_t *sm, ip4_address_t *addr, u32 vrf_id)
160 {
161   snat_address_t * ap;
162   snat_interface_t *i;
163
164   if (vrf_id != ~0)
165     sm->vrf_mode = 1;
166
167   /* Check if address already exists */
168   vec_foreach (ap, sm->addresses)
169     {
170       if (ap->addr.as_u32 == addr->as_u32)
171         return;
172     }
173
174   vec_add2 (sm->addresses, ap, 1);
175   ap->addr = *addr;
176   ap->fib_index = ip4_fib_index_from_table_id(vrf_id);
177 #define _(N, i, n, s) \
178   clib_bitmap_alloc (ap->busy_##n##_port_bitmap, 65535);
179   foreach_snat_protocol
180 #undef _
181
182   /* Add external address to FIB */
183   pool_foreach (i, sm->interfaces,
184   ({
185     if (i->is_inside)
186       continue;
187
188     snat_add_del_addr_to_fib(addr, 32, i->sw_if_index, 1);
189     break;
190   }));
191 }
192
193 static int is_snat_address_used_in_static_mapping (snat_main_t *sm,
194                                                    ip4_address_t addr)
195 {
196   snat_static_mapping_t *m;
197   pool_foreach (m, sm->static_mappings,
198   ({
199       if (m->external_addr.as_u32 == addr.as_u32)
200         return 1;
201   }));
202
203   return 0;
204 }
205
206 static void increment_v4_address (ip4_address_t * a)
207 {
208   u32 v;
209   
210   v = clib_net_to_host_u32(a->as_u32) + 1;
211   a->as_u32 = clib_host_to_net_u32(v);
212 }
213
214 static void 
215 snat_add_static_mapping_when_resolved (snat_main_t * sm, 
216                                        ip4_address_t l_addr, 
217                                        u16 l_port, 
218                                        u32 sw_if_index, 
219                                        u16 e_port, 
220                                        u32 vrf_id,
221                                        snat_protocol_t proto,
222                                        int addr_only,  
223                                        int is_add)
224 {
225   snat_static_map_resolve_t *rp;
226
227   vec_add2 (sm->to_resolve, rp, 1);
228   rp->l_addr.as_u32 = l_addr.as_u32;
229   rp->l_port = l_port;
230   rp->sw_if_index = sw_if_index;
231   rp->e_port = e_port;
232   rp->vrf_id = vrf_id;
233   rp->proto = proto;
234   rp->addr_only = addr_only;
235   rp->is_add = is_add;
236 }
237
238 /**
239  * @brief Add static mapping.
240  *
241  * Create static mapping between local addr+port and external addr+port.
242  *
243  * @param l_addr Local IPv4 address.
244  * @param e_addr External IPv4 address.
245  * @param l_port Local port number.
246  * @param e_port External port number.
247  * @param vrf_id VRF ID.
248  * @param addr_only If 0 address port and pair mapping, otherwise address only.
249  * @param sw_if_index External port instead of specific IP address.
250  * @param is_add If 0 delete static mapping, otherwise add.
251  *
252  * @returns
253  */
254 int snat_add_static_mapping(ip4_address_t l_addr, ip4_address_t e_addr,
255                             u16 l_port, u16 e_port, u32 vrf_id, int addr_only,
256                             u32 sw_if_index, snat_protocol_t proto, int is_add)
257 {
258   snat_main_t * sm = &snat_main;
259   snat_static_mapping_t *m;
260   snat_session_key_t m_key;
261   clib_bihash_kv_8_8_t kv, value;
262   snat_address_t *a = 0;
263   u32 fib_index = ~0;
264   uword * p;
265   snat_interface_t *interface;
266   int i;
267
268   /* If the external address is a specific interface address */
269   if (sw_if_index != ~0)
270     {
271       ip4_address_t * first_int_addr;
272
273       /* Might be already set... */
274       first_int_addr = ip4_interface_first_address 
275         (sm->ip4_main, sw_if_index, 0 /* just want the address*/);
276
277       /* DHCP resolution required? */
278       if (first_int_addr == 0)
279         {
280           snat_add_static_mapping_when_resolved 
281             (sm, l_addr, l_port, sw_if_index, e_port, vrf_id, proto,
282              addr_only,  is_add);
283           return 0;
284         }
285         else
286           e_addr.as_u32 = first_int_addr->as_u32;
287     }
288
289   m_key.addr = e_addr;
290   m_key.port = addr_only ? 0 : e_port;
291   m_key.protocol = addr_only ? 0 : proto;
292   m_key.fib_index = sm->outside_fib_index;
293   kv.key = m_key.as_u64;
294   if (clib_bihash_search_8_8 (&sm->static_mapping_by_external, &kv, &value))
295     m = 0;
296   else
297     m = pool_elt_at_index (sm->static_mappings, value.value);
298
299   if (is_add)
300     {
301       if (m)
302         return VNET_API_ERROR_VALUE_EXIST;
303
304       /* Convert VRF id to FIB index */
305       if (vrf_id != ~0)
306         {
307           p = hash_get (sm->ip4_main->fib_index_by_table_id, vrf_id);
308           if (!p)
309             return VNET_API_ERROR_NO_SUCH_FIB;
310           fib_index = p[0];
311         }
312       /* If not specified use inside VRF id from SNAT plugin startup config */
313       else
314         {
315           fib_index = sm->inside_fib_index;
316           vrf_id = sm->inside_vrf_id;
317         }
318
319       /* Find external address in allocated addresses and reserve port for
320          address and port pair mapping when dynamic translations enabled */
321       if (!addr_only && !(sm->static_mapping_only))
322         {
323           for (i = 0; i < vec_len (sm->addresses); i++)
324             {
325               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
326                 {
327                   a = sm->addresses + i;
328                   /* External port must be unused */
329                   switch (proto)
330                     {
331 #define _(N, j, n, s) \
332                     case SNAT_PROTOCOL_##N: \
333                       if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, e_port)) \
334                         return VNET_API_ERROR_INVALID_VALUE; \
335                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 1); \
336                       if (e_port > 1024) \
337                         a->busy_##n##_ports++; \
338                       break;
339                       foreach_snat_protocol
340 #undef _
341                     default:
342                       clib_warning("unknown_protocol");
343                       return VNET_API_ERROR_INVALID_VALUE_2;
344                     }
345                   break;
346                 }
347             }
348           /* External address must be allocated */
349           if (!a)
350             return VNET_API_ERROR_NO_SUCH_ENTRY;
351         }
352
353       pool_get (sm->static_mappings, m);
354       memset (m, 0, sizeof (*m));
355       m->local_addr = l_addr;
356       m->external_addr = e_addr;
357       m->addr_only = addr_only;
358       m->vrf_id = vrf_id;
359       m->fib_index = fib_index;
360       if (!addr_only)
361         {
362           m->local_port = l_port;
363           m->external_port = e_port;
364           m->proto = proto;
365         }
366
367       m_key.addr = m->local_addr;
368       m_key.port = m->local_port;
369       m_key.protocol = m->proto;
370       m_key.fib_index = m->fib_index;
371       kv.key = m_key.as_u64;
372       kv.value = m - sm->static_mappings;
373       clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 1);
374
375       m_key.addr = m->external_addr;
376       m_key.port = m->external_port;
377       m_key.fib_index = sm->outside_fib_index;
378       kv.key = m_key.as_u64;
379       kv.value = m - sm->static_mappings;
380       clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 1);
381
382       /* Assign worker */
383       if (sm->workers)
384         {
385           snat_user_key_t w_key0;
386           snat_worker_key_t w_key1;
387
388           w_key0.addr = m->local_addr;
389           w_key0.fib_index = m->fib_index;
390           kv.key = w_key0.as_u64;
391
392           if (clib_bihash_search_8_8 (&sm->worker_by_in, &kv, &value))
393             {
394               kv.value = sm->first_worker_index +
395                 sm->workers[sm->next_worker++ % vec_len (sm->workers)];
396
397               clib_bihash_add_del_8_8 (&sm->worker_by_in, &kv, 1);
398             }
399           else
400             {
401               kv.value = value.value;
402             }
403
404           w_key1.addr = m->external_addr;
405           w_key1.port = clib_host_to_net_u16 (m->external_port);
406           w_key1.fib_index = sm->outside_fib_index;
407           kv.key = w_key1.as_u64;
408           clib_bihash_add_del_8_8 (&sm->worker_by_out, &kv, 1);
409         }
410     }
411   else
412     {
413       if (!m)
414         return VNET_API_ERROR_NO_SUCH_ENTRY;
415
416       /* Free external address port */
417       if (!addr_only && !(sm->static_mapping_only))
418         {
419           for (i = 0; i < vec_len (sm->addresses); i++)
420             {
421               if (sm->addresses[i].addr.as_u32 == e_addr.as_u32)
422                 {
423                   a = sm->addresses + i;
424                   switch (proto)
425                     {
426 #define _(N, j, n, s) \
427                     case SNAT_PROTOCOL_##N: \
428                       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, e_port, 0); \
429                       if (e_port > 1024) \
430                         a->busy_##n##_ports--; \
431                       break;
432                       foreach_snat_protocol
433 #undef _
434                     default:
435                       clib_warning("unknown_protocol");
436                       return VNET_API_ERROR_INVALID_VALUE_2;
437                     }
438                   break;
439                 }
440             }
441         }
442
443       m_key.addr = m->local_addr;
444       m_key.port = m->local_port;
445       m_key.protocol = m->proto;
446       m_key.fib_index = m->fib_index;
447       kv.key = m_key.as_u64;
448       clib_bihash_add_del_8_8(&sm->static_mapping_by_local, &kv, 0);
449
450       m_key.addr = m->external_addr;
451       m_key.port = m->external_port;
452       m_key.fib_index = sm->outside_fib_index;
453       kv.key = m_key.as_u64;
454       clib_bihash_add_del_8_8(&sm->static_mapping_by_external, &kv, 0);
455
456       /* Delete session(s) for static mapping if exist */
457       if (!(sm->static_mapping_only) ||
458           (sm->static_mapping_only && sm->static_mapping_connection_tracking))
459         {
460           snat_user_key_t u_key;
461           snat_user_t *u;
462           dlist_elt_t * head, * elt;
463           u32 elt_index, head_index, del_elt_index;
464           u32 ses_index;
465           u64 user_index;
466           snat_session_t * s;
467           snat_main_per_thread_data_t *tsm;
468
469           u_key.addr = m->local_addr;
470           u_key.fib_index = m->fib_index;
471           kv.key = u_key.as_u64;
472           if (!clib_bihash_search_8_8 (&sm->user_hash, &kv, &value))
473             {
474               user_index = value.value;
475               if (!clib_bihash_search_8_8 (&sm->worker_by_in, &kv, &value))
476                 tsm = vec_elt_at_index (sm->per_thread_data, value.value);
477               else
478                 tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
479               u = pool_elt_at_index (tsm->users, user_index);
480               if (u->nstaticsessions)
481                 {
482                   head_index = u->sessions_per_user_list_head_index;
483                   head = pool_elt_at_index (tsm->list_pool, head_index);
484                   elt_index = head->next;
485                   elt = pool_elt_at_index (tsm->list_pool, elt_index);
486                   ses_index = elt->value;
487                   while (ses_index != ~0)
488                     {
489                       s =  pool_elt_at_index (tsm->sessions, ses_index);
490                       del_elt_index = elt_index;
491                       elt_index = elt->next;
492                       elt = pool_elt_at_index (tsm->list_pool, elt_index);
493                       ses_index = elt->value;
494
495                       if (!addr_only)
496                         {
497                           if ((s->out2in.addr.as_u32 != e_addr.as_u32) &&
498                               (clib_net_to_host_u16 (s->out2in.port) != e_port))
499                             continue;
500                         }
501
502                       /* log NAT event */
503                       snat_ipfix_logging_nat44_ses_delete(s->in2out.addr.as_u32,
504                                                           s->out2in.addr.as_u32,
505                                                           s->in2out.protocol,
506                                                           s->in2out.port,
507                                                           s->out2in.port,
508                                                           s->in2out.fib_index);
509
510                       value.key = s->in2out.as_u64;
511                       clib_bihash_add_del_8_8 (&sm->in2out, &value, 0);
512                       value.key = s->out2in.as_u64;
513                       clib_bihash_add_del_8_8 (&sm->out2in, &value, 0);
514                       pool_put (tsm->sessions, s);
515
516                       clib_dlist_remove (tsm->list_pool, del_elt_index);
517                       pool_put_index (tsm->list_pool, del_elt_index);
518                       u->nstaticsessions--;
519
520                       if (!addr_only)
521                         break;
522                     }
523                   if (addr_only)
524                     {
525                       pool_put (tsm->users, u);
526                       clib_bihash_add_del_8_8 (&sm->user_hash, &kv, 0);
527                     }
528                 }
529             }
530         }
531
532       /* Delete static mapping from pool */
533       pool_put (sm->static_mappings, m);
534     }
535
536   if (!addr_only)
537     return 0;
538
539   /* Add/delete external address to FIB */
540   pool_foreach (interface, sm->interfaces,
541   ({
542     if (interface->is_inside)
543       continue;
544
545     snat_add_del_addr_to_fib(&e_addr, 32, interface->sw_if_index, is_add);
546     break;
547   }));
548
549   return 0;
550 }
551
552 int snat_del_address (snat_main_t *sm, ip4_address_t addr, u8 delete_sm)
553 {
554   snat_address_t *a = 0;
555   snat_session_t *ses;
556   u32 *ses_to_be_removed = 0, *ses_index;
557   clib_bihash_kv_8_8_t kv, value;
558   snat_user_key_t user_key;
559   snat_user_t *u;
560   snat_main_per_thread_data_t *tsm;
561   snat_static_mapping_t *m;
562   snat_interface_t *interface;
563   int i;
564
565   /* Find SNAT address */
566   for (i=0; i < vec_len (sm->addresses); i++)
567     {
568       if (sm->addresses[i].addr.as_u32 == addr.as_u32)
569         {
570           a = sm->addresses + i;
571           break;
572         }
573     }
574   if (!a)
575     return VNET_API_ERROR_NO_SUCH_ENTRY;
576
577   if (delete_sm)
578     {
579       pool_foreach (m, sm->static_mappings,
580       ({
581           if (m->external_addr.as_u32 == addr.as_u32)
582             (void) snat_add_static_mapping (m->local_addr, m->external_addr,
583                                             m->local_port, m->external_port,
584                                             m->vrf_id, m->addr_only, ~0,
585                                             m->proto, 0);
586       }));
587     }
588   else
589     {
590       /* Check if address is used in some static mapping */
591       if (is_snat_address_used_in_static_mapping(sm, addr))
592         {
593           clib_warning ("address used in static mapping");
594           return VNET_API_ERROR_UNSPECIFIED;
595         }
596     }
597
598   /* Delete sessions using address */
599   if (a->busy_tcp_ports || a->busy_udp_ports || a->busy_icmp_ports)
600     {
601       vec_foreach (tsm, sm->per_thread_data)
602         {
603           pool_foreach (ses, tsm->sessions, ({
604             if (ses->out2in.addr.as_u32 == addr.as_u32)
605               {
606                 /* log NAT event */
607                 snat_ipfix_logging_nat44_ses_delete(ses->in2out.addr.as_u32,
608                                                     ses->out2in.addr.as_u32,
609                                                     ses->in2out.protocol,
610                                                     ses->in2out.port,
611                                                     ses->out2in.port,
612                                                     ses->in2out.fib_index);
613                 vec_add1 (ses_to_be_removed, ses - tsm->sessions);
614                 kv.key = ses->in2out.as_u64;
615                 clib_bihash_add_del_8_8 (&sm->in2out, &kv, 0);
616                 kv.key = ses->out2in.as_u64;
617                 clib_bihash_add_del_8_8 (&sm->out2in, &kv, 0);
618                 clib_dlist_remove (tsm->list_pool, ses->per_user_index);
619                 user_key.addr = ses->in2out.addr;
620                 user_key.fib_index = ses->in2out.fib_index;
621                 kv.key = user_key.as_u64;
622                 if (!clib_bihash_search_8_8 (&sm->user_hash, &kv, &value))
623                   {
624                     u = pool_elt_at_index (tsm->users, value.value);
625                     u->nsessions--;
626                   }
627               }
628           }));
629
630           vec_foreach (ses_index, ses_to_be_removed)
631             pool_put_index (tsm->sessions, ses_index[0]);
632
633           vec_free (ses_to_be_removed);
634        }
635     }
636
637   vec_del1 (sm->addresses, i);
638
639   /* Delete external address from FIB */
640   pool_foreach (interface, sm->interfaces,
641   ({
642     if (interface->is_inside)
643       continue;
644
645     snat_add_del_addr_to_fib(&addr, 32, interface->sw_if_index, 0);
646     break;
647   }));
648
649   return 0;
650 }
651
652 static int snat_interface_add_del (u32 sw_if_index, u8 is_inside, int is_del)
653 {
654   snat_main_t *sm = &snat_main;
655   snat_interface_t *i;
656   const char * feature_name;
657   snat_address_t * ap;
658   snat_static_mapping_t * m;
659   snat_det_map_t * dm;
660
661   if (sm->static_mapping_only && !(sm->static_mapping_connection_tracking))
662     feature_name = is_inside ?  "snat-in2out-fast" : "snat-out2in-fast";
663   else
664     {
665       if (sm->num_workers > 1 && !sm->deterministic)
666         feature_name = is_inside ?  "snat-in2out-worker-handoff" : "snat-out2in-worker-handoff";
667       else if (sm->deterministic)
668         feature_name = is_inside ?  "snat-det-in2out" : "snat-det-out2in";
669       else
670         feature_name = is_inside ?  "snat-in2out" : "snat-out2in";
671     }
672
673   vnet_feature_enable_disable ("ip4-unicast", feature_name, sw_if_index,
674                                !is_del, 0, 0);
675
676   if (sm->fq_in2out_index == ~0 && !sm->deterministic && sm->num_workers > 1)
677     sm->fq_in2out_index = vlib_frame_queue_main_init (sm->in2out_node_index, 0);
678
679   if (sm->fq_out2in_index == ~0 && !sm->deterministic && sm->num_workers > 1)
680     sm->fq_out2in_index = vlib_frame_queue_main_init (sm->out2in_node_index, 0);
681
682   pool_foreach (i, sm->interfaces,
683   ({
684     if (i->sw_if_index == sw_if_index)
685       {
686         if (is_del)
687           pool_put (sm->interfaces, i);
688         else
689           return VNET_API_ERROR_VALUE_EXIST;
690
691         goto fib;
692       }
693   }));
694
695   if (is_del)
696     return VNET_API_ERROR_NO_SUCH_ENTRY;
697
698   pool_get (sm->interfaces, i);
699   i->sw_if_index = sw_if_index;
700   i->is_inside = is_inside;
701
702   /* Add/delete external addresses to FIB */
703 fib:
704   if (is_inside)
705     return 0;
706
707   vec_foreach (ap, sm->addresses)
708     snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, !is_del);
709
710   pool_foreach (m, sm->static_mappings,
711   ({
712     if (!(m->addr_only))
713       continue;
714
715     snat_add_del_addr_to_fib(&m->external_addr, 32, sw_if_index, !is_del);
716   }));
717
718   pool_foreach (dm, sm->det_maps,
719   ({
720     snat_add_del_addr_to_fib(&dm->out_addr, dm->out_plen, sw_if_index, !is_del);
721   }));
722
723   return 0;
724 }
725
726 static int snat_set_workers (uword * bitmap)
727 {
728   snat_main_t *sm = &snat_main;
729   int i;
730
731   if (sm->num_workers < 2)
732     return VNET_API_ERROR_FEATURE_DISABLED;
733
734   if (clib_bitmap_last_set (bitmap) >= sm->num_workers)
735     return VNET_API_ERROR_INVALID_WORKER;
736
737   vec_free (sm->workers);
738   clib_bitmap_foreach (i, bitmap,
739     ({
740       vec_add1(sm->workers, i);
741     }));
742
743   return 0;
744 }
745
746 static void 
747 vl_api_snat_add_address_range_t_handler
748 (vl_api_snat_add_address_range_t * mp)
749 {
750   snat_main_t * sm = &snat_main;
751   vl_api_snat_add_address_range_reply_t * rmp;
752   ip4_address_t this_addr;
753   u32 start_host_order, end_host_order;
754   u32 vrf_id;
755   int i, count;
756   int rv = 0;
757   u32 * tmp;
758
759   if (mp->is_ip4 != 1)
760     {
761       rv = VNET_API_ERROR_UNIMPLEMENTED;
762       goto send_reply;
763     }
764
765   if (sm->static_mapping_only)
766     {
767       rv = VNET_API_ERROR_FEATURE_DISABLED;
768       goto send_reply;
769     }
770
771   tmp = (u32 *) mp->first_ip_address;
772   start_host_order = clib_host_to_net_u32 (tmp[0]);
773   tmp = (u32 *) mp->last_ip_address;
774   end_host_order = clib_host_to_net_u32 (tmp[0]);
775
776   count = (end_host_order - start_host_order) + 1;
777
778   vrf_id = clib_host_to_net_u32 (mp->vrf_id);
779
780   if (count > 1024)
781     clib_warning ("%U - %U, %d addresses...",
782                   format_ip4_address, mp->first_ip_address,
783                   format_ip4_address, mp->last_ip_address,
784                   count);
785   
786   memcpy (&this_addr.as_u8, mp->first_ip_address, 4);
787
788   for (i = 0; i < count; i++)
789     {
790       if (mp->is_add)
791         snat_add_address (sm, &this_addr, vrf_id);
792       else
793         rv = snat_del_address (sm, this_addr, 0);
794
795       if (rv)
796         goto send_reply;
797
798       increment_v4_address (&this_addr);
799     }
800
801  send_reply:
802   REPLY_MACRO (VL_API_SNAT_ADD_ADDRESS_RANGE_REPLY);
803 }
804
805 static void *vl_api_snat_add_address_range_t_print
806 (vl_api_snat_add_address_range_t *mp, void * handle)
807 {
808   u8 * s;
809
810   s = format (0, "SCRIPT: snat_add_address_range ");
811   s = format (s, "%U ", format_ip4_address, mp->first_ip_address);
812   if (memcmp (mp->first_ip_address, mp->last_ip_address, 4))
813     {
814       s = format (s, " - %U ", format_ip4_address, mp->last_ip_address);
815     }
816   FINISH;
817 }
818
819 static void
820 send_snat_address_details
821 (snat_address_t * a, unix_shared_memory_queue_t * q, u32 context)
822 {
823   vl_api_snat_address_details_t *rmp;
824   snat_main_t * sm = &snat_main;
825
826   rmp = vl_msg_api_alloc (sizeof (*rmp));
827   memset (rmp, 0, sizeof (*rmp));
828   rmp->_vl_msg_id = ntohs (VL_API_SNAT_ADDRESS_DETAILS+sm->msg_id_base);
829   rmp->is_ip4 = 1;
830   clib_memcpy (rmp->ip_address, &(a->addr), 4);
831   if (a->fib_index != ~0)
832     rmp->vrf_id = ntohl(ip4_fib_get(a->fib_index)->table_id);
833   else
834     rmp->vrf_id = ~0;
835   rmp->context = context;
836
837   vl_msg_api_send_shmem (q, (u8 *) & rmp);
838 }
839
840 static void
841 vl_api_snat_address_dump_t_handler
842 (vl_api_snat_address_dump_t * mp)
843 {
844   unix_shared_memory_queue_t *q;
845   snat_main_t * sm = &snat_main;
846   snat_address_t * a;
847
848   q = vl_api_client_index_to_input_queue (mp->client_index);
849   if (q == 0)
850     return;
851
852   vec_foreach (a, sm->addresses)
853     send_snat_address_details (a, q, mp->context);
854 }
855
856 static void *vl_api_snat_address_dump_t_print
857 (vl_api_snat_address_dump_t *mp, void * handle)
858 {
859   u8 *s;
860
861   s = format (0, "SCRIPT: snat_address_dump ");
862
863   FINISH;
864 }
865
866 static void
867 vl_api_snat_interface_add_del_feature_t_handler
868 (vl_api_snat_interface_add_del_feature_t * mp)
869 {
870   snat_main_t * sm = &snat_main;
871   vl_api_snat_interface_add_del_feature_reply_t * rmp;
872   u8 is_del = mp->is_add == 0;
873   u32 sw_if_index = ntohl(mp->sw_if_index);
874   int rv = 0;
875
876   VALIDATE_SW_IF_INDEX(mp);
877
878   rv = snat_interface_add_del (sw_if_index, mp->is_inside, is_del);
879   
880   BAD_SW_IF_INDEX_LABEL;
881
882   REPLY_MACRO(VL_API_SNAT_INTERFACE_ADD_DEL_FEATURE_REPLY);
883 }
884
885 static void *vl_api_snat_interface_add_del_feature_t_print
886 (vl_api_snat_interface_add_del_feature_t * mp, void *handle)
887 {
888   u8 * s;
889
890   s = format (0, "SCRIPT: snat_interface_add_del_feature ");
891   s = format (s, "sw_if_index %d %s %s",
892               clib_host_to_net_u32(mp->sw_if_index),
893               mp->is_inside ? "in":"out",
894               mp->is_add ? "" : "del");
895
896   FINISH;
897 }
898
899 static void
900 send_snat_interface_details
901 (snat_interface_t * i, unix_shared_memory_queue_t * q, u32 context)
902 {
903   vl_api_snat_interface_details_t *rmp;
904   snat_main_t * sm = &snat_main;
905
906   rmp = vl_msg_api_alloc (sizeof (*rmp));
907   memset (rmp, 0, sizeof (*rmp));
908   rmp->_vl_msg_id = ntohs (VL_API_SNAT_INTERFACE_DETAILS+sm->msg_id_base);
909   rmp->sw_if_index = ntohl (i->sw_if_index);
910   rmp->is_inside = i->is_inside;
911   rmp->context = context;
912
913   vl_msg_api_send_shmem (q, (u8 *) & rmp);
914 }
915
916 static void
917 vl_api_snat_interface_dump_t_handler
918 (vl_api_snat_interface_dump_t * mp)
919 {
920   unix_shared_memory_queue_t *q;
921   snat_main_t * sm = &snat_main;
922   snat_interface_t * i;
923
924   q = vl_api_client_index_to_input_queue (mp->client_index);
925   if (q == 0)
926     return;
927
928   pool_foreach (i, sm->interfaces,
929   ({
930     send_snat_interface_details(i, q, mp->context);
931   }));
932 }
933
934 static void *vl_api_snat_interface_dump_t_print
935 (vl_api_snat_interface_dump_t *mp, void * handle)
936 {
937   u8 *s;
938
939   s = format (0, "SCRIPT: snat_interface_dump ");
940
941   FINISH;
942 }static void
943
944 vl_api_snat_add_static_mapping_t_handler
945 (vl_api_snat_add_static_mapping_t * mp)
946 {
947   snat_main_t * sm = &snat_main;
948   vl_api_snat_add_static_mapping_reply_t * rmp;
949   ip4_address_t local_addr, external_addr;
950   u16 local_port = 0, external_port = 0;
951   u32 vrf_id, external_sw_if_index;
952   int rv = 0;
953   snat_protocol_t proto;
954
955   if (mp->is_ip4 != 1)
956     {
957       rv = VNET_API_ERROR_UNIMPLEMENTED;
958       goto send_reply;
959     }
960
961   memcpy (&local_addr.as_u8, mp->local_ip_address, 4);
962   memcpy (&external_addr.as_u8, mp->external_ip_address, 4);
963   if (mp->addr_only == 0)
964     {
965       local_port = clib_net_to_host_u16 (mp->local_port);
966       external_port = clib_net_to_host_u16 (mp->external_port);
967     }
968   vrf_id = clib_net_to_host_u32 (mp->vrf_id);
969   external_sw_if_index = clib_net_to_host_u32 (mp->external_sw_if_index);
970   proto = ip_proto_to_snat_proto (mp->protocol);
971
972   rv = snat_add_static_mapping(local_addr, external_addr, local_port,
973                                external_port, vrf_id, mp->addr_only,
974                                external_sw_if_index, proto, mp->is_add);
975
976  send_reply:
977   REPLY_MACRO (VL_API_SNAT_ADD_ADDRESS_RANGE_REPLY);
978 }
979
980 static void *vl_api_snat_add_static_mapping_t_print
981 (vl_api_snat_add_static_mapping_t *mp, void * handle)
982 {
983   u8 * s;
984
985   s = format (0, "SCRIPT: snat_add_static_mapping ");
986   s = format (s, "protocol %d local_addr %U external_addr %U ",
987               mp->protocol,
988               format_ip4_address, mp->local_ip_address,
989               format_ip4_address, mp->external_ip_address);
990
991   if (mp->addr_only == 0)
992     s = format (s, "local_port %d external_port %d ",
993                 clib_net_to_host_u16 (mp->local_port),
994                 clib_net_to_host_u16 (mp->external_port));
995
996   if (mp->vrf_id != ~0)
997     s = format (s, "vrf %d", clib_net_to_host_u32 (mp->vrf_id));
998
999   if (mp->external_sw_if_index != ~0)
1000     s = format (s, "external_sw_if_index %d",
1001                 clib_net_to_host_u32 (mp->external_sw_if_index));
1002   FINISH;
1003 }
1004
1005 static void
1006 send_snat_static_mapping_details
1007 (snat_static_mapping_t * m, unix_shared_memory_queue_t * q, u32 context)
1008 {
1009   vl_api_snat_static_mapping_details_t *rmp;
1010   snat_main_t * sm = &snat_main;
1011
1012   rmp = vl_msg_api_alloc (sizeof (*rmp));
1013   memset (rmp, 0, sizeof (*rmp));
1014   rmp->_vl_msg_id = ntohs (VL_API_SNAT_STATIC_MAPPING_DETAILS+sm->msg_id_base);
1015   rmp->is_ip4 = 1;
1016   rmp->addr_only = m->addr_only;
1017   clib_memcpy (rmp->local_ip_address, &(m->local_addr), 4);
1018   clib_memcpy (rmp->external_ip_address, &(m->external_addr), 4);
1019   rmp->local_port = htons (m->local_port);
1020   rmp->external_port = htons (m->external_port);
1021   rmp->external_sw_if_index = ~0; 
1022   rmp->vrf_id = htonl (m->vrf_id);
1023   rmp->protocol = snat_proto_to_ip_proto (m->proto);
1024   rmp->context = context;
1025
1026   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1027 }
1028
1029 static void
1030 send_snat_static_map_resolve_details
1031 (snat_static_map_resolve_t * m, unix_shared_memory_queue_t * q, u32 context)
1032 {
1033   vl_api_snat_static_mapping_details_t *rmp;
1034   snat_main_t * sm = &snat_main;
1035
1036   rmp = vl_msg_api_alloc (sizeof (*rmp));
1037   memset (rmp, 0, sizeof (*rmp));
1038   rmp->_vl_msg_id = ntohs (VL_API_SNAT_STATIC_MAPPING_DETAILS+sm->msg_id_base);
1039   rmp->is_ip4 = 1;
1040   rmp->addr_only = m->addr_only;
1041   clib_memcpy (rmp->local_ip_address, &(m->l_addr), 4);
1042   rmp->local_port = htons (m->l_port);
1043   rmp->external_port = htons (m->e_port);
1044   rmp->external_sw_if_index = htonl (m->sw_if_index); 
1045   rmp->vrf_id = htonl (m->vrf_id);
1046   rmp->protocol = snat_proto_to_ip_proto (m->proto);
1047   rmp->context = context;
1048
1049   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1050 }
1051
1052 static void
1053 vl_api_snat_static_mapping_dump_t_handler
1054 (vl_api_snat_static_mapping_dump_t * mp)
1055 {
1056   unix_shared_memory_queue_t *q;
1057   snat_main_t * sm = &snat_main;
1058   snat_static_mapping_t * m;
1059   snat_static_map_resolve_t *rp;
1060   int j;
1061
1062   q = vl_api_client_index_to_input_queue (mp->client_index);
1063   if (q == 0)
1064     return;
1065
1066   pool_foreach (m, sm->static_mappings,
1067   ({
1068       send_snat_static_mapping_details (m, q, mp->context);
1069   }));
1070
1071   for (j = 0; j < vec_len (sm->to_resolve); j++)
1072    {
1073      rp = sm->to_resolve + j;
1074      send_snat_static_map_resolve_details (rp, q, mp->context);
1075    }
1076 }
1077
1078 static void *vl_api_snat_static_mapping_dump_t_print
1079 (vl_api_snat_static_mapping_dump_t *mp, void * handle)
1080 {
1081   u8 *s;
1082
1083   s = format (0, "SCRIPT: snat_static_mapping_dump ");
1084
1085   FINISH;
1086 }
1087
1088 static void
1089 vl_api_snat_control_ping_t_handler
1090 (vl_api_snat_control_ping_t * mp)
1091 {
1092   vl_api_snat_control_ping_reply_t *rmp;
1093   snat_main_t * sm = &snat_main;
1094   int rv = 0;
1095
1096   REPLY_MACRO2(VL_API_SNAT_CONTROL_PING_REPLY,
1097   ({
1098     rmp->vpe_pid = ntohl (getpid());
1099   }));
1100 }
1101
1102 static void *vl_api_snat_control_ping_t_print
1103 (vl_api_snat_control_ping_t *mp, void * handle)
1104 {
1105   u8 *s;
1106
1107   s = format (0, "SCRIPT: snat_control_ping ");
1108
1109   FINISH;
1110 }
1111
1112 static void
1113 vl_api_snat_show_config_t_handler
1114 (vl_api_snat_show_config_t * mp)
1115 {
1116   vl_api_snat_show_config_reply_t *rmp;
1117   snat_main_t * sm = &snat_main;
1118   int rv = 0;
1119
1120   REPLY_MACRO2(VL_API_SNAT_SHOW_CONFIG_REPLY,
1121   ({
1122     rmp->translation_buckets = htonl (sm->translation_buckets);
1123     rmp->translation_memory_size = htonl (sm->translation_memory_size);
1124     rmp->user_buckets = htonl (sm->user_buckets);
1125     rmp->user_memory_size = htonl (sm->user_memory_size);
1126     rmp->max_translations_per_user = htonl (sm->max_translations_per_user);
1127     rmp->outside_vrf_id = htonl (sm->outside_vrf_id);
1128     rmp->inside_vrf_id = htonl (sm->inside_vrf_id);
1129     rmp->static_mapping_only = sm->static_mapping_only;
1130     rmp->static_mapping_connection_tracking =
1131       sm->static_mapping_connection_tracking;
1132     rmp->deterministic = sm->deterministic;
1133   }));
1134 }
1135
1136 static void *vl_api_snat_show_config_t_print
1137 (vl_api_snat_show_config_t *mp, void * handle)
1138 {
1139   u8 *s;
1140
1141   s = format (0, "SCRIPT: snat_show_config ");
1142
1143   FINISH;
1144 }
1145
1146 static void 
1147 vl_api_snat_set_workers_t_handler
1148 (vl_api_snat_set_workers_t * mp)
1149 {
1150   snat_main_t * sm = &snat_main;
1151   vl_api_snat_set_workers_reply_t * rmp;
1152   int rv = 0;
1153   uword *bitmap = 0;
1154   u64 mask = clib_net_to_host_u64 (mp->worker_mask);
1155
1156   if (sm->num_workers < 2)
1157     {
1158       rv = VNET_API_ERROR_FEATURE_DISABLED;
1159       goto send_reply;
1160     }
1161
1162   bitmap = clib_bitmap_set_multiple (bitmap, 0, mask, BITS (mask)); 
1163   rv = snat_set_workers(bitmap);
1164   clib_bitmap_free (bitmap);
1165
1166  send_reply:
1167   REPLY_MACRO (VL_API_SNAT_SET_WORKERS_REPLY);
1168 }
1169
1170 static void *vl_api_snat_set_workers_t_print
1171 (vl_api_snat_set_workers_t *mp, void * handle)
1172 {
1173   u8 * s;
1174   uword *bitmap = 0;
1175   u8 first = 1;
1176   int i;
1177   u64 mask = clib_net_to_host_u64 (mp->worker_mask);
1178
1179   s = format (0, "SCRIPT: snat_set_workers ");
1180   bitmap = clib_bitmap_set_multiple (bitmap, 0, mask, BITS (mask)); 
1181   clib_bitmap_foreach (i, bitmap,
1182     ({
1183       if (first)
1184         s = format (s, "%d", i);
1185       else
1186         s = format (s, ",%d", i);
1187       first = 0;
1188     }));
1189   clib_bitmap_free (bitmap);
1190   FINISH;
1191 }
1192
1193 static void
1194 send_snat_worker_details
1195 (u32 worker_index, unix_shared_memory_queue_t * q, u32 context)
1196 {
1197   vl_api_snat_worker_details_t *rmp;
1198   snat_main_t * sm = &snat_main;
1199   vlib_worker_thread_t *w =
1200     vlib_worker_threads + worker_index + sm->first_worker_index;
1201
1202   rmp = vl_msg_api_alloc (sizeof (*rmp));
1203   memset (rmp, 0, sizeof (*rmp));
1204   rmp->_vl_msg_id = ntohs (VL_API_SNAT_WORKER_DETAILS+sm->msg_id_base);
1205   rmp->context = context;
1206   rmp->worker_index = htonl (worker_index);
1207   rmp->lcore_id = htonl (w->lcore_id);
1208   strncpy ((char *) rmp->name, (char *) w->name, ARRAY_LEN (rmp->name) - 1);
1209
1210   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1211 }
1212
1213 static void
1214 vl_api_snat_worker_dump_t_handler
1215 (vl_api_snat_worker_dump_t * mp)
1216 {
1217   unix_shared_memory_queue_t *q;
1218   snat_main_t * sm = &snat_main;
1219   u32 * worker_index;
1220
1221   q = vl_api_client_index_to_input_queue (mp->client_index);
1222   if (q == 0)
1223     return;
1224
1225   vec_foreach (worker_index, sm->workers)
1226     {
1227       send_snat_worker_details(*worker_index, q, mp->context);
1228     }
1229 }
1230
1231 static void *vl_api_snat_worker_dump_t_print
1232 (vl_api_snat_worker_dump_t *mp, void * handle)
1233 {
1234   u8 *s;
1235
1236   s = format (0, "SCRIPT: snat_worker_dump ");
1237
1238   FINISH;
1239 }
1240
1241 static int snat_add_interface_address(snat_main_t *sm,
1242                                       u32 sw_if_index,
1243                                       int is_del);
1244
1245 static void
1246 vl_api_snat_add_del_interface_addr_t_handler
1247 (vl_api_snat_add_del_interface_addr_t * mp)
1248 {
1249   snat_main_t * sm = &snat_main;
1250   vl_api_snat_add_del_interface_addr_reply_t * rmp;
1251   u8 is_del = mp->is_add == 0;
1252   u32 sw_if_index = ntohl(mp->sw_if_index);
1253   int rv = 0;
1254
1255   VALIDATE_SW_IF_INDEX(mp);
1256
1257   rv = snat_add_interface_address (sm, sw_if_index, is_del);
1258   
1259   BAD_SW_IF_INDEX_LABEL;
1260
1261   REPLY_MACRO(VL_API_SNAT_ADD_DEL_INTERFACE_ADDR_REPLY);
1262 }
1263
1264 static void *vl_api_snat_add_del_interface_addr_t_print
1265 (vl_api_snat_add_del_interface_addr_t * mp, void *handle)
1266 {
1267   u8 * s;
1268
1269   s = format (0, "SCRIPT: snat_add_del_interface_addr ");
1270   s = format (s, "sw_if_index %d %s",
1271               clib_host_to_net_u32(mp->sw_if_index),
1272               mp->is_add ? "" : "del");
1273
1274   FINISH;
1275 }
1276
1277 static void
1278 send_snat_interface_addr_details
1279 (u32 sw_if_index, unix_shared_memory_queue_t * q, u32 context)
1280 {
1281   vl_api_snat_interface_addr_details_t *rmp;
1282   snat_main_t * sm = &snat_main;
1283
1284   rmp = vl_msg_api_alloc (sizeof (*rmp));
1285   memset (rmp, 0, sizeof (*rmp));
1286   rmp->_vl_msg_id = ntohs (VL_API_SNAT_INTERFACE_ADDR_DETAILS+sm->msg_id_base);
1287   rmp->sw_if_index = ntohl (sw_if_index);
1288   rmp->context = context;
1289
1290   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1291 }
1292
1293 static void
1294 vl_api_snat_interface_addr_dump_t_handler
1295 (vl_api_snat_interface_addr_dump_t * mp)
1296 {
1297   unix_shared_memory_queue_t *q;
1298   snat_main_t * sm = &snat_main;
1299   u32 * i;
1300
1301   q = vl_api_client_index_to_input_queue (mp->client_index);
1302   if (q == 0)
1303     return;
1304
1305   vec_foreach (i, sm->auto_add_sw_if_indices)
1306     send_snat_interface_addr_details(*i, q, mp->context);
1307 }
1308
1309 static void *vl_api_snat_interface_addr_dump_t_print
1310 (vl_api_snat_interface_addr_dump_t *mp, void * handle)
1311 {
1312   u8 *s;
1313
1314   s = format (0, "SCRIPT: snat_interface_addr_dump ");
1315
1316   FINISH;
1317 }
1318
1319 static void
1320 vl_api_snat_ipfix_enable_disable_t_handler
1321 (vl_api_snat_ipfix_enable_disable_t * mp)
1322 {
1323   snat_main_t * sm = &snat_main;
1324   vl_api_snat_ipfix_enable_disable_reply_t * rmp;
1325   int rv = 0;
1326
1327   rv = snat_ipfix_logging_enable_disable(mp->enable,
1328                                          clib_host_to_net_u32 (mp->domain_id),
1329                                          clib_host_to_net_u16 (mp->src_port));
1330
1331   REPLY_MACRO (VL_API_SNAT_IPFIX_ENABLE_DISABLE_REPLY);
1332 }
1333
1334 static void *vl_api_snat_ipfix_enable_disable_t_print
1335 (vl_api_snat_ipfix_enable_disable_t *mp, void * handle)
1336 {
1337   u8 * s;
1338
1339   s = format (0, "SCRIPT: snat_ipfix_enable_disable ");
1340   if (mp->domain_id)
1341     s = format (s, "domain %d ", clib_net_to_host_u32 (mp->domain_id));
1342   if (mp->src_port)
1343     s = format (s, "src_port %d ", clib_net_to_host_u16 (mp->src_port));
1344   if (!mp->enable)
1345     s = format (s, "disable ");
1346
1347   FINISH;
1348 }
1349
1350 static void
1351 send_snat_user_details
1352 (snat_user_t * u, unix_shared_memory_queue_t * q, u32 context)
1353 {
1354   vl_api_snat_user_details_t * rmp;
1355   snat_main_t * sm = &snat_main;
1356   ip4_fib_t * fib_table;
1357
1358   rmp = vl_msg_api_alloc (sizeof (*rmp));
1359   memset (rmp, 0, sizeof (*rmp));
1360   rmp->_vl_msg_id = ntohs (VL_API_SNAT_USER_DETAILS+sm->msg_id_base);
1361
1362   fib_table = ip4_fib_get(u->fib_index);
1363   rmp->vrf_id = ntohl (fib_table->table_id);
1364
1365   rmp->is_ip4 = 1;
1366   clib_memcpy(rmp->ip_address, &(u->addr), 4);
1367   rmp->nsessions = ntohl (u->nsessions);
1368   rmp->nstaticsessions = ntohl (u->nstaticsessions);
1369   rmp->context = context;
1370
1371   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1372 }
1373
1374 static void
1375 vl_api_snat_user_dump_t_handler
1376 (vl_api_snat_user_dump_t * mp)
1377 {
1378   unix_shared_memory_queue_t *q;
1379   snat_main_t * sm = &snat_main;
1380   snat_main_per_thread_data_t * tsm;
1381   snat_user_t * u;
1382
1383   q = vl_api_client_index_to_input_queue (mp->client_index);
1384   if (q == 0)
1385     return;
1386
1387   vec_foreach (tsm, sm->per_thread_data)
1388     vec_foreach (u, tsm->users)
1389       send_snat_user_details (u, q, mp->context);
1390 }
1391
1392 static void *vl_api_snat_user_dump_t_print
1393 (vl_api_snat_user_dump_t *mp, void * handle)
1394 {
1395   u8 *s;
1396
1397   s = format (0, "SCRIPT: snat_user_dump ");
1398
1399   FINISH;
1400 }
1401
1402 static void
1403 send_snat_user_session_details
1404 (snat_session_t * s, unix_shared_memory_queue_t * q, u32 context)
1405 {
1406   vl_api_snat_user_session_details_t * rmp;
1407   snat_main_t * sm = &snat_main;
1408
1409   rmp = vl_msg_api_alloc (sizeof(*rmp));
1410   memset (rmp, 0, sizeof (*rmp));
1411   rmp->_vl_msg_id = ntohs (VL_API_SNAT_USER_SESSION_DETAILS+sm->msg_id_base);
1412   rmp->is_ip4 = 1;
1413   clib_memcpy(rmp->outside_ip_address, (&s->out2in.addr), 4);
1414   rmp->outside_port = s->out2in.port;
1415   clib_memcpy(rmp->inside_ip_address, (&s->in2out.addr), 4);
1416   rmp->inside_port = s->in2out.port;
1417   rmp->protocol = ntohs(snat_proto_to_ip_proto(s->in2out.protocol));
1418   rmp->is_static = s->flags & SNAT_SESSION_FLAG_STATIC_MAPPING ? 1 : 0;
1419   rmp->last_heard = clib_host_to_net_u64((u64)s->last_heard);
1420   rmp->total_bytes = clib_host_to_net_u64(s->total_bytes);
1421   rmp->total_pkts = ntohl(s->total_pkts);
1422   rmp->context = context;
1423
1424   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1425 }
1426
1427 static void
1428 vl_api_snat_user_session_dump_t_handler
1429 (vl_api_snat_user_session_dump_t * mp)
1430 {
1431   unix_shared_memory_queue_t *q;
1432   snat_main_t * sm = &snat_main;
1433   snat_main_per_thread_data_t *tsm;
1434   snat_session_t * s;
1435   clib_bihash_kv_8_8_t key, value;
1436   snat_user_key_t ukey;
1437   snat_user_t * u;
1438   u32 session_index, head_index, elt_index;
1439   dlist_elt_t * head, * elt;
1440
1441   q = vl_api_client_index_to_input_queue (mp->client_index);
1442   if (q == 0)
1443     return;
1444   if (!mp->is_ip4)
1445     return;
1446
1447   clib_memcpy (&ukey.addr, mp->ip_address, 4);
1448   ukey.fib_index = ip4_fib_index_from_table_id (ntohl(mp->vrf_id));
1449   key.key = ukey.as_u64;
1450   if (!clib_bihash_search_8_8 (&sm->worker_by_in, &key, &value))
1451     tsm = vec_elt_at_index (sm->per_thread_data, value.value);
1452   else
1453     tsm = vec_elt_at_index (sm->per_thread_data, sm->num_workers);
1454   if (clib_bihash_search_8_8 (&sm->user_hash, &key, &value))
1455     return;
1456   u = pool_elt_at_index (tsm->users, value.value);
1457   if (!u->nsessions && !u->nstaticsessions)
1458     return;
1459
1460   head_index = u->sessions_per_user_list_head_index;
1461   head = pool_elt_at_index (tsm->list_pool, head_index);
1462   elt_index = head->next;
1463   elt = pool_elt_at_index (tsm->list_pool, elt_index);
1464   session_index = elt->value;
1465   while (session_index != ~0)
1466     {
1467       s = pool_elt_at_index (tsm->sessions, session_index);
1468
1469       send_snat_user_session_details (s, q, mp->context);
1470
1471       elt_index = elt->next;
1472       elt = pool_elt_at_index (tsm->list_pool, elt_index);
1473       session_index = elt->value;
1474     }
1475 }
1476
1477 static void *vl_api_snat_user_session_dump_t_print
1478 (vl_api_snat_user_session_dump_t *mp, void * handle)
1479 {
1480   u8 *s;
1481
1482   s = format (0, "SCRIPT: snat_user_session_dump ");
1483   s = format (s, "ip_address %U vrf_id %d\n",
1484               format_ip4_address, mp->ip_address,
1485               clib_net_to_host_u32 (mp->vrf_id));
1486
1487   FINISH;
1488 }
1489
1490 static void
1491 vl_api_snat_add_det_map_t_handler
1492 (vl_api_snat_add_det_map_t * mp)
1493 {
1494   snat_main_t * sm = &snat_main;
1495   vl_api_snat_add_det_map_reply_t * rmp;
1496   int rv = 0;
1497   ip4_address_t in_addr, out_addr;
1498
1499   clib_memcpy(&in_addr, mp->in_addr, 4);
1500   clib_memcpy(&out_addr, mp->out_addr, 4);
1501   rv = snat_det_add_map(sm, &in_addr, mp->in_plen, &out_addr,
1502                         mp->out_plen, mp->is_add);
1503
1504   REPLY_MACRO (VL_API_SNAT_ADD_DET_MAP_REPLY);
1505 }
1506
1507 static void *vl_api_snat_add_det_map_t_print
1508 (vl_api_snat_add_det_map_t *mp, void * handle)
1509 {
1510   u8 * s;
1511
1512   s = format (0, "SCRIPT: snat_add_det_map ");
1513   s = format (s, "inside address %U/%d outside address %U/%d\n",
1514               format_ip4_address, mp->in_addr, mp->in_plen,
1515               format_ip4_address, mp->out_addr, mp->out_plen);
1516
1517   FINISH;
1518 }
1519
1520 static void
1521 vl_api_snat_det_forward_t_handler
1522 (vl_api_snat_det_forward_t * mp)
1523 {
1524   snat_main_t * sm = &snat_main;
1525   vl_api_snat_det_forward_reply_t * rmp;
1526   int rv = 0;
1527   u16 lo_port = 0, hi_port = 0;
1528   snat_det_map_t * dm;
1529   ip4_address_t in_addr, out_addr;
1530
1531   out_addr.as_u32 = 0;
1532   clib_memcpy(&in_addr, mp->in_addr, 4);
1533   dm = snat_det_map_by_user(sm, &in_addr);
1534   if (!dm)
1535     {
1536       rv = VNET_API_ERROR_NO_SUCH_ENTRY;
1537       goto send_reply;
1538     }
1539
1540   snat_det_forward(dm, &in_addr, &out_addr, &lo_port);
1541   hi_port = lo_port + dm->ports_per_host - 1;
1542
1543 send_reply:
1544   REPLY_MACRO2(VL_API_SNAT_DET_FORWARD_REPLY,
1545   ({
1546     rmp->out_port_lo = ntohs(lo_port);
1547     rmp->out_port_hi = ntohs(hi_port);
1548     rmp->is_ip4 = 1;
1549     memset(rmp->out_addr, 0, 16);
1550     clib_memcpy(rmp->out_addr, &out_addr, 4);
1551   }))
1552 }
1553
1554 static void *vl_api_snat_det_forward_t_print
1555 (vl_api_snat_det_forward_t * mp, void * handle)
1556 {
1557   u8 * s;
1558
1559   s = format (0, "SCRIPT: smat_det_forward_t");
1560   s = format (s, "inside ip address %U\n",
1561               format_ip4_address, mp->in_addr);
1562
1563   FINISH;
1564 }
1565
1566 static void
1567 vl_api_snat_det_reverse_t_handler
1568 (vl_api_snat_det_reverse_t * mp)
1569 {
1570   snat_main_t * sm = &snat_main;
1571   vl_api_snat_det_reverse_reply_t * rmp;
1572   int rv = 0;
1573   ip4_address_t out_addr, in_addr;
1574   snat_det_map_t * dm;
1575
1576   in_addr.as_u32 = 0;
1577   clib_memcpy(&out_addr, mp->out_addr, 4);
1578   dm = snat_det_map_by_out(sm, &out_addr);
1579   if (!dm)
1580     {
1581       rv = VNET_API_ERROR_NO_SUCH_ENTRY;
1582       goto send_reply;
1583     }
1584
1585   snat_det_reverse(dm, &out_addr, htons(mp->out_port), &in_addr);
1586
1587  send_reply:
1588   REPLY_MACRO2(VL_API_SNAT_DET_REVERSE_REPLY,
1589   ({
1590     rmp->is_ip4 = 1;
1591     memset(rmp->in_addr, 0, 16);
1592     clib_memcpy(rmp->in_addr, &in_addr, 4);
1593   }))
1594 }
1595
1596 static void *vl_api_snat_det_reverse_t_print
1597 (vl_api_snat_det_reverse_t * mp, void * handle)
1598 {
1599   u8 * s;
1600
1601   s = format(0, "SCRIPT: smat_det_reverse_t");
1602   s = format(s, "outside ip address %U outside port %d",
1603              format_ip4_address, mp->out_addr, ntohs(mp->out_port));
1604
1605   FINISH;
1606 }
1607
1608 static void
1609 sent_snat_det_map_details
1610 (snat_det_map_t * m, unix_shared_memory_queue_t * q, u32 context)
1611 {
1612   vl_api_snat_det_map_details_t *rmp;
1613   snat_main_t * sm = &snat_main;
1614
1615   rmp = vl_msg_api_alloc (sizeof (*rmp));
1616   memset (rmp, 0, sizeof (*rmp));
1617   rmp->_vl_msg_id = ntohs (VL_API_SNAT_DET_MAP_DETAILS+sm->msg_id_base);
1618   rmp->is_ip4 = 1;
1619   clib_memcpy (rmp->in_addr, &m->in_addr, 4);
1620   rmp->in_plen = m->in_plen;
1621   clib_memcpy (rmp->out_addr, &m->out_addr, 4);
1622   rmp->out_plen = m->out_plen;
1623   rmp->sharing_ratio = htonl (m->sharing_ratio);
1624   rmp->ports_per_host = htons (m->ports_per_host);
1625   rmp->ses_num = htonl (m->ses_num);
1626   rmp->context = context;
1627
1628   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1629 }
1630
1631 static void
1632 vl_api_snat_det_map_dump_t_handler
1633 (vl_api_snat_det_map_dump_t * mp)
1634 {
1635   unix_shared_memory_queue_t *q;
1636   snat_main_t * sm = &snat_main;
1637   snat_det_map_t * m;
1638
1639   q = vl_api_client_index_to_input_queue (mp->client_index);
1640   if (q == 0)
1641     return;
1642
1643   vec_foreach(m, sm->det_maps)
1644     sent_snat_det_map_details(m, q, mp->context);
1645 }
1646
1647 static void * vl_api_snat_det_map_dump_t_print
1648 (vl_api_snat_det_map_dump_t *mp, void * handle)
1649 {
1650   u8 * s;
1651
1652   s = format (0, "SCRIPT: snat_det_map_dump ");
1653
1654   FINISH;
1655 }
1656
1657 static void
1658 vl_api_snat_det_set_timeouts_t_handler
1659 (vl_api_snat_det_set_timeouts_t * mp)
1660 {
1661   snat_main_t * sm = &snat_main;
1662   vl_api_snat_det_set_timeouts_reply_t * rmp;
1663   int rv = 0;
1664
1665   sm->udp_timeout = ntohl(mp->udp);
1666   sm->tcp_established_timeout = ntohl(mp->tcp_established);
1667   sm->tcp_transitory_timeout = ntohl(mp->tcp_transitory);
1668   sm->icmp_timeout = ntohl(mp->icmp);
1669
1670   REPLY_MACRO (VL_API_SNAT_DET_SET_TIMEOUTS_REPLY);
1671 }
1672
1673 static void *vl_api_snat_det_set_timeouts_t_print
1674 (vl_api_snat_det_set_timeouts_t *mp, void * handle)
1675 {
1676   u8 * s;
1677
1678   s = format (0, "SCRIPT: snat_det_set_timeouts ");
1679   s = format (s, "udp %d tcp_established %d tcp_transitory %d icmp %d\n",
1680               ntohl(mp->udp),
1681               ntohl(mp->tcp_established),
1682               ntohl(mp->tcp_transitory),
1683               ntohl(mp->icmp));
1684
1685   FINISH;
1686 }
1687
1688 static void
1689 vl_api_snat_det_get_timeouts_t_handler
1690 (vl_api_snat_det_get_timeouts_t * mp)
1691 {
1692   snat_main_t * sm = &snat_main;
1693   vl_api_snat_det_get_timeouts_reply_t * rmp;
1694   int rv = 0;
1695
1696   REPLY_MACRO2(VL_API_SNAT_DET_GET_TIMEOUTS_REPLY,
1697   ({
1698     rmp->udp = htonl(sm->udp_timeout);
1699     rmp->tcp_established = htonl(sm->tcp_established_timeout);
1700     rmp->tcp_transitory = htonl(sm->tcp_transitory_timeout);
1701     rmp->icmp = htonl(sm->icmp_timeout);
1702   }))
1703 }
1704
1705 static void *vl_api_snat_det_get_timeouts_t_print
1706 (vl_api_snat_det_get_timeouts_t * mp, void * handle)
1707 {
1708   u8 * s;
1709
1710   s = format(0, "SCRIPT: snat_det_get_timeouts");
1711
1712   FINISH;
1713 }
1714
1715 static void
1716 vl_api_snat_det_close_session_out_t_handler
1717 (vl_api_snat_det_close_session_out_t * mp)
1718 {
1719   snat_main_t * sm = &snat_main;
1720   vl_api_snat_det_close_session_out_reply_t * rmp;
1721   ip4_address_t out_addr, ext_addr, in_addr;
1722   snat_det_out_key_t key;
1723   snat_det_map_t * dm;
1724   snat_det_session_t * ses;
1725   int rv = 0;
1726
1727   clib_memcpy(&out_addr, mp->out_addr, 4);
1728   clib_memcpy(&ext_addr, mp->ext_addr, 4);
1729
1730   dm = snat_det_map_by_out(sm, &out_addr);
1731   if (!dm)
1732     {
1733       rv = VNET_API_ERROR_NO_SUCH_ENTRY;
1734       goto send_reply;
1735     }
1736   snat_det_reverse(dm, &ext_addr, ntohs(mp->out_port), &in_addr);
1737   key.ext_host_addr = ext_addr;
1738   key.ext_host_port = mp->ext_port;
1739   key.out_port = mp->out_port;
1740   ses = snat_det_get_ses_by_out(dm, &in_addr, key.as_u64);
1741   if (!ses)
1742     {
1743       rv = VNET_API_ERROR_NO_SUCH_ENTRY;
1744       goto send_reply;
1745     }
1746   snat_det_ses_close(dm, ses);
1747
1748 send_reply:
1749   REPLY_MACRO (VL_API_SNAT_DET_CLOSE_SESSION_OUT_REPLY);
1750 }
1751
1752 static void *vl_api_snat_det_close_session_out_t_print
1753 (vl_api_snat_det_close_session_out_t *mp, void * handle)
1754 {
1755   u8 * s;
1756
1757   s = format (0, "SCRIPT: snat_det_close_session_out ");
1758   s = format (s, "out_addr %U out_port %d "
1759                  "ext_addr %U ext_port %d\n",
1760               format_ip4_address, mp->out_addr, ntohs(mp->out_port),
1761               format_ip4_address, mp->ext_addr, ntohs(mp->ext_port));
1762
1763   FINISH;
1764 }
1765
1766 static void
1767 vl_api_snat_det_close_session_in_t_handler
1768 (vl_api_snat_det_close_session_in_t * mp)
1769 {
1770   snat_main_t * sm = &snat_main;
1771   vl_api_snat_det_close_session_in_reply_t * rmp;
1772   ip4_address_t in_addr, ext_addr;
1773   snat_det_out_key_t key;
1774   snat_det_map_t * dm;
1775   snat_det_session_t * ses;
1776   int rv = 0;
1777
1778   clib_memcpy(&in_addr, mp->in_addr, 4);
1779   clib_memcpy(&ext_addr, mp->ext_addr, 4);
1780
1781   dm = snat_det_map_by_user(sm, &in_addr);
1782   if (!dm)
1783     {
1784       rv = VNET_API_ERROR_NO_SUCH_ENTRY;
1785       goto send_reply;
1786     }
1787   key.ext_host_addr = ext_addr;
1788   key.ext_host_port = mp->ext_port;
1789   ses = snat_det_find_ses_by_in(dm, &in_addr, mp->in_port, key);
1790   if (!ses)
1791     {
1792       rv = VNET_API_ERROR_NO_SUCH_ENTRY;
1793       goto send_reply;
1794     }
1795   snat_det_ses_close(dm, ses);
1796
1797 send_reply:
1798   REPLY_MACRO (VL_API_SNAT_DET_CLOSE_SESSION_OUT_REPLY);
1799 }
1800
1801 static void *vl_api_snat_det_close_session_in_t_print
1802 (vl_api_snat_det_close_session_in_t *mp, void * handle)
1803 {
1804   u8 * s;
1805   s = format (0, "SCRIPT: snat_det_close_session_in ");
1806   s = format (s, "in_addr %U in_port %d "
1807                  "ext_addr %U ext_port %d\n",
1808               format_ip4_address, mp->in_addr, ntohs(mp->in_port),
1809               format_ip4_address, mp->ext_addr, ntohs(mp->ext_port));
1810
1811   FINISH;
1812 }
1813
1814 static void
1815 send_snat_det_session_details
1816 (snat_det_session_t * s, unix_shared_memory_queue_t * q, u32 context)
1817 {
1818   vl_api_snat_det_session_details_t * rmp;
1819   snat_main_t * sm = &snat_main;
1820
1821   rmp = vl_msg_api_alloc (sizeof (*rmp));
1822   memset (rmp, 0, sizeof (*rmp));
1823   rmp->_vl_msg_id = ntohs (VL_API_SNAT_DET_SESSION_DETAILS+sm->msg_id_base);
1824   rmp->is_ip4 = 1;
1825   rmp->in_port = s->in_port;
1826   clib_memcpy (rmp->ext_addr, &s->out.ext_host_addr, 4);
1827   rmp->ext_port = s->out.ext_host_port;
1828   rmp->out_port = s->out.out_port;
1829   rmp->state = s->state;
1830   rmp->expire = ntohl (s->expire);
1831   rmp->context = context;
1832
1833   vl_msg_api_send_shmem (q, (u8 *) & rmp);
1834 }
1835
1836 static void
1837 vl_api_snat_det_session_dump_t_handler
1838 (vl_api_snat_det_session_dump_t * mp)
1839 {
1840   unix_shared_memory_queue_t *q;
1841   snat_main_t * sm = &snat_main;
1842   ip4_address_t user_addr;
1843   snat_det_map_t * dm;
1844   snat_det_session_t * s, empty_ses;
1845   u16 i;
1846
1847   q = vl_api_client_index_to_input_queue (mp->client_index);
1848   if (q == 0)
1849     return;
1850   if (!mp->is_ip4)
1851     return;
1852
1853   memset (&empty_ses, 0, sizeof (empty_ses));
1854   clib_memcpy (&user_addr, mp->user_addr, 4);
1855   dm = snat_det_map_by_user (sm, &user_addr);
1856   if (!dm)
1857     return;
1858
1859   s = dm->sessions + snat_det_user_ses_offset (&user_addr, dm->in_plen);
1860   for (i = 0; i < SNAT_DET_SES_PER_USER; i++)
1861     {
1862       if (s->out.as_u64)
1863         send_snat_det_session_details (s, q, mp->context);
1864       s++;
1865     }
1866 }
1867
1868 static void *vl_api_snat_det_session_dump_t_print
1869 (vl_api_snat_det_session_dump_t * mp, void * handle)
1870 {
1871   u8 *s;
1872
1873   s = format (0, "SCRIPT: snat_det_session_dump ");
1874   s = format (s, "user_addr %U\n",
1875               format_ip4_address, mp->user_addr);
1876
1877   FINISH;
1878 }
1879
1880 /* List of message types that this plugin understands */
1881 #define foreach_snat_plugin_api_msg                                     \
1882 _(SNAT_ADD_ADDRESS_RANGE, snat_add_address_range)                       \
1883 _(SNAT_INTERFACE_ADD_DEL_FEATURE, snat_interface_add_del_feature)       \
1884 _(SNAT_ADD_STATIC_MAPPING, snat_add_static_mapping)                     \
1885 _(SNAT_CONTROL_PING, snat_control_ping)                                 \
1886 _(SNAT_STATIC_MAPPING_DUMP, snat_static_mapping_dump)                   \
1887 _(SNAT_SHOW_CONFIG, snat_show_config)                                   \
1888 _(SNAT_ADDRESS_DUMP, snat_address_dump)                                 \
1889 _(SNAT_INTERFACE_DUMP, snat_interface_dump)                             \
1890 _(SNAT_SET_WORKERS, snat_set_workers)                                   \
1891 _(SNAT_WORKER_DUMP, snat_worker_dump)                                   \
1892 _(SNAT_ADD_DEL_INTERFACE_ADDR, snat_add_del_interface_addr)             \
1893 _(SNAT_INTERFACE_ADDR_DUMP, snat_interface_addr_dump)                   \
1894 _(SNAT_IPFIX_ENABLE_DISABLE, snat_ipfix_enable_disable)                 \
1895 _(SNAT_USER_DUMP, snat_user_dump)                                       \
1896 _(SNAT_USER_SESSION_DUMP, snat_user_session_dump)                       \
1897 _(SNAT_ADD_DET_MAP, snat_add_det_map)                                   \
1898 _(SNAT_DET_FORWARD, snat_det_forward)                                   \
1899 _(SNAT_DET_REVERSE, snat_det_reverse)                                   \
1900 _(SNAT_DET_MAP_DUMP, snat_det_map_dump)                                 \
1901 _(SNAT_DET_SET_TIMEOUTS, snat_det_set_timeouts)                         \
1902 _(SNAT_DET_GET_TIMEOUTS, snat_det_get_timeouts)                         \
1903 _(SNAT_DET_CLOSE_SESSION_OUT, snat_det_close_session_out)               \
1904 _(SNAT_DET_CLOSE_SESSION_IN, snat_det_close_session_in)                 \
1905 _(SNAT_DET_SESSION_DUMP, snat_det_session_dump)
1906
1907
1908 /* Set up the API message handling tables */
1909 static clib_error_t *
1910 snat_plugin_api_hookup (vlib_main_t *vm)
1911 {
1912    snat_main_t * sm __attribute__ ((unused)) = &snat_main;
1913 #define _(N,n)                                                  \
1914     vl_msg_api_set_handlers((VL_API_##N + sm->msg_id_base),     \
1915                            #n,                                  \
1916                            vl_api_##n##_t_handler,              \
1917                            vl_noop_handler,                     \
1918                            vl_api_##n##_t_endian,               \
1919                            vl_api_##n##_t_print,                \
1920                            sizeof(vl_api_##n##_t), 1); 
1921     foreach_snat_plugin_api_msg;
1922 #undef _
1923
1924     return 0;
1925 }
1926
1927 #define vl_msg_name_crc_list
1928 #include <snat/snat_all_api_h.h>
1929 #undef vl_msg_name_crc_list
1930
1931 static void
1932 setup_message_id_table (snat_main_t * sm, api_main_t * am)
1933 {
1934 #define _(id,n,crc) \
1935   vl_msg_api_add_msg_name_crc (am, #n "_" #crc, id + sm->msg_id_base);
1936   foreach_vl_msg_name_crc_snat;
1937 #undef _
1938 }
1939
1940 static void plugin_custom_dump_configure (snat_main_t * sm) 
1941 {
1942 #define _(n,f) sm->api_main->msg_print_handlers \
1943   [VL_API_##n + sm->msg_id_base]                \
1944     = (void *) vl_api_##f##_t_print;
1945   foreach_snat_plugin_api_msg;
1946 #undef _
1947 }
1948
1949
1950 static void
1951 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
1952                                        uword opaque,
1953                                        u32 sw_if_index,
1954                                        ip4_address_t * address,
1955                                        u32 address_length,
1956                                        u32 if_address_index,
1957                                        u32 is_delete);
1958
1959 static clib_error_t * snat_init (vlib_main_t * vm)
1960 {
1961   snat_main_t * sm = &snat_main;
1962   clib_error_t * error = 0;
1963   ip4_main_t * im = &ip4_main;
1964   ip_lookup_main_t * lm = &im->lookup_main;
1965   u8 * name;
1966   uword *p;
1967   vlib_thread_registration_t *tr;
1968   vlib_thread_main_t *tm = vlib_get_thread_main ();
1969   uword *bitmap = 0;
1970   u32 i;
1971   ip4_add_del_interface_address_callback_t cb4;
1972
1973   name = format (0, "snat_%08x%c", api_version, 0);
1974
1975   /* Ask for a correctly-sized block of API message decode slots */
1976   sm->msg_id_base = vl_msg_api_get_msg_ids 
1977       ((char *) name, VL_MSG_FIRST_AVAILABLE);
1978
1979   sm->vlib_main = vm;
1980   sm->vnet_main = vnet_get_main();
1981   sm->ip4_main = im;
1982   sm->ip4_lookup_main = lm;
1983   sm->api_main = &api_main;
1984   sm->first_worker_index = 0;
1985   sm->next_worker = 0;
1986   sm->num_workers = 0;
1987   sm->workers = 0;
1988   sm->fq_in2out_index = ~0;
1989   sm->fq_out2in_index = ~0;
1990   sm->udp_timeout = SNAT_UDP_TIMEOUT;
1991   sm->tcp_established_timeout = SNAT_TCP_ESTABLISHED_TIMEOUT;
1992   sm->tcp_transitory_timeout = SNAT_TCP_TRANSITORY_TIMEOUT;
1993   sm->icmp_timeout = SNAT_ICMP_TIMEOUT;
1994
1995   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
1996   if (p)
1997     {
1998       tr = (vlib_thread_registration_t *) p[0];
1999       if (tr)
2000         {
2001           sm->num_workers = tr->count;
2002           sm->first_worker_index = tr->first_index;
2003         }
2004     }
2005
2006   /* Use all available workers by default */
2007   if (sm->num_workers > 1)
2008     {
2009       for (i=0; i < sm->num_workers; i++)
2010         bitmap = clib_bitmap_set (bitmap, i, 1);
2011       snat_set_workers(bitmap);
2012       clib_bitmap_free (bitmap);
2013     }
2014
2015   error = snat_plugin_api_hookup (vm);
2016
2017   /* Add our API messages to the global name_crc hash table */
2018   setup_message_id_table (sm, &api_main);
2019
2020   plugin_custom_dump_configure (sm);
2021   vec_free(name);
2022
2023   /* Set up the interface address add/del callback */
2024   cb4.function = snat_ip4_add_del_interface_address_cb;
2025   cb4.function_opaque = 0;
2026
2027   vec_add1 (im->add_del_interface_address_callbacks, cb4);
2028
2029   /* Init IPFIX logging */
2030   snat_ipfix_logging_init(vm);
2031
2032   return error;
2033 }
2034
2035 VLIB_INIT_FUNCTION (snat_init);
2036
2037 void snat_free_outside_address_and_port (snat_main_t * sm, 
2038                                          snat_session_key_t * k, 
2039                                          u32 address_index)
2040 {
2041   snat_address_t *a;
2042   u16 port_host_byte_order = clib_net_to_host_u16 (k->port);
2043   
2044   ASSERT (address_index < vec_len (sm->addresses));
2045
2046   a = sm->addresses + address_index;
2047
2048   switch (k->protocol)
2049     {
2050 #define _(N, i, n, s) \
2051     case SNAT_PROTOCOL_##N: \
2052       ASSERT (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, \
2053         port_host_byte_order) == 1); \
2054       clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, \
2055         port_host_byte_order, 0); \
2056       a->busy_##n##_ports--; \
2057       break;
2058       foreach_snat_protocol
2059 #undef _
2060     default:
2061       clib_warning("unknown_protocol");
2062       return;
2063     }
2064 }  
2065
2066 /**
2067  * @brief Match SNAT static mapping.
2068  *
2069  * @param sm          SNAT main.
2070  * @param match       Address and port to match.
2071  * @param mapping     External or local address and port of the matched mapping.
2072  * @param by_external If 0 match by local address otherwise match by external
2073  *                    address.
2074  * @param is_addr_only If matched mapping is address only
2075  *
2076  * @returns 0 if match found otherwise 1.
2077  */
2078 int snat_static_mapping_match (snat_main_t * sm,
2079                                snat_session_key_t match,
2080                                snat_session_key_t * mapping,
2081                                u8 by_external,
2082                                u8 *is_addr_only)
2083 {
2084   clib_bihash_kv_8_8_t kv, value;
2085   snat_static_mapping_t *m;
2086   snat_session_key_t m_key;
2087   clib_bihash_8_8_t *mapping_hash = &sm->static_mapping_by_local;
2088
2089   if (by_external)
2090     mapping_hash = &sm->static_mapping_by_external;
2091
2092   m_key.addr = match.addr;
2093   m_key.port = clib_net_to_host_u16 (match.port);
2094   m_key.protocol = match.protocol;
2095   m_key.fib_index = match.fib_index;
2096
2097   kv.key = m_key.as_u64;
2098
2099   if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
2100     {
2101       /* Try address only mapping */
2102       m_key.port = 0;
2103       m_key.protocol = 0;
2104       kv.key = m_key.as_u64;
2105       if (clib_bihash_search_8_8 (mapping_hash, &kv, &value))
2106         return 1;
2107     }
2108
2109   m = pool_elt_at_index (sm->static_mappings, value.value);
2110
2111   if (by_external)
2112     {
2113       mapping->addr = m->local_addr;
2114       /* Address only mapping doesn't change port */
2115       mapping->port = m->addr_only ? match.port
2116         : clib_host_to_net_u16 (m->local_port);
2117       mapping->fib_index = m->fib_index;
2118     }
2119   else
2120     {
2121       mapping->addr = m->external_addr;
2122       /* Address only mapping doesn't change port */
2123       mapping->port = m->addr_only ? match.port
2124         : clib_host_to_net_u16 (m->external_port);
2125       mapping->fib_index = sm->outside_fib_index;
2126     }
2127
2128   if (PREDICT_FALSE(is_addr_only != 0))
2129     *is_addr_only = m->addr_only;
2130
2131   return 0;
2132 }
2133
2134 int snat_alloc_outside_address_and_port (snat_main_t * sm, 
2135                                          u32 fib_index,
2136                                          snat_session_key_t * k,
2137                                          u32 * address_indexp)
2138 {
2139   int i;
2140   snat_address_t *a;
2141   u32 portnum;
2142
2143   for (i = 0; i < vec_len (sm->addresses); i++)
2144     {
2145       a = sm->addresses + i;
2146       if (sm->vrf_mode && a->fib_index != ~0 && a->fib_index != fib_index)
2147         continue;
2148       switch (k->protocol)
2149         {
2150 #define _(N, j, n, s) \
2151         case SNAT_PROTOCOL_##N: \
2152           if (a->busy_##n##_ports < (65535-1024)) \
2153             { \
2154               while (1) \
2155                 { \
2156                   portnum = random_u32 (&sm->random_seed); \
2157                   portnum &= 0xFFFF; \
2158                   if (portnum < 1024) \
2159                     continue; \
2160                   if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, portnum)) \
2161                     continue; \
2162                   clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, portnum, 1); \
2163                   a->busy_##n##_ports++; \
2164                   k->addr = a->addr; \
2165                   k->port = clib_host_to_net_u16(portnum); \
2166                   *address_indexp = i; \
2167                   return 0; \
2168                 } \
2169             } \
2170           break;
2171           foreach_snat_protocol
2172 #undef _
2173         default:
2174           clib_warning("unknown protocol");
2175           return 1;
2176         }
2177
2178     }
2179   /* Totally out of translations to use... */
2180   snat_ipfix_logging_addresses_exhausted(0);
2181   return 1;
2182 }
2183
2184
2185 static clib_error_t *
2186 add_address_command_fn (vlib_main_t * vm,
2187                         unformat_input_t * input,
2188                         vlib_cli_command_t * cmd)
2189 {
2190   unformat_input_t _line_input, *line_input = &_line_input;
2191   snat_main_t * sm = &snat_main;
2192   ip4_address_t start_addr, end_addr, this_addr;
2193   u32 start_host_order, end_host_order;
2194   u32 vrf_id = ~0;
2195   int i, count;
2196   int is_add = 1;
2197   int rv = 0;
2198   clib_error_t *error = 0;
2199
2200   /* Get a line of input. */
2201   if (!unformat_user (input, unformat_line_input, line_input))
2202     return 0;
2203
2204   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2205     {
2206       if (unformat (line_input, "%U - %U",
2207                     unformat_ip4_address, &start_addr,
2208                     unformat_ip4_address, &end_addr))
2209         ;
2210       else if (unformat (line_input, "tenant-vrf %u", &vrf_id))
2211         ;
2212       else if (unformat (line_input, "%U", unformat_ip4_address, &start_addr))
2213         end_addr = start_addr;
2214       else if (unformat (line_input, "del"))
2215         is_add = 0;
2216       else
2217         {
2218           error = clib_error_return (0, "unknown input '%U'",
2219             format_unformat_error, line_input);
2220           goto done;
2221         }
2222      }
2223
2224   if (sm->static_mapping_only)
2225     {
2226       error = clib_error_return (0, "static mapping only mode");
2227       goto done;
2228     }
2229
2230   start_host_order = clib_host_to_net_u32 (start_addr.as_u32);
2231   end_host_order = clib_host_to_net_u32 (end_addr.as_u32);
2232   
2233   if (end_host_order < start_host_order)
2234     {
2235       error = clib_error_return (0, "end address less than start address");
2236       goto done;
2237     }
2238
2239   count = (end_host_order - start_host_order) + 1;
2240
2241   if (count > 1024)
2242     clib_warning ("%U - %U, %d addresses...",
2243                   format_ip4_address, &start_addr,
2244                   format_ip4_address, &end_addr,
2245                   count);
2246   
2247   this_addr = start_addr;
2248
2249   for (i = 0; i < count; i++)
2250     {
2251       if (is_add)
2252         snat_add_address (sm, &this_addr, vrf_id);
2253       else
2254         rv = snat_del_address (sm, this_addr, 0);
2255
2256       switch (rv)
2257         {
2258         case VNET_API_ERROR_NO_SUCH_ENTRY:
2259           error = clib_error_return (0, "S-NAT address not exist.");
2260           goto done;
2261         case VNET_API_ERROR_UNSPECIFIED:
2262           error = clib_error_return (0, "S-NAT address used in static mapping.");
2263           goto done;
2264         default:
2265           break;
2266         }
2267
2268       increment_v4_address (&this_addr);
2269     }
2270
2271 done:
2272   unformat_free (line_input);
2273
2274   return error;
2275 }
2276
2277 VLIB_CLI_COMMAND (add_address_command, static) = {
2278   .path = "snat add address",
2279   .short_help = "snat add addresses <ip4-range-start> [- <ip4-range-end>] "
2280                 "[tenant-vrf <vrf-id>] [del]",
2281   .function = add_address_command_fn,
2282 };
2283
2284 static clib_error_t *
2285 snat_feature_command_fn (vlib_main_t * vm,
2286                           unformat_input_t * input,
2287                           vlib_cli_command_t * cmd)
2288 {
2289   unformat_input_t _line_input, *line_input = &_line_input;
2290   vnet_main_t * vnm = vnet_get_main();
2291   clib_error_t * error = 0;
2292   u32 sw_if_index;
2293   u32 * inside_sw_if_indices = 0;
2294   u32 * outside_sw_if_indices = 0;
2295   int is_del = 0;
2296   int i;
2297
2298   sw_if_index = ~0;
2299
2300   /* Get a line of input. */
2301   if (!unformat_user (input, unformat_line_input, line_input))
2302     return 0;
2303
2304   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2305     {
2306       if (unformat (line_input, "in %U", unformat_vnet_sw_interface,
2307                     vnm, &sw_if_index))
2308         vec_add1 (inside_sw_if_indices, sw_if_index);
2309       else if (unformat (line_input, "out %U", unformat_vnet_sw_interface,
2310                          vnm, &sw_if_index))
2311         vec_add1 (outside_sw_if_indices, sw_if_index);
2312       else if (unformat (line_input, "del"))
2313         is_del = 1;
2314       else
2315         {
2316           error = clib_error_return (0, "unknown input '%U'",
2317             format_unformat_error, line_input);
2318           goto done;
2319         }
2320     }
2321
2322   if (vec_len (inside_sw_if_indices))
2323     {
2324       for (i = 0; i < vec_len(inside_sw_if_indices); i++)
2325         {
2326           sw_if_index = inside_sw_if_indices[i];
2327           snat_interface_add_del (sw_if_index, 1, is_del);
2328         }
2329     }
2330
2331   if (vec_len (outside_sw_if_indices))
2332     {
2333       for (i = 0; i < vec_len(outside_sw_if_indices); i++)
2334         {
2335           sw_if_index = outside_sw_if_indices[i];
2336           snat_interface_add_del (sw_if_index, 0, is_del);
2337         }
2338     }
2339
2340 done:
2341   unformat_free (line_input);
2342   vec_free (inside_sw_if_indices);
2343   vec_free (outside_sw_if_indices);
2344
2345   return error;
2346 }
2347
2348 VLIB_CLI_COMMAND (set_interface_snat_command, static) = {
2349   .path = "set interface snat",
2350   .function = snat_feature_command_fn,
2351   .short_help = "set interface snat in <intfc> out <intfc> [del]",
2352 };
2353
2354 uword
2355 unformat_snat_protocol (unformat_input_t * input, va_list * args)
2356 {
2357   u32 *r = va_arg (*args, u32 *);
2358
2359   if (0);
2360 #define _(N, i, n, s) else if (unformat (input, s)) *r = SNAT_PROTOCOL_##N;
2361   foreach_snat_protocol
2362 #undef _
2363   else
2364     return 0;
2365   return 1;
2366 }
2367
2368 u8 *
2369 format_snat_protocol (u8 * s, va_list * args)
2370 {
2371   u32 i = va_arg (*args, u32);
2372   u8 *t = 0;
2373
2374   switch (i)
2375     {
2376 #define _(N, j, n, str) case SNAT_PROTOCOL_##N: t = (u8 *) str; break;
2377       foreach_snat_protocol
2378 #undef _
2379     default:
2380       s = format (s, "unknown");
2381     }
2382   s = format (s, "%s", t);
2383   return s;
2384 }
2385
2386 static clib_error_t *
2387 add_static_mapping_command_fn (vlib_main_t * vm,
2388                                unformat_input_t * input,
2389                                vlib_cli_command_t * cmd)
2390 {
2391   unformat_input_t _line_input, *line_input = &_line_input;
2392   clib_error_t * error = 0;
2393   ip4_address_t l_addr, e_addr;
2394   u32 l_port = 0, e_port = 0, vrf_id = ~0;
2395   int is_add = 1;
2396   int addr_only = 1;
2397   u32 sw_if_index = ~0;
2398   vnet_main_t * vnm = vnet_get_main();
2399   int rv;
2400   snat_protocol_t proto;
2401   u8 proto_set = 0;
2402
2403   /* Get a line of input. */
2404   if (!unformat_user (input, unformat_line_input, line_input))
2405     return 0;
2406
2407   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2408     {
2409       if (unformat (line_input, "local %U %u", unformat_ip4_address, &l_addr,
2410                     &l_port))
2411         addr_only = 0;
2412       else if (unformat (line_input, "local %U", unformat_ip4_address, &l_addr))
2413         ;
2414       else if (unformat (line_input, "external %U %u", unformat_ip4_address,
2415                          &e_addr, &e_port))
2416         addr_only = 0;
2417       else if (unformat (line_input, "external %U", unformat_ip4_address,
2418                          &e_addr))
2419         ;
2420       else if (unformat (line_input, "external %U %u",
2421                          unformat_vnet_sw_interface, vnm, &sw_if_index,
2422                          &e_port))
2423         addr_only = 0;
2424
2425       else if (unformat (line_input, "external %U",
2426                          unformat_vnet_sw_interface, vnm, &sw_if_index))
2427         ;
2428       else if (unformat (line_input, "vrf %u", &vrf_id))
2429         ;
2430       else if (unformat (line_input, "%U", unformat_snat_protocol, &proto))
2431         proto_set = 1;
2432       else if (unformat (line_input, "del"))
2433         is_add = 0;
2434       else
2435         {
2436           error = clib_error_return (0, "unknown input: '%U'",
2437             format_unformat_error, line_input);
2438           goto done;
2439         }
2440     }
2441
2442   if (!addr_only && !proto_set)
2443     {
2444       error = clib_error_return (0, "missing protocol");
2445       goto done;
2446     }
2447
2448   rv = snat_add_static_mapping(l_addr, e_addr, (u16) l_port, (u16) e_port,
2449                                vrf_id, addr_only, sw_if_index, proto, is_add);
2450
2451   switch (rv)
2452     {
2453     case VNET_API_ERROR_INVALID_VALUE:
2454       error = clib_error_return (0, "External port already in use.");
2455       goto done;
2456     case VNET_API_ERROR_NO_SUCH_ENTRY:
2457       if (is_add)
2458         error = clib_error_return (0, "External addres must be allocated.");
2459       else
2460         error = clib_error_return (0, "Mapping not exist.");
2461       goto done;
2462     case VNET_API_ERROR_NO_SUCH_FIB:
2463       error = clib_error_return (0, "No such VRF id.");
2464       goto done;
2465     case VNET_API_ERROR_VALUE_EXIST:
2466       error = clib_error_return (0, "Mapping already exist.");
2467       goto done;
2468     default:
2469       break;
2470     }
2471
2472 done:
2473   unformat_free (line_input);
2474
2475   return error;
2476 }
2477
2478 /*?
2479  * @cliexpar
2480  * @cliexstart{snat add static mapping}
2481  * Static mapping allows hosts on the external network to initiate connection
2482  * to to the local network host.
2483  * To create static mapping between local host address 10.0.0.3 port 6303 and
2484  * external address 4.4.4.4 port 3606 for TCP protocol use:
2485  *  vpp# snat add static mapping local tcp 10.0.0.3 6303 external 4.4.4.4 3606
2486  * If not runnig "static mapping only" S-NAT plugin mode use before:
2487  *  vpp# snat add address 4.4.4.4
2488  * To create static mapping between local and external address use:
2489  *  vpp# snat add static mapping local 10.0.0.3 external 4.4.4.4
2490  * @cliexend
2491 ?*/
2492 VLIB_CLI_COMMAND (add_static_mapping_command, static) = {
2493   .path = "snat add static mapping",
2494   .function = add_static_mapping_command_fn,
2495   .short_help =
2496     "snat add static mapping local tcp|udp|icmp <addr> [<port>] external <addr> [<port>] [vrf <table-id>] [del]",
2497 };
2498
2499 static clib_error_t *
2500 set_workers_command_fn (vlib_main_t * vm,
2501                         unformat_input_t * input,
2502                         vlib_cli_command_t * cmd)
2503 {
2504   unformat_input_t _line_input, *line_input = &_line_input;
2505   uword *bitmap = 0;
2506   int rv = 0;
2507   clib_error_t *error = 0;
2508
2509   /* Get a line of input. */
2510   if (!unformat_user (input, unformat_line_input, line_input))
2511     return 0;
2512
2513   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2514     {
2515       if (unformat (line_input, "%U", unformat_bitmap_list, &bitmap))
2516         ;
2517       else
2518         {
2519           error = clib_error_return (0, "unknown input '%U'",
2520             format_unformat_error, line_input);
2521           goto done;
2522         }
2523      }
2524
2525   if (bitmap == 0)
2526     {
2527       error = clib_error_return (0, "List of workers must be specified.");
2528       goto done;
2529     }
2530
2531   rv = snat_set_workers(bitmap);
2532
2533   clib_bitmap_free (bitmap);
2534
2535   switch (rv)
2536     {
2537     case VNET_API_ERROR_INVALID_WORKER:
2538       error = clib_error_return (0, "Invalid worker(s).");
2539       goto done;
2540     case VNET_API_ERROR_FEATURE_DISABLED:
2541       error = clib_error_return (0,
2542         "Supported only if 2 or more workes available.");
2543       goto done;
2544     default:
2545       break;
2546     }
2547
2548 done:
2549   unformat_free (line_input);
2550
2551   return error;
2552 }
2553
2554 /*?
2555  * @cliexpar
2556  * @cliexstart{set snat workers}
2557  * Set SNAT workers if 2 or more workers available, use:
2558  *  vpp# set snat workers 0-2,5
2559  * @cliexend
2560 ?*/
2561 VLIB_CLI_COMMAND (set_workers_command, static) = {
2562   .path = "set snat workers",
2563   .function = set_workers_command_fn,
2564   .short_help =
2565     "set snat workers <workers-list>",
2566 };
2567
2568 static clib_error_t *
2569 snat_ipfix_logging_enable_disable_command_fn (vlib_main_t * vm,
2570                                               unformat_input_t * input,
2571                                               vlib_cli_command_t * cmd)
2572 {
2573   unformat_input_t _line_input, *line_input = &_line_input;
2574   u32 domain_id = 0;
2575   u32 src_port = 0;
2576   u8 enable = 1;
2577   int rv = 0;
2578   clib_error_t *error = 0;
2579
2580   /* Get a line of input. */
2581   if (!unformat_user (input, unformat_line_input, line_input))
2582     return 0;
2583
2584   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2585     {
2586       if (unformat (line_input, "domain %d", &domain_id))
2587         ;
2588       else if (unformat (line_input, "src-port %d", &src_port))
2589         ;
2590       else if (unformat (line_input, "disable"))
2591         enable = 0;
2592       else
2593         {
2594           error = clib_error_return (0, "unknown input '%U'",
2595             format_unformat_error, line_input);
2596           goto done;
2597         }
2598      }
2599
2600   rv = snat_ipfix_logging_enable_disable (enable, domain_id, (u16) src_port);
2601
2602   if (rv)
2603     {
2604       error = clib_error_return (0, "ipfix logging enable failed");
2605       goto done;
2606     }
2607
2608 done:
2609   unformat_free (line_input);
2610
2611   return error;
2612 }
2613
2614 /*?
2615  * @cliexpar
2616  * @cliexstart{snat ipfix logging}
2617  * To enable SNAT IPFIX logging use:
2618  *  vpp# snat ipfix logging
2619  * To set IPFIX exporter use:
2620  *  vpp# set ipfix exporter collector 10.10.10.3 src 10.10.10.1
2621  * @cliexend
2622 ?*/
2623 VLIB_CLI_COMMAND (snat_ipfix_logging_enable_disable_command, static) = {
2624   .path = "snat ipfix logging",
2625   .function = snat_ipfix_logging_enable_disable_command_fn,
2626   .short_help = "snat ipfix logging [domain <domain-id>] [src-port <port>] [disable]",
2627 };
2628
2629 static u32
2630 snat_get_worker_in2out_cb (ip4_header_t * ip0, u32 rx_fib_index0)
2631 {
2632   snat_main_t *sm = &snat_main;
2633   snat_user_key_t key0;
2634   clib_bihash_kv_8_8_t kv0, value0;
2635   u32 next_worker_index = 0;
2636
2637   key0.addr = ip0->src_address;
2638   key0.fib_index = rx_fib_index0;
2639
2640   kv0.key = key0.as_u64;
2641
2642   /* Ever heard of of the "user" before? */
2643   if (clib_bihash_search_8_8 (&sm->worker_by_in, &kv0, &value0))
2644     {
2645       /* No, assign next available worker (RR) */
2646       next_worker_index = sm->first_worker_index;
2647       if (vec_len (sm->workers))
2648         {
2649           next_worker_index +=
2650             sm->workers[sm->next_worker++ % _vec_len (sm->workers)];
2651         }
2652
2653       /* add non-traslated packets worker lookup */
2654       kv0.value = next_worker_index;
2655       clib_bihash_add_del_8_8 (&sm->worker_by_in, &kv0, 1);
2656     }
2657   else
2658     next_worker_index = value0.value;
2659
2660   return next_worker_index;
2661 }
2662
2663 static u32
2664 snat_get_worker_out2in_cb (ip4_header_t * ip0, u32 rx_fib_index0)
2665 {
2666   snat_main_t *sm = &snat_main;
2667   snat_worker_key_t key0;
2668   clib_bihash_kv_8_8_t kv0, value0;
2669   udp_header_t * udp0;
2670   u32 next_worker_index = 0;
2671
2672   udp0 = ip4_next_header (ip0);
2673
2674   key0.addr = ip0->dst_address;
2675   key0.port = udp0->dst_port;
2676   key0.fib_index = rx_fib_index0;
2677
2678   if (PREDICT_FALSE(ip0->protocol == IP_PROTOCOL_ICMP))
2679     {
2680       icmp46_header_t * icmp0 = (icmp46_header_t *) udp0;
2681       icmp_echo_header_t *echo0 = (icmp_echo_header_t *)(icmp0+1);
2682       key0.port = echo0->identifier;
2683     }
2684
2685   kv0.key = key0.as_u64;
2686
2687   /* Ever heard of of the "user" before? */
2688   if (clib_bihash_search_8_8 (&sm->worker_by_out, &kv0, &value0))
2689     {
2690       key0.port = 0;
2691       kv0.key = key0.as_u64;
2692
2693       if (clib_bihash_search_8_8 (&sm->worker_by_out, &kv0, &value0))
2694         {
2695           /* No, assign next available worker (RR) */
2696           next_worker_index = sm->first_worker_index;
2697           if (vec_len (sm->workers))
2698             {
2699               next_worker_index +=
2700                 sm->workers[sm->next_worker++ % _vec_len (sm->workers)];
2701             }
2702         }
2703       else
2704         {
2705           /* Static mapping without port */
2706           next_worker_index = value0.value;
2707         }
2708
2709       /* Add to translated packets worker lookup */
2710       kv0.value = next_worker_index;
2711       clib_bihash_add_del_8_8 (&sm->worker_by_out, &kv0, 1);
2712     }
2713   else
2714     next_worker_index = value0.value;
2715
2716   return next_worker_index;
2717 }
2718
2719 static clib_error_t *
2720 snat_config (vlib_main_t * vm, unformat_input_t * input)
2721 {
2722   snat_main_t * sm = &snat_main;
2723   u32 translation_buckets = 1024;
2724   u32 translation_memory_size = 128<<20;
2725   u32 user_buckets = 128;
2726   u32 user_memory_size = 64<<20;
2727   u32 max_translations_per_user = 100;
2728   u32 outside_vrf_id = 0;
2729   u32 inside_vrf_id = 0;
2730   u32 static_mapping_buckets = 1024;
2731   u32 static_mapping_memory_size = 64<<20;
2732   u8 static_mapping_only = 0;
2733   u8 static_mapping_connection_tracking = 0;
2734   vlib_thread_main_t *tm = vlib_get_thread_main ();
2735
2736   sm->deterministic = 0;
2737
2738   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2739     {
2740       if (unformat (input, "translation hash buckets %d", &translation_buckets))
2741         ;
2742       else if (unformat (input, "translation hash memory %d",
2743                          &translation_memory_size));
2744       else if (unformat (input, "user hash buckets %d", &user_buckets))
2745         ;
2746       else if (unformat (input, "user hash memory %d",
2747                          &user_memory_size))
2748         ;
2749       else if (unformat (input, "max translations per user %d",
2750                          &max_translations_per_user))
2751         ;
2752       else if (unformat (input, "outside VRF id %d",
2753                          &outside_vrf_id))
2754         ;
2755       else if (unformat (input, "inside VRF id %d",
2756                          &inside_vrf_id))
2757         ;
2758       else if (unformat (input, "static mapping only"))
2759         {
2760           static_mapping_only = 1;
2761           if (unformat (input, "connection tracking"))
2762             static_mapping_connection_tracking = 1;
2763         }
2764       else if (unformat (input, "deterministic"))
2765         sm->deterministic = 1;
2766       else
2767         return clib_error_return (0, "unknown input '%U'",
2768                                   format_unformat_error, input);
2769     }
2770
2771   /* for show commands, etc. */
2772   sm->translation_buckets = translation_buckets;
2773   sm->translation_memory_size = translation_memory_size;
2774   sm->user_buckets = user_buckets;
2775   sm->user_memory_size = user_memory_size;
2776   sm->max_translations_per_user = max_translations_per_user;
2777   sm->outside_vrf_id = outside_vrf_id;
2778   sm->outside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
2779                                                              outside_vrf_id);
2780   sm->inside_vrf_id = inside_vrf_id;
2781   sm->inside_fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP4,
2782                                                             inside_vrf_id);
2783   sm->static_mapping_only = static_mapping_only;
2784   sm->static_mapping_connection_tracking = static_mapping_connection_tracking;
2785
2786   if (sm->deterministic)
2787     {
2788       sm->in2out_node_index = snat_det_in2out_node.index;
2789       sm->out2in_node_index = snat_det_out2in_node.index;
2790       sm->icmp_match_in2out_cb = icmp_match_in2out_det;
2791       sm->icmp_match_out2in_cb = icmp_match_out2in_det;
2792     }
2793   else
2794     {
2795       sm->worker_in2out_cb = snat_get_worker_in2out_cb;
2796       sm->worker_out2in_cb = snat_get_worker_out2in_cb;
2797       sm->in2out_node_index = snat_in2out_node.index;
2798       sm->out2in_node_index = snat_out2in_node.index;
2799       if (!static_mapping_only ||
2800           (static_mapping_only && static_mapping_connection_tracking))
2801         {
2802           sm->icmp_match_in2out_cb = icmp_match_in2out_slow;
2803           sm->icmp_match_out2in_cb = icmp_match_out2in_slow;
2804
2805           clib_bihash_init_8_8 (&sm->worker_by_in, "worker-by-in", user_buckets,
2806                                 user_memory_size);
2807
2808           clib_bihash_init_8_8 (&sm->worker_by_out, "worker-by-out", user_buckets,
2809                                 user_memory_size);
2810
2811           vec_validate (sm->per_thread_data, tm->n_vlib_mains - 1);
2812
2813           clib_bihash_init_8_8 (&sm->in2out, "in2out", translation_buckets,
2814                                 translation_memory_size);
2815
2816           clib_bihash_init_8_8 (&sm->out2in, "out2in", translation_buckets,
2817                                 translation_memory_size);
2818
2819           clib_bihash_init_8_8 (&sm->user_hash, "users", user_buckets,
2820                                 user_memory_size);
2821         }
2822       else
2823         {
2824           sm->icmp_match_in2out_cb = icmp_match_in2out_fast;
2825           sm->icmp_match_out2in_cb = icmp_match_out2in_fast;
2826         }
2827       clib_bihash_init_8_8 (&sm->static_mapping_by_local,
2828                             "static_mapping_by_local", static_mapping_buckets,
2829                             static_mapping_memory_size);
2830
2831       clib_bihash_init_8_8 (&sm->static_mapping_by_external,
2832                             "static_mapping_by_external", static_mapping_buckets,
2833                             static_mapping_memory_size);
2834     }
2835
2836   return 0;
2837 }
2838
2839 VLIB_CONFIG_FUNCTION (snat_config, "snat");
2840
2841 u8 * format_snat_session_state (u8 * s, va_list * args)
2842 {
2843   u32 i = va_arg (*args, u32);
2844   u8 *t = 0;
2845
2846   switch (i)
2847     {
2848 #define _(v, N, str) case SNAT_SESSION_##N: t = (u8 *) str; break;
2849     foreach_snat_session_state
2850 #undef _
2851     default:
2852       t = format (t, "unknown");
2853     }
2854   s = format (s, "%s", t);
2855   return s;
2856 }
2857
2858 u8 * format_snat_key (u8 * s, va_list * args)
2859 {
2860   snat_session_key_t * key = va_arg (*args, snat_session_key_t *);
2861   char * protocol_string = "unknown";
2862   static char *protocol_strings[] = {
2863       "UDP",
2864       "TCP",
2865       "ICMP",
2866   };
2867
2868   if (key->protocol < ARRAY_LEN(protocol_strings))
2869       protocol_string = protocol_strings[key->protocol];
2870
2871   s = format (s, "%U proto %s port %d fib %d",
2872               format_ip4_address, &key->addr, protocol_string,
2873               clib_net_to_host_u16 (key->port), key->fib_index);
2874   return s;
2875 }
2876
2877 u8 * format_snat_session (u8 * s, va_list * args)
2878 {
2879   snat_main_t * sm __attribute__((unused)) = va_arg (*args, snat_main_t *);
2880   snat_session_t * sess = va_arg (*args, snat_session_t *);
2881
2882   s = format (s, "  i2o %U\n", format_snat_key, &sess->in2out);
2883   s = format (s, "    o2i %U\n", format_snat_key, &sess->out2in);
2884   s = format (s, "       last heard %.2f\n", sess->last_heard);
2885   s = format (s, "       total pkts %d, total bytes %lld\n",
2886               sess->total_pkts, sess->total_bytes);
2887   if (snat_is_session_static (sess))
2888     s = format (s, "       static translation\n");
2889   else
2890     s = format (s, "       dynamic translation\n");
2891
2892   return s;
2893 }
2894
2895 u8 * format_snat_user (u8 * s, va_list * args)
2896 {
2897   snat_main_per_thread_data_t * sm = va_arg (*args, snat_main_per_thread_data_t *);
2898   snat_user_t * u = va_arg (*args, snat_user_t *);
2899   int verbose = va_arg (*args, int);
2900   dlist_elt_t * head, * elt;
2901   u32 elt_index, head_index;
2902   u32 session_index;
2903   snat_session_t * sess;
2904
2905   s = format (s, "%U: %d dynamic translations, %d static translations\n",
2906               format_ip4_address, &u->addr, u->nsessions, u->nstaticsessions);
2907
2908   if (verbose == 0)
2909     return s;
2910
2911   if (u->nsessions || u->nstaticsessions)
2912     {
2913       head_index = u->sessions_per_user_list_head_index;
2914       head = pool_elt_at_index (sm->list_pool, head_index);
2915
2916       elt_index = head->next;
2917       elt = pool_elt_at_index (sm->list_pool, elt_index);
2918       session_index = elt->value;
2919
2920       while (session_index != ~0)
2921         {
2922           sess = pool_elt_at_index (sm->sessions, session_index);
2923
2924           s = format (s, "  %U\n", format_snat_session, sm, sess);
2925
2926           elt_index = elt->next;
2927           elt = pool_elt_at_index (sm->list_pool, elt_index);
2928           session_index = elt->value;
2929         }
2930     }
2931
2932   return s;
2933 }
2934
2935 u8 * format_snat_static_mapping (u8 * s, va_list * args)
2936 {
2937   snat_static_mapping_t *m = va_arg (*args, snat_static_mapping_t *);
2938
2939   if (m->addr_only)
2940       s = format (s, "local %U external %U vrf %d",
2941                   format_ip4_address, &m->local_addr,
2942                   format_ip4_address, &m->external_addr,
2943                   m->vrf_id);
2944   else
2945       s = format (s, "%U local %U:%d external %U:%d vrf %d",
2946                   format_snat_protocol, m->proto,
2947                   format_ip4_address, &m->local_addr, m->local_port,
2948                   format_ip4_address, &m->external_addr, m->external_port,
2949                   m->vrf_id);
2950
2951   return s;
2952 }
2953
2954 u8 * format_snat_static_map_to_resolve (u8 * s, va_list * args)
2955 {
2956   snat_static_map_resolve_t *m = va_arg (*args, snat_static_map_resolve_t *);
2957   vnet_main_t *vnm = vnet_get_main();
2958
2959   if (m->addr_only)
2960       s = format (s, "local %U external %U vrf %d",
2961                   format_ip4_address, &m->l_addr,
2962                   format_vnet_sw_interface_name, vnm,
2963                   vnet_get_sw_interface (vnm, m->sw_if_index),
2964                   m->vrf_id);
2965   else
2966       s = format (s, "%U local %U:%d external %U:%d vrf %d",
2967                   format_snat_protocol, m->proto,
2968                   format_ip4_address, &m->l_addr, m->l_port,
2969                   format_vnet_sw_interface_name, vnm,
2970                   vnet_get_sw_interface (vnm, m->sw_if_index), m->e_port,
2971                   m->vrf_id);
2972
2973   return s;
2974 }
2975
2976 u8 * format_det_map_ses (u8 * s, va_list * args)
2977 {
2978   snat_det_map_t * det_map = va_arg (*args, snat_det_map_t *);
2979   ip4_address_t in_addr, out_addr;
2980   u32 in_offset, out_offset;
2981   snat_det_session_t * ses = va_arg (*args, snat_det_session_t *);
2982   u32 * i = va_arg (*args, u32 *);
2983
2984   u32 user_index = *i / SNAT_DET_SES_PER_USER;
2985   in_addr.as_u32 = clib_host_to_net_u32 (
2986     clib_net_to_host_u32(det_map->in_addr.as_u32) + user_index);
2987   in_offset = clib_net_to_host_u32(in_addr.as_u32) -
2988     clib_net_to_host_u32(det_map->in_addr.as_u32);
2989   out_offset = in_offset / det_map->sharing_ratio;
2990   out_addr.as_u32 = clib_host_to_net_u32(
2991     clib_net_to_host_u32(det_map->out_addr.as_u32) + out_offset);
2992   s = format (s, "in %U:%d out %U:%d external host %U:%d state: %U expire: %d\n",
2993               format_ip4_address, &in_addr,
2994               clib_net_to_host_u16 (ses->in_port),
2995               format_ip4_address, &out_addr,
2996               clib_net_to_host_u16 (ses->out.out_port),
2997               format_ip4_address, &ses->out.ext_host_addr,
2998               clib_net_to_host_u16 (ses->out.ext_host_port),
2999               format_snat_session_state, ses->state,
3000               ses->expire);
3001
3002   return s;
3003 }
3004
3005 static clib_error_t *
3006 show_snat_command_fn (vlib_main_t * vm,
3007                  unformat_input_t * input,
3008                  vlib_cli_command_t * cmd)
3009 {
3010   int verbose = 0;
3011   snat_main_t * sm = &snat_main;
3012   snat_user_t * u;
3013   snat_static_mapping_t *m;
3014   snat_interface_t *i;
3015   snat_address_t * ap;
3016   vnet_main_t *vnm = vnet_get_main();
3017   snat_main_per_thread_data_t *tsm;
3018   u32 users_num = 0, sessions_num = 0, *worker, *sw_if_index;
3019   uword j = 0;
3020   snat_static_map_resolve_t *rp;
3021   snat_det_map_t * dm;
3022   snat_det_session_t * ses;
3023
3024   if (unformat (input, "detail"))
3025     verbose = 1;
3026   else if (unformat (input, "verbose"))
3027     verbose = 2;
3028
3029   if (sm->static_mapping_only)
3030     {
3031       if (sm->static_mapping_connection_tracking)
3032         vlib_cli_output (vm, "SNAT mode: static mapping only connection "
3033                          "tracking");
3034       else
3035         vlib_cli_output (vm, "SNAT mode: static mapping only");
3036     }
3037   else if (sm->deterministic)
3038     {
3039       vlib_cli_output (vm, "SNAT mode: deterministic mapping");
3040     }
3041   else
3042     {
3043       vlib_cli_output (vm, "SNAT mode: dynamic translations enabled");
3044     }
3045
3046   if (verbose > 0)
3047     {
3048       pool_foreach (i, sm->interfaces,
3049       ({
3050         vlib_cli_output (vm, "%U %s", format_vnet_sw_interface_name, vnm,
3051                          vnet_get_sw_interface (vnm, i->sw_if_index),
3052                          i->is_inside ? "in" : "out");
3053       }));
3054
3055       if (vec_len (sm->auto_add_sw_if_indices))
3056         {
3057           vlib_cli_output (vm, "SNAT pool addresses interfaces:");
3058           vec_foreach (sw_if_index, sm->auto_add_sw_if_indices)
3059             {
3060               vlib_cli_output (vm, "%U", format_vnet_sw_interface_name, vnm,
3061                                vnet_get_sw_interface (vnm, *sw_if_index));
3062             }
3063         }
3064
3065       vec_foreach (ap, sm->addresses)
3066         {
3067           vlib_cli_output (vm, "%U", format_ip4_address, &ap->addr);
3068           if (ap->fib_index != ~0)
3069               vlib_cli_output (vm, "  tenant VRF: %u",
3070                                ip4_fib_get(ap->fib_index)->table_id);
3071           else
3072             vlib_cli_output (vm, "  tenant VRF independent");
3073 #define _(N, i, n, s) \
3074           vlib_cli_output (vm, "  %d busy %s ports", ap->busy_##n##_ports, s);
3075           foreach_snat_protocol
3076 #undef _
3077         }
3078     }
3079
3080   if (sm->num_workers > 1)
3081     {
3082       vlib_cli_output (vm, "%d workers", vec_len (sm->workers));
3083       if (verbose > 0)
3084         {
3085           vec_foreach (worker, sm->workers)
3086             {
3087               vlib_worker_thread_t *w =
3088                 vlib_worker_threads + *worker + sm->first_worker_index;
3089               vlib_cli_output (vm, "  %s", w->name);
3090             }
3091         }
3092     }
3093
3094   if (sm->deterministic)
3095     {
3096       vlib_cli_output (vm, "udp timeout: %dsec", sm->udp_timeout);
3097       vlib_cli_output (vm, "tcp-established timeout: %dsec",
3098                        sm->tcp_established_timeout);
3099       vlib_cli_output (vm, "tcp-transitory timeout: %dsec",
3100                        sm->tcp_transitory_timeout);
3101       vlib_cli_output (vm, "icmp timeout: %dsec", sm->icmp_timeout);
3102       vlib_cli_output (vm, "%d deterministic mappings",
3103                        pool_elts (sm->det_maps));
3104       if (verbose > 0)
3105         {
3106           pool_foreach (dm, sm->det_maps,
3107           ({
3108             vlib_cli_output (vm, "in %U/%d out %U/%d\n",
3109                              format_ip4_address, &dm->in_addr, dm->in_plen,
3110                              format_ip4_address, &dm->out_addr, dm->out_plen);
3111             vlib_cli_output (vm, " outside address sharing ratio: %d\n",
3112                              dm->sharing_ratio);
3113             vlib_cli_output (vm, " number of ports per inside host: %d\n",
3114                              dm->ports_per_host);
3115             vlib_cli_output (vm, " sessions number: %d\n", dm->ses_num);
3116             if (verbose > 1)
3117               {
3118                 vec_foreach_index (j, dm->sessions)
3119                   {
3120                     ses = vec_elt_at_index (dm->sessions, j);
3121                     if (ses->in_port)
3122                       vlib_cli_output (vm, "  %U", format_det_map_ses, dm, ses,
3123                                        &j);
3124                   }
3125               }
3126           }));
3127         }
3128     }
3129   else
3130     {
3131       if (sm->static_mapping_only && !(sm->static_mapping_connection_tracking))
3132         {
3133           vlib_cli_output (vm, "%d static mappings",
3134                            pool_elts (sm->static_mappings));
3135
3136           if (verbose > 0)
3137             {
3138               pool_foreach (m, sm->static_mappings,
3139               ({
3140                 vlib_cli_output (vm, "%U", format_snat_static_mapping, m);
3141               }));
3142             }
3143         }
3144       else
3145         {
3146           vec_foreach (tsm, sm->per_thread_data)
3147             {
3148               users_num += pool_elts (tsm->users);
3149               sessions_num += pool_elts (tsm->sessions);
3150             }
3151
3152           vlib_cli_output (vm, "%d users, %d outside addresses, %d active sessions,"
3153                            " %d static mappings",
3154                            users_num,
3155                            vec_len (sm->addresses),
3156                            sessions_num,
3157                            pool_elts (sm->static_mappings));
3158
3159           if (verbose > 0)
3160             {
3161               vlib_cli_output (vm, "%U", format_bihash_8_8, &sm->in2out,
3162                                verbose - 1);
3163               vlib_cli_output (vm, "%U", format_bihash_8_8, &sm->out2in,
3164                                verbose - 1);
3165               vlib_cli_output (vm, "%U", format_bihash_8_8, &sm->worker_by_in,
3166                                verbose - 1);
3167               vlib_cli_output (vm, "%U", format_bihash_8_8, &sm->worker_by_out,
3168                                verbose - 1);
3169               vec_foreach_index (j, sm->per_thread_data)
3170                 {
3171                   tsm = vec_elt_at_index (sm->per_thread_data, j);
3172
3173                   if (pool_elts (tsm->users) == 0)
3174                     continue;
3175
3176                   vlib_worker_thread_t *w = vlib_worker_threads + j;
3177                   vlib_cli_output (vm, "Thread %d (%s at lcore %u):", j, w->name,
3178                                    w->lcore_id);
3179                   vlib_cli_output (vm, "  %d list pool elements",
3180                                    pool_elts (tsm->list_pool));
3181
3182                   pool_foreach (u, tsm->users,
3183                   ({
3184                     vlib_cli_output (vm, "  %U", format_snat_user, tsm, u,
3185                                      verbose - 1);
3186                   }));
3187                 }
3188
3189               if (pool_elts (sm->static_mappings))
3190                 {
3191                   vlib_cli_output (vm, "static mappings:");
3192                   pool_foreach (m, sm->static_mappings,
3193                   ({
3194                     vlib_cli_output (vm, "%U", format_snat_static_mapping, m);
3195                   }));
3196                   for (j = 0; j < vec_len (sm->to_resolve); j++)
3197                     {
3198                       rp = sm->to_resolve + j;
3199                       vlib_cli_output (vm, "%U",
3200                                        format_snat_static_map_to_resolve, rp);
3201                     }
3202                 }
3203             }
3204         }
3205     }
3206   return 0;
3207 }
3208
3209 VLIB_CLI_COMMAND (show_snat_command, static) = {
3210     .path = "show snat",
3211     .short_help = "show snat",
3212     .function = show_snat_command_fn,
3213 };
3214
3215
3216 static void
3217 snat_ip4_add_del_interface_address_cb (ip4_main_t * im,
3218                                        uword opaque,
3219                                        u32 sw_if_index,
3220                                        ip4_address_t * address,
3221                                        u32 address_length,
3222                                        u32 if_address_index,
3223                                        u32 is_delete)
3224 {
3225   snat_main_t *sm = &snat_main;
3226   snat_static_map_resolve_t *rp;
3227   u32 *indices_to_delete = 0;
3228   int i, j;
3229   int rv;
3230
3231   for (i = 0; i < vec_len(sm->auto_add_sw_if_indices); i++)
3232     {
3233       if (sw_if_index == sm->auto_add_sw_if_indices[i])
3234         {
3235           if (!is_delete)
3236             {
3237               /* Don't trip over lease renewal, static config */
3238               for (j = 0; j < vec_len(sm->addresses); j++)
3239                 if (sm->addresses[j].addr.as_u32 == address->as_u32)
3240                   return;
3241
3242               snat_add_address (sm, address, ~0);
3243               /* Scan static map resolution vector */
3244               for (j = 0; j < vec_len (sm->to_resolve); j++)
3245                 {
3246                   rp = sm->to_resolve + j;
3247                   /* On this interface? */
3248                   if (rp->sw_if_index == sw_if_index)
3249                     {
3250                       /* Add the static mapping */
3251                       rv = snat_add_static_mapping (rp->l_addr,
3252                                                     address[0],
3253                                                     rp->l_port,
3254                                                     rp->e_port,
3255                                                     rp->vrf_id,
3256                                                     rp->addr_only,
3257                                                     ~0 /* sw_if_index */,
3258                                                     rp->proto,
3259                                                     rp->is_add);
3260                       if (rv)
3261                         clib_warning ("snat_add_static_mapping returned %d", 
3262                                       rv);
3263                       vec_add1 (indices_to_delete, j);
3264                     }
3265                 }
3266               /* If we resolved any of the outstanding static mappings */
3267               if (vec_len(indices_to_delete))
3268                 {
3269                   /* Delete them */
3270                   for (j = vec_len(indices_to_delete)-1; j >= 0; j--)
3271                     vec_delete(sm->to_resolve, 1, j);
3272                   vec_free(indices_to_delete);
3273                 }
3274               return;
3275             }
3276           else
3277             {
3278               (void) snat_del_address(sm, address[0], 1);
3279               return;
3280             }
3281         }
3282     }
3283 }
3284
3285
3286 static int snat_add_interface_address (snat_main_t *sm,
3287                                        u32 sw_if_index,
3288                                        int is_del)
3289 {
3290   ip4_main_t * ip4_main = sm->ip4_main;
3291   ip4_address_t * first_int_addr;
3292   snat_static_map_resolve_t *rp;
3293   u32 *indices_to_delete = 0;
3294   int i, j;
3295
3296   first_int_addr = ip4_interface_first_address (ip4_main, sw_if_index,
3297                                                 0 /* just want the address*/);
3298
3299   for (i = 0; i < vec_len(sm->auto_add_sw_if_indices); i++)
3300     {
3301       if (sm->auto_add_sw_if_indices[i] == sw_if_index)
3302         {
3303           if (is_del)
3304             {
3305               /* if have address remove it */
3306               if (first_int_addr)
3307                   (void) snat_del_address (sm, first_int_addr[0], 1);
3308               else
3309                 {
3310                   for (j = 0; j < vec_len (sm->to_resolve); j++)
3311                     {
3312                       rp = sm->to_resolve + j;
3313                       if (rp->sw_if_index == sw_if_index)
3314                         vec_add1 (indices_to_delete, j);
3315                     }
3316                   if (vec_len(indices_to_delete))
3317                     {
3318                       for (j = vec_len(indices_to_delete)-1; j >= 0; j--)
3319                         vec_del1(sm->to_resolve, j);
3320                       vec_free(indices_to_delete);
3321                     }
3322                 }
3323               vec_del1(sm->auto_add_sw_if_indices, i);
3324             }
3325           else
3326             return VNET_API_ERROR_VALUE_EXIST;
3327
3328           return 0;
3329         }
3330     }
3331   
3332   if (is_del)
3333     return VNET_API_ERROR_NO_SUCH_ENTRY;
3334
3335   /* add to the auto-address list */
3336   vec_add1(sm->auto_add_sw_if_indices, sw_if_index);
3337
3338   /* If the address is already bound - or static - add it now */
3339   if (first_int_addr)
3340       snat_add_address (sm, first_int_addr, ~0);
3341
3342   return 0;
3343 }
3344
3345 static clib_error_t *
3346 snat_add_interface_address_command_fn (vlib_main_t * vm,
3347                                        unformat_input_t * input,
3348                                        vlib_cli_command_t * cmd)
3349 {
3350   snat_main_t *sm = &snat_main;
3351   unformat_input_t _line_input, *line_input = &_line_input;
3352   u32 sw_if_index;
3353   int rv;
3354   int is_del = 0;
3355   clib_error_t *error = 0;
3356
3357   /* Get a line of input. */
3358   if (!unformat_user (input, unformat_line_input, line_input))
3359     return 0;
3360
3361   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3362     {
3363       if (unformat (line_input, "%U", unformat_vnet_sw_interface,
3364                     sm->vnet_main, &sw_if_index))
3365         ;
3366       else if (unformat (line_input, "del"))
3367         is_del = 1;
3368       else
3369         {
3370           error = clib_error_return (0, "unknown input '%U'",
3371                                      format_unformat_error, line_input);
3372           goto done;
3373         }
3374     }
3375
3376   rv = snat_add_interface_address (sm, sw_if_index, is_del);
3377
3378   switch (rv)
3379     {
3380     case 0:
3381       break;
3382
3383     default:
3384       error = clib_error_return (0, "snat_add_interface_address returned %d",
3385                                  rv);
3386       goto done;
3387     }
3388
3389 done:
3390   unformat_free (line_input);
3391
3392   return error;
3393 }
3394
3395 VLIB_CLI_COMMAND (snat_add_interface_address_command, static) = {
3396     .path = "snat add interface address",
3397     .short_help = "snat add interface address <interface> [del]",
3398     .function = snat_add_interface_address_command_fn,
3399 };
3400
3401 static clib_error_t *
3402 snat_det_map_command_fn (vlib_main_t * vm,
3403                          unformat_input_t * input,
3404                          vlib_cli_command_t * cmd)
3405 {
3406   snat_main_t *sm = &snat_main;
3407   unformat_input_t _line_input, *line_input = &_line_input;
3408   ip4_address_t in_addr, out_addr;
3409   u32 in_plen, out_plen;
3410   int is_add = 1, rv;
3411   clib_error_t *error = 0;
3412
3413   /* Get a line of input. */
3414   if (!unformat_user (input, unformat_line_input, line_input))
3415     return 0;
3416
3417   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3418     {
3419       if (unformat (line_input, "in %U/%u", unformat_ip4_address, &in_addr, &in_plen))
3420         ;
3421       else if (unformat (line_input, "out %U/%u", unformat_ip4_address, &out_addr, &out_plen))
3422         ;
3423       else if (unformat (line_input, "del"))
3424         is_add = 0;
3425       else
3426         {
3427           error = clib_error_return (0, "unknown input '%U'",
3428                                      format_unformat_error, line_input);
3429           goto done;
3430         }
3431     }
3432
3433   unformat_free (line_input);
3434
3435   rv = snat_det_add_map(sm, &in_addr, (u8) in_plen, &out_addr, (u8)out_plen,
3436                         is_add);
3437
3438   if (rv)
3439     {
3440       error = clib_error_return (0, "snat_det_add_map return %d", rv);
3441       goto done;
3442     }
3443
3444 done:
3445   unformat_free (line_input);
3446
3447   return error;
3448 }
3449
3450 /*?
3451  * @cliexpar
3452  * @cliexstart{snat deterministic add}
3453  * Create bijective mapping of inside address to outside address and port range
3454  * pairs, with the purpose of enabling deterministic NAT to reduce logging in
3455  * CGN deployments.
3456  * To create deterministic mapping between inside network 10.0.0.0/18 and
3457  * outside network 1.1.1.0/30 use:
3458  * # vpp# snat deterministic add in 10.0.0.0/18 out 1.1.1.0/30
3459  * @cliexend
3460 ?*/
3461 VLIB_CLI_COMMAND (snat_det_map_command, static) = {
3462     .path = "snat deterministic add",
3463     .short_help = "snat deterministic add in <addr>/<plen> out <addr>/<plen> [del]",
3464     .function = snat_det_map_command_fn,
3465 };
3466
3467 static clib_error_t *
3468 snat_det_forward_command_fn (vlib_main_t * vm,
3469                              unformat_input_t * input,
3470                              vlib_cli_command_t * cmd)
3471 {
3472   snat_main_t *sm = &snat_main;
3473   unformat_input_t _line_input, *line_input = &_line_input;
3474   ip4_address_t in_addr, out_addr;
3475   u16 lo_port;
3476   snat_det_map_t * dm;
3477   clib_error_t *error = 0;
3478
3479   /* Get a line of input. */
3480   if (!unformat_user (input, unformat_line_input, line_input))
3481     return 0;
3482
3483   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3484     {
3485       if (unformat (line_input, "%U", unformat_ip4_address, &in_addr))
3486         ;
3487       else
3488         {
3489           error = clib_error_return (0, "unknown input '%U'",
3490                                      format_unformat_error, line_input);
3491           goto done;
3492         }
3493     }
3494
3495   unformat_free (line_input);
3496
3497   dm = snat_det_map_by_user(sm, &in_addr);
3498   if (!dm)
3499     vlib_cli_output (vm, "no match");
3500   else
3501     {
3502       snat_det_forward (dm, &in_addr, &out_addr, &lo_port);
3503       vlib_cli_output (vm, "%U:<%d-%d>", format_ip4_address, &out_addr,
3504                        lo_port, lo_port + dm->ports_per_host - 1);
3505     }
3506
3507 done:
3508   unformat_free (line_input);
3509
3510   return error;
3511 }
3512
3513 /*?
3514  * @cliexpar
3515  * @cliexstart{snat deterministic forward}
3516  * Return outside address and port range from inside address for deterministic
3517  * NAT.
3518  * To obtain outside address and port of inside host use:
3519  *  vpp# snat deterministic forward 10.0.0.2
3520  *  1.1.1.0:<1054-1068>
3521  * @cliexend
3522 ?*/
3523 VLIB_CLI_COMMAND (snat_det_forward_command, static) = {
3524     .path = "snat deterministic forward",
3525     .short_help = "snat deterministic forward <addr>",
3526     .function = snat_det_forward_command_fn,
3527 };
3528
3529 static clib_error_t *
3530 snat_det_reverse_command_fn (vlib_main_t * vm,
3531                              unformat_input_t * input,
3532                              vlib_cli_command_t * cmd)
3533 {
3534   snat_main_t *sm = &snat_main;
3535   unformat_input_t _line_input, *line_input = &_line_input;
3536   ip4_address_t in_addr, out_addr;
3537   u32 out_port;
3538   snat_det_map_t * dm;
3539   clib_error_t *error = 0;
3540
3541   /* Get a line of input. */
3542   if (!unformat_user (input, unformat_line_input, line_input))
3543     return 0;
3544
3545   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3546     {
3547       if (unformat (line_input, "%U:%d", unformat_ip4_address, &out_addr, &out_port))
3548         ;
3549       else
3550         {
3551           error =  clib_error_return (0, "unknown input '%U'",
3552                                       format_unformat_error, line_input);
3553         }
3554     }
3555
3556   unformat_free (line_input);
3557
3558   if (out_port < 1024 || out_port > 65535)
3559     {
3560       error = clib_error_return (0, "wrong port, must be <1024-65535>");
3561       goto done;
3562     }
3563
3564   dm = snat_det_map_by_out(sm, &out_addr);
3565   if (!dm)
3566     vlib_cli_output (vm, "no match");
3567   else
3568     {
3569       snat_det_reverse (dm, &out_addr, (u16) out_port, &in_addr);
3570       vlib_cli_output (vm, "%U", format_ip4_address, &in_addr);
3571     }
3572
3573 done:
3574   unformat_free (line_input);
3575
3576   return error;
3577 }
3578
3579 /*?
3580  * @cliexpar
3581  * @cliexstart{snat deterministic reverse}
3582  * Return inside address from outside address and port for deterministic NAT.
3583  * To obtain inside host address from outside address and port use:
3584  *  #vpp snat deterministic reverse 1.1.1.1:1276
3585  *  10.0.16.16
3586  * @cliexend
3587 ?*/
3588 VLIB_CLI_COMMAND (snat_det_reverse_command, static) = {
3589     .path = "snat deterministic reverse",
3590     .short_help = "snat deterministic reverse <addr>:<port>",
3591     .function = snat_det_reverse_command_fn,
3592 };
3593
3594 static clib_error_t *
3595 set_timeout_command_fn (vlib_main_t * vm,
3596                         unformat_input_t * input,
3597                         vlib_cli_command_t * cmd)
3598 {
3599   snat_main_t *sm = &snat_main;
3600   unformat_input_t _line_input, *line_input = &_line_input;
3601   clib_error_t *error = 0;
3602
3603   /* Get a line of input. */
3604   if (!unformat_user (input, unformat_line_input, line_input))
3605     return 0;
3606
3607   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3608     {
3609       if (unformat (line_input, "udp %u", &sm->udp_timeout))
3610         ;
3611       else if (unformat (line_input, "tcp-established %u",
3612                &sm->tcp_established_timeout))
3613         ;
3614       else if (unformat (line_input, "tcp-transitory %u",
3615                &sm->tcp_transitory_timeout))
3616         ;
3617       else if (unformat (line_input, "icmp %u", &sm->icmp_timeout))
3618         ;
3619       else if (unformat (line_input, "reset"))
3620         {
3621           sm->udp_timeout = SNAT_UDP_TIMEOUT;
3622           sm->tcp_established_timeout = SNAT_TCP_ESTABLISHED_TIMEOUT;
3623           sm->tcp_transitory_timeout = SNAT_TCP_TRANSITORY_TIMEOUT;
3624           sm->icmp_timeout = SNAT_ICMP_TIMEOUT;
3625         }
3626       else
3627         {
3628           error = clib_error_return (0, "unknown input '%U'",
3629                                      format_unformat_error, line_input);
3630           goto done;
3631         }
3632     }
3633
3634   unformat_free (line_input);
3635
3636 done:
3637   unformat_free (line_input);
3638
3639   return error;
3640 }
3641
3642 /*?
3643  * @cliexpar
3644  * @cliexstart{set snat deterministic timeout}
3645  * Set values of timeouts for deterministic NAT (in seconds), use:
3646  *  vpp# set snat deterministic timeout udp 120 tcp-established 7500
3647  *  tcp-transitory 250 icmp 90
3648  * To reset default values use:
3649  *  vpp# set snat deterministic timeout reset
3650  * @cliexend
3651 ?*/
3652 VLIB_CLI_COMMAND (set_timeout_command, static) = {
3653   .path = "set snat deterministic timeout",
3654   .function = set_timeout_command_fn,
3655   .short_help =
3656     "set snat deterministic timeout [udp <sec> | tcp-established <sec> "
3657     "tcp-transitory <sec> | icmp <sec> | reset]",
3658 };
3659
3660 static clib_error_t *
3661 snat_det_close_session_out_fn (vlib_main_t *vm,
3662                                unformat_input_t * input,
3663                                vlib_cli_command_t * cmd)
3664 {
3665   snat_main_t *sm = &snat_main;
3666   unformat_input_t _line_input, *line_input = &_line_input;
3667   ip4_address_t out_addr, ext_addr, in_addr;
3668   u16 out_port, ext_port;
3669   snat_det_map_t * dm;
3670   snat_det_session_t * ses;
3671   snat_det_out_key_t key;
3672   clib_error_t *error = 0;
3673
3674   /* Get a line of input. */
3675   if (!unformat_user (input, unformat_line_input, line_input))
3676     return 0;
3677
3678   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3679     {
3680       if (unformat (line_input, "%U:%d %U:%d",
3681                     unformat_ip4_address, &out_addr, &out_port,
3682                     unformat_ip4_address, &ext_addr, &ext_port))
3683         ;
3684       else
3685         {
3686           error = clib_error_return (0, "unknown input '%U'",
3687                                      format_unformat_error, line_input);
3688           goto done;
3689         }
3690     }
3691
3692   unformat_free (line_input);
3693
3694   dm = snat_det_map_by_out(sm, &out_addr);
3695   if (!dm)
3696     vlib_cli_output (vm, "no match");
3697   else
3698     {
3699       snat_det_reverse(dm, &ext_addr, out_port, &in_addr);
3700       key.ext_host_addr = out_addr;
3701       key.ext_host_port = ntohs(ext_port);
3702       key.out_port = ntohs(out_port);
3703       ses = snat_det_get_ses_by_out(dm, &out_addr, key.as_u64);
3704       if (!ses)
3705         vlib_cli_output (vm, "no match");
3706       else
3707        snat_det_ses_close(dm, ses);
3708     }
3709
3710 done:
3711   unformat_free (line_input);
3712
3713   return error;
3714 }
3715
3716 /*?
3717  * @cliexpar
3718  * @cliexstart{snat deterministic close session out}
3719  * Close session using outside ip address and port
3720  * and external ip address and port, use:
3721  *  vpp# snat deterministic close session out 1.1.1.1:1276 2.2.2.2:2387
3722  * @cliexend
3723 ?*/
3724 VLIB_CLI_COMMAND (snat_det_close_sesion_out_command, static) = {
3725   .path = "snat deterministic close session out",
3726   .short_help = "snat deterministic close session out "
3727                 "<out_addr>:<out_port> <ext_addr>:<ext_port>",
3728   .function = snat_det_close_session_out_fn,
3729 };
3730
3731 static clib_error_t *
3732 snat_det_close_session_in_fn (vlib_main_t *vm,
3733                               unformat_input_t * input,
3734                               vlib_cli_command_t * cmd)
3735 {
3736   snat_main_t *sm = &snat_main;
3737   unformat_input_t _line_input, *line_input = &_line_input;
3738   ip4_address_t in_addr, ext_addr;
3739   u16 in_port, ext_port;
3740   snat_det_map_t * dm;
3741   snat_det_session_t * ses;
3742   snat_det_out_key_t key;
3743   clib_error_t *error = 0;
3744
3745   /* Get a line of input. */
3746   if (!unformat_user (input, unformat_line_input, line_input))
3747     return 0;
3748
3749   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
3750     {
3751       if (unformat (line_input, "%U:%d %U:%d",
3752                     unformat_ip4_address, &in_addr, &in_port,
3753                     unformat_ip4_address, &ext_addr, &ext_port))
3754         ;
3755       else
3756         {
3757           error = clib_error_return (0, "unknown input '%U'",
3758                                      format_unformat_error, line_input);
3759           goto done;
3760         }
3761     }
3762
3763   unformat_free (line_input);
3764
3765   dm = snat_det_map_by_user (sm, &in_addr);
3766   if (!dm)
3767     vlib_cli_output (vm, "no match");
3768   else
3769     {
3770       key.ext_host_addr = ext_addr;
3771       key.ext_host_port = ntohs (ext_port);
3772       ses = snat_det_find_ses_by_in (dm, &in_addr, ntohs(in_port), key);
3773       if (!ses)
3774         vlib_cli_output (vm, "no match");
3775       else
3776         snat_det_ses_close(dm, ses);
3777     }
3778
3779 done:
3780   unformat_free(line_input);
3781
3782   return error;
3783 }
3784
3785 /*?
3786  * @cliexpar
3787  * @cliexstart{snat deterministic close_session_in}
3788  * Close session using inside ip address and port
3789  * and external ip address and port, use:
3790  *  vpp# snat deterministic close session in 3.3.3.3:3487 2.2.2.2:2387
3791  * @cliexend
3792 ?*/
3793 VLIB_CLI_COMMAND (snat_det_close_session_in_command, static) = {
3794   .path = "snat deterministic close session in",
3795   .short_help = "snat deterministic close session in "
3796                 "<in_addr>:<in_port> <ext_addr>:<ext_port>",
3797   .function = snat_det_close_session_in_fn,
3798 };