session: fix workers race to allocate lookup table
[vpp.git] / src / vnet / session / session_api.c
1 /*
2  * Copyright (c) 2015-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/vnet.h>
17 #include <vlibmemory/api.h>
18 #include <vnet/session/application.h>
19 #include <vnet/session/application_interface.h>
20 #include <vnet/session/application_local.h>
21 #include <vnet/session/session_rules_table.h>
22 #include <vnet/session/session_table.h>
23 #include <vnet/session/session.h>
24 #include <vnet/ip/ip_types_api.h>
25
26 #include <vnet/format_fns.h>
27 #include <vnet/session/session.api_enum.h>
28 #include <vnet/session/session.api_types.h>
29
30 #define REPLY_MSG_ID_BASE session_main.msg_id_base
31 #include <vlibapi/api_helper_macros.h>
32
33 static transport_proto_t
34 api_session_transport_proto_decode (const vl_api_transport_proto_t * api_tp)
35 {
36   switch (*api_tp)
37     {
38     case TRANSPORT_PROTO_API_TCP:
39       return TRANSPORT_PROTO_TCP;
40     case TRANSPORT_PROTO_API_UDP:
41       return TRANSPORT_PROTO_UDP;
42     case TRANSPORT_PROTO_API_TLS:
43       return TRANSPORT_PROTO_TLS;
44     case TRANSPORT_PROTO_API_QUIC:
45       return TRANSPORT_PROTO_QUIC;
46     default:
47       return TRANSPORT_PROTO_NONE;
48     }
49 }
50
51 static vl_api_transport_proto_t
52 api_session_transport_proto_encode (const transport_proto_t tp)
53 {
54   switch (tp)
55     {
56     case TRANSPORT_PROTO_TCP:
57       return TRANSPORT_PROTO_API_TCP;
58     case TRANSPORT_PROTO_UDP:
59       return TRANSPORT_PROTO_API_UDP;
60     case TRANSPORT_PROTO_TLS:
61       return TRANSPORT_PROTO_API_TLS;
62     case TRANSPORT_PROTO_QUIC:
63       return TRANSPORT_PROTO_API_QUIC;
64     default:
65       return TRANSPORT_PROTO_API_NONE;
66     }
67 }
68
69 static int
70 session_send_fds (vl_api_registration_t * reg, int fds[], int n_fds)
71 {
72   clib_error_t *error;
73   if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
74     return SESSION_E_BAPI_NO_FD;
75   error = vl_api_send_fd_msg (reg, fds, n_fds);
76   if (error)
77     {
78       clib_error_report (error);
79       return SESSION_E_BAPI_SEND_FD;
80     }
81   return 0;
82 }
83
84 static int
85 mq_send_session_accepted_cb (session_t * s)
86 {
87   app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
88   session_accepted_msg_t m = { 0 };
89   fifo_segment_t *eq_seg;
90   session_t *listener;
91   application_t *app;
92
93   app = application_get (app_wrk->app_index);
94
95   m.context = app->app_index;
96   m.server_rx_fifo = fifo_segment_fifo_offset (s->rx_fifo);
97   m.server_tx_fifo = fifo_segment_fifo_offset (s->tx_fifo);
98   m.segment_handle = session_segment_handle (s);
99   m.flags = s->flags;
100
101   eq_seg = application_get_rx_mqs_segment (app);
102
103   if (session_has_transport (s))
104     {
105       listener = listen_session_get_from_handle (s->listener_handle);
106       m.listener_handle = app_listen_session_handle (listener);
107       if (application_is_proxy (app))
108         {
109           listener =
110             app_worker_first_listener (app_wrk, session_get_fib_proto (s),
111                                        session_get_transport_proto (s));
112           if (listener)
113             m.listener_handle = listen_session_get_handle (listener);
114         }
115       m.vpp_event_queue_address =
116         fifo_segment_msg_q_offset (eq_seg, s->thread_index);
117       m.mq_index = s->thread_index;
118       m.handle = session_handle (s);
119
120       session_get_endpoint (s, &m.rmt, 0 /* is_lcl */);
121       session_get_endpoint (s, &m.lcl, 1 /* is_lcl */);
122     }
123   else
124     {
125       ct_connection_t *ct;
126
127       ct = (ct_connection_t *) session_get_transport (s);
128       listener = listen_session_get_from_handle (s->listener_handle);
129       m.listener_handle = app_listen_session_handle (listener);
130       m.rmt.is_ip4 = session_type_is_ip4 (listener->session_type);
131       m.rmt.port = ct->c_rmt_port;
132       m.lcl.port = ct->c_lcl_port;
133       m.handle = session_handle (s);
134       m.vpp_event_queue_address =
135         fifo_segment_msg_q_offset (eq_seg, s->thread_index);
136       m.mq_index = s->thread_index;
137     }
138
139   if (application_original_dst_is_enabled (app))
140     {
141       session_get_original_dst (&m.lcl, &m.rmt,
142                                 session_get_transport_proto (s),
143                                 &m.original_dst_ip4, &m.original_dst_port);
144     }
145
146   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_ACCEPTED, &m, sizeof (m));
147
148   return 0;
149 }
150
151 static inline void
152 mq_send_session_close_evt (app_worker_t * app_wrk, session_handle_t sh,
153                            session_evt_type_t evt_type)
154 {
155   session_disconnected_msg_t m = { 0 };
156
157   m.handle = sh;
158   m.context = app_wrk->api_client_index;
159
160   app_wrk_send_ctrl_evt (app_wrk, evt_type, &m, sizeof (m));
161 }
162
163 static inline void
164 mq_notify_close_subscribers (u32 app_index, session_handle_t sh,
165                              svm_fifo_t * f, session_evt_type_t evt_type)
166 {
167   app_worker_t *app_wrk;
168   application_t *app;
169   int i;
170
171   app = application_get (app_index);
172   if (!app)
173     return;
174
175   for (i = 0; i < f->shr->n_subscribers; i++)
176     {
177       if (!(app_wrk = application_get_worker (app, f->shr->subscribers[i])))
178         continue;
179       mq_send_session_close_evt (app_wrk, sh, SESSION_CTRL_EVT_DISCONNECTED);
180     }
181 }
182
183 static void
184 mq_send_session_disconnected_cb (session_t * s)
185 {
186   app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
187   session_handle_t sh = session_handle (s);
188
189   mq_send_session_close_evt (app_wrk, session_handle (s),
190                              SESSION_CTRL_EVT_DISCONNECTED);
191
192   if (svm_fifo_n_subscribers (s->rx_fifo))
193     mq_notify_close_subscribers (app_wrk->app_index, sh, s->rx_fifo,
194                                  SESSION_CTRL_EVT_DISCONNECTED);
195 }
196
197 static void
198 mq_send_session_reset_cb (session_t * s)
199 {
200   app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
201   session_handle_t sh = session_handle (s);
202
203   mq_send_session_close_evt (app_wrk, sh, SESSION_CTRL_EVT_RESET);
204
205   if (svm_fifo_n_subscribers (s->rx_fifo))
206     mq_notify_close_subscribers (app_wrk->app_index, sh, s->rx_fifo,
207                                  SESSION_CTRL_EVT_RESET);
208 }
209
210 int
211 mq_send_session_connected_cb (u32 app_wrk_index, u32 api_context,
212                               session_t * s, session_error_t err)
213 {
214   session_connected_msg_t m = { 0 };
215   fifo_segment_t *eq_seg;
216   app_worker_t *app_wrk;
217   application_t *app;
218
219   app_wrk = app_worker_get (app_wrk_index);
220
221   m.context = api_context;
222   m.retval = err;
223
224   if (err)
225     goto snd_msg;
226
227   app = application_get (app_wrk->app_index);
228   eq_seg = application_get_rx_mqs_segment (app);
229
230   if (session_has_transport (s))
231     {
232       m.handle = session_handle (s);
233       m.vpp_event_queue_address =
234         fifo_segment_msg_q_offset (eq_seg, s->thread_index);
235
236       session_get_endpoint (s, &m.lcl, 1 /* is_lcl */);
237
238       m.server_rx_fifo = fifo_segment_fifo_offset (s->rx_fifo);
239       m.server_tx_fifo = fifo_segment_fifo_offset (s->tx_fifo);
240       m.segment_handle = session_segment_handle (s);
241       m.mq_index = s->thread_index;
242     }
243   else
244     {
245       ct_connection_t *cct;
246
247       cct = (ct_connection_t *) session_get_transport (s);
248       m.handle = session_handle (s);
249       m.lcl.port = cct->c_lcl_port;
250       m.lcl.is_ip4 = cct->c_is_ip4;
251       m.vpp_event_queue_address =
252         fifo_segment_msg_q_offset (eq_seg, s->thread_index);
253       m.server_rx_fifo = fifo_segment_fifo_offset (s->rx_fifo);
254       m.server_tx_fifo = fifo_segment_fifo_offset (s->tx_fifo);
255       m.segment_handle = session_segment_handle (s);
256       m.mq_index = s->thread_index;
257       m.ct_rx_fifo = fifo_segment_fifo_offset (cct->client_rx_fifo);
258       m.ct_tx_fifo = fifo_segment_fifo_offset (cct->client_tx_fifo);
259       m.ct_segment_handle = cct->segment_handle;
260     }
261
262   /* Setup client session index in advance, in case data arrives
263    * before the app processes message and updates it */
264   s->rx_fifo->shr->client_session_index = api_context;
265   s->tx_fifo->shr->client_session_index = api_context;
266
267 snd_msg:
268
269   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_CONNECTED, &m, sizeof (m));
270
271   return 0;
272 }
273
274 static int
275 mq_send_session_bound_cb (u32 app_wrk_index, u32 api_context,
276                           session_handle_t handle, int rv)
277 {
278   session_bound_msg_t m = { 0 };
279   transport_connection_t *ltc;
280   fifo_segment_t *eq_seg;
281   app_worker_t *app_wrk;
282   application_t *app;
283   app_listener_t *al;
284   session_t *ls = 0;
285
286   app_wrk = app_worker_get (app_wrk_index);
287
288   m.context = api_context;
289   m.retval = rv;
290
291   if (rv)
292     goto snd_msg;
293
294   m.handle = handle;
295   al = app_listener_get_w_handle (handle);
296   if (al->session_index != SESSION_INVALID_INDEX)
297     ls = app_listener_get_session (al);
298   else
299     ls = app_listener_get_local_session (al);
300
301   ltc = session_get_transport (ls);
302   m.lcl_port = ltc->lcl_port;
303   m.lcl_is_ip4 = ltc->is_ip4;
304   clib_memcpy_fast (m.lcl_ip, &ltc->lcl_ip, sizeof (m.lcl_ip));
305   app = application_get (app_wrk->app_index);
306   eq_seg = application_get_rx_mqs_segment (app);
307   m.vpp_evt_q = fifo_segment_msg_q_offset (eq_seg, ls->thread_index);
308   m.mq_index = ls->thread_index;
309
310   if (transport_connection_is_cless (ltc))
311     {
312       session_t *wrk_ls;
313       m.mq_index = transport_cl_thread ();
314       m.vpp_evt_q = fifo_segment_msg_q_offset (eq_seg, m.mq_index);
315       wrk_ls = app_listener_get_wrk_cl_session (al, app_wrk->wrk_map_index);
316       m.rx_fifo = fifo_segment_fifo_offset (wrk_ls->rx_fifo);
317       m.tx_fifo = fifo_segment_fifo_offset (wrk_ls->tx_fifo);
318       m.segment_handle = session_segment_handle (wrk_ls);
319     }
320
321 snd_msg:
322
323   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_BOUND, &m, sizeof (m));
324
325   return 0;
326 }
327
328 static void
329 mq_send_unlisten_cb (u32 app_wrk_index, session_handle_t sh, u32 context,
330                      int rv)
331 {
332   session_unlisten_reply_msg_t m = { 0 };
333   app_worker_t *app_wrk;
334
335   app_wrk = app_worker_get (app_wrk_index);
336
337   m.context = context;
338   m.handle = sh;
339   m.retval = rv;
340   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_UNLISTEN_REPLY, &m,
341                          sizeof (m));
342 }
343
344 static void
345 mq_send_session_migrate_cb (session_t * s, session_handle_t new_sh)
346 {
347   session_migrated_msg_t m = { 0 };
348   fifo_segment_t *eq_seg;
349   app_worker_t *app_wrk;
350   application_t *app;
351   u32 thread_index;
352
353   thread_index = session_thread_from_handle (new_sh);
354   app_wrk = app_worker_get (s->app_wrk_index);
355   app = application_get (app_wrk->app_index);
356   eq_seg = application_get_rx_mqs_segment (app);
357
358   m.handle = session_handle (s);
359   m.new_handle = new_sh;
360   m.vpp_thread_index = thread_index;
361   m.vpp_evt_q = fifo_segment_msg_q_offset (eq_seg, thread_index);
362   m.segment_handle = SESSION_INVALID_HANDLE;
363
364   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_MIGRATED, &m, sizeof (m));
365 }
366
367 static int
368 mq_send_add_segment_cb (u32 app_wrk_index, u64 segment_handle)
369 {
370   session_app_add_segment_msg_t m = { 0 };
371   vl_api_registration_t *reg;
372   app_worker_t *app_wrk;
373   fifo_segment_t *fs;
374   ssvm_private_t *sp;
375   u8 fd_flags = 0;
376
377   app_wrk = app_worker_get (app_wrk_index);
378
379   reg = vl_mem_api_client_index_to_registration (app_wrk->api_client_index);
380   if (!reg)
381     {
382       clib_warning ("no api registration for client: %u",
383                     app_wrk->api_client_index);
384       return -1;
385     }
386
387   fs = segment_manager_get_segment_w_handle (segment_handle);
388   sp = &fs->ssvm;
389   if (ssvm_type (sp) == SSVM_SEGMENT_MEMFD)
390     {
391       if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
392         {
393           clib_warning ("can't send memfd fd");
394           return -1;
395         }
396
397       fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
398     }
399
400   m.segment_size = sp->ssvm_size;
401   m.fd_flags = fd_flags;
402   m.segment_handle = segment_handle;
403   strncpy ((char *) m.segment_name, (char *) sp->name,
404            sizeof (m.segment_name) - 1);
405
406   app_wrk_send_ctrl_evt_fd (app_wrk, SESSION_CTRL_EVT_APP_ADD_SEGMENT, &m,
407                             sizeof (m), sp->fd);
408
409   return 0;
410 }
411
412 static int
413 mq_send_del_segment_cb (u32 app_wrk_index, u64 segment_handle)
414 {
415   session_app_del_segment_msg_t m = { 0 };
416   vl_api_registration_t *reg;
417   app_worker_t *app_wrk;
418
419   app_wrk = app_worker_get (app_wrk_index);
420   reg = vl_mem_api_client_index_to_registration (app_wrk->api_client_index);
421   if (!reg)
422     {
423       clib_warning ("no registration: %u", app_wrk->api_client_index);
424       return -1;
425     }
426
427   m.segment_handle = segment_handle;
428
429   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_APP_DEL_SEGMENT, &m,
430                          sizeof (m));
431
432   return 0;
433 }
434
435 static void
436 mq_send_session_cleanup_cb (session_t * s, session_cleanup_ntf_t ntf)
437 {
438   session_cleanup_msg_t m = { 0 };
439   app_worker_t *app_wrk;
440
441   /* Propagate transport cleanup notifications only if app didn't close */
442   if (ntf == SESSION_CLEANUP_TRANSPORT
443       && s->session_state != SESSION_STATE_TRANSPORT_DELETED)
444     return;
445
446   app_wrk = app_worker_get_if_valid (s->app_wrk_index);
447   if (!app_wrk)
448     return;
449
450   m.handle = session_handle (s);
451   m.type = ntf;
452
453   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_CLEANUP, &m, sizeof (m));
454 }
455
456 static int
457 mq_send_io_rx_event (session_t *s)
458 {
459   session_event_t *mq_evt;
460   svm_msg_q_msg_t mq_msg;
461   app_worker_t *app_wrk;
462   svm_msg_q_t *mq;
463
464   if (svm_fifo_has_event (s->rx_fifo))
465     return 0;
466
467   app_wrk = app_worker_get (s->app_wrk_index);
468   mq = app_wrk->event_queue;
469
470   mq_msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
471   mq_evt = svm_msg_q_msg_data (mq, &mq_msg);
472
473   mq_evt->event_type = SESSION_IO_EVT_RX;
474   mq_evt->session_index = s->rx_fifo->shr->client_session_index;
475
476   (void) svm_fifo_set_event (s->rx_fifo);
477
478   svm_msg_q_add_raw (mq, &mq_msg);
479
480   return 0;
481 }
482
483 static int
484 mq_send_io_tx_event (session_t *s)
485 {
486   app_worker_t *app_wrk = app_worker_get (s->app_wrk_index);
487   svm_msg_q_t *mq = app_wrk->event_queue;
488   session_event_t *mq_evt;
489   svm_msg_q_msg_t mq_msg;
490
491   mq_msg = svm_msg_q_alloc_msg_w_ring (mq, SESSION_MQ_IO_EVT_RING);
492   mq_evt = svm_msg_q_msg_data (mq, &mq_msg);
493
494   mq_evt->event_type = SESSION_IO_EVT_TX;
495   mq_evt->session_index = s->tx_fifo->shr->client_session_index;
496
497   svm_msg_q_add_raw (mq, &mq_msg);
498
499   return 0;
500 }
501
502 static session_cb_vft_t session_mq_cb_vft = {
503   .session_accept_callback = mq_send_session_accepted_cb,
504   .session_disconnect_callback = mq_send_session_disconnected_cb,
505   .session_connected_callback = mq_send_session_connected_cb,
506   .session_reset_callback = mq_send_session_reset_cb,
507   .session_migrate_callback = mq_send_session_migrate_cb,
508   .session_cleanup_callback = mq_send_session_cleanup_cb,
509   .session_listened_callback = mq_send_session_bound_cb,
510   .session_unlistened_callback = mq_send_unlisten_cb,
511   .add_segment_callback = mq_send_add_segment_cb,
512   .del_segment_callback = mq_send_del_segment_cb,
513   .builtin_app_rx_callback = mq_send_io_rx_event,
514   .builtin_app_tx_callback = mq_send_io_tx_event,
515 };
516
517 static void
518 vl_api_session_enable_disable_t_handler (vl_api_session_enable_disable_t * mp)
519 {
520   vl_api_session_enable_disable_reply_t *rmp;
521   vlib_main_t *vm = vlib_get_main ();
522   int rv = 0;
523
524   vnet_session_enable_disable (vm, mp->is_enable);
525   REPLY_MACRO (VL_API_SESSION_ENABLE_DISABLE_REPLY);
526 }
527
528 static void
529 vl_api_session_sapi_enable_disable_t_handler (
530   vl_api_session_sapi_enable_disable_t *mp)
531 {
532   vl_api_session_sapi_enable_disable_reply_t *rmp;
533   int rv = 0;
534
535   rv = appns_sapi_enable_disable (mp->is_enable);
536   REPLY_MACRO (VL_API_SESSION_SAPI_ENABLE_DISABLE_REPLY);
537 }
538
539 static void
540 vl_api_app_attach_t_handler (vl_api_app_attach_t * mp)
541 {
542   int rv = 0, *fds = 0, n_fds = 0, n_workers, i;
543   fifo_segment_t *segp, *rx_mqs_seg = 0;
544   vnet_app_attach_args_t _a, *a = &_a;
545   vl_api_app_attach_reply_t *rmp;
546   u8 fd_flags = 0, ctrl_thread;
547   vl_api_registration_t *reg;
548   svm_msg_q_t *rx_mq;
549   application_t *app;
550
551   reg = vl_api_client_index_to_registration (mp->client_index);
552   if (!reg)
553     return;
554
555   n_workers = vlib_num_workers ();
556   if (!session_main_is_enabled () || appns_sapi_enabled ())
557     {
558       rv = VNET_API_ERROR_FEATURE_DISABLED;
559       goto done;
560     }
561   /* Only support binary api with socket transport */
562   if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
563     {
564       rv = VNET_API_ERROR_APP_UNSUPPORTED_CFG;
565       goto done;
566     }
567
568   STATIC_ASSERT (sizeof (u64) * APP_OPTIONS_N_OPTIONS <=
569                  sizeof (mp->options),
570                  "Out of options, fix api message definition");
571
572   clib_memset (a, 0, sizeof (*a));
573   a->api_client_index = mp->client_index;
574   a->options = mp->options;
575   a->session_cb_vft = &session_mq_cb_vft;
576   a->namespace_id = vl_api_from_api_to_new_vec (mp, &mp->namespace_id);
577
578   if ((rv = vnet_application_attach (a)))
579     {
580       clib_warning ("attach returned: %U", format_session_error, rv);
581       rv = VNET_API_ERROR_UNSPECIFIED;
582       vec_free (a->namespace_id);
583       goto done;
584     }
585   vec_free (a->namespace_id);
586
587   vec_validate (fds, 3 /* segs + tx evtfd */ + n_workers);
588
589   /* Send rx mqs segment */
590   app = application_get (a->app_index);
591   rx_mqs_seg = application_get_rx_mqs_segment (app);
592
593   fd_flags |= SESSION_FD_F_VPP_MQ_SEGMENT;
594   fds[n_fds] = rx_mqs_seg->ssvm.fd;
595   n_fds += 1;
596
597   /* Send fifo segment fd if needed */
598   if (ssvm_type (a->segment) == SSVM_SEGMENT_MEMFD)
599     {
600       fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
601       fds[n_fds] = a->segment->fd;
602       n_fds += 1;
603     }
604   if (a->options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD)
605     {
606       fd_flags |= SESSION_FD_F_MQ_EVENTFD;
607       fds[n_fds] = svm_msg_q_get_eventfd (a->app_evt_q);
608       n_fds += 1;
609     }
610
611   if (application_use_private_rx_mqs ())
612     {
613       fd_flags |= SESSION_FD_F_VPP_MQ_EVENTFD;
614       for (i = 0; i < n_workers + 1; i++)
615         {
616           rx_mq = application_rx_mq_get (app, i);
617           fds[n_fds] = svm_msg_q_get_eventfd (rx_mq);
618           n_fds += 1;
619         }
620     }
621
622 done:
623   REPLY_MACRO3 (
624     VL_API_APP_ATTACH_REPLY,
625     ((!rv) ? vec_len (((fifo_segment_t *) a->segment)->ssvm.name) : 0), ({
626       if (!rv)
627         {
628           ctrl_thread = n_workers ? 1 : 0;
629           segp = (fifo_segment_t *) a->segment;
630           rmp->app_index = clib_host_to_net_u32 (a->app_index);
631           rmp->app_mq = fifo_segment_msg_q_offset (segp, 0);
632           rmp->vpp_ctrl_mq =
633             fifo_segment_msg_q_offset (rx_mqs_seg, ctrl_thread);
634           rmp->vpp_ctrl_mq_thread = ctrl_thread;
635           rmp->n_fds = n_fds;
636           rmp->fd_flags = fd_flags;
637           if (vec_len (segp->ssvm.name))
638             {
639               vl_api_vec_to_api_string (segp->ssvm.name, &rmp->segment_name);
640             }
641           rmp->segment_size = segp->ssvm.ssvm_size;
642           rmp->segment_handle = clib_host_to_net_u64 (a->segment_handle);
643         }
644     }));
645
646   if (n_fds)
647     session_send_fds (reg, fds, n_fds);
648   vec_free (fds);
649 }
650
651 static void
652 vl_api_app_worker_add_del_t_handler (vl_api_app_worker_add_del_t * mp)
653 {
654   int rv = 0, fds[SESSION_N_FD_TYPE], n_fds = 0;
655   vl_api_app_worker_add_del_reply_t *rmp;
656   vl_api_registration_t *reg;
657   application_t *app;
658   u8 fd_flags = 0;
659
660   if (!session_main_is_enabled () || appns_sapi_enabled ())
661     {
662       rv = VNET_API_ERROR_FEATURE_DISABLED;
663       goto done;
664     }
665
666   reg = vl_api_client_index_to_registration (mp->client_index);
667   if (!reg)
668     return;
669
670   app = application_get_if_valid (clib_net_to_host_u32 (mp->app_index));
671   if (!app)
672     {
673       rv = VNET_API_ERROR_INVALID_VALUE;
674       goto done;
675     }
676
677   vnet_app_worker_add_del_args_t args = {
678     .app_index = app->app_index,
679     .wrk_map_index = clib_net_to_host_u32 (mp->wrk_index),
680     .api_client_index = mp->client_index,
681     .is_add = mp->is_add
682   };
683   rv = vnet_app_worker_add_del (&args);
684   if (rv)
685     {
686       clib_warning ("app worker add/del returned: %U", format_session_error,
687                     rv);
688       rv = VNET_API_ERROR_UNSPECIFIED;
689       goto done;
690     }
691
692   if (!mp->is_add)
693     goto done;
694
695   /* Send fifo segment fd if needed */
696   if (ssvm_type (args.segment) == SSVM_SEGMENT_MEMFD)
697     {
698       fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
699       fds[n_fds] = args.segment->fd;
700       n_fds += 1;
701     }
702   if (application_segment_manager_properties (app)->use_mq_eventfd)
703     {
704       fd_flags |= SESSION_FD_F_MQ_EVENTFD;
705       fds[n_fds] = svm_msg_q_get_eventfd (args.evt_q);
706       n_fds += 1;
707     }
708
709 done:
710   REPLY_MACRO3 (
711     VL_API_APP_WORKER_ADD_DEL_REPLY,
712     ((!rv && mp->is_add) ? vec_len (args.segment->name) : 0), ({
713       rmp->is_add = mp->is_add;
714       rmp->wrk_index = clib_host_to_net_u32 (args.wrk_map_index);
715       if (!rv && mp->is_add)
716         {
717           rmp->segment_handle = clib_host_to_net_u64 (args.segment_handle);
718           rmp->app_event_queue_address =
719             fifo_segment_msg_q_offset ((fifo_segment_t *) args.segment, 0);
720           rmp->n_fds = n_fds;
721           rmp->fd_flags = fd_flags;
722           if (vec_len (args.segment->name))
723             {
724               vl_api_vec_to_api_string (args.segment->name,
725                                         &rmp->segment_name);
726             }
727         }
728     }));
729
730   if (n_fds)
731     session_send_fds (reg, fds, n_fds);
732 }
733
734 static void
735 vl_api_application_detach_t_handler (vl_api_application_detach_t * mp)
736 {
737   vl_api_application_detach_reply_t *rmp;
738   int rv = VNET_API_ERROR_INVALID_VALUE_2;
739   vnet_app_detach_args_t _a, *a = &_a;
740   application_t *app;
741
742   if (!session_main_is_enabled () || appns_sapi_enabled ())
743     {
744       rv = VNET_API_ERROR_FEATURE_DISABLED;
745       goto done;
746     }
747
748   app = application_lookup (mp->client_index);
749   if (app)
750     {
751       a->app_index = app->app_index;
752       a->api_client_index = mp->client_index;
753       rv = vnet_application_detach (a);
754       if (rv)
755         {
756           clib_warning ("vnet_application_detach: %U", format_session_error,
757                         rv);
758           rv = VNET_API_ERROR_UNSPECIFIED;
759         }
760     }
761
762 done:
763   REPLY_MACRO (VL_API_APPLICATION_DETACH_REPLY);
764 }
765
766 static void
767 vl_api_app_namespace_add_del_t_handler (vl_api_app_namespace_add_del_t * mp)
768 {
769   vl_api_app_namespace_add_del_reply_t *rmp;
770   u32 appns_index = 0;
771   u8 *ns_id = 0;
772   int rv = 0;
773   if (session_main_is_enabled () == 0)
774     {
775       rv = VNET_API_ERROR_FEATURE_DISABLED;
776       goto done;
777     }
778
779   ns_id = vl_api_from_api_to_new_vec (mp, &mp->namespace_id);
780
781   vnet_app_namespace_add_del_args_t args = {
782     .ns_id = ns_id,
783     .sock_name = 0,
784     .secret = clib_net_to_host_u64 (mp->secret),
785     .sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
786     .ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
787     .ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
788     .is_add = 1
789   };
790   rv = vnet_app_namespace_add_del (&args);
791   if (!rv)
792     {
793       appns_index = app_namespace_index_from_id (ns_id);
794       if (appns_index == APP_NAMESPACE_INVALID_INDEX)
795         {
796           clib_warning ("app ns lookup failed");
797           rv = VNET_API_ERROR_UNSPECIFIED;
798         }
799     }
800   vec_free (ns_id);
801
802 done:
803   REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_REPLY, ({
804     if (!rv)
805       rmp->appns_index = clib_host_to_net_u32 (appns_index);
806   }));
807 }
808
809 static void
810 vl_api_app_namespace_add_del_v2_t_handler (
811   vl_api_app_namespace_add_del_v2_t *mp)
812 {
813   vl_api_app_namespace_add_del_v2_reply_t *rmp;
814   u8 *ns_id = 0;
815   u32 appns_index = 0;
816   int rv = 0;
817
818   if (session_main_is_enabled () == 0)
819     {
820       rv = VNET_API_ERROR_FEATURE_DISABLED;
821       goto done;
822     }
823
824   mp->namespace_id[sizeof (mp->namespace_id) - 1] = 0;
825   ns_id = format (0, "%s", &mp->namespace_id);
826
827   vnet_app_namespace_add_del_args_t args = {
828     .ns_id = ns_id,
829     .sock_name = 0,
830     .secret = clib_net_to_host_u64 (mp->secret),
831     .sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
832     .ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
833     .ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
834     .is_add = 1
835   };
836   rv = vnet_app_namespace_add_del (&args);
837   if (!rv)
838     {
839       appns_index = app_namespace_index_from_id (ns_id);
840       if (appns_index == APP_NAMESPACE_INVALID_INDEX)
841         {
842           clib_warning ("app ns lookup failed id:%s", ns_id);
843           rv = VNET_API_ERROR_UNSPECIFIED;
844         }
845     }
846   vec_free (ns_id);
847
848 done:
849   REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_V2_REPLY, ({
850                   if (!rv)
851                     rmp->appns_index = clib_host_to_net_u32 (appns_index);
852                 }));
853 }
854
855 static void
856 vl_api_app_namespace_add_del_v4_t_handler (
857   vl_api_app_namespace_add_del_v4_t *mp)
858 {
859   vl_api_app_namespace_add_del_v4_reply_t *rmp;
860   u8 *ns_id = 0, *sock_name = 0;
861   u32 appns_index = 0;
862   int rv = 0;
863   if (session_main_is_enabled () == 0)
864     {
865       rv = VNET_API_ERROR_FEATURE_DISABLED;
866       goto done;
867     }
868   mp->namespace_id[sizeof (mp->namespace_id) - 1] = 0;
869   ns_id = format (0, "%s", &mp->namespace_id);
870   sock_name = vl_api_from_api_to_new_vec (mp, &mp->sock_name);
871   vnet_app_namespace_add_del_args_t args = {
872     .ns_id = ns_id,
873     .sock_name = sock_name,
874     .secret = clib_net_to_host_u64 (mp->secret),
875     .sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
876     .ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
877     .ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
878     .is_add = mp->is_add,
879   };
880   rv = vnet_app_namespace_add_del (&args);
881   if (!rv && mp->is_add)
882     {
883       appns_index = app_namespace_index_from_id (ns_id);
884       if (appns_index == APP_NAMESPACE_INVALID_INDEX)
885         {
886           clib_warning ("app ns lookup failed id:%s", ns_id);
887           rv = VNET_API_ERROR_UNSPECIFIED;
888         }
889     }
890   vec_free (ns_id);
891   vec_free (sock_name);
892 done:
893   REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_V4_REPLY, ({
894                   if (!rv)
895                     rmp->appns_index = clib_host_to_net_u32 (appns_index);
896                 }));
897 }
898
899 static void
900 vl_api_app_namespace_add_del_v3_t_handler (
901   vl_api_app_namespace_add_del_v3_t *mp)
902 {
903   vl_api_app_namespace_add_del_v3_reply_t *rmp;
904   u8 *ns_id = 0, *sock_name = 0, *api_sock_name = 0;
905   u32 appns_index = 0;
906   int rv = 0;
907   if (session_main_is_enabled () == 0)
908     {
909       rv = VNET_API_ERROR_FEATURE_DISABLED;
910       goto done;
911     }
912   mp->namespace_id[sizeof (mp->namespace_id) - 1] = 0;
913   ns_id = format (0, "%s", &mp->namespace_id);
914   api_sock_name = vl_api_from_api_to_new_vec (mp, &mp->sock_name);
915   mp->netns[sizeof (mp->netns) - 1] = 0;
916   if (strlen ((char *) mp->netns) != 0)
917     {
918       sock_name =
919         format (0, "abstract:%v,netns_name=%s", api_sock_name, &mp->netns);
920     }
921   else
922     {
923       sock_name = api_sock_name;
924       api_sock_name = 0; // for vec_free
925     }
926
927   vnet_app_namespace_add_del_args_t args = {
928     .ns_id = ns_id,
929     .sock_name = sock_name,
930     .secret = clib_net_to_host_u64 (mp->secret),
931     .sw_if_index = clib_net_to_host_u32 (mp->sw_if_index),
932     .ip4_fib_id = clib_net_to_host_u32 (mp->ip4_fib_id),
933     .ip6_fib_id = clib_net_to_host_u32 (mp->ip6_fib_id),
934     .is_add = mp->is_add,
935   };
936   rv = vnet_app_namespace_add_del (&args);
937   if (!rv && mp->is_add)
938     {
939       appns_index = app_namespace_index_from_id (ns_id);
940       if (appns_index == APP_NAMESPACE_INVALID_INDEX)
941         {
942           clib_warning ("app ns lookup failed id:%s", ns_id);
943           rv = VNET_API_ERROR_UNSPECIFIED;
944         }
945     }
946   vec_free (ns_id);
947   vec_free (sock_name);
948   vec_free (api_sock_name);
949 done:
950   REPLY_MACRO2 (VL_API_APP_NAMESPACE_ADD_DEL_V3_REPLY, ({
951                   if (!rv)
952                     rmp->appns_index = clib_host_to_net_u32 (appns_index);
953                 }));
954 }
955
956 static void
957 vl_api_session_rule_add_del_t_handler (vl_api_session_rule_add_del_t * mp)
958 {
959   vl_api_session_rule_add_del_reply_t *rmp;
960   session_rule_add_del_args_t args;
961   session_rule_table_add_del_args_t *table_args = &args.table_args;
962   int rv = 0;
963
964   clib_memset (&args, 0, sizeof (args));
965
966   ip_prefix_decode (&mp->lcl, &table_args->lcl);
967   ip_prefix_decode (&mp->rmt, &table_args->rmt);
968
969   table_args->lcl_port = mp->lcl_port;
970   table_args->rmt_port = mp->rmt_port;
971   table_args->action_index = clib_net_to_host_u32 (mp->action_index);
972   table_args->is_add = mp->is_add;
973   mp->tag[sizeof (mp->tag) - 1] = 0;
974   table_args->tag = format (0, "%s", mp->tag);
975   args.appns_index = clib_net_to_host_u32 (mp->appns_index);
976   args.scope = mp->scope;
977   args.transport_proto =
978     api_session_transport_proto_decode (&mp->transport_proto) ==
979     TRANSPORT_PROTO_UDP ? 1 : 0;
980
981   rv = vnet_session_rule_add_del (&args);
982   if (rv)
983     {
984       clib_warning ("rule add del returned: %U", format_session_error, rv);
985       rv = VNET_API_ERROR_UNSPECIFIED;
986     }
987   vec_free (table_args->tag);
988   REPLY_MACRO (VL_API_SESSION_RULE_ADD_DEL_REPLY);
989 }
990
991 static void
992 send_session_rule_details4 (mma_rule_16_t * rule, u8 is_local,
993                             u8 transport_proto, u32 appns_index, u8 * tag,
994                             vl_api_registration_t * reg, u32 context)
995 {
996   vl_api_session_rules_details_t *rmp = 0;
997   session_mask_or_match_4_t *match =
998     (session_mask_or_match_4_t *) & rule->match;
999   session_mask_or_match_4_t *mask =
1000     (session_mask_or_match_4_t *) & rule->mask;
1001   fib_prefix_t lcl, rmt;
1002
1003   rmp = vl_msg_api_alloc (sizeof (*rmp));
1004   clib_memset (rmp, 0, sizeof (*rmp));
1005   rmp->_vl_msg_id = ntohs (REPLY_MSG_ID_BASE + VL_API_SESSION_RULES_DETAILS);
1006   rmp->context = context;
1007
1008   clib_memset (&lcl, 0, sizeof (lcl));
1009   clib_memset (&rmt, 0, sizeof (rmt));
1010   ip_set (&lcl.fp_addr, &match->lcl_ip, 1);
1011   ip_set (&rmt.fp_addr, &match->rmt_ip, 1);
1012   lcl.fp_len = ip4_mask_to_preflen (&mask->lcl_ip);
1013   rmt.fp_len = ip4_mask_to_preflen (&mask->rmt_ip);
1014
1015   ip_prefix_encode (&lcl, &rmp->lcl);
1016   ip_prefix_encode (&rmt, &rmp->rmt);
1017   rmp->lcl_port = match->lcl_port;
1018   rmp->rmt_port = match->rmt_port;
1019   rmp->action_index = clib_host_to_net_u32 (rule->action_index);
1020   rmp->scope =
1021     is_local ? SESSION_RULE_SCOPE_API_LOCAL : SESSION_RULE_SCOPE_API_GLOBAL;
1022   rmp->transport_proto = api_session_transport_proto_encode (transport_proto);
1023   rmp->appns_index = clib_host_to_net_u32 (appns_index);
1024   if (tag)
1025     {
1026       clib_memcpy_fast (rmp->tag, tag, vec_len (tag));
1027       rmp->tag[vec_len (tag)] = 0;
1028     }
1029
1030   vl_api_send_msg (reg, (u8 *) rmp);
1031 }
1032
1033 static void
1034 send_session_rule_details6 (mma_rule_40_t * rule, u8 is_local,
1035                             u8 transport_proto, u32 appns_index, u8 * tag,
1036                             vl_api_registration_t * reg, u32 context)
1037 {
1038   vl_api_session_rules_details_t *rmp = 0;
1039   session_mask_or_match_6_t *match =
1040     (session_mask_or_match_6_t *) & rule->match;
1041   session_mask_or_match_6_t *mask =
1042     (session_mask_or_match_6_t *) & rule->mask;
1043   fib_prefix_t lcl, rmt;
1044
1045   rmp = vl_msg_api_alloc (sizeof (*rmp));
1046   clib_memset (rmp, 0, sizeof (*rmp));
1047   rmp->_vl_msg_id = ntohs (REPLY_MSG_ID_BASE + VL_API_SESSION_RULES_DETAILS);
1048   rmp->context = context;
1049
1050   clib_memset (&lcl, 0, sizeof (lcl));
1051   clib_memset (&rmt, 0, sizeof (rmt));
1052   ip_set (&lcl.fp_addr, &match->lcl_ip, 0);
1053   ip_set (&rmt.fp_addr, &match->rmt_ip, 0);
1054   lcl.fp_len = ip6_mask_to_preflen (&mask->lcl_ip);
1055   rmt.fp_len = ip6_mask_to_preflen (&mask->rmt_ip);
1056
1057   ip_prefix_encode (&lcl, &rmp->lcl);
1058   ip_prefix_encode (&rmt, &rmp->rmt);
1059   rmp->lcl_port = match->lcl_port;
1060   rmp->rmt_port = match->rmt_port;
1061   rmp->action_index = clib_host_to_net_u32 (rule->action_index);
1062   rmp->scope =
1063     is_local ? SESSION_RULE_SCOPE_API_LOCAL : SESSION_RULE_SCOPE_API_GLOBAL;
1064   rmp->transport_proto = api_session_transport_proto_encode (transport_proto);
1065   rmp->appns_index = clib_host_to_net_u32 (appns_index);
1066   if (tag)
1067     {
1068       clib_memcpy_fast (rmp->tag, tag, vec_len (tag));
1069       rmp->tag[vec_len (tag)] = 0;
1070     }
1071
1072   vl_api_send_msg (reg, (u8 *) rmp);
1073 }
1074
1075 static void
1076 send_session_rules_table_details (session_rules_table_t * srt, u8 fib_proto,
1077                                   u8 tp, u8 is_local, u32 appns_index,
1078                                   vl_api_registration_t * reg, u32 context)
1079 {
1080   mma_rule_16_t *rule16;
1081   mma_rule_40_t *rule40;
1082   mma_rules_table_16_t *srt16;
1083   mma_rules_table_40_t *srt40;
1084   u32 ri;
1085
1086   if (is_local || fib_proto == FIB_PROTOCOL_IP4)
1087     {
1088       u8 *tag = 0;
1089       srt16 = &srt->session_rules_tables_16;
1090       pool_foreach (rule16, srt16->rules)  {
1091         ri = mma_rules_table_rule_index_16 (srt16, rule16);
1092         tag = session_rules_table_rule_tag (srt, ri, 1);
1093         send_session_rule_details4 (rule16, is_local, tp, appns_index, tag,
1094                                     reg, context);
1095       }
1096     }
1097   if (is_local || fib_proto == FIB_PROTOCOL_IP6)
1098     {
1099       u8 *tag = 0;
1100       srt40 = &srt->session_rules_tables_40;
1101       pool_foreach (rule40, srt40->rules)  {
1102         ri = mma_rules_table_rule_index_40 (srt40, rule40);
1103         tag = session_rules_table_rule_tag (srt, ri, 1);
1104         send_session_rule_details6 (rule40, is_local, tp, appns_index, tag,
1105                                     reg, context);
1106       }
1107     }
1108 }
1109
1110 static void
1111 vl_api_session_rules_dump_t_handler (vl_api_session_rules_dump_t * mp)
1112 {
1113   vl_api_registration_t *reg;
1114   session_table_t *st;
1115   u8 tp;
1116
1117   reg = vl_api_client_index_to_registration (mp->client_index);
1118   if (!reg)
1119     return;
1120
1121   session_table_foreach (st, ({
1122     for (tp = 0; tp < TRANSPORT_N_PROTOS; tp++)
1123       {
1124         send_session_rules_table_details (&st->session_rules[tp],
1125                                           st->active_fib_proto, tp,
1126                                           st->is_local, st->appns_index, reg,
1127                                           mp->context);
1128       }
1129   }));
1130 }
1131
1132 static void
1133 vl_api_app_add_cert_key_pair_t_handler (vl_api_app_add_cert_key_pair_t * mp)
1134 {
1135   vl_api_app_add_cert_key_pair_reply_t *rmp;
1136   vnet_app_add_cert_key_pair_args_t _a, *a = &_a;
1137   u32 certkey_len, key_len, cert_len;
1138   int rv = 0;
1139   if (session_main_is_enabled () == 0)
1140     {
1141       rv = VNET_API_ERROR_FEATURE_DISABLED;
1142       goto done;
1143     }
1144
1145   cert_len = clib_net_to_host_u16 (mp->cert_len);
1146   if (cert_len > 10000)
1147     {
1148       rv = VNET_API_ERROR_INVALID_VALUE;
1149       goto done;
1150     }
1151
1152   certkey_len = clib_net_to_host_u16 (mp->certkey_len);
1153   if (certkey_len < cert_len)
1154     {
1155       rv = VNET_API_ERROR_INVALID_VALUE;
1156       goto done;
1157     }
1158
1159   key_len = certkey_len - cert_len;
1160   if (key_len > 10000)
1161     {
1162       rv = VNET_API_ERROR_INVALID_VALUE;
1163       goto done;
1164     }
1165
1166   clib_memset (a, 0, sizeof (*a));
1167   a->cert = mp->certkey;
1168   a->key = mp->certkey + cert_len;
1169   a->cert_len = cert_len;
1170   a->key_len = key_len;
1171   rv = vnet_app_add_cert_key_pair (a);
1172
1173 done:
1174   REPLY_MACRO2 (VL_API_APP_ADD_CERT_KEY_PAIR_REPLY, ({
1175     if (!rv)
1176       rmp->index = clib_host_to_net_u32 (a->index);
1177   }));
1178 }
1179
1180 static void
1181 vl_api_app_del_cert_key_pair_t_handler (vl_api_app_del_cert_key_pair_t * mp)
1182 {
1183   vl_api_app_del_cert_key_pair_reply_t *rmp;
1184   u32 ckpair_index;
1185   int rv = 0;
1186   if (session_main_is_enabled () == 0)
1187     {
1188       rv = VNET_API_ERROR_FEATURE_DISABLED;
1189       goto done;
1190     }
1191   ckpair_index = clib_net_to_host_u32 (mp->index);
1192   rv = vnet_app_del_cert_key_pair (ckpair_index);
1193   if (rv)
1194     {
1195       clib_warning ("vnet_app_del_cert_key_pair: %U", format_session_error,
1196                     rv);
1197       rv = VNET_API_ERROR_UNSPECIFIED;
1198     }
1199
1200 done:
1201   REPLY_MACRO (VL_API_APP_DEL_CERT_KEY_PAIR_REPLY);
1202 }
1203
1204 static clib_error_t *
1205 application_reaper_cb (u32 client_index)
1206 {
1207   application_t *app = application_lookup (client_index);
1208   vnet_app_detach_args_t _a, *a = &_a;
1209   if (app)
1210     {
1211       a->app_index = app->app_index;
1212       a->api_client_index = client_index;
1213       vnet_application_detach (a);
1214     }
1215   return 0;
1216 }
1217
1218 VL_MSG_API_REAPER_FUNCTION (application_reaper_cb);
1219
1220 /*
1221  * Socket api functions
1222  */
1223
1224 static int
1225 mq_send_add_segment_sapi_cb (u32 app_wrk_index, u64 segment_handle)
1226 {
1227   session_app_add_segment_msg_t m = { 0 };
1228   app_worker_t *app_wrk;
1229   fifo_segment_t *fs;
1230   ssvm_private_t *sp;
1231   u8 fd_flags = 0;
1232
1233   app_wrk = app_worker_get (app_wrk_index);
1234
1235   fs = segment_manager_get_segment_w_handle (segment_handle);
1236   sp = &fs->ssvm;
1237   ASSERT (ssvm_type (sp) == SSVM_SEGMENT_MEMFD);
1238
1239   fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
1240
1241   m.segment_size = sp->ssvm_size;
1242   m.fd_flags = fd_flags;
1243   m.segment_handle = segment_handle;
1244   strncpy ((char *) m.segment_name, (char *) sp->name,
1245            sizeof (m.segment_name) - 1);
1246
1247   app_wrk_send_ctrl_evt_fd (app_wrk, SESSION_CTRL_EVT_APP_ADD_SEGMENT, &m,
1248                             sizeof (m), sp->fd);
1249
1250   return 0;
1251 }
1252
1253 static int
1254 mq_send_del_segment_sapi_cb (u32 app_wrk_index, u64 segment_handle)
1255 {
1256   session_app_del_segment_msg_t m = { 0 };
1257   app_worker_t *app_wrk;
1258
1259   app_wrk = app_worker_get (app_wrk_index);
1260
1261   m.segment_handle = segment_handle;
1262
1263   app_wrk_send_ctrl_evt (app_wrk, SESSION_CTRL_EVT_APP_DEL_SEGMENT, &m,
1264                          sizeof (m));
1265
1266   return 0;
1267 }
1268
1269 static session_cb_vft_t session_mq_sapi_cb_vft = {
1270   .session_accept_callback = mq_send_session_accepted_cb,
1271   .session_disconnect_callback = mq_send_session_disconnected_cb,
1272   .session_connected_callback = mq_send_session_connected_cb,
1273   .session_reset_callback = mq_send_session_reset_cb,
1274   .session_migrate_callback = mq_send_session_migrate_cb,
1275   .session_cleanup_callback = mq_send_session_cleanup_cb,
1276   .session_listened_callback = mq_send_session_bound_cb,
1277   .session_unlistened_callback = mq_send_unlisten_cb,
1278   .add_segment_callback = mq_send_add_segment_sapi_cb,
1279   .del_segment_callback = mq_send_del_segment_sapi_cb,
1280   .builtin_app_rx_callback = mq_send_io_rx_event,
1281   .builtin_app_tx_callback = mq_send_io_tx_event,
1282 };
1283
1284 static void
1285 session_api_attach_handler (app_namespace_t * app_ns, clib_socket_t * cs,
1286                             app_sapi_attach_msg_t * mp)
1287 {
1288   int rv = 0, *fds = 0, n_fds = 0, i, n_workers;
1289   vnet_app_attach_args_t _a, *a = &_a;
1290   app_sapi_attach_reply_msg_t *rmp;
1291   u8 fd_flags = 0, ctrl_thread;
1292   app_ns_api_handle_t *handle;
1293   fifo_segment_t *rx_mqs_seg;
1294   app_sapi_msg_t msg = { 0 };
1295   app_worker_t *app_wrk;
1296   application_t *app;
1297   svm_msg_q_t *rx_mq;
1298
1299   /* Make sure name is null terminated */
1300   mp->name[63] = 0;
1301
1302   clib_memset (a, 0, sizeof (*a));
1303   a->api_client_index = appns_sapi_socket_handle (app_ns, cs);
1304   a->name = format (0, "%s", (char *) mp->name);
1305   a->options = mp->options;
1306   a->session_cb_vft = &session_mq_sapi_cb_vft;
1307   a->use_sock_api = 1;
1308   a->options[APP_OPTIONS_NAMESPACE] = app_namespace_index (app_ns);
1309
1310   if ((rv = vnet_application_attach (a)))
1311     {
1312       clib_warning ("attach returned: %d", rv);
1313       goto done;
1314     }
1315
1316   n_workers = vlib_num_workers ();
1317   vec_validate (fds, 3 /* segs + tx evtfd */ + n_workers);
1318
1319   /* Send event queues segment */
1320   app = application_get (a->app_index);
1321   rx_mqs_seg = application_get_rx_mqs_segment (app);
1322
1323   fd_flags |= SESSION_FD_F_VPP_MQ_SEGMENT;
1324   fds[n_fds] = rx_mqs_seg->ssvm.fd;
1325   n_fds += 1;
1326
1327   /* Send fifo segment fd if needed */
1328   if (ssvm_type (a->segment) == SSVM_SEGMENT_MEMFD)
1329     {
1330       fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
1331       fds[n_fds] = a->segment->fd;
1332       n_fds += 1;
1333     }
1334   if (a->options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_EVT_MQ_USE_EVENTFD)
1335     {
1336       fd_flags |= SESSION_FD_F_MQ_EVENTFD;
1337       fds[n_fds] = svm_msg_q_get_eventfd (a->app_evt_q);
1338       n_fds += 1;
1339     }
1340
1341   if (application_use_private_rx_mqs ())
1342     {
1343       fd_flags |= SESSION_FD_F_VPP_MQ_EVENTFD;
1344       for (i = 0; i < n_workers + 1; i++)
1345         {
1346           rx_mq = application_rx_mq_get (app, i);
1347           fds[n_fds] = svm_msg_q_get_eventfd (rx_mq);
1348           n_fds += 1;
1349         }
1350     }
1351
1352 done:
1353
1354   msg.type = APP_SAPI_MSG_TYPE_ATTACH_REPLY;
1355   rmp = &msg.attach_reply;
1356   rmp->retval = rv;
1357   if (!rv)
1358     {
1359       ctrl_thread = n_workers ? 1 : 0;
1360       rmp->app_index = a->app_index;
1361       rmp->app_mq =
1362         fifo_segment_msg_q_offset ((fifo_segment_t *) a->segment, 0);
1363       rmp->vpp_ctrl_mq = fifo_segment_msg_q_offset (rx_mqs_seg, ctrl_thread);
1364       rmp->vpp_ctrl_mq_thread = ctrl_thread;
1365       rmp->n_fds = n_fds;
1366       rmp->fd_flags = fd_flags;
1367       /* No segment name and size since we only support memfds
1368        * in this configuration */
1369       rmp->segment_handle = a->segment_handle;
1370       rmp->api_client_handle = a->api_client_index;
1371
1372       /* Update app index for socket */
1373       handle = (app_ns_api_handle_t *) & cs->private_data;
1374       app_wrk = application_get_worker (app, 0);
1375       handle->aah_app_wrk_index = app_wrk->wrk_index;
1376     }
1377
1378   clib_socket_sendmsg (cs, &msg, sizeof (msg), fds, n_fds);
1379   vec_free (a->name);
1380   vec_free (fds);
1381 }
1382
1383 void
1384 sapi_socket_close_w_handle (u32 api_handle)
1385 {
1386   app_namespace_t *app_ns = app_namespace_get (api_handle >> 16);
1387   u16 sock_index = api_handle & 0xffff;
1388   app_ns_api_handle_t *handle;
1389   clib_socket_t *cs;
1390   clib_file_t *cf;
1391
1392   cs = appns_sapi_get_socket (app_ns, sock_index);
1393   if (!cs)
1394     return;
1395
1396   handle = (app_ns_api_handle_t *) & cs->private_data;
1397   cf = clib_file_get (&file_main, handle->aah_file_index);
1398   clib_file_del (&file_main, cf);
1399
1400   clib_socket_close (cs);
1401   appns_sapi_free_socket (app_ns, cs);
1402 }
1403
1404 static void
1405 sapi_add_del_worker_handler (app_namespace_t * app_ns,
1406                              clib_socket_t * cs,
1407                              app_sapi_worker_add_del_msg_t * mp)
1408 {
1409   int rv = 0, fds[SESSION_N_FD_TYPE], n_fds = 0;
1410   app_sapi_worker_add_del_reply_msg_t *rmp;
1411   app_ns_api_handle_t *handle;
1412   app_sapi_msg_t msg = { 0 };
1413   app_worker_t *app_wrk;
1414   u32 sapi_handle = -1;
1415   application_t *app;
1416   u8 fd_flags = 0;
1417
1418   app = application_get_if_valid (mp->app_index);
1419   if (!app)
1420     {
1421       rv = SESSION_E_INVALID;
1422       goto done;
1423     }
1424
1425   sapi_handle = appns_sapi_socket_handle (app_ns, cs);
1426
1427   vnet_app_worker_add_del_args_t args = {
1428     .app_index = app->app_index,
1429     .wrk_map_index = mp->wrk_index,
1430     .api_client_index = sapi_handle,
1431     .is_add = mp->is_add
1432   };
1433   rv = vnet_app_worker_add_del (&args);
1434   if (rv)
1435     {
1436       clib_warning ("app worker add/del returned: %U", format_session_error,
1437                     rv);
1438       goto done;
1439     }
1440
1441   if (!mp->is_add)
1442     goto done;
1443
1444   /* Send fifo segment fd if needed */
1445   if (ssvm_type (args.segment) == SSVM_SEGMENT_MEMFD)
1446     {
1447       fd_flags |= SESSION_FD_F_MEMFD_SEGMENT;
1448       fds[n_fds] = args.segment->fd;
1449       n_fds += 1;
1450     }
1451   if (application_segment_manager_properties (app)->use_mq_eventfd)
1452     {
1453       fd_flags |= SESSION_FD_F_MQ_EVENTFD;
1454       fds[n_fds] = svm_msg_q_get_eventfd (args.evt_q);
1455       n_fds += 1;
1456     }
1457
1458 done:
1459
1460   /* With app sock api socket expected to be closed, no reply */
1461   if (!mp->is_add && appns_sapi_enabled ())
1462     return;
1463
1464   msg.type = APP_SAPI_MSG_TYPE_ADD_DEL_WORKER_REPLY;
1465   rmp = &msg.worker_add_del_reply;
1466   rmp->retval = rv;
1467   rmp->is_add = mp->is_add;
1468   rmp->api_client_handle = sapi_handle;
1469   rmp->wrk_index = args.wrk_map_index;
1470   if (!rv && mp->is_add)
1471     {
1472       rmp->segment_handle = args.segment_handle;
1473       /* No segment name and size. This supports only memfds */
1474       rmp->app_event_queue_address =
1475         fifo_segment_msg_q_offset ((fifo_segment_t *) args.segment, 0);
1476       rmp->n_fds = n_fds;
1477       rmp->fd_flags = fd_flags;
1478
1479       /* Update app index for socket */
1480       handle = (app_ns_api_handle_t *) & cs->private_data;
1481       app_wrk = application_get_worker (app, args.wrk_map_index);
1482       handle->aah_app_wrk_index = app_wrk->wrk_index;
1483     }
1484
1485   clib_socket_sendmsg (cs, &msg, sizeof (msg), fds, n_fds);
1486 }
1487
1488 /* This is a workaround for the case when session layer starts reading
1489  * the socket before the client actualy sends the data
1490  */
1491 static clib_error_t *
1492 sapi_socket_receive_wait (clib_socket_t *cs, u8 *msg, u32 msg_len)
1493 {
1494   clib_error_t *err;
1495   int n_tries = 5;
1496
1497   while (1)
1498     {
1499       err = clib_socket_recvmsg (cs, msg, msg_len, 0, 0);
1500       if (!err)
1501         break;
1502
1503       if (!n_tries)
1504         return err;
1505
1506       n_tries--;
1507       usleep (1);
1508     }
1509
1510   return err;
1511 }
1512
1513 static void
1514 sapi_add_del_cert_key_handler (app_namespace_t *app_ns, clib_socket_t *cs,
1515                                app_sapi_cert_key_add_del_msg_t *mp)
1516 {
1517   vnet_app_add_cert_key_pair_args_t _a, *a = &_a;
1518   app_sapi_cert_key_add_del_reply_msg_t *rmp;
1519   app_sapi_msg_t msg = { 0 };
1520   int rv = 0;
1521
1522   if (mp->is_add)
1523     {
1524       const u32 max_certkey_len = 2e4, max_cert_len = 1e4, max_key_len = 1e4;
1525       clib_error_t *err;
1526       u8 *certkey = 0;
1527       u32 key_len;
1528
1529       if (mp->certkey_len > max_certkey_len)
1530         {
1531           rv = SESSION_E_INVALID;
1532           goto send_reply;
1533         }
1534
1535       vec_validate (certkey, mp->certkey_len - 1);
1536
1537       err = sapi_socket_receive_wait (cs, certkey, mp->certkey_len);
1538       if (err)
1539         {
1540           clib_error_report (err);
1541           rv = SESSION_E_INVALID;
1542           goto send_reply;
1543         }
1544
1545       if (mp->cert_len > max_cert_len)
1546         {
1547           rv = SESSION_E_INVALID;
1548           goto send_reply;
1549         }
1550
1551       if (mp->certkey_len < mp->cert_len)
1552         {
1553           rv = SESSION_E_INVALID;
1554           goto send_reply;
1555         }
1556
1557       key_len = mp->certkey_len - mp->cert_len;
1558       if (key_len > max_key_len)
1559         {
1560           rv = SESSION_E_INVALID;
1561           goto send_reply;
1562         }
1563
1564       clib_memset (a, 0, sizeof (*a));
1565       a->cert = certkey;
1566       a->key = certkey + mp->cert_len;
1567       a->cert_len = mp->cert_len;
1568       a->key_len = key_len;
1569       rv = vnet_app_add_cert_key_pair (a);
1570
1571       vec_free (certkey);
1572     }
1573   else
1574     {
1575       rv = vnet_app_del_cert_key_pair (mp->index);
1576     }
1577
1578 send_reply:
1579
1580   msg.type = APP_SAPI_MSG_TYPE_ADD_DEL_CERT_KEY_REPLY;
1581   rmp = &msg.cert_key_add_del_reply;
1582   rmp->retval = rv;
1583   rmp->context = mp->context;
1584   if (!rv && mp->is_add)
1585     rmp->index = a->index;
1586
1587   clib_socket_sendmsg (cs, &msg, sizeof (msg), 0, 0);
1588 }
1589
1590 static void
1591 sapi_socket_detach (app_namespace_t * app_ns, clib_socket_t * cs)
1592 {
1593   app_ns_api_handle_t *handle;
1594   app_worker_t *app_wrk;
1595   u32 api_client_handle;
1596
1597   api_client_handle = appns_sapi_socket_handle (app_ns, cs);
1598
1599   /* Cleanup everything because app worker closed socket or crashed */
1600   handle = (app_ns_api_handle_t *) & cs->private_data;
1601   app_wrk = app_worker_get_if_valid (handle->aah_app_wrk_index);
1602   if (!app_wrk)
1603     return;
1604
1605   vnet_app_worker_add_del_args_t args = {
1606     .app_index = app_wrk->app_index,
1607     .wrk_map_index = app_wrk->wrk_map_index,
1608     .api_client_index = api_client_handle,
1609     .is_add = 0
1610   };
1611   /* Send rpc to main thread for worker barrier */
1612   vlib_rpc_call_main_thread (vnet_app_worker_add_del, (u8 *) & args,
1613                              sizeof (args));
1614 }
1615
1616 static clib_error_t *
1617 sapi_sock_read_ready (clib_file_t * cf)
1618 {
1619   app_ns_api_handle_t *handle = (app_ns_api_handle_t *) & cf->private_data;
1620   vlib_main_t *vm = vlib_get_main ();
1621   app_sapi_msg_t msg = { 0 };
1622   app_namespace_t *app_ns;
1623   clib_error_t *err = 0;
1624   clib_socket_t *cs;
1625
1626   app_ns = app_namespace_get (handle->aah_app_ns_index);
1627   cs = appns_sapi_get_socket (app_ns, handle->aah_sock_index);
1628   if (!cs)
1629     goto error;
1630
1631   err = clib_socket_recvmsg (cs, &msg, sizeof (msg), 0, 0);
1632   if (err)
1633     {
1634       clib_error_free (err);
1635       sapi_socket_detach (app_ns, cs);
1636       goto error;
1637     }
1638
1639   handle = (app_ns_api_handle_t *) & cs->private_data;
1640
1641   vlib_worker_thread_barrier_sync (vm);
1642
1643   switch (msg.type)
1644     {
1645     case APP_SAPI_MSG_TYPE_ATTACH:
1646       session_api_attach_handler (app_ns, cs, &msg.attach);
1647       break;
1648     case APP_SAPI_MSG_TYPE_ADD_DEL_WORKER:
1649       sapi_add_del_worker_handler (app_ns, cs, &msg.worker_add_del);
1650       break;
1651     case APP_SAPI_MSG_TYPE_ADD_DEL_CERT_KEY:
1652       sapi_add_del_cert_key_handler (app_ns, cs, &msg.cert_key_add_del);
1653       break;
1654     default:
1655       clib_warning ("app wrk %u unknown message type: %u",
1656                     handle->aah_app_wrk_index, msg.type);
1657       break;
1658     }
1659
1660   vlib_worker_thread_barrier_release (vm);
1661
1662 error:
1663   return 0;
1664 }
1665
1666 static clib_error_t *
1667 sapi_sock_write_ready (clib_file_t * cf)
1668 {
1669   app_ns_api_handle_t *handle = (app_ns_api_handle_t *) & cf->private_data;
1670   clib_warning ("called for app ns %u", handle->aah_app_ns_index);
1671   return 0;
1672 }
1673
1674 static clib_error_t *
1675 sapi_sock_error (clib_file_t * cf)
1676 {
1677   app_ns_api_handle_t *handle = (app_ns_api_handle_t *) & cf->private_data;
1678   app_namespace_t *app_ns;
1679   clib_socket_t *cs;
1680
1681   app_ns = app_namespace_get (handle->aah_app_ns_index);
1682   cs = appns_sapi_get_socket (app_ns, handle->aah_sock_index);
1683   if (!cs)
1684     return 0;
1685
1686   sapi_socket_detach (app_ns, cs);
1687   return 0;
1688 }
1689
1690 static clib_error_t *
1691 sapi_sock_accept_ready (clib_file_t * scf)
1692 {
1693   app_ns_api_handle_t handle = *(app_ns_api_handle_t *) & scf->private_data;
1694   app_namespace_t *app_ns;
1695   clib_file_t cf = { 0 };
1696   clib_error_t *err = 0;
1697   clib_socket_t *ccs, *scs;
1698
1699   /* Listener files point to namespace */
1700   app_ns = app_namespace_get (handle.aah_app_ns_index);
1701
1702   /*
1703    * Initialize client socket
1704    */
1705   ccs = appns_sapi_alloc_socket (app_ns);
1706
1707   /* Grab server socket after client is initialized  */
1708   scs = appns_sapi_get_socket (app_ns, handle.aah_sock_index);
1709   if (!scs)
1710     goto error;
1711
1712   err = clib_socket_accept (scs, ccs);
1713   if (err)
1714     {
1715       clib_error_report (err);
1716       goto error;
1717     }
1718
1719   cf.read_function = sapi_sock_read_ready;
1720   cf.write_function = sapi_sock_write_ready;
1721   cf.error_function = sapi_sock_error;
1722   cf.file_descriptor = ccs->fd;
1723   /* File points to app namespace and socket */
1724   handle.aah_sock_index = appns_sapi_socket_index (app_ns, ccs);
1725   cf.private_data = handle.as_u64;
1726   cf.description = format (0, "app sock conn fd: %d", ccs->fd);
1727
1728   /* Poll until we get an attach message. Socket points to file and
1729    * application that owns the socket */
1730   handle.aah_app_wrk_index = APP_INVALID_INDEX;
1731   handle.aah_file_index = clib_file_add (&file_main, &cf);
1732   ccs->private_data = handle.as_u64;
1733
1734   return err;
1735
1736 error:
1737   appns_sapi_free_socket (app_ns, ccs);
1738   return err;
1739 }
1740
1741 void
1742 appns_sapi_del_ns_socket (app_namespace_t *app_ns)
1743 {
1744   app_ns_api_handle_t *handle;
1745   clib_socket_t *cs;
1746
1747   pool_foreach (cs, app_ns->app_sockets)
1748     {
1749       handle = (app_ns_api_handle_t *) &cs->private_data;
1750       clib_file_del_by_index (&file_main, handle->aah_file_index);
1751
1752       clib_socket_close (cs);
1753       clib_socket_free (cs);
1754     }
1755   pool_free (app_ns->app_sockets);
1756 }
1757
1758 int
1759 appns_sapi_add_ns_socket (app_namespace_t * app_ns)
1760 {
1761   char *subdir = "/app_ns_sockets/";
1762   app_ns_api_handle_t *handle;
1763   clib_file_t cf = { 0 };
1764   struct stat file_stat;
1765   clib_error_t *err;
1766   clib_socket_t *cs;
1767   char dir[4096];
1768
1769   snprintf (dir, sizeof (dir), "%s%s", vlib_unix_get_runtime_dir (), subdir);
1770
1771   if (!app_ns->sock_name)
1772     app_ns->sock_name = format (0, "%s%v%c", dir, app_ns->ns_id, 0);
1773
1774   /*
1775    * Create and initialize socket to listen on
1776    */
1777   cs = appns_sapi_alloc_socket (app_ns);
1778   cs->config = (char *) vec_dup (app_ns->sock_name);
1779   cs->flags = CLIB_SOCKET_F_IS_SERVER |
1780     CLIB_SOCKET_F_ALLOW_GROUP_WRITE |
1781     CLIB_SOCKET_F_SEQPACKET | CLIB_SOCKET_F_PASSCRED;
1782
1783   if (clib_socket_prefix_get_type (cs->config) == CLIB_SOCKET_TYPE_UNIX)
1784     {
1785       err = vlib_unix_recursive_mkdir ((char *) dir);
1786       if (err)
1787         {
1788           clib_error_report (err);
1789           return SESSION_E_SYSCALL;
1790         }
1791     }
1792
1793   if ((err = clib_socket_init (cs)))
1794     {
1795       clib_error_report (err);
1796       return -1;
1797     }
1798
1799   if (clib_socket_prefix_get_type (cs->config) == CLIB_SOCKET_TYPE_UNIX &&
1800       stat ((char *) app_ns->sock_name, &file_stat) == -1)
1801     return -1;
1802
1803   /*
1804    * Start polling it
1805    */
1806   cf.read_function = sapi_sock_accept_ready;
1807   cf.file_descriptor = cs->fd;
1808   /* File points to namespace */
1809   handle = (app_ns_api_handle_t *) & cf.private_data;
1810   handle->aah_app_ns_index = app_namespace_index (app_ns);
1811   handle->aah_sock_index = appns_sapi_socket_index (app_ns, cs);
1812   cf.description = format (0, "app sock listener: %s", app_ns->sock_name);
1813
1814   /* Socket points to clib file index */
1815   handle = (app_ns_api_handle_t *) & cs->private_data;
1816   handle->aah_file_index = clib_file_add (&file_main, &cf);
1817   handle->aah_app_wrk_index = APP_INVALID_INDEX;
1818
1819   return 0;
1820 }
1821
1822 #include <vnet/session/session.api.c>
1823 static clib_error_t *
1824 session_api_hookup (vlib_main_t *vm)
1825 {
1826   /*
1827    * Set up the (msg_name, crc, message-id) table
1828    */
1829   REPLY_MSG_ID_BASE = setup_message_id_table ();
1830
1831   return 0;
1832 }
1833
1834 VLIB_API_INIT_FUNCTION (session_api_hookup);
1835
1836 /*
1837  * fd.io coding-style-patch-verification: ON
1838  *
1839  * Local Variables:
1840  * eval: (c-set-style "gnu")
1841  * End:
1842  */