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