vcl session: switch to generic cert key apis
[vpp.git] / src / plugins / hs_apps / echo_server.c
1 /*
2 * Copyright (c) 2017-2019 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <vnet/vnet.h>
17 #include <vlibmemory/api.h>
18 #include <vnet/session/application.h>
19 #include <vnet/session/application_interface.h>
20 #include <vnet/session/session.h>
21
22 #define ECHO_SERVER_DBG (0)
23 #define DBG(_fmt, _args...)                     \
24     if (ECHO_SERVER_DBG)                                \
25       clib_warning (_fmt, ##_args)
26
27 typedef struct
28 {
29   /*
30    * Server app parameters
31    */
32   svm_msg_q_t **vpp_queue;
33   svm_queue_t *vl_input_queue;  /**< Sever's event queue */
34
35   u32 app_index;                /**< Server app index */
36   u32 my_client_index;          /**< API client handle */
37   u32 node_index;               /**< process node index for event scheduling */
38
39   /*
40    * Config params
41    */
42   u8 no_echo;                   /**< Don't echo traffic */
43   u32 fifo_size;                /**< Fifo size */
44   u32 rcv_buffer_size;          /**< Rcv buffer size */
45   u32 prealloc_fifos;           /**< Preallocate fifos */
46   u32 private_segment_count;    /**< Number of private segments  */
47   u32 private_segment_size;     /**< Size of private segments  */
48   char *server_uri;             /**< Server URI */
49   u32 tls_engine;               /**< TLS engine: mbedtls/openssl */
50   u32 ckpair_index;             /**< Cert and key for tls/quic */
51   u8 is_dgram;                  /**< set if transport is dgram */
52
53   /*
54    * Test state
55    */
56   u8 **rx_buf;                  /**< Per-thread RX buffer */
57   u64 byte_index;
58   u32 **rx_retries;
59   u8 transport_proto;
60   u64 listener_handle;          /**< Session handle of the root listener */
61
62   vlib_main_t *vlib_main;
63 } echo_server_main_t;
64
65 echo_server_main_t echo_server_main;
66
67 int
68 quic_echo_server_qsession_accept_callback (session_t * s)
69 {
70   DBG ("QSession %u accept w/opaque %d", s->session_index, s->opaque);
71   return 0;
72 }
73
74 int
75 quic_echo_server_session_accept_callback (session_t * s)
76 {
77   echo_server_main_t *esm = &echo_server_main;
78   if (s->listener_handle == esm->listener_handle)
79     return quic_echo_server_qsession_accept_callback (s);
80   DBG ("SSESSION %u accept w/opaque %d", s->session_index, s->opaque);
81
82   esm->vpp_queue[s->thread_index] =
83     session_main_get_vpp_event_queue (s->thread_index);
84   s->session_state = SESSION_STATE_READY;
85   esm->byte_index = 0;
86   ASSERT (vec_len (esm->rx_retries) > s->thread_index);
87   vec_validate (esm->rx_retries[s->thread_index], s->session_index);
88   esm->rx_retries[s->thread_index][s->session_index] = 0;
89   return 0;
90 }
91
92 int
93 echo_server_session_accept_callback (session_t * s)
94 {
95   echo_server_main_t *esm = &echo_server_main;
96   esm->vpp_queue[s->thread_index] =
97     session_main_get_vpp_event_queue (s->thread_index);
98   s->session_state = SESSION_STATE_READY;
99   esm->byte_index = 0;
100   ASSERT (vec_len (esm->rx_retries) > s->thread_index);
101   vec_validate (esm->rx_retries[s->thread_index], s->session_index);
102   esm->rx_retries[s->thread_index][s->session_index] = 0;
103   return 0;
104 }
105
106 void
107 echo_server_session_disconnect_callback (session_t * s)
108 {
109   echo_server_main_t *esm = &echo_server_main;
110   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
111
112   a->handle = session_handle (s);
113   a->app_index = esm->app_index;
114   vnet_disconnect_session (a);
115 }
116
117 void
118 echo_server_session_reset_callback (session_t * s)
119 {
120   echo_server_main_t *esm = &echo_server_main;
121   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
122   clib_warning ("Reset session %U", format_session, s, 2);
123   a->handle = session_handle (s);
124   a->app_index = esm->app_index;
125   vnet_disconnect_session (a);
126 }
127
128 int
129 echo_server_session_connected_callback (u32 app_index, u32 api_context,
130                                         session_t * s, session_error_t err)
131 {
132   clib_warning ("called...");
133   return -1;
134 }
135
136 int
137 echo_server_add_segment_callback (u32 client_index, u64 segment_handle)
138 {
139   /* New heaps may be added */
140   return 0;
141 }
142
143 int
144 echo_server_redirect_connect_callback (u32 client_index, void *mp)
145 {
146   clib_warning ("called...");
147   return -1;
148 }
149
150 void
151 test_bytes (echo_server_main_t * esm, int actual_transfer)
152 {
153   int i;
154   u32 my_thread_id = vlib_get_thread_index ();
155
156   for (i = 0; i < actual_transfer; i++)
157     {
158       if (esm->rx_buf[my_thread_id][i] != ((esm->byte_index + i) & 0xff))
159         {
160           clib_warning ("at %lld expected %d got %d", esm->byte_index + i,
161                         (esm->byte_index + i) & 0xff,
162                         esm->rx_buf[my_thread_id][i]);
163         }
164     }
165   esm->byte_index += actual_transfer;
166 }
167
168 /*
169  * If no-echo, just drop the data and be done with it.
170  */
171 int
172 echo_server_builtin_server_rx_callback_no_echo (session_t * s)
173 {
174   svm_fifo_t *rx_fifo = s->rx_fifo;
175   svm_fifo_dequeue_drop (rx_fifo, svm_fifo_max_dequeue_cons (rx_fifo));
176   return 0;
177 }
178
179 int
180 echo_server_rx_callback (session_t * s)
181 {
182   u32 n_written, max_dequeue, max_enqueue, max_transfer;
183   int actual_transfer;
184   svm_fifo_t *tx_fifo, *rx_fifo;
185   echo_server_main_t *esm = &echo_server_main;
186   u32 thread_index = vlib_get_thread_index ();
187   app_session_transport_t at;
188
189   ASSERT (s->thread_index == thread_index);
190
191   rx_fifo = s->rx_fifo;
192   tx_fifo = s->tx_fifo;
193
194   ASSERT (rx_fifo->master_thread_index == thread_index);
195   ASSERT (tx_fifo->master_thread_index == thread_index);
196
197   max_enqueue = svm_fifo_max_enqueue_prod (tx_fifo);
198   if (!esm->is_dgram)
199     {
200       max_dequeue = svm_fifo_max_dequeue_cons (rx_fifo);
201     }
202   else
203     {
204       session_dgram_pre_hdr_t ph;
205       svm_fifo_peek (rx_fifo, 0, sizeof (ph), (u8 *) & ph);
206       max_dequeue = ph.data_length - ph.data_offset;
207       if (!esm->vpp_queue[s->thread_index])
208         {
209           svm_msg_q_t *mq;
210           mq = session_main_get_vpp_event_queue (s->thread_index);
211           esm->vpp_queue[s->thread_index] = mq;
212         }
213       max_enqueue -= sizeof (session_dgram_hdr_t);
214     }
215
216   if (PREDICT_FALSE (max_dequeue == 0))
217     return 0;
218
219   /* Number of bytes we're going to copy */
220   max_transfer = clib_min (max_dequeue, max_enqueue);
221
222   /* No space in tx fifo */
223   if (PREDICT_FALSE (max_transfer == 0))
224     {
225       /* XXX timeout for session that are stuck */
226
227     rx_event:
228       /* Program self-tap to retry */
229       if (svm_fifo_set_event (rx_fifo))
230         {
231           if (session_send_io_evt_to_thread (rx_fifo,
232                                              SESSION_IO_EVT_BUILTIN_RX))
233             clib_warning ("failed to enqueue self-tap");
234
235           vec_validate (esm->rx_retries[s->thread_index], s->session_index);
236           if (esm->rx_retries[thread_index][s->session_index] == 500000)
237             {
238               clib_warning ("session stuck: %U", format_session, s, 2);
239             }
240           if (esm->rx_retries[thread_index][s->session_index] < 500001)
241             esm->rx_retries[thread_index][s->session_index]++;
242         }
243
244       return 0;
245     }
246
247   vec_validate (esm->rx_buf[thread_index], max_transfer);
248   if (!esm->is_dgram)
249     {
250       actual_transfer = app_recv_stream_raw (rx_fifo,
251                                              esm->rx_buf[thread_index],
252                                              max_transfer,
253                                              0 /* don't clear event */ ,
254                                              0 /* peek */ );
255     }
256   else
257     {
258       actual_transfer = app_recv_dgram_raw (rx_fifo,
259                                             esm->rx_buf[thread_index],
260                                             max_transfer, &at,
261                                             0 /* don't clear event */ ,
262                                             0 /* peek */ );
263     }
264   ASSERT (actual_transfer == max_transfer);
265   /* test_bytes (esm, actual_transfer); */
266
267   /*
268    * Echo back
269    */
270
271   if (!esm->is_dgram)
272     {
273       n_written = app_send_stream_raw (tx_fifo,
274                                        esm->vpp_queue[thread_index],
275                                        esm->rx_buf[thread_index],
276                                        actual_transfer, SESSION_IO_EVT_TX,
277                                        1 /* do_evt */ , 0);
278     }
279   else
280     {
281       n_written = app_send_dgram_raw (tx_fifo, &at,
282                                       esm->vpp_queue[s->thread_index],
283                                       esm->rx_buf[thread_index],
284                                       actual_transfer, SESSION_IO_EVT_TX,
285                                       1 /* do_evt */ , 0);
286     }
287
288   if (n_written != max_transfer)
289     clib_warning ("short trout! written %u read %u", n_written, max_transfer);
290
291   if (PREDICT_FALSE (svm_fifo_max_dequeue_cons (rx_fifo)))
292     goto rx_event;
293
294   return 0;
295 }
296
297 static session_cb_vft_t echo_server_session_cb_vft = {
298   .session_accept_callback = echo_server_session_accept_callback,
299   .session_disconnect_callback = echo_server_session_disconnect_callback,
300   .session_connected_callback = echo_server_session_connected_callback,
301   .add_segment_callback = echo_server_add_segment_callback,
302   .builtin_app_rx_callback = echo_server_rx_callback,
303   .session_reset_callback = echo_server_session_reset_callback
304 };
305
306 static int
307 echo_server_attach (u8 * appns_id, u64 appns_flags, u64 appns_secret)
308 {
309   vnet_app_add_cert_key_pair_args_t _ck_pair, *ck_pair = &_ck_pair;
310   echo_server_main_t *esm = &echo_server_main;
311   vnet_app_attach_args_t _a, *a = &_a;
312   u64 options[APP_OPTIONS_N_OPTIONS];
313   u32 segment_size = 512 << 20;
314
315   clib_memset (a, 0, sizeof (*a));
316   clib_memset (options, 0, sizeof (options));
317
318   if (esm->no_echo)
319     echo_server_session_cb_vft.builtin_app_rx_callback =
320       echo_server_builtin_server_rx_callback_no_echo;
321   else
322     echo_server_session_cb_vft.builtin_app_rx_callback =
323       echo_server_rx_callback;
324   if (esm->transport_proto == TRANSPORT_PROTO_QUIC)
325     echo_server_session_cb_vft.session_accept_callback =
326       quic_echo_server_session_accept_callback;
327
328   if (esm->private_segment_size)
329     segment_size = esm->private_segment_size;
330
331   a->api_client_index = ~0;
332   a->name = format (0, "echo_server");
333   a->session_cb_vft = &echo_server_session_cb_vft;
334   a->options = options;
335   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
336   a->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = segment_size;
337   a->options[APP_OPTIONS_RX_FIFO_SIZE] = esm->fifo_size;
338   a->options[APP_OPTIONS_TX_FIFO_SIZE] = esm->fifo_size;
339   a->options[APP_OPTIONS_PRIVATE_SEGMENT_COUNT] = esm->private_segment_count;
340   a->options[APP_OPTIONS_TLS_ENGINE] = esm->tls_engine;
341   a->options[APP_OPTIONS_PCT_FIRST_ALLOC] = 100;
342   a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] =
343     esm->prealloc_fifos ? esm->prealloc_fifos : 1;
344
345   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
346   if (appns_id)
347     {
348       a->namespace_id = appns_id;
349       a->options[APP_OPTIONS_FLAGS] |= appns_flags;
350       a->options[APP_OPTIONS_NAMESPACE_SECRET] = appns_secret;
351     }
352
353   if (vnet_application_attach (a))
354     {
355       clib_warning ("failed to attach server");
356       return -1;
357     }
358   esm->app_index = a->app_index;
359   vec_free (a->name);
360
361   clib_memset (ck_pair, 0, sizeof (*ck_pair));
362   ck_pair->cert = (u8 *) test_srv_crt_rsa;
363   ck_pair->key = (u8 *) test_srv_key_rsa;
364   ck_pair->cert_len = test_srv_crt_rsa_len;
365   ck_pair->key_len = test_srv_key_rsa_len;
366   vnet_app_add_cert_key_pair (ck_pair);
367   esm->ckpair_index = ck_pair->index;
368
369   return 0;
370 }
371
372 static int
373 echo_server_detach (void)
374 {
375   echo_server_main_t *esm = &echo_server_main;
376   vnet_app_detach_args_t _da, *da = &_da;
377   int rv;
378
379   da->app_index = esm->app_index;
380   rv = vnet_application_detach (da);
381   esm->app_index = ~0;
382   vnet_app_del_cert_key_pair (esm->ckpair_index);
383   return rv;
384 }
385
386 static int
387 echo_server_listen ()
388 {
389   i32 rv;
390   echo_server_main_t *esm = &echo_server_main;
391   vnet_listen_args_t _args = { 0 }, *args = &_args;
392
393   args->sep_ext.app_wrk_index = 0;
394
395   if ((rv = parse_uri (esm->server_uri, &args->sep_ext)))
396     {
397       return -1;
398     }
399   args->app_index = esm->app_index;
400   args->sep_ext.ckpair_index = esm->ckpair_index;
401
402   if (args->sep_ext.transport_proto == TRANSPORT_PROTO_UDP)
403     {
404       args->sep_ext.transport_flags = TRANSPORT_CFG_F_CONNECTED;
405     }
406
407   rv = vnet_listen (args);
408   esm->listener_handle = args->handle;
409   return rv;
410 }
411
412 static int
413 echo_server_create (vlib_main_t * vm, u8 * appns_id, u64 appns_flags,
414                     u64 appns_secret)
415 {
416   echo_server_main_t *esm = &echo_server_main;
417   vlib_thread_main_t *vtm = vlib_get_thread_main ();
418   u32 num_threads;
419   int i;
420
421   num_threads = 1 /* main thread */  + vtm->n_threads;
422   vec_validate (echo_server_main.vpp_queue, num_threads - 1);
423   vec_validate (esm->rx_buf, num_threads - 1);
424   vec_validate (esm->rx_retries, num_threads - 1);
425   for (i = 0; i < vec_len (esm->rx_retries); i++)
426     vec_validate (esm->rx_retries[i],
427                   pool_elts (session_main.wrk[i].sessions));
428   esm->rcv_buffer_size = clib_max (esm->rcv_buffer_size, esm->fifo_size);
429   for (i = 0; i < num_threads; i++)
430     vec_validate (esm->rx_buf[i], esm->rcv_buffer_size);
431
432   if (echo_server_attach (appns_id, appns_flags, appns_secret))
433     {
434       clib_warning ("failed to attach server");
435       return -1;
436     }
437   if (echo_server_listen ())
438     {
439       clib_warning ("failed to start listening");
440       if (echo_server_detach ())
441         clib_warning ("failed to detach");
442       return -1;
443     }
444   return 0;
445 }
446
447 static clib_error_t *
448 echo_server_create_command_fn (vlib_main_t * vm, unformat_input_t * input,
449                                vlib_cli_command_t * cmd)
450 {
451   echo_server_main_t *esm = &echo_server_main;
452   u8 server_uri_set = 0, *appns_id = 0;
453   u64 tmp, appns_flags = 0, appns_secret = 0;
454   char *default_uri = "tcp://0.0.0.0/1234";
455   int rv, is_stop = 0;
456   session_endpoint_cfg_t sep = SESSION_ENDPOINT_CFG_NULL;
457
458   esm->no_echo = 0;
459   esm->fifo_size = 64 << 10;
460   esm->rcv_buffer_size = 128 << 10;
461   esm->prealloc_fifos = 0;
462   esm->private_segment_count = 0;
463   esm->private_segment_size = 0;
464   esm->tls_engine = CRYPTO_ENGINE_OPENSSL;
465   vec_free (esm->server_uri);
466
467   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
468     {
469       if (unformat (input, "uri %s", &esm->server_uri))
470         server_uri_set = 1;
471       else if (unformat (input, "no-echo"))
472         esm->no_echo = 1;
473       else if (unformat (input, "fifo-size %d", &esm->fifo_size))
474         esm->fifo_size <<= 10;
475       else if (unformat (input, "rcv-buf-size %d", &esm->rcv_buffer_size))
476         ;
477       else if (unformat (input, "prealloc-fifos %d", &esm->prealloc_fifos))
478         ;
479       else if (unformat (input, "private-segment-count %d",
480                          &esm->private_segment_count))
481         ;
482       else if (unformat (input, "private-segment-size %U",
483                          unformat_memory_size, &tmp))
484         {
485           if (tmp >= 0x100000000ULL)
486             return clib_error_return
487               (0, "private segment size %lld (%llu) too large", tmp, tmp);
488           esm->private_segment_size = tmp;
489         }
490       else if (unformat (input, "appns %_%v%_", &appns_id))
491         ;
492       else if (unformat (input, "all-scope"))
493         appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE
494                         | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE);
495       else if (unformat (input, "local-scope"))
496         appns_flags |= APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
497       else if (unformat (input, "global-scope"))
498         appns_flags |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
499       else if (unformat (input, "secret %lu", &appns_secret))
500         ;
501       else if (unformat (input, "stop"))
502         is_stop = 1;
503       else if (unformat (input, "tls-engine %d", &esm->tls_engine))
504         ;
505       else
506         return clib_error_return (0, "failed: unknown input `%U'",
507                                   format_unformat_error, input);
508     }
509
510   if (is_stop)
511     {
512       if (esm->app_index == (u32) ~ 0)
513         {
514           clib_warning ("server not running");
515           return clib_error_return (0, "failed: server not running");
516         }
517       rv = echo_server_detach ();
518       if (rv)
519         {
520           clib_warning ("failed: detach");
521           return clib_error_return (0, "failed: server detach %d", rv);
522         }
523       return 0;
524     }
525
526   vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
527
528   if (!server_uri_set)
529     {
530       clib_warning ("No uri provided! Using default: %s", default_uri);
531       esm->server_uri = (char *) format (0, "%s%c", default_uri, 0);
532     }
533
534   if ((rv = parse_uri ((char *) esm->server_uri, &sep)))
535     return clib_error_return (0, "Uri parse error: %d", rv);
536   esm->transport_proto = sep.transport_proto;
537   esm->is_dgram = (sep.transport_proto == TRANSPORT_PROTO_UDP);
538
539   rv = echo_server_create (vm, appns_id, appns_flags, appns_secret);
540   vec_free (appns_id);
541   if (rv)
542     {
543       vec_free (esm->server_uri);
544       return clib_error_return (0, "failed: server_create returned %d", rv);
545     }
546
547   return 0;
548 }
549
550 /* *INDENT-OFF* */
551 VLIB_CLI_COMMAND (echo_server_create_command, static) =
552 {
553   .path = "test echo server",
554   .short_help = "test echo server proto <proto> [no echo][fifo-size <mbytes>]"
555       "[rcv-buf-size <bytes>][prealloc-fifos <count>]"
556       "[private-segment-count <count>][private-segment-size <bytes[m|g]>]"
557       "[uri <tcp://ip/port>]",
558   .function = echo_server_create_command_fn,
559 };
560 /* *INDENT-ON* */
561
562 clib_error_t *
563 echo_server_main_init (vlib_main_t * vm)
564 {
565   echo_server_main_t *esm = &echo_server_main;
566   esm->my_client_index = ~0;
567   return 0;
568 }
569
570 VLIB_INIT_FUNCTION (echo_server_main_init);
571
572 /*
573 * fd.io coding-style-patch-verification: ON
574 *
575 * Local Variables:
576 * eval: (c-set-style "gnu")
577 * End:
578 */