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