5c8efe1c438e1f9a6629682680e962b0c4daeac3
[vpp.git] / src / vnet / session / application.c
1 /*
2  * Copyright (c) 2017-2019 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 #include <vnet/session/application.h>
17 #include <vnet/session/application_interface.h>
18 #include <vnet/session/application_namespace.h>
19 #include <vnet/session/application_local.h>
20 #include <vnet/session/session.h>
21
22 static app_main_t app_main;
23
24 #define app_interface_check_thread_and_barrier(_fn, _arg)               \
25   if (PREDICT_FALSE (!vlib_thread_is_main_w_barrier ()))                \
26     {                                                                   \
27       vlib_rpc_call_main_thread (_fn, (u8 *) _arg, sizeof(*_arg));      \
28       return 0;                                                         \
29     }
30
31 static app_listener_t *
32 app_listener_alloc (application_t * app)
33 {
34   app_listener_t *app_listener;
35   pool_get (app->listeners, app_listener);
36   clib_memset (app_listener, 0, sizeof (*app_listener));
37   app_listener->al_index = app_listener - app->listeners;
38   app_listener->app_index = app->app_index;
39   app_listener->session_index = SESSION_INVALID_INDEX;
40   app_listener->local_index = SESSION_INVALID_INDEX;
41   app_listener->ls_handle = SESSION_INVALID_HANDLE;
42   return app_listener;
43 }
44
45 app_listener_t *
46 app_listener_get (application_t * app, u32 app_listener_index)
47 {
48   return pool_elt_at_index (app->listeners, app_listener_index);
49 }
50
51 static void
52 app_listener_free (application_t * app, app_listener_t * app_listener)
53 {
54   clib_bitmap_free (app_listener->workers);
55   vec_free (app_listener->cl_listeners);
56   if (CLIB_DEBUG)
57     clib_memset (app_listener, 0xfa, sizeof (*app_listener));
58   pool_put (app->listeners, app_listener);
59 }
60
61 session_handle_t
62 app_listener_handle (app_listener_t * al)
63 {
64   return al->ls_handle;
65 }
66
67 app_listener_t *
68 app_listener_get_w_session (session_t * ls)
69 {
70   application_t *app;
71
72   app = application_get_if_valid (ls->app_index);
73   if (!app)
74     return 0;
75   return app_listener_get (app, ls->al_index);
76 }
77
78 session_handle_t
79 app_listen_session_handle (session_t * ls)
80 {
81   app_listener_t *al;
82   al = app_listener_get_w_session (ls);
83   if (!al)
84     return listen_session_get_handle (ls);
85   return al->ls_handle;
86 }
87
88 app_listener_t *
89 app_listener_get_w_handle (session_handle_t handle)
90 {
91   session_t *ls;
92   ls = session_get_from_handle_if_valid (handle);
93   if (!ls)
94     return 0;
95   return app_listener_get_w_session (ls);
96 }
97
98 app_listener_t *
99 app_listener_lookup (application_t * app, session_endpoint_cfg_t * sep_ext)
100 {
101   u32 table_index, fib_proto;
102   session_endpoint_t *sep;
103   session_handle_t handle;
104   session_t *ls;
105   void *iface_ip;
106   ip46_address_t original_ip;
107
108   sep = (session_endpoint_t *) sep_ext;
109   if (application_has_local_scope (app) && session_endpoint_is_local (sep))
110     {
111       table_index = application_local_session_table (app);
112       handle = session_lookup_endpoint_listener (table_index, sep, 1);
113       if (handle != SESSION_INVALID_HANDLE)
114         {
115           ls = listen_session_get_from_handle (handle);
116           return app_listener_get_w_session (ls);
117         }
118     }
119
120   fib_proto = session_endpoint_fib_proto (sep);
121   table_index = session_lookup_get_index_for_fib (fib_proto, sep->fib_index);
122   handle = session_lookup_endpoint_listener (table_index, sep, 1);
123   if (handle != SESSION_INVALID_HANDLE)
124     {
125       ls = listen_session_get_from_handle (handle);
126       return app_listener_get_w_session ((session_t *) ls);
127     }
128
129   /*
130    * When binds to "inaddr_any", we add zero address in the local lookup table
131    * and interface address in the global lookup table. If local scope disable,
132    * the latter is the only clue to find the listener.
133    */
134   if (!application_has_local_scope (app) &&
135       ip_is_zero (&sep_ext->ip, sep_ext->is_ip4) &&
136       sep_ext->sw_if_index != ENDPOINT_INVALID_INDEX)
137     {
138       if ((iface_ip = ip_interface_get_first_ip (sep_ext->sw_if_index,
139                                                  sep_ext->is_ip4)))
140         {
141           ip_copy (&original_ip, &sep_ext->ip, sep_ext->is_ip4);
142           ip_set (&sep_ext->ip, iface_ip, sep_ext->is_ip4);
143           handle = session_lookup_endpoint_listener (table_index, sep, 1);
144           ip_copy (&sep_ext->ip, &original_ip, sep_ext->is_ip4);
145           if (handle != SESSION_INVALID_HANDLE)
146             {
147               ls = listen_session_get_from_handle (handle);
148               return app_listener_get_w_session ((session_t *) ls);
149             }
150         }
151     }
152
153   return 0;
154 }
155
156 int
157 app_listener_alloc_and_init (application_t * app,
158                              session_endpoint_cfg_t * sep,
159                              app_listener_t ** listener)
160 {
161   app_listener_t *app_listener;
162   transport_connection_t *tc;
163   u32 al_index, table_index;
164   session_handle_t lh;
165   session_type_t st;
166   session_t *ls = 0;
167   int rv;
168
169   app_listener = app_listener_alloc (app);
170   al_index = app_listener->al_index;
171   st = session_type_from_proto_and_ip (sep->transport_proto, sep->is_ip4);
172
173   /*
174    * Add session endpoint to local session table. Only binds to "inaddr_any"
175    * (i.e., zero address) are added to local scope table.
176    */
177   if (application_has_local_scope (app)
178       && session_endpoint_is_local ((session_endpoint_t *) sep))
179     {
180       session_type_t local_st;
181
182       local_st = session_type_from_proto_and_ip (TRANSPORT_PROTO_NONE,
183                                                  sep->is_ip4);
184       ls = listen_session_alloc (0, local_st);
185       ls->app_index = app->app_index;
186       ls->app_wrk_index = sep->app_wrk_index;
187       lh = session_handle (ls);
188
189       if ((rv = session_listen (ls, sep)))
190         {
191           ls = session_get_from_handle (lh);
192           session_free (ls);
193           app_listener_free (app, app_listener);
194           return rv;
195         }
196
197       ls = session_get_from_handle (lh);
198       app_listener = app_listener_get (app, al_index);
199       app_listener->local_index = ls->session_index;
200       app_listener->ls_handle = lh;
201       ls->al_index = al_index;
202
203       table_index = application_local_session_table (app);
204       session_lookup_add_session_endpoint (table_index,
205                                            (session_endpoint_t *) sep, lh);
206     }
207
208   if (application_has_global_scope (app))
209     {
210       /*
211        * Start listening on local endpoint for requested transport and scope.
212        * Creates a stream session with state LISTENING to be used in session
213        * lookups, prior to establishing connection. Requests transport to
214        * build it's own specific listening connection.
215        */
216       ls = listen_session_alloc (0, st);
217       ls->app_index = app->app_index;
218       ls->app_wrk_index = sep->app_wrk_index;
219
220       /* Listen pool can be reallocated if the transport is
221        * recursive (tls) */
222       lh = listen_session_get_handle (ls);
223
224       if ((rv = session_listen (ls, sep)))
225         {
226           ls = listen_session_get_from_handle (lh);
227           session_free (ls);
228           app_listener_free (app, app_listener);
229           return rv;
230         }
231       ls = listen_session_get_from_handle (lh);
232       app_listener = app_listener_get (app, al_index);
233       app_listener->session_index = ls->session_index;
234       app_listener->ls_handle = lh;
235       ls->al_index = al_index;
236
237       /* Add to the global lookup table after transport was initialized.
238        * Lookup table needs to be populated only now because sessions
239        * with cut-through transport are are added to app local tables that
240        * are not related to network fibs, i.e., cannot be added as
241        * connections */
242       tc = session_get_transport (ls);
243       if (!(tc->flags & TRANSPORT_CONNECTION_F_NO_LOOKUP))
244         {
245           fib_protocol_t fib_proto;
246           fib_proto = session_endpoint_fib_proto ((session_endpoint_t *) sep);
247           /* Assume namespace vetted previously so make sure table exists */
248           table_index = session_lookup_get_or_alloc_index_for_fib (
249             fib_proto, sep->fib_index);
250           session_lookup_add_session_endpoint (table_index,
251                                                (session_endpoint_t *) sep,
252                                                lh);
253         }
254     }
255
256   if (!ls)
257     {
258       app_listener_free (app, app_listener);
259       return -1;
260     }
261
262   *listener = app_listener;
263   return 0;
264 }
265
266 void
267 app_listener_cleanup (app_listener_t * al)
268 {
269   application_t *app = application_get (al->app_index);
270   session_t *ls;
271
272   if (al->session_index != SESSION_INVALID_INDEX)
273     {
274       ls = session_get (al->session_index, 0);
275       session_stop_listen (ls);
276       listen_session_free (ls);
277     }
278   if (al->local_index != SESSION_INVALID_INDEX)
279     {
280       session_endpoint_t sep = SESSION_ENDPOINT_NULL;
281       u32 table_index;
282
283       table_index = application_local_session_table (app);
284       ls = listen_session_get (al->local_index);
285       ct_session_endpoint (ls, &sep);
286       session_lookup_del_session_endpoint (table_index, &sep);
287       session_stop_listen (ls);
288       listen_session_free (ls);
289     }
290   app_listener_free (app, al);
291 }
292
293 static app_worker_t *
294 app_listener_select_worker (application_t * app, app_listener_t * al)
295 {
296   u32 wrk_index;
297
298   app = application_get (al->app_index);
299   wrk_index = clib_bitmap_next_set (al->workers, al->accept_rotor + 1);
300   if (wrk_index == ~0)
301     wrk_index = clib_bitmap_first_set (al->workers);
302
303   ASSERT (wrk_index != ~0);
304   al->accept_rotor = wrk_index;
305   return application_get_worker (app, wrk_index);
306 }
307
308 session_t *
309 app_listener_get_session (app_listener_t * al)
310 {
311   if (al->session_index == SESSION_INVALID_INDEX)
312     return 0;
313
314   return listen_session_get (al->session_index);
315 }
316
317 session_t *
318 app_listener_get_local_session (app_listener_t * al)
319 {
320   if (al->local_index == SESSION_INVALID_INDEX)
321     return 0;
322   return listen_session_get (al->local_index);
323 }
324
325 session_t *
326 app_listener_get_wrk_cl_session (app_listener_t *al, u32 wrk_map_index)
327 {
328   u32 si = vec_elt (al->cl_listeners, wrk_map_index);
329   return session_get (si, 0 /* listener thread */);
330 }
331
332 static app_worker_map_t *
333 app_worker_map_alloc (application_t * app)
334 {
335   app_worker_map_t *map;
336   pool_get (app->worker_maps, map);
337   clib_memset (map, 0, sizeof (*map));
338   return map;
339 }
340
341 static u32
342 app_worker_map_index (application_t * app, app_worker_map_t * map)
343 {
344   return (map - app->worker_maps);
345 }
346
347 static void
348 app_worker_map_free (application_t * app, app_worker_map_t * map)
349 {
350   pool_put (app->worker_maps, map);
351 }
352
353 static app_worker_map_t *
354 app_worker_map_get (application_t * app, u32 map_index)
355 {
356   if (pool_is_free_index (app->worker_maps, map_index))
357     return 0;
358   return pool_elt_at_index (app->worker_maps, map_index);
359 }
360
361 static const u8 *
362 app_get_name (application_t * app)
363 {
364   return app->name;
365 }
366
367 u32
368 application_session_table (application_t * app, u8 fib_proto)
369 {
370   app_namespace_t *app_ns;
371   app_ns = app_namespace_get (app->ns_index);
372   if (!application_has_global_scope (app))
373     return APP_INVALID_INDEX;
374   if (fib_proto == FIB_PROTOCOL_IP4)
375     return session_lookup_get_index_for_fib (fib_proto,
376                                              app_ns->ip4_fib_index);
377   else
378     return session_lookup_get_index_for_fib (fib_proto,
379                                              app_ns->ip6_fib_index);
380 }
381
382 u32
383 application_local_session_table (application_t * app)
384 {
385   app_namespace_t *app_ns;
386   if (!application_has_local_scope (app))
387     return APP_INVALID_INDEX;
388   app_ns = app_namespace_get (app->ns_index);
389   return app_ns->local_table_index;
390 }
391
392 /**
393  * Returns app name for app-index
394  */
395 const u8 *
396 application_name_from_index (u32 app_index)
397 {
398   application_t *app = application_get (app_index);
399   if (!app)
400     return 0;
401   return app_get_name (app);
402 }
403
404 static void
405 application_api_table_add (u32 app_index, u32 api_client_index)
406 {
407   if (api_client_index != APP_INVALID_INDEX)
408     hash_set (app_main.app_by_api_client_index, api_client_index, app_index);
409 }
410
411 static void
412 application_api_table_del (u32 api_client_index)
413 {
414   hash_unset (app_main.app_by_api_client_index, api_client_index);
415 }
416
417 static void
418 application_name_table_add (application_t * app)
419 {
420   hash_set_mem (app_main.app_by_name, app->name, app->app_index);
421 }
422
423 static void
424 application_name_table_del (application_t * app)
425 {
426   hash_unset_mem (app_main.app_by_name, app->name);
427 }
428
429 application_t *
430 application_lookup (u32 api_client_index)
431 {
432   uword *p;
433   p = hash_get (app_main.app_by_api_client_index, api_client_index);
434   if (p)
435     return application_get_if_valid (p[0]);
436
437   return 0;
438 }
439
440 application_t *
441 application_lookup_name (const u8 * name)
442 {
443   uword *p;
444   p = hash_get_mem (app_main.app_by_name, name);
445   if (p)
446     return application_get (p[0]);
447
448   return 0;
449 }
450
451 void
452 appsl_pending_rx_mqs_add_tail (appsl_wrk_t *aw, app_rx_mq_elt_t *elt)
453 {
454   app_rx_mq_elt_t *head;
455
456   if (!aw->pending_rx_mqs)
457     {
458       elt->next = elt->prev = elt;
459       aw->pending_rx_mqs = elt;
460       return;
461     }
462
463   head = aw->pending_rx_mqs;
464
465   ASSERT (head != elt);
466
467   elt->prev = head->prev;
468   elt->next = head;
469
470   head->prev->next = elt;
471   head->prev = elt;
472 }
473
474 void
475 appsl_pending_rx_mqs_del (appsl_wrk_t *aw, app_rx_mq_elt_t *elt)
476 {
477   if (elt->next == elt)
478     {
479       elt->next = elt->prev = 0;
480       aw->pending_rx_mqs = 0;
481       return;
482     }
483
484   if (elt == aw->pending_rx_mqs)
485     aw->pending_rx_mqs = elt->next;
486
487   elt->next->prev = elt->prev;
488   elt->prev->next = elt->next;
489   elt->next = elt->prev = 0;
490 }
491
492 vlib_node_registration_t appsl_rx_mqs_input_node;
493
494 VLIB_NODE_FN (appsl_rx_mqs_input_node)
495 (vlib_main_t *vm, vlib_node_runtime_t *node, vlib_frame_t *frame)
496 {
497   u32 thread_index = vm->thread_index, n_msgs = 0;
498   app_rx_mq_elt_t *elt, *next;
499   app_main_t *am = &app_main;
500   session_worker_t *wrk;
501   int __clib_unused rv;
502   appsl_wrk_t *aw;
503   u64 buf;
504
505   aw = &am->wrk[thread_index];
506   elt = aw->pending_rx_mqs;
507   if (!elt)
508     return 0;
509
510   wrk = session_main_get_worker (thread_index);
511
512   do
513     {
514       if (!(elt->flags & APP_RX_MQ_F_POSTPONED))
515         rv = read (svm_msg_q_get_eventfd (elt->mq), &buf, sizeof (buf));
516       n_msgs += session_wrk_handle_mq (wrk, elt->mq);
517
518       next = elt->next;
519       appsl_pending_rx_mqs_del (aw, elt);
520       if (!svm_msg_q_is_empty (elt->mq))
521         {
522           elt->flags |= APP_RX_MQ_F_POSTPONED;
523           appsl_pending_rx_mqs_add_tail (aw, elt);
524         }
525       else
526         {
527           elt->flags = 0;
528         }
529       elt = next;
530     }
531   while (aw->pending_rx_mqs && elt != aw->pending_rx_mqs);
532
533   if (aw->pending_rx_mqs)
534     vlib_node_set_interrupt_pending (vm, appsl_rx_mqs_input_node.index);
535
536   if (n_msgs && wrk->state == SESSION_WRK_INTERRUPT)
537     vlib_node_set_interrupt_pending (vm, session_queue_node.index);
538
539   return n_msgs;
540 }
541
542 VLIB_REGISTER_NODE (appsl_rx_mqs_input_node) = {
543   .name = "appsl-rx-mqs-input",
544   .type = VLIB_NODE_TYPE_INPUT,
545   .state = VLIB_NODE_STATE_DISABLED,
546 };
547
548 static clib_error_t *
549 app_rx_mq_fd_read_ready (clib_file_t *cf)
550 {
551   app_rx_mq_handle_t *handle = (app_rx_mq_handle_t *) &cf->private_data;
552   vlib_main_t *vm = vlib_get_main ();
553   app_main_t *am = &app_main;
554   app_rx_mq_elt_t *mqe;
555   application_t *app;
556   appsl_wrk_t *aw;
557
558   ASSERT (vlib_get_thread_index () == handle->thread_index);
559   app = application_get_if_valid (handle->app_index);
560   if (!app)
561     return 0;
562
563   mqe = &app->rx_mqs[handle->thread_index];
564   if ((mqe->flags & APP_RX_MQ_F_PENDING) || svm_msg_q_is_empty (mqe->mq))
565     return 0;
566
567   aw = &am->wrk[handle->thread_index];
568   appsl_pending_rx_mqs_add_tail (aw, mqe);
569   mqe->flags |= APP_RX_MQ_F_PENDING;
570
571   vlib_node_set_interrupt_pending (vm, appsl_rx_mqs_input_node.index);
572
573   return 0;
574 }
575
576 static clib_error_t *
577 app_rx_mq_fd_write_ready (clib_file_t *cf)
578 {
579   clib_warning ("should not be called");
580   return 0;
581 }
582
583 static void
584 app_rx_mqs_epoll_add (application_t *app, app_rx_mq_elt_t *mqe)
585 {
586   clib_file_t template = { 0 };
587   app_rx_mq_handle_t handle;
588   u32 thread_index;
589   int fd;
590
591   thread_index = mqe - app->rx_mqs;
592   fd = svm_msg_q_get_eventfd (mqe->mq);
593
594   handle.app_index = app->app_index;
595   handle.thread_index = thread_index;
596
597   template.read_function = app_rx_mq_fd_read_ready;
598   template.write_function = app_rx_mq_fd_write_ready;
599   template.file_descriptor = fd;
600   template.private_data = handle.as_u64;
601   template.polling_thread_index = thread_index;
602   template.description =
603     format (0, "app-%u-rx-mq-%u", app->app_index, thread_index);
604   mqe->file_index = clib_file_add (&file_main, &template);
605 }
606
607 static void
608 app_rx_mqs_epoll_del (application_t *app, app_rx_mq_elt_t *mqe)
609 {
610   u32 thread_index = mqe - app->rx_mqs;
611   app_main_t *am = &app_main;
612   appsl_wrk_t *aw;
613
614   aw = &am->wrk[thread_index];
615
616   session_wrk_handle_mq (session_main_get_worker (thread_index), mqe->mq);
617
618   if (mqe->flags & APP_RX_MQ_F_PENDING)
619     appsl_pending_rx_mqs_del (aw, mqe);
620
621   clib_file_del_by_index (&file_main, mqe->file_index);
622 }
623
624 svm_msg_q_t *
625 application_rx_mq_get (application_t *app, u32 mq_index)
626 {
627   if (!app->rx_mqs)
628     return 0;
629
630   return app->rx_mqs[mq_index].mq;
631 }
632
633 static int
634 app_rx_mqs_alloc (application_t *app)
635 {
636   u32 evt_q_length, evt_size = sizeof (session_event_t);
637   fifo_segment_t *eqs = &app->rx_mqs_segment;
638   u32 n_mqs = vlib_num_workers () + 1;
639   segment_manager_props_t *props;
640   int i;
641
642   props = application_segment_manager_properties (app);
643   evt_q_length = clib_max (props->evt_q_size, 128);
644
645   svm_msg_q_cfg_t _cfg, *cfg = &_cfg;
646   svm_msg_q_ring_cfg_t rc[SESSION_MQ_N_RINGS] = {
647     { evt_q_length, evt_size, 0 }, { evt_q_length >> 1, 256, 0 }
648   };
649   cfg->consumer_pid = 0;
650   cfg->n_rings = 2;
651   cfg->q_nitems = evt_q_length;
652   cfg->ring_cfgs = rc;
653
654   eqs->ssvm.ssvm_size = svm_msg_q_size_to_alloc (cfg) * n_mqs + (1 << 20);
655   eqs->ssvm.name = format (0, "%v-rx-mqs-seg%c", app->name, 0);
656
657   if (ssvm_server_init (&eqs->ssvm, SSVM_SEGMENT_MEMFD))
658     {
659       clib_warning ("failed to initialize queue segment");
660       return SESSION_E_SEG_CREATE;
661     }
662
663   fifo_segment_init (eqs);
664
665   /* Fifo segment filled only with mqs */
666   eqs->h->n_mqs = n_mqs;
667   vec_validate (app->rx_mqs, n_mqs - 1);
668
669   for (i = 0; i < n_mqs; i++)
670     {
671       app->rx_mqs[i].mq = fifo_segment_msg_q_alloc (eqs, i, cfg);
672       if (svm_msg_q_alloc_eventfd (app->rx_mqs[i].mq))
673         {
674           clib_warning ("eventfd returned");
675           fifo_segment_cleanup (eqs);
676           ssvm_delete (&eqs->ssvm);
677           return SESSION_E_EVENTFD_ALLOC;
678         }
679       app_rx_mqs_epoll_add (app, &app->rx_mqs[i]);
680       app->rx_mqs[i].app_index = app->app_index;
681     }
682
683   return 0;
684 }
685
686 u8
687 application_use_private_rx_mqs (void)
688 {
689   return session_main.use_private_rx_mqs;
690 }
691
692 fifo_segment_t *
693 application_get_rx_mqs_segment (application_t *app)
694 {
695   if (application_use_private_rx_mqs ())
696     return &app->rx_mqs_segment;
697   return session_main_get_wrk_mqs_segment ();
698 }
699
700 void
701 application_enable_rx_mqs_nodes (u8 is_en)
702 {
703   u8 state = is_en ? VLIB_NODE_STATE_INTERRUPT : VLIB_NODE_STATE_DISABLED;
704
705   foreach_vlib_main ()
706     vlib_node_set_state (this_vlib_main, appsl_rx_mqs_input_node.index, state);
707 }
708
709 static application_t *
710 application_alloc (void)
711 {
712   application_t *app;
713   pool_get (app_main.app_pool, app);
714   clib_memset (app, 0, sizeof (*app));
715   app->app_index = app - app_main.app_pool;
716   return app;
717 }
718
719 application_t *
720 application_get (u32 app_index)
721 {
722   if (app_index == APP_INVALID_INDEX)
723     return 0;
724   return pool_elt_at_index (app_main.app_pool, app_index);
725 }
726
727 application_t *
728 application_get_if_valid (u32 app_index)
729 {
730   if (pool_is_free_index (app_main.app_pool, app_index))
731     return 0;
732
733   return pool_elt_at_index (app_main.app_pool, app_index);
734 }
735
736 static int
737 _null_app_tx_callback (session_t *s)
738 {
739   return 0;
740 }
741
742 static void
743 application_verify_cb_fns (session_cb_vft_t * cb_fns)
744 {
745   if (cb_fns->session_accept_callback == 0)
746     clib_warning ("No accept callback function provided");
747   if (cb_fns->session_connected_callback == 0)
748     clib_warning ("No session connected callback function provided");
749   if (cb_fns->session_disconnect_callback == 0)
750     clib_warning ("No session disconnect callback function provided");
751   if (cb_fns->session_reset_callback == 0)
752     clib_warning ("No session reset callback function provided");
753   if (!cb_fns->builtin_app_tx_callback)
754     cb_fns->builtin_app_tx_callback = _null_app_tx_callback;
755 }
756
757 /**
758  * Check app config for given segment type
759  *
760  * Returns 1 on success and 0 otherwise
761  */
762 static u8
763 application_verify_cfg (ssvm_segment_type_t st)
764 {
765   u8 is_valid;
766   if (st == SSVM_SEGMENT_MEMFD)
767     {
768       is_valid = (session_main_get_wrk_mqs_segment () != 0);
769       if (!is_valid)
770         clib_warning ("memfd seg: vpp's event qs IN binary api svm region");
771       return is_valid;
772     }
773   else if (st == SSVM_SEGMENT_SHM)
774     {
775       is_valid = (session_main_get_wrk_mqs_segment () == 0);
776       if (!is_valid)
777         clib_warning ("shm seg: vpp's event qs NOT IN binary api svm region");
778       return is_valid;
779     }
780   else
781     return 1;
782 }
783
784 static session_error_t
785 application_alloc_and_init (app_init_args_t *a)
786 {
787   ssvm_segment_type_t seg_type = SSVM_SEGMENT_MEMFD;
788   segment_manager_props_t *props;
789   application_t *app;
790   u64 *opts;
791
792   app = application_alloc ();
793   opts = a->options;
794   /*
795    * Make sure we support the requested configuration
796    */
797   if ((opts[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_IS_BUILTIN) &&
798       !(opts[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_MEMFD_FOR_BUILTIN))
799     seg_type = SSVM_SEGMENT_PRIVATE;
800
801   if ((opts[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD) &&
802       seg_type != SSVM_SEGMENT_MEMFD)
803     {
804       clib_warning ("mq eventfds can only be used if socket transport is "
805                     "used for binary api");
806       return SESSION_E_NOSUPPORT;
807     }
808
809   if (!application_verify_cfg (seg_type))
810     return SESSION_E_NOSUPPORT;
811
812   if (opts[APP_OPTIONS_PREALLOC_FIFO_PAIRS] &&
813       opts[APP_OPTIONS_PREALLOC_FIFO_HDRS])
814     return SESSION_E_NOSUPPORT;
815
816   /* Check that the obvious things are properly set up */
817   application_verify_cb_fns (a->session_cb_vft);
818
819   app->flags = opts[APP_OPTIONS_FLAGS];
820   app->cb_fns = *a->session_cb_vft;
821   app->ns_index = opts[APP_OPTIONS_NAMESPACE];
822   app->proxied_transports = opts[APP_OPTIONS_PROXY_TRANSPORT];
823   app->name = vec_dup (a->name);
824
825   /* If no scope enabled, default to global */
826   if (!application_has_global_scope (app)
827       && !application_has_local_scope (app))
828     app->flags |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
829
830   props = application_segment_manager_properties (app);
831   segment_manager_props_init (props);
832   props->segment_size = opts[APP_OPTIONS_SEGMENT_SIZE];
833   props->prealloc_fifos = opts[APP_OPTIONS_PREALLOC_FIFO_PAIRS];
834   props->prealloc_fifo_hdrs = opts[APP_OPTIONS_PREALLOC_FIFO_HDRS];
835   if (opts[APP_OPTIONS_ADD_SEGMENT_SIZE])
836     {
837       props->add_segment_size = opts[APP_OPTIONS_ADD_SEGMENT_SIZE];
838       props->add_segment = 1;
839     }
840   if (opts[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_USE_HUGE_PAGE)
841     props->huge_page = 1;
842   if (opts[APP_OPTIONS_RX_FIFO_SIZE])
843     props->rx_fifo_size = opts[APP_OPTIONS_RX_FIFO_SIZE];
844   if (opts[APP_OPTIONS_TX_FIFO_SIZE])
845     props->tx_fifo_size = opts[APP_OPTIONS_TX_FIFO_SIZE];
846   if (opts[APP_OPTIONS_EVT_QUEUE_SIZE])
847     props->evt_q_size = opts[APP_OPTIONS_EVT_QUEUE_SIZE];
848   if (opts[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD)
849     props->use_mq_eventfd = 1;
850   if (opts[APP_OPTIONS_TLS_ENGINE])
851     app->tls_engine = opts[APP_OPTIONS_TLS_ENGINE];
852   if (opts[APP_OPTIONS_MAX_FIFO_SIZE])
853     props->max_fifo_size = opts[APP_OPTIONS_MAX_FIFO_SIZE];
854   if (opts[APP_OPTIONS_HIGH_WATERMARK])
855     props->high_watermark = opts[APP_OPTIONS_HIGH_WATERMARK];
856   if (opts[APP_OPTIONS_LOW_WATERMARK])
857     props->low_watermark = opts[APP_OPTIONS_LOW_WATERMARK];
858   if (opts[APP_OPTIONS_PCT_FIRST_ALLOC])
859     props->pct_first_alloc = opts[APP_OPTIONS_PCT_FIRST_ALLOC];
860   props->segment_type = seg_type;
861
862   /* Add app to lookup by api_client_index table */
863   if (!application_is_builtin (app))
864     application_api_table_add (app->app_index, a->api_client_index);
865   else
866     application_name_table_add (app);
867
868   a->app_index = app->app_index;
869
870   APP_DBG ("New app name: %v api index: %u index %u", app->name,
871            a->api_client_index, app->app_index);
872
873   return 0;
874 }
875
876 static void
877 application_free (application_t * app)
878 {
879   app_worker_map_t *wrk_map;
880   app_worker_t *app_wrk;
881
882   /*
883    * The app event queue allocated in first segment is cleared with
884    * the segment manager. No need to explicitly free it.
885    */
886   APP_DBG ("Delete app name %v index: %d", app->name, app->app_index);
887
888   if (application_is_proxy (app))
889     application_remove_proxy (app);
890
891   /*
892    * Free workers
893    */
894
895   /* *INDENT-OFF* */
896   pool_flush (wrk_map, app->worker_maps, ({
897     app_wrk = app_worker_get (wrk_map->wrk_index);
898     app_worker_free (app_wrk);
899   }));
900   /* *INDENT-ON* */
901   pool_free (app->worker_maps);
902
903   /*
904    * Free rx mqs if allocated
905    */
906   if (app->rx_mqs)
907     {
908       int i;
909       for (i = 0; i < vec_len (app->rx_mqs); i++)
910         app_rx_mqs_epoll_del (app, &app->rx_mqs[i]);
911
912       fifo_segment_cleanup (&app->rx_mqs_segment);
913       ssvm_delete (&app->rx_mqs_segment.ssvm);
914       vec_free (app->rx_mqs);
915     }
916
917   /*
918    * Cleanup remaining state
919    */
920   if (application_is_builtin (app))
921     application_name_table_del (app);
922   vec_free (app->name);
923   pool_put (app_main.app_pool, app);
924 }
925
926 static void
927 application_detach_process (application_t * app, u32 api_client_index)
928 {
929   vnet_app_worker_add_del_args_t _args = { 0 }, *args = &_args;
930   app_worker_map_t *wrk_map;
931   u32 *wrks = 0, *wrk_index;
932   app_worker_t *app_wrk;
933
934   if (api_client_index == ~0)
935     {
936       application_free (app);
937       return;
938     }
939
940   APP_DBG ("Detaching for app %v index %u api client index %u", app->name,
941            app->app_index, api_client_index);
942
943   /* *INDENT-OFF* */
944   pool_foreach (wrk_map, app->worker_maps)  {
945     app_wrk = app_worker_get (wrk_map->wrk_index);
946     if (app_wrk->api_client_index == api_client_index)
947       vec_add1 (wrks, app_wrk->wrk_index);
948   }
949   /* *INDENT-ON* */
950
951   if (!vec_len (wrks))
952     {
953       clib_warning ("no workers for app %u api_index %u", app->app_index,
954                     api_client_index);
955       return;
956     }
957
958   args->app_index = app->app_index;
959   args->api_client_index = api_client_index;
960   vec_foreach (wrk_index, wrks)
961   {
962     app_wrk = app_worker_get (wrk_index[0]);
963     args->wrk_map_index = app_wrk->wrk_map_index;
964     args->is_add = 0;
965     vnet_app_worker_add_del (args);
966   }
967   vec_free (wrks);
968 }
969
970 void
971 application_namespace_cleanup (app_namespace_t *app_ns)
972 {
973   u32 *app_indices = 0, *app_index;
974   application_t *app;
975   u32 ns_index;
976
977   ns_index = app_namespace_index (app_ns);
978   pool_foreach (app, app_main.app_pool)
979     if (app->ns_index == ns_index)
980       vec_add1 (app_indices, app->ns_index);
981
982   vec_foreach (app_index, app_indices)
983     {
984       app = application_get (*app_index);
985
986       if (application_is_proxy (app))
987         application_remove_proxy (app);
988       app->flags &= ~APP_OPTIONS_FLAGS_IS_PROXY;
989
990       application_free (app);
991     }
992   vec_free (app_indices);
993 }
994
995 app_worker_t *
996 application_get_worker (application_t * app, u32 wrk_map_index)
997 {
998   app_worker_map_t *map;
999   map = app_worker_map_get (app, wrk_map_index);
1000   if (!map)
1001     return 0;
1002   return app_worker_get (map->wrk_index);
1003 }
1004
1005 app_worker_t *
1006 application_get_default_worker (application_t * app)
1007 {
1008   return application_get_worker (app, 0);
1009 }
1010
1011 u32
1012 application_n_workers (application_t * app)
1013 {
1014   return pool_elts (app->worker_maps);
1015 }
1016
1017 app_worker_t *
1018 application_listener_select_worker (session_t * ls)
1019 {
1020   application_t *app;
1021   app_listener_t *al;
1022
1023   app = application_get (ls->app_index);
1024   al = app_listener_get (app, ls->al_index);
1025   return app_listener_select_worker (app, al);
1026 }
1027
1028 always_inline u32
1029 app_listener_cl_flow_hash (session_dgram_hdr_t *hdr)
1030 {
1031   u32 hash = 0;
1032
1033   if (hdr->is_ip4)
1034     {
1035       hash = clib_crc32c_u32 (hash, hdr->rmt_ip.ip4.as_u32);
1036       hash = clib_crc32c_u32 (hash, hdr->lcl_ip.ip4.as_u32);
1037       hash = clib_crc32c_u16 (hash, hdr->rmt_port);
1038       hash = clib_crc32c_u16 (hash, hdr->lcl_port);
1039     }
1040   else
1041     {
1042       hash = clib_crc32c_u64 (hash, hdr->rmt_ip.ip6.as_u64[0]);
1043       hash = clib_crc32c_u64 (hash, hdr->rmt_ip.ip6.as_u64[1]);
1044       hash = clib_crc32c_u64 (hash, hdr->lcl_ip.ip6.as_u64[0]);
1045       hash = clib_crc32c_u64 (hash, hdr->lcl_ip.ip6.as_u64[1]);
1046       hash = clib_crc32c_u16 (hash, hdr->rmt_port);
1047       hash = clib_crc32c_u16 (hash, hdr->lcl_port);
1048     }
1049
1050   return hash;
1051 }
1052
1053 session_t *
1054 app_listener_select_wrk_cl_session (session_t *ls, session_dgram_hdr_t *hdr)
1055 {
1056   u32 wrk_map_index = 0;
1057   application_t *app;
1058   app_listener_t *al;
1059
1060   app = application_get (ls->app_index);
1061   al = app_listener_get (app, ls->al_index);
1062   /* Crude test to check if only worker 0 is set */
1063   if (al->workers[0] != 1)
1064     {
1065       u32 hash = app_listener_cl_flow_hash (hdr);
1066       hash %= vec_len (al->workers) * sizeof (uword);
1067       wrk_map_index = clib_bitmap_next_set (al->workers, hash);
1068       if (wrk_map_index == ~0)
1069         wrk_map_index = clib_bitmap_first_set (al->workers);
1070     }
1071
1072   return app_listener_get_wrk_cl_session (al, wrk_map_index);
1073 }
1074
1075 int
1076 application_alloc_worker_and_init (application_t * app, app_worker_t ** wrk)
1077 {
1078   app_worker_map_t *wrk_map;
1079   app_worker_t *app_wrk;
1080   segment_manager_t *sm;
1081   int rv;
1082
1083   app_wrk = app_worker_alloc (app);
1084   wrk_map = app_worker_map_alloc (app);
1085   wrk_map->wrk_index = app_wrk->wrk_index;
1086   app_wrk->wrk_map_index = app_worker_map_index (app, wrk_map);
1087
1088   /*
1089    * Setup first segment manager
1090    */
1091   sm = segment_manager_alloc ();
1092   sm->app_wrk_index = app_wrk->wrk_index;
1093
1094   if ((rv = segment_manager_init_first (sm)))
1095     {
1096       app_worker_free (app_wrk);
1097       return rv;
1098     }
1099   sm->first_is_protected = 1;
1100
1101   /*
1102    * Setup app worker
1103    */
1104   app_wrk->connects_seg_manager = segment_manager_index (sm);
1105   app_wrk->listeners_table = hash_create (0, sizeof (u64));
1106   app_wrk->event_queue = segment_manager_event_queue (sm);
1107   app_wrk->app_is_builtin = application_is_builtin (app);
1108
1109   *wrk = app_wrk;
1110
1111   return 0;
1112 }
1113
1114 session_error_t
1115 vnet_app_worker_add_del (vnet_app_worker_add_del_args_t *a)
1116 {
1117   fifo_segment_t *fs;
1118   app_worker_map_t *wrk_map;
1119   app_worker_t *app_wrk;
1120   segment_manager_t *sm;
1121   application_t *app;
1122   int rv;
1123
1124   app = application_get (a->app_index);
1125   if (!app)
1126     return SESSION_E_INVALID;
1127
1128   if (a->is_add)
1129     {
1130       if ((rv = application_alloc_worker_and_init (app, &app_wrk)))
1131         return rv;
1132
1133       /* Map worker api index to the app */
1134       app_wrk->api_client_index = a->api_client_index;
1135       application_api_table_add (app->app_index, a->api_client_index);
1136
1137       sm = segment_manager_get (app_wrk->connects_seg_manager);
1138       fs = segment_manager_get_segment_w_lock (sm, 0);
1139       a->segment = &fs->ssvm;
1140       a->segment_handle = segment_manager_segment_handle (sm, fs);
1141       segment_manager_segment_reader_unlock (sm);
1142       a->evt_q = app_wrk->event_queue;
1143       a->wrk_map_index = app_wrk->wrk_map_index;
1144     }
1145   else
1146     {
1147       wrk_map = app_worker_map_get (app, a->wrk_map_index);
1148       if (!wrk_map)
1149         return SESSION_E_INVALID;
1150
1151       app_wrk = app_worker_get (wrk_map->wrk_index);
1152       if (!app_wrk)
1153         return SESSION_E_INVALID;
1154
1155       application_api_table_del (app_wrk->api_client_index);
1156       if (appns_sapi_enabled ())
1157         sapi_socket_close_w_handle (app_wrk->api_client_index);
1158       app_worker_free (app_wrk);
1159       app_worker_map_free (app, wrk_map);
1160       if (application_n_workers (app) == 0)
1161         application_free (app);
1162     }
1163   return 0;
1164 }
1165
1166 static session_error_t
1167 app_validate_namespace (u8 *namespace_id, u64 secret, u32 *app_ns_index)
1168 {
1169   app_namespace_t *app_ns;
1170   if (vec_len (namespace_id) == 0)
1171     {
1172       /* Use default namespace */
1173       *app_ns_index = 0;
1174       return 0;
1175     }
1176
1177   *app_ns_index = app_namespace_index_from_id (namespace_id);
1178   if (*app_ns_index == APP_NAMESPACE_INVALID_INDEX)
1179     return SESSION_E_INVALID_NS;
1180   app_ns = app_namespace_get (*app_ns_index);
1181   if (!app_ns)
1182     return SESSION_E_INVALID_NS;
1183   if (app_ns->ns_secret != secret)
1184     return SESSION_E_WRONG_NS_SECRET;
1185   return 0;
1186 }
1187
1188 static u8 *
1189 app_name_from_api_index (u32 api_client_index)
1190 {
1191   vl_api_registration_t *regp;
1192   regp = vl_api_client_index_to_registration (api_client_index);
1193   if (regp)
1194     return format (0, "%s", regp->name);
1195
1196   clib_warning ("api client index %u does not have an api registration!",
1197                 api_client_index);
1198   return format (0, "unknown");
1199 }
1200
1201 /**
1202  * Attach application to vpp
1203  *
1204  * Allocates a vpp app, i.e., a structure that keeps back pointers
1205  * to external app and a segment manager for shared memory fifo based
1206  * communication with the external app.
1207  */
1208 session_error_t
1209 vnet_application_attach (vnet_app_attach_args_t *a)
1210 {
1211   fifo_segment_t *fs;
1212   application_t *app = 0;
1213   app_worker_t *app_wrk;
1214   segment_manager_t *sm;
1215   u32 app_ns_index = 0;
1216   u8 *app_name = 0;
1217   u64 secret;
1218   session_error_t rv;
1219
1220   if (a->api_client_index != APP_INVALID_INDEX)
1221     app = application_lookup (a->api_client_index);
1222   else if (a->name)
1223     app = application_lookup_name (a->name);
1224   else
1225     return SESSION_E_INVALID;
1226
1227   if (app)
1228     return SESSION_E_APP_ATTACHED;
1229
1230   /* Socket api sets the name and validates namespace prior to attach */
1231   if (!a->use_sock_api)
1232     {
1233       if (a->api_client_index != APP_INVALID_INDEX)
1234         {
1235           app_name = app_name_from_api_index (a->api_client_index);
1236           a->name = app_name;
1237         }
1238
1239       secret = a->options[APP_OPTIONS_NAMESPACE_SECRET];
1240       if ((rv = app_validate_namespace (a->namespace_id, secret,
1241                                         &app_ns_index)))
1242         return rv;
1243       a->options[APP_OPTIONS_NAMESPACE] = app_ns_index;
1244     }
1245
1246   if ((rv = application_alloc_and_init ((app_init_args_t *) a)))
1247     return rv;
1248
1249   app = application_get (a->app_index);
1250   if ((rv = application_alloc_worker_and_init (app, &app_wrk)))
1251     return rv;
1252
1253   a->app_evt_q = app_wrk->event_queue;
1254   app_wrk->api_client_index = a->api_client_index;
1255   sm = segment_manager_get (app_wrk->connects_seg_manager);
1256   fs = segment_manager_get_segment_w_lock (sm, 0);
1257
1258   if (application_is_proxy (app))
1259     {
1260       application_setup_proxy (app);
1261       /* The segment manager pool is reallocated because a new listener
1262        * is added. Re-grab segment manager to avoid dangling reference */
1263       sm = segment_manager_get (app_wrk->connects_seg_manager);
1264     }
1265
1266   ASSERT (vec_len (fs->ssvm.name) <= 128);
1267   a->segment = &fs->ssvm;
1268   a->segment_handle = segment_manager_segment_handle (sm, fs);
1269
1270   segment_manager_segment_reader_unlock (sm);
1271
1272   if (!application_is_builtin (app) && application_use_private_rx_mqs ())
1273     rv = app_rx_mqs_alloc (app);
1274
1275   vec_free (app_name);
1276   return rv;
1277 }
1278
1279 /**
1280  * Detach application from vpp
1281  */
1282 session_error_t
1283 vnet_application_detach (vnet_app_detach_args_t *a)
1284 {
1285   application_t *app;
1286
1287   app = application_get_if_valid (a->app_index);
1288   if (!app)
1289     {
1290       clib_warning ("app not attached");
1291       return SESSION_E_NOAPP;
1292     }
1293
1294   app_interface_check_thread_and_barrier (vnet_application_detach, a);
1295   application_detach_process (app, a->api_client_index);
1296   return 0;
1297 }
1298
1299 static u8
1300 session_endpoint_in_ns (session_endpoint_cfg_t *sep)
1301 {
1302   u8 is_lep;
1303
1304   if (sep->flags & SESSION_ENDPT_CFG_F_PROXY_LISTEN)
1305     return 1;
1306
1307   is_lep = session_endpoint_is_local ((session_endpoint_t *) sep);
1308   if (!is_lep && sep->sw_if_index != ENDPOINT_INVALID_INDEX
1309       && !ip_interface_has_address (sep->sw_if_index, &sep->ip, sep->is_ip4))
1310     {
1311       clib_warning ("sw_if_index %u not configured with ip %U",
1312                     sep->sw_if_index, format_ip46_address, &sep->ip,
1313                     sep->is_ip4);
1314       return 0;
1315     }
1316
1317   return (is_lep || ip_is_local (sep->fib_index, &sep->ip, sep->is_ip4));
1318 }
1319
1320 static void
1321 session_endpoint_update_for_app (session_endpoint_cfg_t * sep,
1322                                  application_t * app, u8 is_connect)
1323 {
1324   app_namespace_t *app_ns;
1325   u32 ns_index, fib_index;
1326
1327   ns_index = app->ns_index;
1328
1329   /* App is a transport proto, so fetch the calling app's ns */
1330   if (app->flags & APP_OPTIONS_FLAGS_IS_TRANSPORT_APP)
1331     ns_index = sep->ns_index;
1332
1333   app_ns = app_namespace_get (ns_index);
1334   if (!app_ns)
1335     return;
1336
1337   /* Ask transport and network to bind to/connect using local interface
1338    * that "supports" app's namespace. This will fix our local connection
1339    * endpoint.
1340    */
1341
1342   /* If in default namespace and user requested a fib index use it */
1343   if (ns_index == 0 && sep->fib_index != ENDPOINT_INVALID_INDEX)
1344     fib_index = sep->fib_index;
1345   else
1346     fib_index = sep->is_ip4 ? app_ns->ip4_fib_index : app_ns->ip6_fib_index;
1347   sep->peer.fib_index = fib_index;
1348   sep->fib_index = fib_index;
1349
1350   if (!is_connect)
1351     {
1352       sep->sw_if_index = app_ns->sw_if_index;
1353     }
1354   else
1355     {
1356       if (app_ns->sw_if_index != APP_NAMESPACE_INVALID_INDEX
1357           && sep->peer.sw_if_index != ENDPOINT_INVALID_INDEX
1358           && sep->peer.sw_if_index != app_ns->sw_if_index)
1359         clib_warning ("Local sw_if_index different from app ns sw_if_index");
1360
1361       sep->peer.sw_if_index = app_ns->sw_if_index;
1362     }
1363 }
1364
1365 session_error_t
1366 vnet_listen (vnet_listen_args_t *a)
1367 {
1368   app_listener_t *app_listener;
1369   app_worker_t *app_wrk;
1370   application_t *app;
1371   int rv;
1372
1373   ASSERT (vlib_thread_is_main_w_barrier ());
1374
1375   app = application_get_if_valid (a->app_index);
1376   if (!app)
1377     return SESSION_E_NOAPP;
1378
1379   app_wrk = application_get_worker (app, a->wrk_map_index);
1380   if (!app_wrk)
1381     return SESSION_E_INVALID_APPWRK;
1382
1383   a->sep_ext.app_wrk_index = app_wrk->wrk_index;
1384
1385   session_endpoint_update_for_app (&a->sep_ext, app, 0 /* is_connect */ );
1386   if (!session_endpoint_in_ns (&a->sep_ext))
1387     return SESSION_E_INVALID_NS;
1388
1389   /*
1390    * Check if we already have an app listener
1391    */
1392   app_listener = app_listener_lookup (app, &a->sep_ext);
1393   if (app_listener)
1394     {
1395       if (app_listener->app_index != app->app_index)
1396         return SESSION_E_ALREADY_LISTENING;
1397       if ((rv = app_worker_start_listen (app_wrk, app_listener)))
1398         return rv;
1399       a->handle = app_listener_handle (app_listener);
1400       return 0;
1401     }
1402
1403   /*
1404    * Create new app listener
1405    */
1406   if ((rv = app_listener_alloc_and_init (app, &a->sep_ext, &app_listener)))
1407     return rv;
1408
1409   if ((rv = app_worker_start_listen (app_wrk, app_listener)))
1410     {
1411       app_listener_cleanup (app_listener);
1412       return rv;
1413     }
1414
1415   a->handle = app_listener_handle (app_listener);
1416   return 0;
1417 }
1418
1419 session_error_t
1420 vnet_connect (vnet_connect_args_t *a)
1421 {
1422   app_worker_t *client_wrk;
1423   application_t *client;
1424
1425   ASSERT (session_vlib_thread_is_cl_thread ());
1426
1427   if (session_endpoint_is_zero (&a->sep))
1428     return SESSION_E_INVALID_RMT_IP;
1429
1430   client = application_get (a->app_index);
1431   session_endpoint_update_for_app (&a->sep_ext, client, 1 /* is_connect */ );
1432   client_wrk = application_get_worker (client, a->wrk_map_index);
1433
1434   a->sep_ext.opaque = a->api_context;
1435
1436   /*
1437    * First check the local scope for locally attached destinations.
1438    * If we have local scope, we pass *all* connects through it since we may
1439    * have special policy rules even for non-local destinations, think proxy.
1440    */
1441   if (application_has_local_scope (client))
1442     {
1443       session_error_t rv;
1444
1445       a->sep_ext.original_tp = a->sep_ext.transport_proto;
1446       a->sep_ext.transport_proto = TRANSPORT_PROTO_NONE;
1447       rv = app_worker_connect_session (client_wrk, &a->sep_ext, &a->sh);
1448       a->sep_ext.transport_proto = a->sep_ext.original_tp;
1449       if (!rv || rv != SESSION_E_LOCAL_CONNECT)
1450         return rv;
1451     }
1452   /*
1453    * Not connecting to a local server, propagate to transport
1454    */
1455   return app_worker_connect_session (client_wrk, &a->sep_ext, &a->sh);
1456 }
1457
1458 session_error_t
1459 vnet_unlisten (vnet_unlisten_args_t *a)
1460 {
1461   app_worker_t *app_wrk;
1462   app_listener_t *al;
1463   application_t *app;
1464
1465   ASSERT (vlib_thread_is_main_w_barrier ());
1466
1467   if (!(app = application_get_if_valid (a->app_index)))
1468     return SESSION_E_NOAPP;
1469
1470   if (!(al = app_listener_get_w_handle (a->handle)))
1471     return SESSION_E_NOLISTEN;
1472
1473   if (al->app_index != app->app_index)
1474     {
1475       clib_warning ("app doesn't own handle %llu!", a->handle);
1476       return SESSION_E_OWNER;
1477     }
1478
1479   app_wrk = application_get_worker (app, a->wrk_map_index);
1480   if (!app_wrk)
1481     {
1482       clib_warning ("no app %u worker %u", app->app_index, a->wrk_map_index);
1483       return SESSION_E_INVALID_APPWRK;
1484     }
1485
1486   return app_worker_stop_listen (app_wrk, al);
1487 }
1488
1489 session_error_t
1490 vnet_shutdown_session (vnet_shutdown_args_t *a)
1491 {
1492   app_worker_t *app_wrk;
1493   session_t *s;
1494
1495   s = session_get_from_handle_if_valid (a->handle);
1496   if (!s)
1497     return SESSION_E_NOSESSION;
1498
1499   app_wrk = app_worker_get (s->app_wrk_index);
1500   if (app_wrk->app_index != a->app_index)
1501     return SESSION_E_OWNER;
1502
1503   /* We're peeking into another's thread pool. Make sure */
1504   ASSERT (s->session_index == session_index_from_handle (a->handle));
1505
1506   session_half_close (s);
1507   return 0;
1508 }
1509
1510 session_error_t
1511 vnet_disconnect_session (vnet_disconnect_args_t *a)
1512 {
1513   app_worker_t *app_wrk;
1514   session_t *s;
1515
1516   s = session_get_from_handle_if_valid (a->handle);
1517   if (!s)
1518     return SESSION_E_NOSESSION;
1519
1520   app_wrk = app_worker_get (s->app_wrk_index);
1521   if (app_wrk->app_index != a->app_index)
1522     return SESSION_E_OWNER;
1523
1524   /* We're peeking into another's thread pool. Make sure */
1525   ASSERT (s->session_index == session_index_from_handle (a->handle));
1526
1527   session_close (s);
1528   return 0;
1529 }
1530
1531 int
1532 application_change_listener_owner (session_t * s, app_worker_t * app_wrk)
1533 {
1534   app_worker_t *old_wrk = app_worker_get (s->app_wrk_index);
1535   app_listener_t *app_listener;
1536   application_t *app;
1537   int rv;
1538
1539   if (!old_wrk)
1540     return SESSION_E_INVALID_APPWRK;
1541
1542   hash_unset (old_wrk->listeners_table, listen_session_get_handle (s));
1543   if (session_transport_service_type (s) == TRANSPORT_SERVICE_CL
1544       && s->rx_fifo)
1545     segment_manager_dealloc_fifos (s->rx_fifo, s->tx_fifo);
1546
1547   app = application_get (old_wrk->app_index);
1548   if (!app)
1549     return SESSION_E_NOAPP;
1550
1551   app_listener = app_listener_get (app, s->al_index);
1552
1553   /* Only remove from lb for now */
1554   app_listener->workers = clib_bitmap_set (app_listener->workers,
1555                                            old_wrk->wrk_map_index, 0);
1556
1557   if ((rv = app_worker_start_listen (app_wrk, app_listener)))
1558     return rv;
1559
1560   s->app_wrk_index = app_wrk->wrk_index;
1561
1562   return 0;
1563 }
1564
1565 int
1566 application_is_proxy (application_t * app)
1567 {
1568   return (app->flags & APP_OPTIONS_FLAGS_IS_PROXY);
1569 }
1570
1571 int
1572 application_is_builtin (application_t * app)
1573 {
1574   return (app->flags & APP_OPTIONS_FLAGS_IS_BUILTIN);
1575 }
1576
1577 int
1578 application_is_builtin_proxy (application_t * app)
1579 {
1580   return (application_is_proxy (app) && application_is_builtin (app));
1581 }
1582
1583 u8
1584 application_has_local_scope (application_t * app)
1585 {
1586   return app->flags & APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
1587 }
1588
1589 u8
1590 application_has_global_scope (application_t * app)
1591 {
1592   return app->flags & APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1593 }
1594
1595 int
1596 application_original_dst_is_enabled (application_t *app)
1597 {
1598   return app->flags & APP_OPTIONS_FLAGS_GET_ORIGINAL_DST;
1599 }
1600
1601 static clib_error_t *
1602 application_start_stop_proxy_fib_proto (application_t * app, u8 fib_proto,
1603                                         u8 transport_proto, u8 is_start)
1604 {
1605   app_namespace_t *app_ns = app_namespace_get (app->ns_index);
1606   u8 is_ip4 = (fib_proto == FIB_PROTOCOL_IP4);
1607   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
1608   transport_connection_t *tc;
1609   app_worker_t *app_wrk;
1610   app_listener_t *al;
1611   session_t *s;
1612   u32 flags;
1613
1614   /* TODO decide if we want proxy to be enabled for all workers */
1615   app_wrk = application_get_default_worker (app);
1616   if (is_start)
1617     {
1618       s = app_worker_first_listener (app_wrk, fib_proto, transport_proto);
1619       if (!s)
1620         {
1621           sep.is_ip4 = is_ip4;
1622           sep.fib_index = app_namespace_get_fib_index (app_ns, fib_proto);
1623           sep.sw_if_index = app_ns->sw_if_index;
1624           sep.transport_proto = transport_proto;
1625           sep.app_wrk_index = app_wrk->wrk_index;       /* only default */
1626
1627           /* force global scope listener */
1628           flags = app->flags;
1629           app->flags &= ~APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
1630           app_listener_alloc_and_init (app, &sep, &al);
1631           app->flags = flags;
1632
1633           app_worker_start_listen (app_wrk, al);
1634           s = listen_session_get (al->session_index);
1635           s->flags |= SESSION_F_PROXY;
1636         }
1637     }
1638   else
1639     {
1640       s = app_worker_proxy_listener (app_wrk, fib_proto, transport_proto);
1641       ASSERT (s);
1642     }
1643
1644   tc = listen_session_get_transport (s);
1645
1646   if (!ip_is_zero (&tc->lcl_ip, 1))
1647     {
1648       u32 sti;
1649       sep.is_ip4 = is_ip4;
1650       sep.fib_index = app_namespace_get_fib_index (app_ns, fib_proto);
1651       sep.transport_proto = transport_proto;
1652       sep.port = 0;
1653       sti = session_lookup_get_index_for_fib (fib_proto, sep.fib_index);
1654       if (is_start)
1655         session_lookup_add_session_endpoint (sti,
1656                                              (session_endpoint_t *) & sep,
1657                                              s->session_index);
1658       else
1659         session_lookup_del_session_endpoint (sti,
1660                                              (session_endpoint_t *) & sep);
1661     }
1662
1663   return 0;
1664 }
1665
1666 static void
1667 application_start_stop_proxy_local_scope (application_t * app,
1668                                           u8 transport_proto, u8 is_start)
1669 {
1670   session_endpoint_t sep = SESSION_ENDPOINT_NULL;
1671   app_namespace_t *app_ns;
1672   app_ns = app_namespace_get (app->ns_index);
1673   sep.is_ip4 = 1;
1674   sep.transport_proto = transport_proto;
1675   sep.port = 0;
1676
1677   if (is_start)
1678     {
1679       session_lookup_add_session_endpoint (app_ns->local_table_index, &sep,
1680                                            app->app_index);
1681       sep.is_ip4 = 0;
1682       session_lookup_add_session_endpoint (app_ns->local_table_index, &sep,
1683                                            app->app_index);
1684     }
1685   else
1686     {
1687       session_lookup_del_session_endpoint (app_ns->local_table_index, &sep);
1688       sep.is_ip4 = 0;
1689       session_lookup_del_session_endpoint (app_ns->local_table_index, &sep);
1690     }
1691 }
1692
1693 void
1694 application_start_stop_proxy (application_t * app,
1695                               transport_proto_t transport_proto, u8 is_start)
1696 {
1697   if (application_has_local_scope (app))
1698     application_start_stop_proxy_local_scope (app, transport_proto, is_start);
1699
1700   if (application_has_global_scope (app))
1701     {
1702       application_start_stop_proxy_fib_proto (app, FIB_PROTOCOL_IP4,
1703                                               transport_proto, is_start);
1704       application_start_stop_proxy_fib_proto (app, FIB_PROTOCOL_IP6,
1705                                               transport_proto, is_start);
1706     }
1707 }
1708
1709 void
1710 application_setup_proxy (application_t * app)
1711 {
1712   u16 transports = app->proxied_transports;
1713   transport_proto_t tp;
1714
1715   ASSERT (application_is_proxy (app));
1716
1717   transport_proto_foreach (tp, transports)
1718     application_start_stop_proxy (app, tp, 1);
1719 }
1720
1721 void
1722 application_remove_proxy (application_t * app)
1723 {
1724   u16 transports = app->proxied_transports;
1725   transport_proto_t tp;
1726
1727   ASSERT (application_is_proxy (app));
1728
1729   transport_proto_foreach (tp, transports)
1730     application_start_stop_proxy (app, tp, 0);
1731 }
1732
1733 segment_manager_props_t *
1734 application_segment_manager_properties (application_t * app)
1735 {
1736   return &app->sm_properties;
1737 }
1738
1739 segment_manager_props_t *
1740 application_get_segment_manager_properties (u32 app_index)
1741 {
1742   application_t *app = application_get (app_index);
1743   return &app->sm_properties;
1744 }
1745
1746 static void
1747 application_format_listeners (application_t * app, int verbose)
1748 {
1749   vlib_main_t *vm = vlib_get_main ();
1750   app_worker_map_t *wrk_map;
1751   app_worker_t *app_wrk;
1752   u32 sm_index;
1753   u64 handle;
1754
1755   if (!app)
1756     {
1757       vlib_cli_output (vm, "%U", format_app_worker_listener, NULL /* header */,
1758                        0, 0, verbose);
1759       return;
1760     }
1761
1762   /* *INDENT-OFF* */
1763   pool_foreach (wrk_map, app->worker_maps)  {
1764     app_wrk = app_worker_get (wrk_map->wrk_index);
1765     if (hash_elts (app_wrk->listeners_table) == 0)
1766       continue;
1767     hash_foreach (handle, sm_index, app_wrk->listeners_table, ({
1768       vlib_cli_output (vm, "%U", format_app_worker_listener, app_wrk,
1769                        handle, sm_index, verbose);
1770     }));
1771   }
1772   /* *INDENT-ON* */
1773 }
1774
1775 static void
1776 application_format_connects (application_t * app, int verbose)
1777 {
1778   app_worker_map_t *wrk_map;
1779   app_worker_t *app_wrk;
1780
1781   if (!app)
1782     {
1783       app_worker_format_connects (0, verbose);
1784       return;
1785     }
1786
1787   /* *INDENT-OFF* */
1788   pool_foreach (wrk_map, app->worker_maps)  {
1789     app_wrk = app_worker_get (wrk_map->wrk_index);
1790     app_worker_format_connects (app_wrk, verbose);
1791   }
1792   /* *INDENT-ON* */
1793 }
1794
1795 u8 *
1796 format_cert_key_pair (u8 * s, va_list * args)
1797 {
1798   app_cert_key_pair_t *ckpair = va_arg (*args, app_cert_key_pair_t *);
1799   int key_len = 0, cert_len = 0;
1800   cert_len = vec_len (ckpair->cert);
1801   key_len = vec_len (ckpair->key);
1802   if (ckpair->cert_key_index == 0)
1803     s = format (s, "DEFAULT (cert:%d, key:%d)", cert_len, key_len);
1804   else
1805     s = format (s, "%d (cert:%d, key:%d)", ckpair->cert_key_index,
1806                 cert_len, key_len);
1807   return s;
1808 }
1809
1810 u8 *
1811 format_crypto_engine (u8 * s, va_list * args)
1812 {
1813   u32 engine = va_arg (*args, u32);
1814   switch (engine)
1815     {
1816     case CRYPTO_ENGINE_NONE:
1817       return format (s, "none");
1818     case CRYPTO_ENGINE_MBEDTLS:
1819       return format (s, "mbedtls");
1820     case CRYPTO_ENGINE_OPENSSL:
1821       return format (s, "openssl");
1822     case CRYPTO_ENGINE_PICOTLS:
1823       return format (s, "picotls");
1824     case CRYPTO_ENGINE_VPP:
1825       return format (s, "vpp");
1826     default:
1827       return format (s, "unknown engine");
1828     }
1829   return s;
1830 }
1831
1832 uword
1833 unformat_crypto_engine (unformat_input_t * input, va_list * args)
1834 {
1835   u8 *a = va_arg (*args, u8 *);
1836   if (unformat (input, "mbedtls"))
1837     *a = CRYPTO_ENGINE_MBEDTLS;
1838   else if (unformat (input, "openssl"))
1839     *a = CRYPTO_ENGINE_OPENSSL;
1840   else if (unformat (input, "picotls"))
1841     *a = CRYPTO_ENGINE_PICOTLS;
1842   else if (unformat (input, "vpp"))
1843     *a = CRYPTO_ENGINE_VPP;
1844   else
1845     return 0;
1846   return 1;
1847 }
1848
1849 u8 *
1850 format_crypto_context (u8 * s, va_list * args)
1851 {
1852   crypto_context_t *crctx = va_arg (*args, crypto_context_t *);
1853   s = format (s, "[0x%x][sub%d,ckpair%x]", crctx->ctx_index,
1854               crctx->n_subscribers, crctx->ckpair_index);
1855   s = format (s, "[%U]", format_crypto_engine, crctx->crypto_engine);
1856   return s;
1857 }
1858
1859 u8 *
1860 format_application (u8 * s, va_list * args)
1861 {
1862   application_t *app = va_arg (*args, application_t *);
1863   CLIB_UNUSED (int verbose) = va_arg (*args, int);
1864   segment_manager_props_t *props;
1865   const u8 *app_ns_name, *app_name;
1866   app_worker_map_t *wrk_map;
1867   app_worker_t *app_wrk;
1868
1869   if (app == 0)
1870     {
1871       if (!verbose)
1872         s = format (s, "%-10s%-20s%-40s", "Index", "Name", "Namespace");
1873       return s;
1874     }
1875
1876   app_name = app_get_name (app);
1877   app_ns_name = app_namespace_id_from_index (app->ns_index);
1878   props = application_segment_manager_properties (app);
1879   if (!verbose)
1880     {
1881       s = format (s, "%-10u%-20v%-40v", app->app_index, app_name,
1882                   app_ns_name);
1883       return s;
1884     }
1885
1886   s = format (s, "app-name %v app-index %u ns-index %u seg-size %U\n",
1887               app_name, app->app_index, app->ns_index,
1888               format_memory_size, props->add_segment_size);
1889   s = format (s, "rx-fifo-size %U tx-fifo-size %U workers:\n",
1890               format_memory_size, props->rx_fifo_size,
1891               format_memory_size, props->tx_fifo_size);
1892
1893   /* *INDENT-OFF* */
1894   pool_foreach (wrk_map, app->worker_maps)  {
1895       app_wrk = app_worker_get (wrk_map->wrk_index);
1896       s = format (s, "%U", format_app_worker, app_wrk);
1897   }
1898   /* *INDENT-ON* */
1899
1900   return s;
1901 }
1902
1903 void
1904 application_format_all_listeners (vlib_main_t * vm, int verbose)
1905 {
1906   application_t *app;
1907
1908   if (!pool_elts (app_main.app_pool))
1909     {
1910       vlib_cli_output (vm, "No active server bindings");
1911       return;
1912     }
1913
1914   application_format_listeners (0, verbose);
1915
1916   /* *INDENT-OFF* */
1917   pool_foreach (app, app_main.app_pool)  {
1918     application_format_listeners (app, verbose);
1919   }
1920   /* *INDENT-ON* */
1921 }
1922
1923 void
1924 application_format_all_clients (vlib_main_t * vm, int verbose)
1925 {
1926   application_t *app;
1927
1928   if (!pool_elts (app_main.app_pool))
1929     {
1930       vlib_cli_output (vm, "No active apps");
1931       return;
1932     }
1933
1934   application_format_connects (0, verbose);
1935
1936   /* *INDENT-OFF* */
1937   pool_foreach (app, app_main.app_pool)  {
1938     application_format_connects (app, verbose);
1939   }
1940   /* *INDENT-ON* */
1941 }
1942
1943 static clib_error_t *
1944 show_certificate_command_fn (vlib_main_t * vm, unformat_input_t * input,
1945                              vlib_cli_command_t * cmd)
1946 {
1947   app_cert_key_pair_t *ckpair;
1948   session_cli_return_if_not_enabled ();
1949
1950   /* *INDENT-OFF* */
1951   pool_foreach (ckpair, app_main.cert_key_pair_store)  {
1952     vlib_cli_output (vm, "%U", format_cert_key_pair, ckpair);
1953   }
1954   /* *INDENT-ON* */
1955   return 0;
1956 }
1957
1958 static inline void
1959 appliction_format_app_mq (vlib_main_t * vm, application_t * app)
1960 {
1961   app_worker_map_t *map;
1962   app_worker_t *wrk;
1963   int i;
1964
1965   /* *INDENT-OFF* */
1966   pool_foreach (map, app->worker_maps)  {
1967     wrk = app_worker_get (map->wrk_index);
1968     vlib_cli_output (vm, "[A%d][%d]%U", app->app_index,
1969                      map->wrk_index, format_svm_msg_q,
1970                      wrk->event_queue);
1971   }
1972   /* *INDENT-ON* */
1973
1974   for (i = 0; i < vec_len (app->rx_mqs); i++)
1975     vlib_cli_output (vm, "[A%d][R%d]%U", app->app_index, i, format_svm_msg_q,
1976                      app->rx_mqs[i].mq);
1977 }
1978
1979 static clib_error_t *
1980 appliction_format_all_app_mq (vlib_main_t * vm)
1981 {
1982   application_t *app;
1983   int i, n_threads;
1984
1985   n_threads = vlib_get_n_threads ();
1986
1987   for (i = 0; i < n_threads; i++)
1988     {
1989       vlib_cli_output (vm, "[Ctrl%d]%U", i, format_svm_msg_q,
1990                        session_main_get_vpp_event_queue (i));
1991     }
1992
1993   /* *INDENT-OFF* */
1994   pool_foreach (app, app_main.app_pool)  {
1995       appliction_format_app_mq (vm, app);
1996   }
1997   /* *INDENT-ON* */
1998   return 0;
1999 }
2000
2001 static clib_error_t *
2002 show_app_command_fn (vlib_main_t * vm, unformat_input_t * input,
2003                      vlib_cli_command_t * cmd)
2004 {
2005   int do_server = 0, do_client = 0, do_mq = 0, do_transports = 0;
2006   application_t *app;
2007   u32 app_index = ~0;
2008   int verbose = 0;
2009   u8 is_ta;
2010
2011   session_cli_return_if_not_enabled ();
2012
2013   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2014     {
2015       if (unformat (input, "server"))
2016         do_server = 1;
2017       else if (unformat (input, "client"))
2018         do_client = 1;
2019       else if (unformat (input, "transports"))
2020         do_transports = 1;
2021       else if (unformat (input, "mq"))
2022         do_mq = 1;
2023       else if (unformat (input, "%u", &app_index))
2024         ;
2025       else if (unformat (input, "verbose"))
2026         verbose = 1;
2027       else
2028         return clib_error_return (0, "unknown input `%U'",
2029                                   format_unformat_error, input);
2030     }
2031
2032   if (do_mq && app_index != ~0)
2033     {
2034       app = application_get_if_valid (app_index);
2035       if (!app)
2036         return clib_error_return (0, "No app with index %u", app_index);
2037
2038       appliction_format_app_mq (vm, app);
2039       return 0;
2040     }
2041
2042   if (do_mq)
2043     {
2044       appliction_format_all_app_mq (vm);
2045       return 0;
2046     }
2047
2048   if (do_server)
2049     {
2050       application_format_all_listeners (vm, verbose);
2051       return 0;
2052     }
2053
2054   if (do_client)
2055     {
2056       application_format_all_clients (vm, verbose);
2057       return 0;
2058     }
2059
2060   if (app_index != ~0)
2061     {
2062       app = application_get_if_valid (app_index);
2063       if (!app)
2064         return clib_error_return (0, "No app with index %u", app_index);
2065
2066       vlib_cli_output (vm, "%U", format_application, app, /* verbose */ 1);
2067       return 0;
2068     }
2069
2070   /* Print app related info */
2071   if (!do_server && !do_client)
2072     {
2073       vlib_cli_output (vm, "%U", format_application, 0, 0);
2074       pool_foreach (app, app_main.app_pool)  {
2075           is_ta = app->flags & APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
2076           if ((!do_transports && !is_ta) || (do_transports && is_ta))
2077             vlib_cli_output (vm, "%U", format_application, app, 0);
2078       }
2079     }
2080
2081   return 0;
2082 }
2083
2084 /* Certificate store */
2085
2086 static app_cert_key_pair_t *
2087 app_cert_key_pair_alloc ()
2088 {
2089   app_cert_key_pair_t *ckpair;
2090   pool_get (app_main.cert_key_pair_store, ckpair);
2091   clib_memset (ckpair, 0, sizeof (*ckpair));
2092   ckpair->cert_key_index = ckpair - app_main.cert_key_pair_store;
2093   return ckpair;
2094 }
2095
2096 app_cert_key_pair_t *
2097 app_cert_key_pair_get_if_valid (u32 index)
2098 {
2099   if (pool_is_free_index (app_main.cert_key_pair_store, index))
2100     return 0;
2101   return app_cert_key_pair_get (index);
2102 }
2103
2104 app_cert_key_pair_t *
2105 app_cert_key_pair_get (u32 index)
2106 {
2107   return pool_elt_at_index (app_main.cert_key_pair_store, index);
2108 }
2109
2110 app_cert_key_pair_t *
2111 app_cert_key_pair_get_default ()
2112 {
2113   /* To maintain legacy bapi */
2114   return app_cert_key_pair_get (0);
2115 }
2116
2117 int
2118 vnet_app_add_cert_key_pair (vnet_app_add_cert_key_pair_args_t * a)
2119 {
2120   app_cert_key_pair_t *ckpair = app_cert_key_pair_alloc ();
2121   vec_validate (ckpair->cert, a->cert_len - 1);
2122   clib_memcpy_fast (ckpair->cert, a->cert, a->cert_len);
2123   vec_validate (ckpair->key, a->key_len - 1);
2124   clib_memcpy_fast (ckpair->key, a->key, a->key_len);
2125   a->index = ckpair->cert_key_index;
2126   return 0;
2127 }
2128
2129 int
2130 vnet_app_add_cert_key_interest (u32 index, u32 app_index)
2131 {
2132   app_cert_key_pair_t *ckpair;
2133   if (!(ckpair = app_cert_key_pair_get_if_valid (index)))
2134     return -1;
2135   if (vec_search (ckpair->app_interests, app_index) != ~0)
2136     vec_add1 (ckpair->app_interests, app_index);
2137   return 0;
2138 }
2139
2140 int
2141 vnet_app_del_cert_key_pair (u32 index)
2142 {
2143   app_cert_key_pair_t *ckpair;
2144   application_t *app;
2145   u32 *app_index;
2146
2147   if (!(ckpair = app_cert_key_pair_get_if_valid (index)))
2148     return SESSION_E_INVALID;
2149
2150   vec_foreach (app_index, ckpair->app_interests)
2151   {
2152     if ((app = application_get_if_valid (*app_index))
2153         && app->cb_fns.app_cert_key_pair_delete_callback)
2154       app->cb_fns.app_cert_key_pair_delete_callback (ckpair);
2155   }
2156
2157   vec_free (ckpair->cert);
2158   vec_free (ckpair->key);
2159   pool_put (app_main.cert_key_pair_store, ckpair);
2160   return 0;
2161 }
2162
2163 clib_error_t *
2164 application_init (vlib_main_t * vm)
2165 {
2166   app_main_t *am = &app_main;
2167   u32 n_workers;
2168
2169   n_workers = vlib_num_workers ();
2170
2171   /* Index 0 was originally used by legacy apis, maintain as invalid */
2172   (void) app_cert_key_pair_alloc ();
2173   am->last_crypto_engine = CRYPTO_ENGINE_LAST;
2174   am->app_by_name = hash_create_vec (0, sizeof (u8), sizeof (uword));
2175
2176   vec_validate (am->wrk, n_workers);
2177
2178   return 0;
2179 }
2180
2181 VLIB_INIT_FUNCTION (application_init);
2182
2183 VLIB_CLI_COMMAND (show_app_command, static) = {
2184   .path = "show app",
2185   .short_help = "show app [index] [server|client] [mq] [verbose] "
2186                 "[transports]",
2187   .function = show_app_command_fn,
2188 };
2189
2190 VLIB_CLI_COMMAND (show_certificate_command, static) = {
2191   .path = "show app certificate",
2192   .short_help = "list app certs and keys present in store",
2193   .function = show_certificate_command_fn,
2194 };
2195
2196 crypto_engine_type_t
2197 app_crypto_engine_type_add (void)
2198 {
2199   return (++app_main.last_crypto_engine);
2200 }
2201
2202 u8
2203 app_crypto_engine_n_types (void)
2204 {
2205   return (app_main.last_crypto_engine + 1);
2206 }
2207
2208 /*
2209  * fd.io coding-style-patch-verification: ON
2210  *
2211  * Local Variables:
2212  * eval: (c-set-style "gnu")
2213  * End:
2214  */