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