fib: Decouple source from priority and behaviour
[vpp.git] / src / plugins / nat / nat64.c
1 /*
2  * Copyright (c) 2017 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /**
16  * @file
17  * @brief NAT64 implementation
18  */
19
20 #include <nat/nat64.h>
21 #include <nat/nat64_db.h>
22 #include <nat/nat_reass.h>
23 #include <nat/nat_inlines.h>
24 #include <vnet/fib/ip4_fib.h>
25 #include <vppinfra/crc32.h>
26
27
28 nat64_main_t nat64_main;
29
30 /* *INDENT-OFF* */
31
32 /* Hook up input features */
33 VNET_FEATURE_INIT (nat64_in2out, static) = {
34   .arc_name = "ip6-unicast",
35   .node_name = "nat64-in2out",
36   .runs_before = VNET_FEATURES ("ip6-lookup"),
37 };
38 VNET_FEATURE_INIT (nat64_out2in, static) = {
39   .arc_name = "ip4-unicast",
40   .node_name = "nat64-out2in",
41   .runs_before = VNET_FEATURES ("ip4-lookup"),
42 };
43 VNET_FEATURE_INIT (nat64_in2out_handoff, static) = {
44   .arc_name = "ip6-unicast",
45   .node_name = "nat64-in2out-handoff",
46   .runs_before = VNET_FEATURES ("ip6-lookup"),
47 };
48 VNET_FEATURE_INIT (nat64_out2in_handoff, static) = {
49   .arc_name = "ip4-unicast",
50   .node_name = "nat64-out2in-handoff",
51   .runs_before = VNET_FEATURES ("ip4-lookup"),
52 };
53
54
55 static u8 well_known_prefix[] = {
56   0x00, 0x64, 0xff, 0x9b,
57   0x00, 0x00, 0x00, 0x00,
58   0x00, 0x00, 0x00, 0x00,
59   0x00, 0x00, 0x00, 0x00
60 };
61
62 /* *INDENT-ON* */
63
64 static void
65 nat64_ip4_add_del_interface_address_cb (ip4_main_t * im, uword opaque,
66                                         u32 sw_if_index,
67                                         ip4_address_t * address,
68                                         u32 address_length,
69                                         u32 if_address_index, u32 is_delete)
70 {
71   nat64_main_t *nm = &nat64_main;
72   int i, j;
73
74   for (i = 0; i < vec_len (nm->auto_add_sw_if_indices); i++)
75     {
76       if (sw_if_index == nm->auto_add_sw_if_indices[i])
77         {
78           if (!is_delete)
79             {
80               /* Don't trip over lease renewal, static config */
81               for (j = 0; j < vec_len (nm->addr_pool); j++)
82                 if (nm->addr_pool[j].addr.as_u32 == address->as_u32)
83                   return;
84
85               (void) nat64_add_del_pool_addr (vlib_get_thread_index (),
86                                               address, ~0, 1);
87               return;
88             }
89           else
90             {
91               (void) nat64_add_del_pool_addr (vlib_get_thread_index (),
92                                               address, ~0, 0);
93               return;
94             }
95         }
96     }
97 }
98
99 u32
100 nat64_get_worker_in2out (ip6_address_t * addr)
101 {
102   nat64_main_t *nm = &nat64_main;
103   snat_main_t *sm = nm->sm;
104   u32 next_worker_index = nm->sm->first_worker_index;
105   u32 hash;
106
107 #ifdef clib_crc32c_uses_intrinsics
108   hash = clib_crc32c ((u8 *) addr->as_u32, 16);
109 #else
110   u64 tmp = addr->as_u64[0] ^ addr->as_u64[1];
111   hash = clib_xxhash (tmp);
112 #endif
113
114   if (PREDICT_TRUE (is_pow2 (_vec_len (sm->workers))))
115     next_worker_index += sm->workers[hash & (_vec_len (sm->workers) - 1)];
116   else
117     next_worker_index += sm->workers[hash % _vec_len (sm->workers)];
118
119   return next_worker_index;
120 }
121
122 u32
123 nat64_get_worker_out2in (ip4_header_t * ip)
124 {
125   nat64_main_t *nm = &nat64_main;
126   snat_main_t *sm = nm->sm;
127   udp_header_t *udp;
128   u16 port;
129   u32 proto;
130
131   proto = ip_proto_to_snat_proto (ip->protocol);
132   udp = ip4_next_header (ip);
133   port = udp->dst_port;
134
135   /* fragments */
136   if (PREDICT_FALSE (ip4_is_fragment (ip)))
137     {
138       if (PREDICT_FALSE (nat_reass_is_drop_frag (0)))
139         return vlib_get_thread_index ();
140
141       nat_reass_ip4_t *reass;
142       reass = nat_ip4_reass_find (ip->src_address, ip->dst_address,
143                                   ip->fragment_id, ip->protocol);
144
145       if (reass && (reass->thread_index != (u32) ~ 0))
146         return reass->thread_index;
147
148       if (ip4_is_first_fragment (ip))
149         {
150           reass =
151             nat_ip4_reass_create (ip->src_address, ip->dst_address,
152                                   ip->fragment_id, ip->protocol);
153           if (!reass)
154             goto no_reass;
155
156           port = clib_net_to_host_u16 (port);
157           if (port > 1024)
158             reass->thread_index =
159               nm->sm->first_worker_index +
160               ((port - 1024) / sm->port_per_thread);
161           else
162             reass->thread_index = vlib_get_thread_index ();
163           return reass->thread_index;
164         }
165       else
166         return vlib_get_thread_index ();
167     }
168
169 no_reass:
170   /* unknown protocol */
171   if (PREDICT_FALSE (proto == ~0))
172     {
173       nat64_db_t *db;
174       ip46_address_t daddr;
175       nat64_db_bib_entry_t *bibe;
176
177       clib_memset (&daddr, 0, sizeof (daddr));
178       daddr.ip4.as_u32 = ip->dst_address.as_u32;
179
180       /* *INDENT-OFF* */
181       vec_foreach (db, nm->db)
182         {
183           bibe = nat64_db_bib_entry_find (db, &daddr, 0, ip->protocol, 0, 0);
184           if (bibe)
185             return (u32) (db - nm->db);
186         }
187       /* *INDENT-ON* */
188       return vlib_get_thread_index ();
189     }
190
191   /* ICMP */
192   if (PREDICT_FALSE (ip->protocol == IP_PROTOCOL_ICMP))
193     {
194       icmp46_header_t *icmp = (icmp46_header_t *) udp;
195       icmp_echo_header_t *echo = (icmp_echo_header_t *) (icmp + 1);
196       if (!icmp_is_error_message (icmp))
197         port = echo->identifier;
198       else
199         {
200           ip4_header_t *inner_ip = (ip4_header_t *) (echo + 1);
201           proto = ip_proto_to_snat_proto (inner_ip->protocol);
202           void *l4_header = ip4_next_header (inner_ip);
203           switch (proto)
204             {
205             case SNAT_PROTOCOL_ICMP:
206               icmp = (icmp46_header_t *) l4_header;
207               echo = (icmp_echo_header_t *) (icmp + 1);
208               port = echo->identifier;
209               break;
210             case SNAT_PROTOCOL_UDP:
211             case SNAT_PROTOCOL_TCP:
212               port = ((tcp_udp_header_t *) l4_header)->src_port;
213               break;
214             default:
215               return vlib_get_thread_index ();
216             }
217         }
218     }
219
220   /* worker by outside port  (TCP/UDP) */
221   port = clib_net_to_host_u16 (port);
222   if (port > 1024)
223     return nm->sm->first_worker_index + ((port - 1024) / sm->port_per_thread);
224
225   return vlib_get_thread_index ();
226 }
227
228 clib_error_t *
229 nat64_init (vlib_main_t * vm)
230 {
231   nat64_main_t *nm = &nat64_main;
232   vlib_thread_main_t *tm = vlib_get_thread_main ();
233   ip4_add_del_interface_address_callback_t cb4;
234   ip4_main_t *im = &ip4_main;
235   nm->sm = &snat_main;
236   vlib_node_t *node;
237
238   vec_validate (nm->db, tm->n_vlib_mains - 1);
239
240   nm->fq_in2out_index = ~0;
241   nm->fq_out2in_index = ~0;
242
243   node = vlib_get_node_by_name (vm, (u8 *) "error-drop");
244   nm->error_node_index = node->index;
245
246   node = vlib_get_node_by_name (vm, (u8 *) "nat64-in2out");
247   nm->in2out_node_index = node->index;
248
249   node = vlib_get_node_by_name (vm, (u8 *) "nat64-in2out-slowpath");
250   nm->in2out_slowpath_node_index = node->index;
251
252   node = vlib_get_node_by_name (vm, (u8 *) "nat64-in2out-reass");
253   nm->in2out_reass_node_index = node->index;
254
255   node = vlib_get_node_by_name (vm, (u8 *) "nat64-out2in");
256   nm->out2in_node_index = node->index;
257
258   node = vlib_get_node_by_name (vm, (u8 *) "nat64-out2in-reass");
259   nm->out2in_reass_node_index = node->index;
260
261   /* set session timeouts to default values */
262   nm->udp_timeout = SNAT_UDP_TIMEOUT;
263   nm->icmp_timeout = SNAT_ICMP_TIMEOUT;
264   nm->tcp_trans_timeout = SNAT_TCP_TRANSITORY_TIMEOUT;
265   nm->tcp_est_timeout = SNAT_TCP_ESTABLISHED_TIMEOUT;
266
267   nm->total_enabled_count = 0;
268
269   /* Set up the interface address add/del callback */
270   cb4.function = nat64_ip4_add_del_interface_address_cb;
271   cb4.function_opaque = 0;
272   vec_add1 (im->add_del_interface_address_callbacks, cb4);
273   nm->ip4_main = im;
274
275   /* Init counters */
276   nm->total_bibs.name = "total-bibs";
277   nm->total_bibs.stat_segment_name = "/nat64/total-bibs";
278   vlib_validate_simple_counter (&nm->total_bibs, 0);
279   vlib_zero_simple_counter (&nm->total_bibs, 0);
280   nm->total_sessions.name = "total-sessions";
281   nm->total_sessions.stat_segment_name = "/nat64/total-sessions";
282   vlib_validate_simple_counter (&nm->total_sessions, 0);
283   vlib_zero_simple_counter (&nm->total_sessions, 0);
284
285   return 0;
286 }
287
288 static void nat64_free_out_addr_and_port (struct nat64_db_s *db,
289                                           ip4_address_t * addr, u16 port,
290                                           u8 protocol);
291
292 void
293 nat64_set_hash (u32 bib_buckets, u32 bib_memory_size, u32 st_buckets,
294                 u32 st_memory_size)
295 {
296   nat64_main_t *nm = &nat64_main;
297   nat64_db_t *db;
298
299   nm->bib_buckets = bib_buckets;
300   nm->bib_memory_size = bib_memory_size;
301   nm->st_buckets = st_buckets;
302   nm->st_memory_size = st_memory_size;
303
304   /* *INDENT-OFF* */
305   vec_foreach (db, nm->db)
306     {
307       if (nat64_db_init (db, bib_buckets, bib_memory_size, st_buckets,
308                          st_memory_size, nat64_free_out_addr_and_port))
309         nat_elog_err ("NAT64 DB init failed");
310     }
311   /* *INDENT-ON* */
312 }
313
314 int
315 nat64_add_del_pool_addr (u32 thread_index,
316                          ip4_address_t * addr, u32 vrf_id, u8 is_add)
317 {
318   nat64_main_t *nm = &nat64_main;
319   snat_address_t *a = 0;
320   snat_interface_t *interface;
321   int i;
322   nat64_db_t *db;
323   vlib_thread_main_t *tm = vlib_get_thread_main ();
324
325   /* Check if address already exists */
326   for (i = 0; i < vec_len (nm->addr_pool); i++)
327     {
328       if (nm->addr_pool[i].addr.as_u32 == addr->as_u32)
329         {
330           a = nm->addr_pool + i;
331           break;
332         }
333     }
334
335   if (is_add)
336     {
337       if (a)
338         return VNET_API_ERROR_VALUE_EXIST;
339
340       vec_add2 (nm->addr_pool, a, 1);
341       a->addr = *addr;
342       a->fib_index = ~0;
343       if (vrf_id != ~0)
344         a->fib_index =
345           fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP6, vrf_id,
346                                              nat_fib_src_hi);
347 #define _(N, id, n, s) \
348       clib_bitmap_alloc (a->busy_##n##_port_bitmap, 65535); \
349       a->busy_##n##_ports = 0; \
350       vec_validate_init_empty (a->busy_##n##_ports_per_thread, tm->n_vlib_mains - 1, 0);
351       foreach_snat_protocol
352 #undef _
353     }
354   else
355     {
356       if (!a)
357         return VNET_API_ERROR_NO_SUCH_ENTRY;
358
359       if (a->fib_index != ~0)
360         fib_table_unlock (a->fib_index, FIB_PROTOCOL_IP6, nat_fib_src_hi);
361       /* Delete sessions using address */
362         /* *INDENT-OFF* */
363         vec_foreach (db, nm->db)
364           {
365             nat64_db_free_out_addr (thread_index, db, &a->addr);
366             vlib_set_simple_counter (&nm->total_bibs, db - nm->db, 0,
367                                      db->bib.bib_entries_num);
368             vlib_set_simple_counter (&nm->total_sessions, db - nm->db, 0,
369                                      db->st.st_entries_num);
370           }
371 #define _(N, id, n, s) \
372       clib_bitmap_free (a->busy_##n##_port_bitmap);
373       foreach_snat_protocol
374 #undef _
375         /* *INDENT-ON* */
376       vec_del1 (nm->addr_pool, i);
377     }
378
379   /* Add/del external address to FIB */
380   /* *INDENT-OFF* */
381   pool_foreach (interface, nm->interfaces,
382   ({
383     if (nat_interface_is_inside(interface))
384       continue;
385
386     snat_add_del_addr_to_fib (addr, 32, interface->sw_if_index, is_add);
387     break;
388   }));
389   /* *INDENT-ON* */
390
391   return 0;
392 }
393
394 void
395 nat64_pool_addr_walk (nat64_pool_addr_walk_fn_t fn, void *ctx)
396 {
397   nat64_main_t *nm = &nat64_main;
398   snat_address_t *a = 0;
399
400   /* *INDENT-OFF* */
401   vec_foreach (a, nm->addr_pool)
402     {
403       if (fn (a, ctx))
404         break;
405     };
406   /* *INDENT-ON* */
407 }
408
409 int
410 nat64_add_interface_address (u32 sw_if_index, int is_add)
411 {
412   nat64_main_t *nm = &nat64_main;
413   ip4_main_t *ip4_main = nm->ip4_main;
414   ip4_address_t *first_int_addr;
415   int i;
416
417   first_int_addr = ip4_interface_first_address (ip4_main, sw_if_index, 0);
418
419   for (i = 0; i < vec_len (nm->auto_add_sw_if_indices); i++)
420     {
421       if (nm->auto_add_sw_if_indices[i] == sw_if_index)
422         {
423           if (is_add)
424             return VNET_API_ERROR_VALUE_EXIST;
425           else
426             {
427               /* if have address remove it */
428               if (first_int_addr)
429                 (void) nat64_add_del_pool_addr (vlib_get_thread_index (),
430                                                 first_int_addr, ~0, 0);
431               vec_del1 (nm->auto_add_sw_if_indices, i);
432               return 0;
433             }
434         }
435     }
436
437   if (!is_add)
438     return VNET_API_ERROR_NO_SUCH_ENTRY;
439
440   /* add to the auto-address list */
441   vec_add1 (nm->auto_add_sw_if_indices, sw_if_index);
442
443   /* If the address is already bound - or static - add it now */
444   if (first_int_addr)
445     (void) nat64_add_del_pool_addr (vlib_get_thread_index (),
446                                     first_int_addr, ~0, 1);
447
448   return 0;
449 }
450
451 int
452 nat64_add_del_interface (u32 sw_if_index, u8 is_inside, u8 is_add)
453 {
454   nat64_main_t *nm = &nat64_main;
455   snat_interface_t *interface = 0, *i;
456   snat_address_t *ap;
457   const char *feature_name, *arc_name;
458
459   /* Check if interface already exists */
460   /* *INDENT-OFF* */
461   pool_foreach (i, nm->interfaces,
462   ({
463     if (i->sw_if_index == sw_if_index)
464       {
465         interface = i;
466         break;
467       }
468   }));
469   /* *INDENT-ON* */
470
471   if (is_add)
472     {
473       if (interface)
474         goto set_flags;
475
476       pool_get (nm->interfaces, interface);
477       interface->sw_if_index = sw_if_index;
478       interface->flags = 0;
479     set_flags:
480       if (is_inside)
481         interface->flags |= NAT_INTERFACE_FLAG_IS_INSIDE;
482       else
483         interface->flags |= NAT_INTERFACE_FLAG_IS_OUTSIDE;
484
485       nm->total_enabled_count++;
486       vlib_process_signal_event (nm->sm->vlib_main,
487                                  nm->nat64_expire_walk_node_index,
488                                  NAT64_CLEANER_RESCHEDULE, 0);
489
490     }
491   else
492     {
493       if (!interface)
494         return VNET_API_ERROR_NO_SUCH_ENTRY;
495
496       if ((nat_interface_is_inside (interface)
497            && nat_interface_is_outside (interface)))
498         interface->flags &=
499           is_inside ? ~NAT_INTERFACE_FLAG_IS_INSIDE :
500           ~NAT_INTERFACE_FLAG_IS_OUTSIDE;
501       else
502         pool_put (nm->interfaces, interface);
503
504       nm->total_enabled_count--;
505     }
506
507   if (!is_inside)
508     {
509       /* *INDENT-OFF* */
510       vec_foreach (ap, nm->addr_pool)
511         snat_add_del_addr_to_fib(&ap->addr, 32, sw_if_index, is_add);
512       /* *INDENT-ON* */
513     }
514
515   if (nm->sm->num_workers > 1)
516     {
517       feature_name =
518         is_inside ? "nat64-in2out-handoff" : "nat64-out2in-handoff";
519       if (nm->fq_in2out_index == ~0)
520         nm->fq_in2out_index =
521           vlib_frame_queue_main_init (nat64_in2out_node.index, 0);
522       if (nm->fq_out2in_index == ~0)
523         nm->fq_out2in_index =
524           vlib_frame_queue_main_init (nat64_out2in_node.index, 0);
525     }
526   else
527     feature_name = is_inside ? "nat64-in2out" : "nat64-out2in";
528
529   arc_name = is_inside ? "ip6-unicast" : "ip4-unicast";
530
531   return vnet_feature_enable_disable (arc_name, feature_name, sw_if_index,
532                                       is_add, 0, 0);
533 }
534
535 void
536 nat64_interfaces_walk (nat64_interface_walk_fn_t fn, void *ctx)
537 {
538   nat64_main_t *nm = &nat64_main;
539   snat_interface_t *i = 0;
540
541   /* *INDENT-OFF* */
542   pool_foreach (i, nm->interfaces,
543   ({
544     if (fn (i, ctx))
545       break;
546   }));
547   /* *INDENT-ON* */
548 }
549
550 int
551 nat64_alloc_out_addr_and_port (u32 fib_index, snat_protocol_t proto,
552                                ip4_address_t * addr, u16 * port,
553                                u32 thread_index)
554 {
555   nat64_main_t *nm = &nat64_main;
556   snat_main_t *sm = nm->sm;
557   snat_session_key_t k;
558   u32 worker_index = 0;
559   int rv;
560
561   k.protocol = proto;
562
563   if (sm->num_workers > 1)
564     worker_index = thread_index - sm->first_worker_index;
565
566   rv =
567     sm->alloc_addr_and_port (nm->addr_pool, fib_index, thread_index, &k,
568                              sm->port_per_thread, worker_index);
569
570   if (!rv)
571     {
572       *port = k.port;
573       addr->as_u32 = k.addr.as_u32;
574     }
575
576   return rv;
577 }
578
579 static void
580 nat64_free_out_addr_and_port (struct nat64_db_s *db, ip4_address_t * addr,
581                               u16 port, u8 protocol)
582 {
583   nat64_main_t *nm = &nat64_main;
584   int i;
585   snat_address_t *a;
586   u32 thread_index = db - nm->db;
587   snat_protocol_t proto = ip_proto_to_snat_proto (protocol);
588   u16 port_host_byte_order = clib_net_to_host_u16 (port);
589
590   for (i = 0; i < vec_len (nm->addr_pool); i++)
591     {
592       a = nm->addr_pool + i;
593       if (addr->as_u32 != a->addr.as_u32)
594         continue;
595       switch (proto)
596         {
597 #define _(N, j, n, s) \
598         case SNAT_PROTOCOL_##N: \
599           ASSERT (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, \
600                   port_host_byte_order) == 1); \
601           clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, port_host_byte_order, 0); \
602           a->busy_##n##_ports--; \
603           a->busy_##n##_ports_per_thread[thread_index]--; \
604           break;
605           foreach_snat_protocol
606 #undef _
607         default:
608           nat_elog_notice ("unknown protocol");
609           return;
610         }
611       break;
612     }
613 }
614
615 /**
616  * @brief Add/delete static BIB entry in worker thread.
617  */
618 static uword
619 nat64_static_bib_worker_fn (vlib_main_t * vm, vlib_node_runtime_t * rt,
620                             vlib_frame_t * f)
621 {
622   nat64_main_t *nm = &nat64_main;
623   u32 thread_index = vm->thread_index;
624   nat64_db_t *db = &nm->db[thread_index];
625   nat64_static_bib_to_update_t *static_bib;
626   nat64_db_bib_entry_t *bibe;
627   ip46_address_t addr;
628
629   /* *INDENT-OFF* */
630   pool_foreach (static_bib, nm->static_bibs,
631   ({
632     if ((static_bib->thread_index != thread_index) || (static_bib->done))
633       continue;
634
635     if (static_bib->is_add)
636       {
637           (void) nat64_db_bib_entry_create (thread_index, db,
638                                             &static_bib->in_addr,
639                                             &static_bib->out_addr,
640                                             static_bib->in_port,
641                                             static_bib->out_port,
642                                             static_bib->fib_index,
643                                             static_bib->proto, 1);
644           vlib_set_simple_counter (&nm->total_bibs, thread_index, 0,
645                                    db->bib.bib_entries_num);
646       }
647     else
648       {
649         addr.as_u64[0] = static_bib->in_addr.as_u64[0];
650         addr.as_u64[1] = static_bib->in_addr.as_u64[1];
651         bibe = nat64_db_bib_entry_find (db, &addr, static_bib->in_port,
652                                         static_bib->proto,
653                                         static_bib->fib_index, 1);
654         if (bibe)
655           {
656             nat64_db_bib_entry_free (thread_index, db, bibe);
657             vlib_set_simple_counter (&nm->total_bibs, thread_index, 0,
658                                      db->bib.bib_entries_num);
659             vlib_set_simple_counter (&nm->total_sessions, thread_index, 0,
660                                      db->st.st_entries_num);
661           }
662       }
663
664       static_bib->done = 1;
665   }));
666   /* *INDENT-ON* */
667
668   return 0;
669 }
670
671 static vlib_node_registration_t nat64_static_bib_worker_node;
672
673 /* *INDENT-OFF* */
674 VLIB_REGISTER_NODE (nat64_static_bib_worker_node, static) = {
675     .function = nat64_static_bib_worker_fn,
676     .type = VLIB_NODE_TYPE_INPUT,
677     .state = VLIB_NODE_STATE_INTERRUPT,
678     .name = "nat64-static-bib-worker",
679 };
680 /* *INDENT-ON* */
681
682 int
683 nat64_add_del_static_bib_entry (ip6_address_t * in_addr,
684                                 ip4_address_t * out_addr, u16 in_port,
685                                 u16 out_port, u8 proto, u32 vrf_id, u8 is_add)
686 {
687   nat64_main_t *nm = &nat64_main;
688   nat64_db_bib_entry_t *bibe;
689   u32 fib_index = fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP6, vrf_id,
690                                                      nat_fib_src_hi);
691   snat_protocol_t p = ip_proto_to_snat_proto (proto);
692   ip46_address_t addr;
693   int i;
694   snat_address_t *a;
695   u32 thread_index = 0;
696   nat64_db_t *db;
697   nat64_static_bib_to_update_t *static_bib;
698   vlib_main_t *worker_vm;
699   u32 *to_be_free = 0, *index;
700
701   if (nm->sm->num_workers > 1)
702     {
703       thread_index = nat64_get_worker_in2out (in_addr);
704       db = &nm->db[thread_index];
705     }
706   else
707     db = &nm->db[nm->sm->num_workers];
708
709   addr.as_u64[0] = in_addr->as_u64[0];
710   addr.as_u64[1] = in_addr->as_u64[1];
711   bibe =
712     nat64_db_bib_entry_find (db, &addr, clib_host_to_net_u16 (in_port),
713                              proto, fib_index, 1);
714
715   if (is_add)
716     {
717       if (bibe)
718         return VNET_API_ERROR_VALUE_EXIST;
719
720       /* outside port must be assigned to same thread as internall address */
721       if ((out_port > 1024) && (nm->sm->num_workers > 1))
722         {
723           if (thread_index != ((out_port - 1024) / nm->sm->port_per_thread))
724             return VNET_API_ERROR_INVALID_VALUE_2;
725         }
726
727       for (i = 0; i < vec_len (nm->addr_pool); i++)
728         {
729           a = nm->addr_pool + i;
730           if (out_addr->as_u32 != a->addr.as_u32)
731             continue;
732           switch (p)
733             {
734 #define _(N, j, n, s) \
735             case SNAT_PROTOCOL_##N: \
736               if (clib_bitmap_get_no_check (a->busy_##n##_port_bitmap, \
737                                             out_port)) \
738                 return VNET_API_ERROR_INVALID_VALUE; \
739               clib_bitmap_set_no_check (a->busy_##n##_port_bitmap, \
740                                         out_port, 1); \
741               if (out_port > 1024) \
742                 { \
743                   a->busy_##n##_ports++; \
744                   a->busy_##n##_ports_per_thread[thread_index]++; \
745                 } \
746               break;
747               foreach_snat_protocol
748 #undef _
749             default:
750               clib_memset (&addr, 0, sizeof (addr));
751               addr.ip4.as_u32 = out_addr->as_u32;
752               if (nat64_db_bib_entry_find (db, &addr, 0, proto, fib_index, 0))
753                 return VNET_API_ERROR_INVALID_VALUE;
754             }
755           break;
756         }
757       if (!nm->sm->num_workers)
758         {
759           bibe =
760             nat64_db_bib_entry_create (thread_index, db, in_addr, out_addr,
761                                        clib_host_to_net_u16 (in_port),
762                                        clib_host_to_net_u16 (out_port),
763                                        fib_index, proto, 1);
764           if (!bibe)
765             return VNET_API_ERROR_UNSPECIFIED;
766
767           vlib_set_simple_counter (&nm->total_bibs, thread_index, 0,
768                                    db->bib.bib_entries_num);
769         }
770     }
771   else
772     {
773       if (!bibe)
774         return VNET_API_ERROR_NO_SUCH_ENTRY;
775
776       if (!nm->sm->num_workers)
777         {
778           nat64_db_bib_entry_free (thread_index, db, bibe);
779           vlib_set_simple_counter (&nm->total_bibs, thread_index, 0,
780                                    db->bib.bib_entries_num);
781         }
782     }
783
784   if (nm->sm->num_workers)
785     {
786       /* *INDENT-OFF* */
787       pool_foreach (static_bib, nm->static_bibs,
788       ({
789         if (static_bib->done)
790           vec_add1 (to_be_free, static_bib - nm->static_bibs);
791       }));
792       vec_foreach (index, to_be_free)
793         pool_put_index (nm->static_bibs, index[0]);
794       /* *INDENT-ON* */
795       vec_free (to_be_free);
796       pool_get (nm->static_bibs, static_bib);
797       static_bib->in_addr.as_u64[0] = in_addr->as_u64[0];
798       static_bib->in_addr.as_u64[1] = in_addr->as_u64[1];
799       static_bib->in_port = clib_host_to_net_u16 (in_port);
800       static_bib->out_addr.as_u32 = out_addr->as_u32;
801       static_bib->out_port = clib_host_to_net_u16 (out_port);
802       static_bib->fib_index = fib_index;
803       static_bib->proto = proto;
804       static_bib->is_add = is_add;
805       static_bib->thread_index = thread_index;
806       static_bib->done = 0;
807       worker_vm = vlib_mains[thread_index];
808       if (worker_vm)
809         vlib_node_set_interrupt_pending (worker_vm,
810                                          nat64_static_bib_worker_node.index);
811       else
812         return VNET_API_ERROR_UNSPECIFIED;
813     }
814
815   return 0;
816 }
817
818 int
819 nat64_set_udp_timeout (u32 timeout)
820 {
821   nat64_main_t *nm = &nat64_main;
822
823   if (timeout == 0)
824     nm->udp_timeout = SNAT_UDP_TIMEOUT;
825   else
826     nm->udp_timeout = timeout;
827
828   return 0;
829 }
830
831 u32
832 nat64_get_udp_timeout (void)
833 {
834   nat64_main_t *nm = &nat64_main;
835
836   return nm->udp_timeout;
837 }
838
839 int
840 nat64_set_icmp_timeout (u32 timeout)
841 {
842   nat64_main_t *nm = &nat64_main;
843
844   if (timeout == 0)
845     nm->icmp_timeout = SNAT_ICMP_TIMEOUT;
846   else
847     nm->icmp_timeout = timeout;
848
849   return 0;
850 }
851
852 u32
853 nat64_get_icmp_timeout (void)
854 {
855   nat64_main_t *nm = &nat64_main;
856
857   return nm->icmp_timeout;
858 }
859
860 int
861 nat64_set_tcp_timeouts (u32 trans, u32 est)
862 {
863   nat64_main_t *nm = &nat64_main;
864
865   if (trans == 0)
866     nm->tcp_trans_timeout = SNAT_TCP_TRANSITORY_TIMEOUT;
867   else
868     nm->tcp_trans_timeout = trans;
869
870   if (est == 0)
871     nm->tcp_est_timeout = SNAT_TCP_ESTABLISHED_TIMEOUT;
872   else
873     nm->tcp_est_timeout = est;
874
875   return 0;
876 }
877
878 u32
879 nat64_get_tcp_trans_timeout (void)
880 {
881   nat64_main_t *nm = &nat64_main;
882
883   return nm->tcp_trans_timeout;
884 }
885
886 u32
887 nat64_get_tcp_est_timeout (void)
888 {
889   nat64_main_t *nm = &nat64_main;
890
891   return nm->tcp_est_timeout;
892 }
893
894 void
895 nat64_session_reset_timeout (nat64_db_st_entry_t * ste, vlib_main_t * vm)
896 {
897   nat64_main_t *nm = &nat64_main;
898   u32 now = (u32) vlib_time_now (vm);
899
900   switch (ip_proto_to_snat_proto (ste->proto))
901     {
902     case SNAT_PROTOCOL_ICMP:
903       ste->expire = now + nm->icmp_timeout;
904       return;
905     case SNAT_PROTOCOL_TCP:
906       {
907         switch (ste->tcp_state)
908           {
909           case NAT64_TCP_STATE_V4_INIT:
910           case NAT64_TCP_STATE_V6_INIT:
911           case NAT64_TCP_STATE_V4_FIN_RCV:
912           case NAT64_TCP_STATE_V6_FIN_RCV:
913           case NAT64_TCP_STATE_V6_FIN_V4_FIN_RCV:
914           case NAT64_TCP_STATE_TRANS:
915             ste->expire = now + nm->tcp_trans_timeout;
916             return;
917           case NAT64_TCP_STATE_ESTABLISHED:
918             ste->expire = now + nm->tcp_est_timeout;
919             return;
920           default:
921             return;
922           }
923       }
924     case SNAT_PROTOCOL_UDP:
925       ste->expire = now + nm->udp_timeout;
926       return;
927     default:
928       ste->expire = now + nm->udp_timeout;
929       return;
930     }
931 }
932
933 void
934 nat64_tcp_session_set_state (nat64_db_st_entry_t * ste, tcp_header_t * tcp,
935                              u8 is_ip6)
936 {
937   switch (ste->tcp_state)
938     {
939     case NAT64_TCP_STATE_CLOSED:
940       {
941         if (tcp->flags & TCP_FLAG_SYN)
942           {
943             if (is_ip6)
944               ste->tcp_state = NAT64_TCP_STATE_V6_INIT;
945             else
946               ste->tcp_state = NAT64_TCP_STATE_V4_INIT;
947           }
948         return;
949       }
950     case NAT64_TCP_STATE_V4_INIT:
951       {
952         if (is_ip6 && (tcp->flags & TCP_FLAG_SYN))
953           ste->tcp_state = NAT64_TCP_STATE_ESTABLISHED;
954         return;
955       }
956     case NAT64_TCP_STATE_V6_INIT:
957       {
958         if (!is_ip6 && (tcp->flags & TCP_FLAG_SYN))
959           ste->tcp_state = NAT64_TCP_STATE_ESTABLISHED;
960         return;
961       }
962     case NAT64_TCP_STATE_ESTABLISHED:
963       {
964         if (tcp->flags & TCP_FLAG_FIN)
965           {
966             if (is_ip6)
967               ste->tcp_state = NAT64_TCP_STATE_V6_FIN_RCV;
968             else
969               ste->tcp_state = NAT64_TCP_STATE_V4_FIN_RCV;
970           }
971         else if (tcp->flags & TCP_FLAG_RST)
972           {
973             ste->tcp_state = NAT64_TCP_STATE_TRANS;
974           }
975         return;
976       }
977     case NAT64_TCP_STATE_V4_FIN_RCV:
978       {
979         if (is_ip6 && (tcp->flags & TCP_FLAG_FIN))
980           ste->tcp_state = NAT64_TCP_STATE_V6_FIN_V4_FIN_RCV;
981         return;
982       }
983     case NAT64_TCP_STATE_V6_FIN_RCV:
984       {
985         if (!is_ip6 && (tcp->flags & TCP_FLAG_FIN))
986           ste->tcp_state = NAT64_TCP_STATE_V6_FIN_V4_FIN_RCV;
987         return;
988       }
989     case NAT64_TCP_STATE_TRANS:
990       {
991         if (!(tcp->flags & TCP_FLAG_RST))
992           ste->tcp_state = NAT64_TCP_STATE_ESTABLISHED;
993         return;
994       }
995     default:
996       return;
997     }
998 }
999
1000 int
1001 nat64_add_del_prefix (ip6_address_t * prefix, u8 plen, u32 vrf_id, u8 is_add)
1002 {
1003   nat64_main_t *nm = &nat64_main;
1004   nat64_prefix_t *p = 0;
1005   int i;
1006
1007   /* Verify prefix length */
1008   if (plen != 32 && plen != 40 && plen != 48 && plen != 56 && plen != 64
1009       && plen != 96)
1010     return VNET_API_ERROR_INVALID_VALUE;
1011
1012   /* Check if tenant already have prefix */
1013   for (i = 0; i < vec_len (nm->pref64); i++)
1014     {
1015       if (nm->pref64[i].vrf_id == vrf_id)
1016         {
1017           p = nm->pref64 + i;
1018           break;
1019         }
1020     }
1021
1022   if (is_add)
1023     {
1024       if (!p)
1025         {
1026           vec_add2 (nm->pref64, p, 1);
1027           p->fib_index =
1028             fib_table_find_or_create_and_lock (FIB_PROTOCOL_IP6, vrf_id,
1029                                                nat_fib_src_hi);
1030           p->vrf_id = vrf_id;
1031         }
1032
1033       p->prefix.as_u64[0] = prefix->as_u64[0];
1034       p->prefix.as_u64[1] = prefix->as_u64[1];
1035       p->plen = plen;
1036     }
1037   else
1038     {
1039       if (!p)
1040         return VNET_API_ERROR_NO_SUCH_ENTRY;
1041
1042       vec_del1 (nm->pref64, i);
1043     }
1044
1045   return 0;
1046 }
1047
1048 void
1049 nat64_prefix_walk (nat64_prefix_walk_fn_t fn, void *ctx)
1050 {
1051   nat64_main_t *nm = &nat64_main;
1052   nat64_prefix_t *p = 0;
1053
1054   /* *INDENT-OFF* */
1055   vec_foreach (p, nm->pref64)
1056     {
1057       if (fn (p, ctx))
1058         break;
1059     };
1060   /* *INDENT-ON* */
1061 }
1062
1063 void
1064 nat64_compose_ip6 (ip6_address_t * ip6, ip4_address_t * ip4, u32 fib_index)
1065 {
1066   nat64_main_t *nm = &nat64_main;
1067   nat64_prefix_t *p, *gp = 0, *prefix = 0;
1068
1069   /* *INDENT-OFF* */
1070   vec_foreach (p, nm->pref64)
1071     {
1072       if (p->fib_index == fib_index)
1073         {
1074           prefix = p;
1075           break;
1076         }
1077
1078       if (p->fib_index == 0)
1079         gp = p;
1080     };
1081   /* *INDENT-ON* */
1082
1083   if (!prefix)
1084     prefix = gp;
1085
1086   if (prefix)
1087     {
1088       clib_memcpy_fast (ip6, &p->prefix, sizeof (ip6_address_t));
1089       switch (p->plen)
1090         {
1091         case 32:
1092           ip6->as_u32[1] = ip4->as_u32;
1093           break;
1094         case 40:
1095           ip6->as_u8[5] = ip4->as_u8[0];
1096           ip6->as_u8[6] = ip4->as_u8[1];
1097           ip6->as_u8[7] = ip4->as_u8[2];
1098           ip6->as_u8[9] = ip4->as_u8[3];
1099           break;
1100         case 48:
1101           ip6->as_u8[6] = ip4->as_u8[0];
1102           ip6->as_u8[7] = ip4->as_u8[1];
1103           ip6->as_u8[9] = ip4->as_u8[2];
1104           ip6->as_u8[10] = ip4->as_u8[3];
1105           break;
1106         case 56:
1107           ip6->as_u8[7] = ip4->as_u8[0];
1108           ip6->as_u8[9] = ip4->as_u8[1];
1109           ip6->as_u8[10] = ip4->as_u8[2];
1110           ip6->as_u8[11] = ip4->as_u8[3];
1111           break;
1112         case 64:
1113           ip6->as_u8[9] = ip4->as_u8[0];
1114           ip6->as_u8[10] = ip4->as_u8[1];
1115           ip6->as_u8[11] = ip4->as_u8[2];
1116           ip6->as_u8[12] = ip4->as_u8[3];
1117           break;
1118         case 96:
1119           ip6->as_u32[3] = ip4->as_u32;
1120           break;
1121         default:
1122           nat_elog_notice ("invalid prefix length");
1123           break;
1124         }
1125     }
1126   else
1127     {
1128       clib_memcpy_fast (ip6, well_known_prefix, sizeof (ip6_address_t));
1129       ip6->as_u32[3] = ip4->as_u32;
1130     }
1131 }
1132
1133 void
1134 nat64_extract_ip4 (ip6_address_t * ip6, ip4_address_t * ip4, u32 fib_index)
1135 {
1136   nat64_main_t *nm = &nat64_main;
1137   nat64_prefix_t *p, *gp = 0;
1138   u8 plen = 0;
1139
1140   /* *INDENT-OFF* */
1141   vec_foreach (p, nm->pref64)
1142     {
1143       if (p->fib_index == fib_index)
1144         {
1145           plen = p->plen;
1146           break;
1147         }
1148
1149       if (p->vrf_id == 0)
1150         gp = p;
1151     };
1152   /* *INDENT-ON* */
1153
1154   if (!plen)
1155     {
1156       if (gp)
1157         plen = gp->plen;
1158       else
1159         plen = 96;
1160     }
1161
1162   switch (plen)
1163     {
1164     case 32:
1165       ip4->as_u32 = ip6->as_u32[1];
1166       break;
1167     case 40:
1168       ip4->as_u8[0] = ip6->as_u8[5];
1169       ip4->as_u8[1] = ip6->as_u8[6];
1170       ip4->as_u8[2] = ip6->as_u8[7];
1171       ip4->as_u8[3] = ip6->as_u8[9];
1172       break;
1173     case 48:
1174       ip4->as_u8[0] = ip6->as_u8[6];
1175       ip4->as_u8[1] = ip6->as_u8[7];
1176       ip4->as_u8[2] = ip6->as_u8[9];
1177       ip4->as_u8[3] = ip6->as_u8[10];
1178       break;
1179     case 56:
1180       ip4->as_u8[0] = ip6->as_u8[7];
1181       ip4->as_u8[1] = ip6->as_u8[9];
1182       ip4->as_u8[2] = ip6->as_u8[10];
1183       ip4->as_u8[3] = ip6->as_u8[11];
1184       break;
1185     case 64:
1186       ip4->as_u8[0] = ip6->as_u8[9];
1187       ip4->as_u8[1] = ip6->as_u8[10];
1188       ip4->as_u8[2] = ip6->as_u8[11];
1189       ip4->as_u8[3] = ip6->as_u8[12];
1190       break;
1191     case 96:
1192       ip4->as_u32 = ip6->as_u32[3];
1193       break;
1194     default:
1195       nat_elog_notice ("invalid prefix length");
1196       break;
1197     }
1198 }
1199
1200 /**
1201  * @brief Per worker process checking expire time for NAT64 sessions.
1202  */
1203 static uword
1204 nat64_expire_worker_walk_fn (vlib_main_t * vm, vlib_node_runtime_t * rt,
1205                              vlib_frame_t * f)
1206 {
1207   nat64_main_t *nm = &nat64_main;
1208   u32 thread_index = vm->thread_index;
1209   nat64_db_t *db = &nm->db[thread_index];
1210   u32 now = (u32) vlib_time_now (vm);
1211
1212   nad64_db_st_free_expired (thread_index, db, now);
1213   vlib_set_simple_counter (&nm->total_bibs, thread_index, 0,
1214                            db->bib.bib_entries_num);
1215   vlib_set_simple_counter (&nm->total_sessions, thread_index, 0,
1216                            db->st.st_entries_num);
1217
1218   return 0;
1219 }
1220
1221 static vlib_node_registration_t nat64_expire_worker_walk_node;
1222
1223 /* *INDENT-OFF* */
1224 VLIB_REGISTER_NODE (nat64_expire_worker_walk_node, static) = {
1225     .function = nat64_expire_worker_walk_fn,
1226     .type = VLIB_NODE_TYPE_INPUT,
1227     .state = VLIB_NODE_STATE_INTERRUPT,
1228     .name = "nat64-expire-worker-walk",
1229 };
1230 /* *INDENT-ON* */
1231
1232 static vlib_node_registration_t nat64_expire_walk_node;
1233
1234 /**
1235  * @brief Centralized process to drive per worker expire walk.
1236  */
1237 static uword
1238 nat64_expire_walk_fn (vlib_main_t * vm, vlib_node_runtime_t * rt,
1239                       vlib_frame_t * f)
1240 {
1241   nat64_main_t *nm = &nat64_main;
1242   vlib_main_t **worker_vms = 0, *worker_vm;
1243   int i;
1244   uword event_type, *event_data = 0;
1245
1246   nm->nat64_expire_walk_node_index = nat64_expire_walk_node.index;
1247
1248   if (vec_len (vlib_mains) == 0)
1249     vec_add1 (worker_vms, vm);
1250   else
1251     {
1252       for (i = 0; i < vec_len (vlib_mains); i++)
1253         {
1254           worker_vm = vlib_mains[i];
1255           if (worker_vm)
1256             vec_add1 (worker_vms, worker_vm);
1257         }
1258     }
1259
1260   while (1)
1261     {
1262       if (nm->total_enabled_count)
1263         {
1264           vlib_process_wait_for_event_or_clock (vm, 10.0);
1265           event_type = vlib_process_get_events (vm, &event_data);
1266         }
1267       else
1268         {
1269           vlib_process_wait_for_event (vm);
1270           event_type = vlib_process_get_events (vm, &event_data);
1271         }
1272
1273       switch (event_type)
1274         {
1275         case ~0:
1276           break;
1277         case NAT64_CLEANER_RESCHEDULE:
1278           break;
1279         default:
1280           nat_elog_notice_X1 ("unknown event %d", "i4", event_type);
1281           break;
1282         }
1283
1284       for (i = 0; i < vec_len (worker_vms); i++)
1285         {
1286           worker_vm = worker_vms[i];
1287           vlib_node_set_interrupt_pending (worker_vm,
1288                                            nat64_expire_worker_walk_node.index);
1289         }
1290     }
1291
1292   return 0;
1293 }
1294
1295 /* *INDENT-OFF* */
1296 VLIB_REGISTER_NODE (nat64_expire_walk_node, static) = {
1297     .function = nat64_expire_walk_fn,
1298     .type = VLIB_NODE_TYPE_PROCESS,
1299     .name = "nat64-expire-walk",
1300 };
1301 /* *INDENT-ON* */
1302
1303 /*
1304  * fd.io coding-style-patch-verification: ON
1305  *
1306  * Local Variables:
1307  * eval: (c-set-style "gnu")
1308  * End:
1309  */