+ rv = tunnel_resolve (&sa->tunnel, FIB_NODE_TYPE_IPSEC_SA, sa_index);
+
+ if (rv)
+ {
+ hash_unset (im->sa_index_by_sa_id, sa->id);
+ pool_put (ipsec_sa_pool, sa);
+ return rv;
+ }
+ ipsec_sa_stack (sa);
+ /* generate header templates */
+ if (ipsec_sa_is_set_IS_TUNNEL_V6 (sa))
+ {
+ tunnel_build_v6_hdr (&sa->tunnel,
+ (ipsec_sa_is_set_UDP_ENCAP (sa) ?
+ IP_PROTOCOL_UDP :
+ IP_PROTOCOL_IPSEC_ESP),
+ &sa->ip6_hdr);
+ }
+ else
+ {
+ tunnel_build_v4_hdr (&sa->tunnel,
+ (ipsec_sa_is_set_UDP_ENCAP (sa) ?
+ IP_PROTOCOL_UDP :
+ IP_PROTOCOL_IPSEC_ESP),
+ &sa->ip4_hdr);
+ }
+ }
+ }
+
+ if (ipsec_sa_is_set_UDP_ENCAP (sa))
+ {
+ if (dst_port != IPSEC_UDP_PORT_NONE &&
+ dst_port != clib_net_to_host_u16 (sa->udp_hdr.dst_port))
+ {
+ if (ipsec_sa_is_set_IS_INBOUND (sa))
+ {
+ ipsec_unregister_udp_port (
+ clib_net_to_host_u16 (sa->udp_hdr.dst_port),
+ !ipsec_sa_is_set_IS_TUNNEL_V6 (sa));
+ ipsec_register_udp_port (dst_port,
+ !ipsec_sa_is_set_IS_TUNNEL_V6 (sa));
+ }
+ sa->udp_hdr.dst_port = clib_host_to_net_u16 (dst_port);
+ }
+ if (src_port != IPSEC_UDP_PORT_NONE &&
+ src_port != clib_net_to_host_u16 (sa->udp_hdr.src_port))
+ sa->udp_hdr.src_port = clib_host_to_net_u16 (src_port);
+ }
+ return (0);
+}
+
+int
+ipsec_sa_add_and_lock (u32 id, u32 spi, ipsec_protocol_t proto,
+ ipsec_crypto_alg_t crypto_alg, const ipsec_key_t *ck,
+ ipsec_integ_alg_t integ_alg, const ipsec_key_t *ik,
+ ipsec_sa_flags_t flags, u32 salt, u16 src_port,
+ u16 dst_port, const tunnel_t *tun, u32 *sa_out_index)
+{
+ vlib_main_t *vm = vlib_get_main ();
+ ipsec_main_t *im = &ipsec_main;
+ clib_error_t *err;
+ ipsec_sa_t *sa;
+ u32 sa_index;
+ u64 rand[2];
+ uword *p;
+ int rv;
+
+ p = hash_get (im->sa_index_by_sa_id, id);
+ if (p)
+ return VNET_API_ERROR_ENTRY_ALREADY_EXISTS;
+
+ if (getrandom (rand, sizeof (rand), 0) != sizeof (rand))
+ return VNET_API_ERROR_INIT_FAILED;
+
+ pool_get_aligned_zero (ipsec_sa_pool, sa, CLIB_CACHE_LINE_BYTES);
+
+ clib_pcg64i_srandom_r (&sa->iv_prng, rand[0], rand[1]);
+
+ fib_node_init (&sa->node, FIB_NODE_TYPE_IPSEC_SA);
+ fib_node_lock (&sa->node);
+ sa_index = sa - ipsec_sa_pool;
+
+ vlib_validate_combined_counter (&ipsec_sa_counters, sa_index);
+ vlib_zero_combined_counter (&ipsec_sa_counters, sa_index);
+ for (int i = 0; i < IPSEC_SA_N_ERRORS; i++)
+ {
+ vlib_validate_simple_counter (&ipsec_sa_err_counters[i], sa_index);
+ vlib_zero_simple_counter (&ipsec_sa_err_counters[i], sa_index);
+ }
+
+ tunnel_copy (tun, &sa->tunnel);
+ sa->id = id;
+ sa->spi = spi;
+ sa->stat_index = sa_index;
+ sa->protocol = proto;
+ sa->flags = flags;
+ sa->salt = salt;
+ sa->thread_index = (vlib_num_workers ()) ? ~0 : 0;
+ if (integ_alg != IPSEC_INTEG_ALG_NONE)