session: avoid session handle conflict with vcl
[vpp.git] / src / vnet / session / application.c
1 /*
2  * Copyright (c) 2017 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/session.h>
20
21 /**
22  * Pool from which we allocate all applications
23  */
24 static application_t *app_pool;
25
26 /**
27  * Hash table of apps by api client index
28  */
29 static uword *app_by_api_client_index;
30
31 static u8 *
32 app_get_name_from_reg_index (application_t * app)
33 {
34   u8 *app_name;
35
36   vl_api_registration_t *regp;
37   regp = vl_api_client_index_to_registration (app->api_client_index);
38   if (!regp)
39     app_name = format (0, "builtin-%d%c", app->index, 0);
40   else
41     app_name = format (0, "%s%c", regp->name, 0);
42
43   return app_name;
44 }
45
46 u32
47 application_session_table (application_t * app, u8 fib_proto)
48 {
49   app_namespace_t *app_ns;
50   app_ns = app_namespace_get (app->ns_index);
51   if (!application_has_global_scope (app))
52     return APP_INVALID_INDEX;
53   if (fib_proto == FIB_PROTOCOL_IP4)
54     return session_lookup_get_index_for_fib (fib_proto,
55                                              app_ns->ip4_fib_index);
56   else
57     return session_lookup_get_index_for_fib (fib_proto,
58                                              app_ns->ip6_fib_index);
59 }
60
61 u32
62 application_local_session_table (application_t * app)
63 {
64   app_namespace_t *app_ns;
65   if (!application_has_local_scope (app))
66     return APP_INVALID_INDEX;
67   app_ns = app_namespace_get (app->ns_index);
68   return app_ns->local_table_index;
69 }
70
71 int
72 application_api_queue_is_full (application_t * app)
73 {
74   svm_queue_t *q;
75
76   /* builtin servers are always OK */
77   if (app->api_client_index == ~0)
78     return 0;
79
80   q = vl_api_client_index_to_input_queue (app->api_client_index);
81   if (!q)
82     return 1;
83
84   if (q->cursize == q->maxsize)
85     return 1;
86   return 0;
87 }
88
89 /**
90  * Returns app name
91  *
92  * Since the name is not stored per app, we generate it on the fly. It is
93  * the caller's responsibility to free the vector
94  */
95 u8 *
96 application_name_from_index (u32 app_index)
97 {
98   application_t *app = application_get (app_index);
99   if (!app)
100     return 0;
101   return app_get_name_from_reg_index (app);
102 }
103
104 static void
105 application_table_add (application_t * app)
106 {
107   hash_set (app_by_api_client_index, app->api_client_index, app->index);
108 }
109
110 static void
111 application_table_del (application_t * app)
112 {
113   hash_unset (app_by_api_client_index, app->api_client_index);
114 }
115
116 application_t *
117 application_lookup (u32 api_client_index)
118 {
119   uword *p;
120   p = hash_get (app_by_api_client_index, api_client_index);
121   if (p)
122     return application_get (p[0]);
123
124   return 0;
125 }
126
127 application_t *
128 application_new ()
129 {
130   application_t *app;
131   pool_get (app_pool, app);
132   memset (app, 0, sizeof (*app));
133   app->index = application_get_index (app);
134   app->connects_seg_manager = APP_INVALID_SEGMENT_MANAGER_INDEX;
135   app->first_segment_manager = APP_INVALID_SEGMENT_MANAGER_INDEX;
136   app->local_segment_manager = APP_INVALID_SEGMENT_MANAGER_INDEX;
137   if (CLIB_DEBUG > 1)
138     clib_warning ("[%d] New app (%d)", getpid (), app->index);
139   return app;
140 }
141
142 void
143 application_del (application_t * app)
144 {
145   vnet_unbind_args_t _a, *a = &_a;
146   u64 handle, *handles = 0;
147   segment_manager_t *sm;
148   u32 index;
149   int i;
150
151   /*
152    * The app event queue allocated in first segment is cleared with
153    * the segment manager. No need to explicitly free it.
154    */
155   if (CLIB_DEBUG > 1)
156     clib_warning ("[%d] Delete app (%d)", getpid (), app->index);
157
158   if (application_is_proxy (app))
159     application_remove_proxy (app);
160
161   /*
162    *  Listener cleanup
163    */
164
165   /* *INDENT-OFF* */
166   hash_foreach (handle, index, app->listeners_table,
167   ({
168     vec_add1 (handles, handle);
169     sm = segment_manager_get (index);
170     sm->app_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
171   }));
172   /* *INDENT-ON* */
173
174   for (i = 0; i < vec_len (handles); i++)
175     {
176       a->app_index = app->index;
177       a->handle = handles[i];
178       /* seg manager is removed when unbind completes */
179       vnet_unbind (a);
180     }
181
182   /*
183    * Connects segment manager cleanup
184    */
185
186   if (app->connects_seg_manager != APP_INVALID_SEGMENT_MANAGER_INDEX)
187     {
188       sm = segment_manager_get (app->connects_seg_manager);
189       sm->app_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
190       segment_manager_init_del (sm);
191     }
192
193   /* If first segment manager is used by a listener */
194   if (app->first_segment_manager != APP_INVALID_SEGMENT_MANAGER_INDEX
195       && app->first_segment_manager != app->connects_seg_manager)
196     {
197       sm = segment_manager_get (app->first_segment_manager);
198       /* .. and has no fifos, e.g. it might be used for redirected sessions,
199        * remove it */
200       if (!segment_manager_has_fifos (sm))
201         {
202           sm->app_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
203           segment_manager_del (sm);
204         }
205     }
206
207   /*
208    * Local connections cleanup
209    */
210   application_local_sessions_del (app);
211
212   application_table_del (app);
213   pool_put (app_pool, app);
214 }
215
216 static void
217 application_verify_cb_fns (session_cb_vft_t * cb_fns)
218 {
219   if (cb_fns->session_accept_callback == 0)
220     clib_warning ("No accept callback function provided");
221   if (cb_fns->session_connected_callback == 0)
222     clib_warning ("No session connected callback function provided");
223   if (cb_fns->session_disconnect_callback == 0)
224     clib_warning ("No session disconnect callback function provided");
225   if (cb_fns->session_reset_callback == 0)
226     clib_warning ("No session reset callback function provided");
227 }
228
229 /**
230  * Check app config for given segment type
231  *
232  * Returns 1 on success and 0 otherwise
233  */
234 static u8
235 application_verify_cfg (ssvm_segment_type_t st)
236 {
237   u8 is_valid;
238   if (st == SSVM_SEGMENT_MEMFD)
239     {
240       is_valid = (session_manager_get_evt_q_segment () != 0);
241       if (!is_valid)
242         clib_warning ("memfd seg: vpp's event qs IN binary api svm region");
243       return is_valid;
244     }
245   else if (st == SSVM_SEGMENT_SHM)
246     {
247       is_valid = (session_manager_get_evt_q_segment () == 0);
248       if (!is_valid)
249         clib_warning ("shm seg: vpp's event qs NOT IN binary api svm region");
250       return is_valid;
251     }
252   else
253     return 1;
254 }
255
256 int
257 application_init (application_t * app, u32 api_client_index, u64 * options,
258                   session_cb_vft_t * cb_fns)
259 {
260   ssvm_segment_type_t seg_type = SSVM_SEGMENT_MEMFD;
261   u32 first_seg_size, prealloc_fifo_pairs;
262   segment_manager_properties_t *props;
263   vl_api_registration_t *reg;
264   segment_manager_t *sm;
265   int rv;
266
267   /*
268    * Make sure we support the requested configuration
269    */
270
271   if (!(options[APP_OPTIONS_FLAGS] & APP_OPTIONS_FLAGS_IS_BUILTIN))
272     {
273       reg = vl_api_client_index_to_registration (api_client_index);
274       if (!reg)
275         return VNET_API_ERROR_APP_UNSUPPORTED_CFG;
276       if (vl_api_registration_file_index (reg) == VL_API_INVALID_FI)
277         seg_type = SSVM_SEGMENT_SHM;
278     }
279   else
280     {
281       seg_type = SSVM_SEGMENT_PRIVATE;
282     }
283
284   if (!application_verify_cfg (seg_type))
285     return VNET_API_ERROR_APP_UNSUPPORTED_CFG;
286
287   /*
288    * Setup segment manager
289    */
290   sm = segment_manager_new ();
291   sm->app_index = app->index;
292   props = application_segment_manager_properties (app);
293   segment_manager_properties_init (props);
294   if (options[APP_OPTIONS_ADD_SEGMENT_SIZE])
295     {
296       props->add_segment_size = options[APP_OPTIONS_ADD_SEGMENT_SIZE];
297       props->add_segment = 1;
298     }
299   if (options[APP_OPTIONS_RX_FIFO_SIZE])
300     props->rx_fifo_size = options[APP_OPTIONS_RX_FIFO_SIZE];
301   if (options[APP_OPTIONS_TX_FIFO_SIZE])
302     props->tx_fifo_size = options[APP_OPTIONS_TX_FIFO_SIZE];
303   if (options[APP_OPTIONS_EVT_QUEUE_SIZE])
304     props->evt_q_size = options[APP_OPTIONS_EVT_QUEUE_SIZE];
305   props->segment_type = seg_type;
306
307   first_seg_size = options[APP_OPTIONS_SEGMENT_SIZE];
308   prealloc_fifo_pairs = options[APP_OPTIONS_PREALLOC_FIFO_PAIRS];
309
310   if ((rv = segment_manager_init (sm, first_seg_size, prealloc_fifo_pairs)))
311     return rv;
312   sm->first_is_protected = 1;
313
314   /*
315    * Setup application
316    */
317   app->first_segment_manager = segment_manager_index (sm);
318   app->api_client_index = api_client_index;
319   app->flags = options[APP_OPTIONS_FLAGS];
320   app->cb_fns = *cb_fns;
321   app->ns_index = options[APP_OPTIONS_NAMESPACE];
322   app->listeners_table = hash_create (0, sizeof (u64));
323   app->local_connects = hash_create (0, sizeof (u64));
324   app->proxied_transports = options[APP_OPTIONS_PROXY_TRANSPORT];
325   app->event_queue = segment_manager_event_queue (sm);
326
327   /* If no scope enabled, default to global */
328   if (!application_has_global_scope (app)
329       && !application_has_local_scope (app))
330     app->flags |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
331
332   /* Check that the obvious things are properly set up */
333   application_verify_cb_fns (cb_fns);
334
335   /* Add app to lookup by api_client_index table */
336   application_table_add (app);
337
338   /*
339    * Segment manager for local sessions
340    */
341   sm = segment_manager_new ();
342   sm->app_index = app->index;
343   app->local_segment_manager = segment_manager_index (sm);
344
345   return 0;
346 }
347
348 application_t *
349 application_get (u32 index)
350 {
351   if (index == APP_INVALID_INDEX)
352     return 0;
353   return pool_elt_at_index (app_pool, index);
354 }
355
356 application_t *
357 application_get_if_valid (u32 index)
358 {
359   if (pool_is_free_index (app_pool, index))
360     return 0;
361
362   return pool_elt_at_index (app_pool, index);
363 }
364
365 u32
366 application_get_index (application_t * app)
367 {
368   return app - app_pool;
369 }
370
371 static segment_manager_t *
372 application_alloc_segment_manager (application_t * app)
373 {
374   segment_manager_t *sm = 0;
375
376   /* If the first segment manager is not in use, don't allocate a new one */
377   if (app->first_segment_manager != APP_INVALID_SEGMENT_MANAGER_INDEX
378       && app->first_segment_manager_in_use == 0)
379     {
380       sm = segment_manager_get (app->first_segment_manager);
381       app->first_segment_manager_in_use = 1;
382       return sm;
383     }
384
385   sm = segment_manager_new ();
386   sm->app_index = app->index;
387
388   return sm;
389 }
390
391 /**
392  * Start listening local transport endpoint for requested transport.
393  *
394  * Creates a 'dummy' stream session with state LISTENING to be used in session
395  * lookups, prior to establishing connection. Requests transport to build
396  * it's own specific listening connection.
397  */
398 int
399 application_start_listen (application_t * srv, session_endpoint_t * sep,
400                           session_handle_t * res)
401 {
402   segment_manager_t *sm;
403   stream_session_t *s;
404   session_handle_t handle;
405   session_type_t sst;
406
407   sst = session_type_from_proto_and_ip (sep->transport_proto, sep->is_ip4);
408   s = listen_session_new (sst);
409   s->app_index = srv->index;
410
411   if (stream_session_listen (s, sep))
412     goto err;
413
414   /* Allocate segment manager. All sessions derived out of a listen session
415    * have fifos allocated by the same segment manager. */
416   sm = application_alloc_segment_manager (srv);
417   if (sm == 0)
418     goto err;
419
420   /* Add to app's listener table. Useful to find all child listeners
421    * when app goes down, although, just for unbinding this is not needed */
422   handle = listen_session_get_handle (s);
423   hash_set (srv->listeners_table, handle, segment_manager_index (sm));
424
425   *res = handle;
426   return 0;
427
428 err:
429   listen_session_del (s);
430   return -1;
431 }
432
433 /**
434  * Stop listening on session associated to handle
435  */
436 int
437 application_stop_listen (application_t * srv, session_handle_t handle)
438 {
439   stream_session_t *listener;
440   uword *indexp;
441   segment_manager_t *sm;
442
443   if (srv && hash_get (srv->listeners_table, handle) == 0)
444     {
445       clib_warning ("app doesn't own handle %llu!", handle);
446       return -1;
447     }
448
449   listener = listen_session_get_from_handle (handle);
450   stream_session_stop_listen (listener);
451
452   indexp = hash_get (srv->listeners_table, handle);
453   ASSERT (indexp);
454
455   sm = segment_manager_get (*indexp);
456   if (srv->first_segment_manager == *indexp)
457     {
458       /* Delete sessions but don't remove segment manager */
459       srv->first_segment_manager_in_use = 0;
460       segment_manager_del_sessions (sm);
461     }
462   else
463     {
464       segment_manager_init_del (sm);
465     }
466   hash_unset (srv->listeners_table, handle);
467   listen_session_del (listener);
468
469   return 0;
470 }
471
472 int
473 application_open_session (application_t * app, session_endpoint_t * sep,
474                           u32 api_context)
475 {
476   segment_manager_t *sm;
477   int rv;
478
479   /* Make sure we have a segment manager for connects */
480   if (app->connects_seg_manager == APP_INVALID_SEGMENT_MANAGER_INDEX)
481     {
482       sm = application_alloc_segment_manager (app);
483       if (sm == 0)
484         return -1;
485       app->connects_seg_manager = segment_manager_index (sm);
486     }
487
488   if ((rv = session_open (app->index, sep, api_context)))
489     return rv;
490
491   return 0;
492 }
493
494 segment_manager_t *
495 application_get_connect_segment_manager (application_t * app)
496 {
497   ASSERT (app->connects_seg_manager != (u32) ~ 0);
498   return segment_manager_get (app->connects_seg_manager);
499 }
500
501 segment_manager_t *
502 application_get_listen_segment_manager (application_t * app,
503                                         stream_session_t * s)
504 {
505   uword *smp;
506   smp = hash_get (app->listeners_table, listen_session_get_handle (s));
507   ASSERT (smp != 0);
508   return segment_manager_get (*smp);
509 }
510
511 segment_manager_t *
512 application_get_local_segment_manager (application_t * app)
513 {
514   return segment_manager_get (app->local_segment_manager);
515 }
516
517 segment_manager_t *
518 application_get_local_segment_manager_w_session (application_t * app,
519                                                  local_session_t * ls)
520 {
521   stream_session_t *listener;
522   if (application_local_session_listener_has_transport (ls))
523     {
524       listener = listen_session_get (ls->listener_session_type,
525                                      ls->listener_index);
526       return application_get_listen_segment_manager (app, listener);
527     }
528   return segment_manager_get (app->local_segment_manager);
529 }
530
531 int
532 application_is_proxy (application_t * app)
533 {
534   return (app->flags & APP_OPTIONS_FLAGS_IS_PROXY);
535 }
536
537 int
538 application_is_builtin (application_t * app)
539 {
540   return (app->flags & APP_OPTIONS_FLAGS_IS_BUILTIN);
541 }
542
543 int
544 application_is_builtin_proxy (application_t * app)
545 {
546   return (application_is_proxy (app) && application_is_builtin (app));
547 }
548
549 /**
550  * Send an API message to the external app, to map new segment
551  */
552 int
553 application_add_segment_notify (u32 app_index, ssvm_private_t * fs)
554 {
555   application_t *app = application_get (app_index);
556   return app->cb_fns.add_segment_callback (app->api_client_index, fs);
557 }
558
559 u8
560 application_has_local_scope (application_t * app)
561 {
562   return app->flags & APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
563 }
564
565 u8
566 application_has_global_scope (application_t * app)
567 {
568   return app->flags & APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
569 }
570
571 u32
572 application_n_listeners (application_t * app)
573 {
574   return hash_elts (app->listeners_table);
575 }
576
577 stream_session_t *
578 application_first_listener (application_t * app, u8 fib_proto,
579                             u8 transport_proto)
580 {
581   stream_session_t *listener;
582   u64 handle;
583   u32 sm_index;
584   u8 sst;
585
586   sst = session_type_from_proto_and_ip (transport_proto,
587                                         fib_proto == FIB_PROTOCOL_IP4);
588
589   /* *INDENT-OFF* */
590    hash_foreach (handle, sm_index, app->listeners_table, ({
591      listener = listen_session_get_from_handle (handle);
592      if (listener->session_type == sst
593          && listener->listener_index != SESSION_PROXY_LISTENER_INDEX)
594        return listener;
595    }));
596   /* *INDENT-ON* */
597
598   return 0;
599 }
600
601 stream_session_t *
602 application_proxy_listener (application_t * app, u8 fib_proto,
603                             u8 transport_proto)
604 {
605   stream_session_t *listener;
606   u64 handle;
607   u32 sm_index;
608   u8 sst;
609
610   sst = session_type_from_proto_and_ip (transport_proto,
611                                         fib_proto == FIB_PROTOCOL_IP4);
612
613   /* *INDENT-OFF* */
614    hash_foreach (handle, sm_index, app->listeners_table, ({
615      listener = listen_session_get_from_handle (handle);
616      if (listener->session_type == sst
617          && listener->listener_index == SESSION_PROXY_LISTENER_INDEX)
618        return listener;
619    }));
620   /* *INDENT-ON* */
621
622   return 0;
623 }
624
625 static clib_error_t *
626 application_start_stop_proxy_fib_proto (application_t * app, u8 fib_proto,
627                                         u8 transport_proto, u8 is_start)
628 {
629   app_namespace_t *app_ns = app_namespace_get (app->ns_index);
630   u8 is_ip4 = (fib_proto == FIB_PROTOCOL_IP4);
631   session_endpoint_t sep = SESSION_ENDPOINT_NULL;
632   transport_connection_t *tc;
633   stream_session_t *s;
634   u64 handle;
635
636   if (is_start)
637     {
638       s = application_first_listener (app, fib_proto, transport_proto);
639       if (!s)
640         {
641           sep.is_ip4 = is_ip4;
642           sep.fib_index = app_namespace_get_fib_index (app_ns, fib_proto);
643           sep.sw_if_index = app_ns->sw_if_index;
644           sep.transport_proto = transport_proto;
645           application_start_listen (app, &sep, &handle);
646           s = listen_session_get_from_handle (handle);
647           s->listener_index = SESSION_PROXY_LISTENER_INDEX;
648         }
649     }
650   else
651     {
652       s = application_proxy_listener (app, fib_proto, transport_proto);
653       ASSERT (s);
654     }
655
656   tc = listen_session_get_transport (s);
657
658   if (!ip_is_zero (&tc->lcl_ip, 1))
659     {
660       u32 sti;
661       sep.is_ip4 = is_ip4;
662       sep.fib_index = app_namespace_get_fib_index (app_ns, fib_proto);
663       sep.transport_proto = transport_proto;
664       sep.port = 0;
665       sti = session_lookup_get_index_for_fib (fib_proto, sep.fib_index);
666       if (is_start)
667         session_lookup_add_session_endpoint (sti, &sep, s->session_index);
668       else
669         session_lookup_del_session_endpoint (sti, &sep);
670     }
671
672   return 0;
673 }
674
675 static void
676 application_start_stop_proxy_local_scope (application_t * app,
677                                           u8 transport_proto, u8 is_start)
678 {
679   session_endpoint_t sep = SESSION_ENDPOINT_NULL;
680   app_namespace_t *app_ns;
681   app_ns = app_namespace_get (app->ns_index);
682   sep.is_ip4 = 1;
683   sep.transport_proto = transport_proto;
684   sep.port = 0;
685
686   if (is_start)
687     {
688       session_lookup_add_session_endpoint (app_ns->local_table_index, &sep,
689                                            app->index);
690       sep.is_ip4 = 0;
691       session_lookup_add_session_endpoint (app_ns->local_table_index, &sep,
692                                            app->index);
693     }
694   else
695     {
696       session_lookup_del_session_endpoint (app_ns->local_table_index, &sep);
697       sep.is_ip4 = 0;
698       session_lookup_del_session_endpoint (app_ns->local_table_index, &sep);
699     }
700 }
701
702 void
703 application_start_stop_proxy (application_t * app,
704                               transport_proto_t transport_proto, u8 is_start)
705 {
706   if (application_has_local_scope (app))
707     application_start_stop_proxy_local_scope (app, transport_proto, is_start);
708
709   if (application_has_global_scope (app))
710     {
711       application_start_stop_proxy_fib_proto (app, FIB_PROTOCOL_IP4,
712                                               transport_proto, is_start);
713       application_start_stop_proxy_fib_proto (app, FIB_PROTOCOL_IP6,
714                                               transport_proto, is_start);
715     }
716 }
717
718 void
719 application_setup_proxy (application_t * app)
720 {
721   u16 transports = app->proxied_transports;
722   transport_proto_t tp;
723
724   ASSERT (application_is_proxy (app));
725
726   /* *INDENT-OFF* */
727   transport_proto_foreach (tp, ({
728     if (transports & (1 << tp))
729       application_start_stop_proxy (app, tp, 1);
730   }));
731   /* *INDENT-ON* */
732 }
733
734 void
735 application_remove_proxy (application_t * app)
736 {
737   u16 transports = app->proxied_transports;
738   transport_proto_t tp;
739
740   ASSERT (application_is_proxy (app));
741
742   /* *INDENT-OFF* */
743   transport_proto_foreach (tp, ({
744     if (transports & (1 << tp))
745       application_start_stop_proxy (app, tp, 0);
746   }));
747   /* *INDENT-ON* */
748 }
749
750 segment_manager_properties_t *
751 application_segment_manager_properties (application_t * app)
752 {
753   return &app->sm_properties;
754 }
755
756 segment_manager_properties_t *
757 application_get_segment_manager_properties (u32 app_index)
758 {
759   application_t *app = application_get (app_index);
760   return &app->sm_properties;
761 }
762
763 local_session_t *
764 application_alloc_local_session (application_t * app)
765 {
766   local_session_t *s;
767   pool_get (app->local_sessions, s);
768   memset (s, 0, sizeof (*s));
769   s->app_index = app->index;
770   s->session_index = s - app->local_sessions;
771   s->session_type = session_type_from_proto_and_ip (TRANSPORT_PROTO_NONE, 0);
772   return s;
773 }
774
775 void
776 application_free_local_session (application_t * app, local_session_t * s)
777 {
778   pool_put (app->local_sessions, s);
779   if (CLIB_DEBUG)
780     memset (s, 0xfc, sizeof (*s));
781 }
782
783 local_session_t *
784 application_get_local_session (application_t * app, u32 session_index)
785 {
786   return pool_elt_at_index (app->local_sessions, session_index);
787 }
788
789 local_session_t *
790 application_get_local_session_from_handle (session_handle_t handle)
791 {
792   application_t *server;
793   u32 session_index, server_index;
794   local_session_parse_handle (handle, &server_index, &session_index);
795   server = application_get (server_index);
796   return application_get_local_session (server, session_index);
797 }
798
799 always_inline void
800 application_local_listener_session_endpoint (local_session_t * ll,
801                                              session_endpoint_t * sep)
802 {
803   sep->transport_proto =
804     session_type_transport_proto (ll->listener_session_type);
805   sep->port = ll->port;
806   sep->is_ip4 = ll->listener_session_type & 1;
807 }
808
809 int
810 application_start_local_listen (application_t * server,
811                                 session_endpoint_t * sep,
812                                 session_handle_t * handle)
813 {
814   session_handle_t lh;
815   local_session_t *ll;
816   u32 table_index;
817
818   table_index = application_local_session_table (server);
819
820   /* An exact sep match, as opposed to session_lookup_local_listener */
821   lh = session_lookup_endpoint_listener (table_index, sep, 1);
822   if (lh != SESSION_INVALID_HANDLE)
823     return VNET_API_ERROR_ADDRESS_IN_USE;
824
825   pool_get (server->local_listen_sessions, ll);
826   memset (ll, 0, sizeof (*ll));
827   ll->session_type = session_type_from_proto_and_ip (TRANSPORT_PROTO_NONE, 0);
828   ll->app_index = server->index;
829   ll->session_index = ll - server->local_listen_sessions;
830   ll->port = sep->port;
831   /* Store the original session type for the unbind */
832   ll->listener_session_type =
833     session_type_from_proto_and_ip (sep->transport_proto, sep->is_ip4);
834   ll->transport_listener_index = ~0;
835
836   *handle = application_local_session_handle (ll);
837   session_lookup_add_session_endpoint (table_index, sep, *handle);
838
839   return 0;
840 }
841
842 /**
843  * Clean up local session table. If we have a listener session use it to
844  * find the port and proto. If not, the handle must be a local table handle
845  * so parse it.
846  */
847 int
848 application_stop_local_listen (application_t * server, session_handle_t lh)
849 {
850   session_endpoint_t sep = SESSION_ENDPOINT_NULL;
851   u32 table_index, ll_index, server_index;
852   stream_session_t *sl = 0;
853   local_session_t *ll, *ls;
854
855   table_index = application_local_session_table (server);
856
857   /* We have both local and global table binds. Figure from global what
858    * the sep we should be cleaning up is.
859    */
860   if (!session_handle_is_local (lh))
861     {
862       sl = listen_session_get_from_handle (lh);
863       if (!sl || listen_session_get_local_session_endpoint (sl, &sep))
864         {
865           clib_warning ("broken listener");
866           return -1;
867         }
868       lh = session_lookup_endpoint_listener (table_index, &sep, 0);
869       if (lh == SESSION_INVALID_HANDLE)
870         return -1;
871     }
872
873   local_session_parse_handle (lh, &server_index, &ll_index);
874   ASSERT (server->index == server_index);
875   if (!(ll = application_get_local_listen_session (server, ll_index)))
876     {
877       clib_warning ("no local listener");
878       return -1;
879     }
880   application_local_listener_session_endpoint (ll, &sep);
881   session_lookup_del_session_endpoint (table_index, &sep);
882
883   /* *INDENT-OFF* */
884   pool_foreach (ls, server->local_sessions, ({
885     if (ls->listener_index == ll->session_index)
886       application_local_session_disconnect (server->index, ls);
887   }));
888   /* *INDENT-ON* */
889   pool_put_index (server->local_listen_sessions, ll->session_index);
890
891   return 0;
892 }
893
894 int
895 application_local_session_connect (u32 table_index, application_t * client,
896                                    application_t * server,
897                                    local_session_t * ll, u32 opaque)
898 {
899   u32 seg_size, evt_q_sz, evt_q_elts, margin = 16 << 10;
900   segment_manager_properties_t *props, *cprops;
901   int rv, has_transport, seg_index;
902   svm_fifo_segment_private_t *seg;
903   segment_manager_t *sm;
904   local_session_t *ls;
905   svm_queue_t *sq, *cq;
906
907   ls = application_alloc_local_session (server);
908
909   props = application_segment_manager_properties (server);
910   cprops = application_segment_manager_properties (client);
911   evt_q_elts = props->evt_q_size + cprops->evt_q_size;
912   evt_q_sz = evt_q_elts * sizeof (session_fifo_event_t);
913   seg_size = props->rx_fifo_size + props->tx_fifo_size + evt_q_sz + margin;
914
915   has_transport = session_has_transport ((stream_session_t *) ll);
916   if (!has_transport)
917     {
918       /* Local sessions don't have backing transport */
919       ls->port = ll->port;
920       sm = application_get_local_segment_manager (server);
921     }
922   else
923     {
924       stream_session_t *sl = (stream_session_t *) ll;
925       transport_connection_t *tc;
926       tc = listen_session_get_transport (sl);
927       ls->port = tc->lcl_port;
928       sm = application_get_listen_segment_manager (server, sl);
929     }
930
931   seg_index = segment_manager_add_segment (sm, seg_size);
932   if (seg_index < 0)
933     {
934       clib_warning ("failed to add new cut-through segment");
935       return seg_index;
936     }
937   seg = segment_manager_get_segment_w_lock (sm, seg_index);
938   sq = segment_manager_alloc_queue (seg, props->evt_q_size);
939   cq = segment_manager_alloc_queue (seg, cprops->evt_q_size);
940   ls->server_evt_q = pointer_to_uword (sq);
941   ls->client_evt_q = pointer_to_uword (cq);
942   rv = segment_manager_try_alloc_fifos (seg, props->rx_fifo_size,
943                                         props->tx_fifo_size,
944                                         &ls->server_rx_fifo,
945                                         &ls->server_tx_fifo);
946   if (rv)
947     {
948       clib_warning ("failed to add fifos in cut-through segment");
949       segment_manager_segment_reader_unlock (sm);
950       goto failed;
951     }
952   ls->server_rx_fifo->master_session_index = ls->session_index;
953   ls->server_tx_fifo->master_session_index = ls->session_index;
954   ls->server_rx_fifo->master_thread_index = ~0;
955   ls->server_tx_fifo->master_thread_index = ~0;
956   ls->svm_segment_index = seg_index;
957   ls->listener_index = ll->session_index;
958   ls->client_index = client->index;
959   ls->client_opaque = opaque;
960   ls->listener_session_type = ll->session_type;
961
962   if ((rv = server->cb_fns.add_segment_callback (server->api_client_index,
963                                                  &seg->ssvm)))
964     {
965       clib_warning ("failed to notify server of new segment");
966       segment_manager_segment_reader_unlock (sm);
967       goto failed;
968     }
969   segment_manager_segment_reader_unlock (sm);
970   if ((rv = server->cb_fns.session_accept_callback ((stream_session_t *) ls)))
971     {
972       clib_warning ("failed to send accept cut-through notify to server");
973       goto failed;
974     }
975   if (server->flags & APP_OPTIONS_FLAGS_IS_BUILTIN)
976     application_local_session_connect_notify (ls);
977
978   return 0;
979
980 failed:
981   if (!has_transport)
982     segment_manager_del_segment (sm, seg);
983   return rv;
984 }
985
986 static uword
987 application_client_local_connect_key (local_session_t * ls)
988 {
989   return ((uword) ls->app_index << 32 | (uword) ls->session_index);
990 }
991
992 static void
993 application_client_local_connect_key_parse (uword key, u32 * app_index,
994                                             u32 * session_index)
995 {
996   *app_index = key >> 32;
997   *session_index = key & 0xFFFFFFFF;
998 }
999
1000 int
1001 application_local_session_connect_notify (local_session_t * ls)
1002 {
1003   svm_fifo_segment_private_t *seg;
1004   application_t *client, *server;
1005   segment_manager_t *sm;
1006   int rv, is_fail = 0;
1007   uword client_key;
1008
1009   client = application_get (ls->client_index);
1010   server = application_get (ls->app_index);
1011   sm = application_get_local_segment_manager_w_session (server, ls);
1012   seg = segment_manager_get_segment_w_lock (sm, ls->svm_segment_index);
1013   if ((rv = client->cb_fns.add_segment_callback (client->api_client_index,
1014                                                  &seg->ssvm)))
1015     {
1016       clib_warning ("failed to notify client %u of new segment",
1017                     ls->client_index);
1018       segment_manager_segment_reader_unlock (sm);
1019       application_local_session_disconnect (ls->client_index, ls);
1020       is_fail = 1;
1021     }
1022   else
1023     {
1024       segment_manager_segment_reader_unlock (sm);
1025     }
1026
1027   client->cb_fns.session_connected_callback (client->index, ls->client_opaque,
1028                                              (stream_session_t *) ls,
1029                                              is_fail);
1030
1031   client_key = application_client_local_connect_key (ls);
1032   hash_set (client->local_connects, client_key, client_key);
1033   return 0;
1034 }
1035
1036 int
1037 application_local_session_disconnect (u32 app_index, local_session_t * ls)
1038 {
1039   svm_fifo_segment_private_t *seg;
1040   application_t *client, *server;
1041   segment_manager_t *sm;
1042   uword client_key;
1043
1044   client = application_get_if_valid (ls->client_index);
1045   server = application_get (ls->app_index);
1046
1047   if (ls->session_state == SESSION_STATE_CLOSED)
1048     {
1049     cleanup:
1050       client_key = application_client_local_connect_key (ls);
1051       sm = application_get_local_segment_manager_w_session (server, ls);
1052       seg = segment_manager_get_segment (sm, ls->svm_segment_index);
1053
1054       if (client)
1055         {
1056           hash_unset (client->local_connects, client_key);
1057           client->cb_fns.del_segment_callback (client->api_client_index,
1058                                                &seg->ssvm);
1059         }
1060
1061       server->cb_fns.del_segment_callback (server->api_client_index,
1062                                            &seg->ssvm);
1063       segment_manager_del_segment (sm, seg);
1064       application_free_local_session (server, ls);
1065       return 0;
1066     }
1067
1068   if (app_index == ls->client_index)
1069     {
1070       send_local_session_disconnect_callback (ls->app_index, ls);
1071     }
1072   else
1073     {
1074       if (!client)
1075         {
1076           goto cleanup;
1077         }
1078       else if (ls->session_state < SESSION_STATE_READY)
1079         {
1080           client->cb_fns.session_connected_callback (client->index,
1081                                                      ls->client_opaque,
1082                                                      (stream_session_t *) ls,
1083                                                      1 /* is_fail */ );
1084           ls->session_state = SESSION_STATE_CLOSED;
1085           goto cleanup;
1086         }
1087       else
1088         {
1089           send_local_session_disconnect_callback (ls->client_index, ls);
1090         }
1091     }
1092
1093   ls->session_state = SESSION_STATE_CLOSED;
1094
1095   return 0;
1096 }
1097
1098 void
1099 application_local_sessions_del (application_t * app)
1100 {
1101   u32 index, server_index, session_index, table_index;
1102   segment_manager_t *sm;
1103   u64 handle, *handles = 0;
1104   local_session_t *ls, *ll;
1105   application_t *server;
1106   session_endpoint_t sep;
1107   int i;
1108
1109   /*
1110    * Local listens. Don't bother with local sessions, we clean them lower
1111    */
1112   table_index = application_local_session_table (app);
1113   /* *INDENT-OFF* */
1114   pool_foreach (ll, app->local_listen_sessions, ({
1115     application_local_listener_session_endpoint (ll, &sep);
1116     session_lookup_del_session_endpoint (table_index, &sep);
1117   }));
1118   /* *INDENT-ON* */
1119
1120   /*
1121    * Local sessions
1122    */
1123   if (app->local_sessions)
1124     {
1125       /* *INDENT-OFF* */
1126       pool_foreach (ls, app->local_sessions, ({
1127         application_local_session_disconnect (app->index, ls);
1128       }));
1129       /* *INDENT-ON* */
1130     }
1131
1132   /*
1133    * Local connects
1134    */
1135   vec_reset_length (handles);
1136   /* *INDENT-OFF* */
1137   hash_foreach (handle, index, app->local_connects, ({
1138     vec_add1 (handles, handle);
1139   }));
1140   /* *INDENT-ON* */
1141
1142   for (i = 0; i < vec_len (handles); i++)
1143     {
1144       application_client_local_connect_key_parse (handles[i], &server_index,
1145                                                   &session_index);
1146       server = application_get_if_valid (server_index);
1147       if (server)
1148         {
1149           ls = application_get_local_session (server, session_index);
1150           application_local_session_disconnect (app->index, ls);
1151         }
1152     }
1153
1154   sm = segment_manager_get (app->local_segment_manager);
1155   sm->app_index = SEGMENT_MANAGER_INVALID_APP_INDEX;
1156   segment_manager_del (sm);
1157 }
1158
1159 u8 *
1160 format_application_listener (u8 * s, va_list * args)
1161 {
1162   application_t *app = va_arg (*args, application_t *);
1163   u64 handle = va_arg (*args, u64);
1164   u32 sm_index = va_arg (*args, u32);
1165   int verbose = va_arg (*args, int);
1166   stream_session_t *listener;
1167   u8 *app_name, *str;
1168
1169   if (app == 0)
1170     {
1171       if (verbose)
1172         s = format (s, "%-40s%-20s%-15s%-15s%-10s", "Connection", "App",
1173                     "API Client", "ListenerID", "SegManager");
1174       else
1175         s = format (s, "%-40s%-20s", "Connection", "App");
1176
1177       return s;
1178     }
1179
1180   app_name = app_get_name_from_reg_index (app);
1181   listener = listen_session_get_from_handle (handle);
1182   str = format (0, "%U", format_stream_session, listener, verbose);
1183
1184   if (verbose)
1185     {
1186       s = format (s, "%-40s%-20s%-15u%-15u%-10u", str, app_name,
1187                   app->api_client_index, handle, sm_index);
1188     }
1189   else
1190     s = format (s, "%-40s%-20s", str, app_name);
1191
1192   vec_free (app_name);
1193   return s;
1194 }
1195
1196 void
1197 application_format_connects (application_t * app, int verbose)
1198 {
1199   svm_fifo_segment_private_t *fifo_segment;
1200   vlib_main_t *vm = vlib_get_main ();
1201   segment_manager_t *sm;
1202   u8 *app_name, *s = 0;
1203
1204   /* Header */
1205   if (app == 0)
1206     {
1207       if (verbose)
1208         vlib_cli_output (vm, "%-40s%-20s%-15s%-10s", "Connection", "App",
1209                          "API Client", "SegManager");
1210       else
1211         vlib_cli_output (vm, "%-40s%-20s", "Connection", "App");
1212       return;
1213     }
1214
1215   /* make sure */
1216   if (app->connects_seg_manager == (u32) ~ 0)
1217     return;
1218
1219   app_name = app_get_name_from_reg_index (app);
1220
1221   /* Across all fifo segments */
1222   sm = segment_manager_get (app->connects_seg_manager);
1223
1224   /* *INDENT-OFF* */
1225   segment_manager_foreach_segment_w_lock (fifo_segment, sm, ({
1226     svm_fifo_t *fifo;
1227     u8 *str;
1228
1229     fifo = svm_fifo_segment_get_fifo_list (fifo_segment);
1230     while (fifo)
1231         {
1232           u32 session_index, thread_index;
1233           stream_session_t *session;
1234
1235           session_index = fifo->master_session_index;
1236           thread_index = fifo->master_thread_index;
1237
1238           session = session_get (session_index, thread_index);
1239           str = format (0, "%U", format_stream_session, session, verbose);
1240
1241           if (verbose)
1242             s = format (s, "%-40s%-20s%-15u%-10u", str, app_name,
1243                         app->api_client_index, app->connects_seg_manager);
1244           else
1245             s = format (s, "%-40s%-20s", str, app_name);
1246
1247           vlib_cli_output (vm, "%v", s);
1248           vec_reset_length (s);
1249           vec_free (str);
1250
1251           fifo = fifo->next;
1252         }
1253     vec_free (s);
1254   }));
1255   /* *INDENT-ON* */
1256
1257   vec_free (app_name);
1258 }
1259
1260 void
1261 application_format_local_sessions (application_t * app, int verbose)
1262 {
1263   vlib_main_t *vm = vlib_get_main ();
1264   local_session_t *ls;
1265   transport_proto_t tp;
1266   u8 *conn = 0;
1267
1268   /* Header */
1269   if (app == 0)
1270     {
1271       vlib_cli_output (vm, "%-40s%-15s%-20s", "Connection", "ServerApp",
1272                        "ClientApp");
1273       return;
1274     }
1275
1276   /* *INDENT-OFF* */
1277   pool_foreach (ls, app->local_listen_sessions, ({
1278     tp = session_type_transport_proto(ls->listener_session_type);
1279     conn = format (0, "[L][%U] *:%u", format_transport_proto_short, tp,
1280                    ls->port);
1281     vlib_cli_output (vm, "%-40v%-15u%-20s", conn, ls->app_index, "*");
1282     vec_reset_length (conn);
1283   }));
1284   pool_foreach (ls, app->local_sessions, ({
1285     tp = session_type_transport_proto(ls->listener_session_type);
1286     conn = format (0, "[L][%U] *:%u", format_transport_proto_short, tp,
1287                    ls->port);
1288     vlib_cli_output (vm, "%-40v%-15u%-20u", conn, ls->app_index,
1289                      ls->client_index);
1290     vec_reset_length (conn);
1291   }));
1292   /* *INDENT-ON* */
1293
1294   vec_free (conn);
1295 }
1296
1297 void
1298 application_format_local_connects (application_t * app, int verbose)
1299 {
1300   vlib_main_t *vm = vlib_get_main ();
1301   u32 app_index, session_index;
1302   application_t *server;
1303   local_session_t *ls;
1304   uword client_key;
1305   u64 value;
1306
1307   /* Header */
1308   if (app == 0)
1309     {
1310       if (verbose)
1311         vlib_cli_output (vm, "%-40s%-15s%-20s%-10s", "Connection", "App",
1312                          "Peer App", "SegManager");
1313       else
1314         vlib_cli_output (vm, "%-40s%-15s%-20s", "Connection", "App",
1315                          "Peer App");
1316       return;
1317     }
1318
1319   /* *INDENT-OFF* */
1320   hash_foreach (client_key, value, app->local_connects, ({
1321     application_client_local_connect_key_parse (client_key, &app_index,
1322                                                 &session_index);
1323     server = application_get (app_index);
1324     ls = application_get_local_session (server, session_index);
1325     vlib_cli_output (vm, "%-40s%-15s%-20s", "TODO", ls->app_index, ls->client_index);
1326   }));
1327   /* *INDENT-ON* */
1328 }
1329
1330 u8 *
1331 format_application (u8 * s, va_list * args)
1332 {
1333   application_t *app = va_arg (*args, application_t *);
1334   CLIB_UNUSED (int verbose) = va_arg (*args, int);
1335   segment_manager_properties_t *props;
1336   const u8 *app_ns_name;
1337   u8 *app_name;
1338
1339   if (app == 0)
1340     {
1341       if (verbose)
1342         s = format (s, "%-10s%-20s%-15s%-15s%-15s%-15s%-15s", "Index", "Name",
1343                     "API Client", "Namespace", "Add seg size", "Rx fifo size",
1344                     "Tx fifo size");
1345       else
1346         s =
1347           format (s, "%-10s%-20s%-15s%-40s", "Index", "Name", "API Client",
1348                   "Namespace");
1349       return s;
1350     }
1351
1352   app_name = app_get_name_from_reg_index (app);
1353   app_ns_name = app_namespace_id_from_index (app->ns_index);
1354   props = application_segment_manager_properties (app);
1355   if (verbose)
1356     s =
1357       format (s, "%-10d%-20s%-15d%-15d%-15d%-15d%-15d", app->index, app_name,
1358               app->api_client_index, app->ns_index,
1359               props->add_segment_size,
1360               props->rx_fifo_size, props->tx_fifo_size);
1361   else
1362     s = format (s, "%-10d%-20s%-15d%-40s", app->index, app_name,
1363                 app->api_client_index, app_ns_name);
1364   return s;
1365 }
1366
1367
1368 void
1369 application_format_all_listeners (vlib_main_t * vm, int do_local, int verbose)
1370 {
1371   application_t *app;
1372   u32 sm_index;
1373   u64 handle;
1374
1375   if (!pool_elts (app_pool))
1376     {
1377       vlib_cli_output (vm, "No active server bindings");
1378       return;
1379     }
1380
1381   if (do_local)
1382     {
1383       application_format_local_sessions (0, verbose);
1384       /* *INDENT-OFF* */
1385       pool_foreach (app, app_pool, ({
1386         if (!pool_elts (app->local_sessions)
1387             && !pool_elts(app->local_connects))
1388           continue;
1389         application_format_local_sessions (app, verbose);
1390       }));
1391       /* *INDENT-ON* */
1392     }
1393   else
1394     {
1395       vlib_cli_output (vm, "%U", format_application_listener, 0 /* header */ ,
1396                        0, 0, verbose);
1397
1398       /* *INDENT-OFF* */
1399       pool_foreach (app, app_pool, ({
1400         if (hash_elts (app->listeners_table) == 0)
1401           continue;
1402         hash_foreach (handle, sm_index, app->listeners_table, ({
1403           vlib_cli_output (vm, "%U", format_application_listener, app,
1404                            handle, sm_index, verbose);
1405         }));
1406       }));
1407       /* *INDENT-ON* */
1408     }
1409 }
1410
1411 void
1412 application_format_all_clients (vlib_main_t * vm, int do_local, int verbose)
1413 {
1414   application_t *app;
1415
1416   if (!pool_elts (app_pool))
1417     {
1418       vlib_cli_output (vm, "No active apps");
1419       return;
1420     }
1421
1422   if (do_local)
1423     {
1424       application_format_local_connects (0, verbose);
1425
1426       /* *INDENT-OFF* */
1427       pool_foreach (app, app_pool, ({
1428         if (app->local_connects)
1429           application_format_local_connects (app, verbose);
1430       }));
1431       /* *INDENT-ON* */
1432     }
1433   else
1434     {
1435       application_format_connects (0, verbose);
1436
1437       /* *INDENT-OFF* */
1438       pool_foreach (app, app_pool, ({
1439         if (app->connects_seg_manager == (u32)~0)
1440           continue;
1441         application_format_connects (app, verbose);
1442       }));
1443       /* *INDENT-ON* */
1444     }
1445 }
1446
1447 static clib_error_t *
1448 show_app_command_fn (vlib_main_t * vm, unformat_input_t * input,
1449                      vlib_cli_command_t * cmd)
1450 {
1451   int do_server = 0, do_client = 0, do_local = 0;
1452   application_t *app;
1453   int verbose = 0;
1454
1455   session_cli_return_if_not_enabled ();
1456
1457   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1458     {
1459       if (unformat (input, "server"))
1460         do_server = 1;
1461       else if (unformat (input, "client"))
1462         do_client = 1;
1463       else if (unformat (input, "local"))
1464         do_local = 1;
1465       else if (unformat (input, "verbose"))
1466         verbose = 1;
1467       else
1468         break;
1469     }
1470
1471   if (do_server)
1472     application_format_all_listeners (vm, do_local, verbose);
1473
1474   if (do_client)
1475     application_format_all_clients (vm, do_local, verbose);
1476
1477   /* Print app related info */
1478   if (!do_server && !do_client)
1479     {
1480       vlib_cli_output (vm, "%U", format_application, 0, verbose);
1481       /* *INDENT-OFF* */
1482       pool_foreach (app, app_pool, ({
1483         vlib_cli_output (vm, "%U", format_application, app, verbose);
1484       }));
1485       /* *INDENT-ON* */
1486     }
1487
1488   return 0;
1489 }
1490
1491 /* *INDENT-OFF* */
1492 VLIB_CLI_COMMAND (show_app_command, static) =
1493 {
1494   .path = "show app",
1495   .short_help = "show app [server|client] [verbose]",
1496   .function = show_app_command_fn,
1497 };
1498 /* *INDENT-ON* */
1499
1500 /*
1501  * fd.io coding-style-patch-verification: ON
1502  *
1503  * Local Variables:
1504  * eval: (c-set-style "gnu")
1505  * End:
1506  */