a0bd9690246c6b38c1869c3c55734032bdc659dd
[vpp.git] / src / tests / vnet / session / quic_echo.c
1 /*
2  * Copyright (c) 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 <stdio.h>
17 #include <signal.h>
18
19 #include <vnet/session/application_interface.h>
20 #include <vlibmemory/api.h>
21
22 #include <vpp/api/vpe_msg_enum.h>
23 #include <svm/fifo_segment.h>
24
25 #define vl_typedefs             /* define message structures */
26 #include <vpp/api/vpe_all_api_h.h>
27 #undef vl_typedefs
28
29 /* declare message handlers for each api */
30
31 #define vl_endianfun            /* define message structures */
32 #include <vpp/api/vpe_all_api_h.h>
33 #undef vl_endianfun
34
35 /* instantiate all the print functions we know about */
36 #define vl_print(handle, ...)
37 #define vl_printfun
38 #include <vpp/api/vpe_all_api_h.h>
39 #undef vl_printfun
40
41 #define QUIC_ECHO_DBG 1
42 #define DBG(_fmt, _args...)                     \
43     if (QUIC_ECHO_DBG)                          \
44       clib_warning (_fmt, ##_args)
45
46 typedef struct
47 {
48   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
49 #define _(type, name) type name;
50   foreach_app_session_field
51 #undef _
52   u64 vpp_session_handle;
53   u64 bytes_sent;
54   u64 bytes_to_send;
55   volatile u64 bytes_received;
56   volatile u64 bytes_to_receive;
57   f64 start;
58 } echo_session_t;
59
60 typedef enum
61 {
62   STATE_START,
63   STATE_ATTACHED,
64   STATE_LISTEN,
65   STATE_READY,
66   STATE_DISCONNECTING,
67   STATE_FAILED,
68   STATE_DETACHED
69 } connection_state_t;
70
71 enum quic_session_type_t
72 {
73   QUIC_SESSION_TYPE_QUIC = 0,
74   QUIC_SESSION_TYPE_STREAM = 1,
75   QUIC_SESSION_TYPE_LISTEN = INT32_MAX,
76 };
77
78 typedef struct
79 {
80   /* vpe input queue */
81   svm_queue_t *vl_input_queue;
82
83   /* API client handle */
84   u32 my_client_index;
85
86   /* The URI we're playing with */
87   u8 *uri;
88
89   /* Session pool */
90   echo_session_t *sessions;
91
92   /* Hash table for disconnect processing */
93   uword *session_index_by_vpp_handles;
94
95   /* Hash table for shared segment_names */
96   uword *shared_segment_handles;
97   clib_spinlock_t segment_handles_lock;
98
99   /* intermediate rx buffer */
100   u8 *rx_buf;
101
102   /* URI for slave's connect */
103   u8 *connect_uri;
104
105   u32 connected_session_index;
106
107   int i_am_master;
108
109   /* drop all packets */
110   int no_return;
111
112   /* Our event queue */
113   svm_msg_q_t *our_event_queue;
114
115   u8 *socket_name;
116
117   pid_t my_pid;
118
119   /* For deadman timers */
120   clib_time_t clib_time;
121
122   /* State of the connection, shared between msg RX thread and main thread */
123   volatile connection_state_t state;
124
125   /* Signal variables */
126   volatile int time_to_stop;
127   volatile int time_to_print_stats;
128
129   u32 configured_segment_size;
130
131   /* VNET_API_ERROR_FOO -> "Foo" hash table */
132   uword *error_string_by_error_number;
133
134   u8 *connect_test_data;
135   pthread_t *client_thread_handles;
136   u32 *thread_args;
137   u32 client_bytes_received;
138   u8 test_return_packets;
139   u64 bytes_to_send;
140   u32 fifo_size;
141   u32 quic_streams;
142   u8 *appns_id;
143   u64 appns_flags;
144   u64 appns_secret;
145
146   u32 n_clients;
147   u64 tx_total;
148   u64 rx_total;
149
150   volatile u32 n_clients_connected;
151   volatile u32 n_active_clients;
152
153
154   /** Flag that decides if socket, instead of svm, api is used to connect to
155    * vpp. If sock api is used, shm binary api is subsequently bootstrapped
156    * and all other messages are exchanged using shm IPC. */
157   u8 use_sock_api;
158   int max_test_msg;
159
160   fifo_segment_main_t segment_main;
161 } echo_main_t;
162
163 echo_main_t echo_main;
164
165 #if CLIB_DEBUG > 0
166 #define NITER 10000
167 #else
168 #define NITER 4000000
169 #endif
170
171 static u8 *
172 format_api_error (u8 * s, va_list * args)
173 {
174   echo_main_t *em = &echo_main;
175   i32 error = va_arg (*args, u32);
176   uword *p;
177
178   p = hash_get (em->error_string_by_error_number, -error);
179
180   if (p)
181     s = format (s, "%s", p[0]);
182   else
183     s = format (s, "%d", error);
184   return s;
185 }
186
187 static void
188 init_error_string_table (echo_main_t * em)
189 {
190   em->error_string_by_error_number = hash_create (0, sizeof (uword));
191
192 #define _(n,v,s) hash_set (em->error_string_by_error_number, -v, s);
193   foreach_vnet_api_error;
194 #undef _
195
196   hash_set (em->error_string_by_error_number, 99, "Misc");
197 }
198
199 static void handle_mq_event (session_event_t * e);
200
201 #if CLIB_DEBUG > 0
202 #define TIMEOUT 10.0
203 #else
204 #define TIMEOUT 10.0
205 #endif
206
207 static int
208 wait_for_segment_allocation (u64 segment_handle)
209 {
210   echo_main_t *em = &echo_main;
211   f64 timeout;
212   timeout = clib_time_now (&em->clib_time) + TIMEOUT;
213   uword *segment_present;
214   DBG ("Waiting for segment %lx...", segment_handle);
215   while (clib_time_now (&em->clib_time) < timeout)
216     {
217       clib_spinlock_lock (&em->segment_handles_lock);
218       segment_present = hash_get (em->shared_segment_handles, segment_handle);
219       clib_spinlock_unlock (&em->segment_handles_lock);
220       if (segment_present != 0)
221         return 0;
222       if (em->time_to_stop == 1)
223         return 0;
224     }
225   DBG ("timeout waiting for segment_allocation %lx", segment_handle);
226   return -1;
227 }
228
229 static int
230 wait_for_disconnected_sessions (echo_main_t * em)
231 {
232   f64 timeout;
233   timeout = clib_time_now (&em->clib_time) + TIMEOUT;
234   while (clib_time_now (&em->clib_time) < timeout)
235     {
236       if (hash_elts (em->session_index_by_vpp_handles) == 0)
237         return 0;
238     }
239   DBG ("timeout waiting for disconnected_sessions");
240   return -1;
241 }
242
243 static int
244 wait_for_state_change (echo_main_t * em, connection_state_t state)
245 {
246   svm_msg_q_msg_t msg;
247   session_event_t *e;
248   f64 timeout;
249   timeout = clib_time_now (&em->clib_time) + TIMEOUT;
250
251   while (clib_time_now (&em->clib_time) < timeout)
252     {
253       if (em->state == state)
254         return 0;
255       if (em->state == STATE_FAILED)
256         return -1;
257       if (em->time_to_stop == 1)
258         return 0;
259       if (!em->our_event_queue || em->state < STATE_ATTACHED)
260         continue;
261
262       if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_NOWAIT, 0))
263         continue;
264       e = svm_msg_q_msg_data (em->our_event_queue, &msg);
265       handle_mq_event (e);
266       svm_msg_q_free_msg (em->our_event_queue, &msg);
267     }
268   clib_warning ("timeout waiting for state %d", state);
269   return -1;
270 }
271
272 void
273 application_send_attach (echo_main_t * em)
274 {
275   vl_api_application_attach_t *bmp;
276   vl_api_application_tls_cert_add_t *cert_mp;
277   vl_api_application_tls_key_add_t *key_mp;
278
279   bmp = vl_msg_api_alloc (sizeof (*bmp));
280   clib_memset (bmp, 0, sizeof (*bmp));
281
282   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
283   bmp->client_index = em->my_client_index;
284   bmp->context = ntohl (0xfeedface);
285   bmp->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_ACCEPT_REDIRECT;
286   bmp->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_ADD_SEGMENT;
287   bmp->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = 16;
288   bmp->options[APP_OPTIONS_RX_FIFO_SIZE] = em->fifo_size;
289   bmp->options[APP_OPTIONS_TX_FIFO_SIZE] = em->fifo_size;
290   bmp->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = 128 << 20;
291   bmp->options[APP_OPTIONS_SEGMENT_SIZE] = 256 << 20;
292   bmp->options[APP_OPTIONS_EVT_QUEUE_SIZE] = 256;
293   if (em->appns_id)
294     {
295       bmp->namespace_id_len = vec_len (em->appns_id);
296       clib_memcpy_fast (bmp->namespace_id, em->appns_id,
297                         bmp->namespace_id_len);
298       bmp->options[APP_OPTIONS_FLAGS] |= em->appns_flags;
299       bmp->options[APP_OPTIONS_NAMESPACE_SECRET] = em->appns_secret;
300     }
301   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp);
302
303   cert_mp = vl_msg_api_alloc (sizeof (*cert_mp) + test_srv_crt_rsa_len);
304   clib_memset (cert_mp, 0, sizeof (*cert_mp));
305   cert_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_CERT_ADD);
306   cert_mp->client_index = em->my_client_index;
307   cert_mp->context = ntohl (0xfeedface);
308   cert_mp->cert_len = clib_host_to_net_u16 (test_srv_crt_rsa_len);
309   clib_memcpy_fast (cert_mp->cert, test_srv_crt_rsa, test_srv_crt_rsa_len);
310   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cert_mp);
311
312   key_mp = vl_msg_api_alloc (sizeof (*key_mp) + test_srv_key_rsa_len);
313   clib_memset (key_mp, 0, sizeof (*key_mp) + test_srv_key_rsa_len);
314   key_mp->_vl_msg_id = ntohs (VL_API_APPLICATION_TLS_KEY_ADD);
315   key_mp->client_index = em->my_client_index;
316   key_mp->context = ntohl (0xfeedface);
317   key_mp->key_len = clib_host_to_net_u16 (test_srv_key_rsa_len);
318   clib_memcpy_fast (key_mp->key, test_srv_key_rsa, test_srv_key_rsa_len);
319   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & key_mp);
320 }
321
322 static int
323 application_attach (echo_main_t * em)
324 {
325   application_send_attach (em);
326   if (wait_for_state_change (em, STATE_ATTACHED))
327     {
328       clib_warning ("timeout waiting for STATE_ATTACHED");
329       return -1;
330     }
331   return 0;
332 }
333
334 void
335 application_detach (echo_main_t * em)
336 {
337   vl_api_application_detach_t *bmp;
338   bmp = vl_msg_api_alloc (sizeof (*bmp));
339   clib_memset (bmp, 0, sizeof (*bmp));
340
341   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
342   bmp->client_index = em->my_client_index;
343   bmp->context = ntohl (0xfeedface);
344   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp);
345
346   DBG ("%s", "Sent detach");
347 }
348
349 static int
350 ssvm_segment_attach (char *name, ssvm_segment_type_t type, int fd)
351 {
352   fifo_segment_create_args_t _a, *a = &_a;
353   fifo_segment_main_t *sm = &echo_main.segment_main;
354   int rv;
355
356   clib_memset (a, 0, sizeof (*a));
357   a->segment_name = (char *) name;
358   a->segment_type = type;
359
360   if (type == SSVM_SEGMENT_MEMFD)
361     a->memfd_fd = fd;
362
363   if ((rv = fifo_segment_attach (sm, a)))
364     {
365       clib_warning ("svm_fifo_segment_attach ('%s') failed", name);
366       return rv;
367     }
368   vec_reset_length (a->new_segment_indices);
369   return 0;
370 }
371
372 static void
373 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
374                                            mp)
375 {
376   echo_main_t *em = &echo_main;
377   int *fds = 0;
378   u32 n_fds = 0;
379   u64 segment_handle;
380   segment_handle = clib_net_to_host_u64 (mp->segment_handle);
381   DBG ("Attached returned app %u", htons (mp->app_index));
382
383   if (mp->retval)
384     {
385       clib_warning ("attach failed: %U", format_api_error,
386                     clib_net_to_host_u32 (mp->retval));
387       goto failed;
388     }
389
390   if (mp->segment_name_length == 0)
391     {
392       clib_warning ("segment_name_length zero");
393       goto failed;
394     }
395
396   ASSERT (mp->app_event_queue_address);
397   em->our_event_queue = uword_to_pointer (mp->app_event_queue_address,
398                                           svm_msg_q_t *);
399
400   if (mp->n_fds)
401     {
402       vec_validate (fds, mp->n_fds);
403       vl_socket_client_recv_fd_msg (fds, mp->n_fds, 5);
404
405       if (mp->fd_flags & SESSION_FD_F_VPP_MQ_SEGMENT)
406         if (ssvm_segment_attach (0, SSVM_SEGMENT_MEMFD, fds[n_fds++]))
407           goto failed;
408
409       if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT)
410         if (ssvm_segment_attach ((char *) mp->segment_name,
411                                  SSVM_SEGMENT_MEMFD, fds[n_fds++]))
412           goto failed;
413
414       if (mp->fd_flags & SESSION_FD_F_MQ_EVENTFD)
415         svm_msg_q_set_consumer_eventfd (em->our_event_queue, fds[n_fds++]);
416
417       vec_free (fds);
418     }
419   else
420     {
421       if (ssvm_segment_attach ((char *) mp->segment_name, SSVM_SEGMENT_SHM,
422                                -1))
423         goto failed;
424     }
425   clib_spinlock_lock (&em->segment_handles_lock);
426   hash_set (em->shared_segment_handles, segment_handle, 1);
427   clib_spinlock_unlock (&em->segment_handles_lock);
428   DBG ("Mapped new segment %lx", segment_handle);
429
430   em->state = STATE_ATTACHED;
431   return;
432 failed:
433   em->state = STATE_FAILED;
434   return;
435 }
436
437 static void
438 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
439                                            mp)
440 {
441   if (mp->retval)
442     clib_warning ("detach returned with err: %d", mp->retval);
443   echo_main.state = STATE_DETACHED;
444 }
445
446 static void
447 stop_signal (int signum)
448 {
449   echo_main_t *um = &echo_main;
450   um->time_to_stop = 1;
451 }
452
453 static void
454 stats_signal (int signum)
455 {
456   echo_main_t *um = &echo_main;
457   um->time_to_print_stats = 1;
458 }
459
460 static clib_error_t *
461 setup_signal_handlers (void)
462 {
463   signal (SIGUSR2, stats_signal);
464   signal (SIGINT, stop_signal);
465   signal (SIGQUIT, stop_signal);
466   signal (SIGTERM, stop_signal);
467   return 0;
468 }
469
470 void
471 vlib_cli_output (struct vlib_main_t *vm, char *fmt, ...)
472 {
473   clib_warning ("BUG");
474 }
475
476 int
477 connect_to_vpp (char *name)
478 {
479   echo_main_t *em = &echo_main;
480   api_main_t *am = &api_main;
481
482   if (em->use_sock_api)
483     {
484       if (vl_socket_client_connect ((char *) em->socket_name, name,
485                                     0 /* default rx, tx buffer */ ))
486         {
487           clib_warning ("socket connect failed");
488           return -1;
489         }
490
491       if (vl_socket_client_init_shm (0, 1 /* want_pthread */ ))
492         {
493           clib_warning ("init shm api failed");
494           return -1;
495         }
496     }
497   else
498     {
499       if (vl_client_connect_to_vlib ("/vpe-api", name, 32) < 0)
500         {
501           clib_warning ("shmem connect failed");
502           return -1;
503         }
504     }
505   em->vl_input_queue = am->shmem_hdr->vl_input_queue;
506   em->my_client_index = am->my_client_index;
507   return 0;
508 }
509
510 void
511 disconnect_from_vpp (echo_main_t * em)
512 {
513   if (em->use_sock_api)
514     vl_socket_client_disconnect ();
515   else
516     vl_client_disconnect_from_vlib ();
517 }
518
519 static void
520 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
521 {
522   fifo_segment_main_t *sm = &echo_main.segment_main;
523   fifo_segment_create_args_t _a, *a = &_a;
524   echo_main_t *em = &echo_main;
525   int rv;
526   int *fds = 0;
527   u64 segment_handle;
528   segment_handle = clib_net_to_host_u64 (mp->segment_handle);
529
530   if (mp->fd_flags & SESSION_FD_F_MEMFD_SEGMENT)
531     {
532       vec_validate (fds, 1);
533       vl_socket_client_recv_fd_msg (fds, 1, 5);
534       if (ssvm_segment_attach
535           ((char *) mp->segment_name, SSVM_SEGMENT_MEMFD, fds[0]))
536         clib_warning
537           ("svm_fifo_segment_attach ('%s') failed on SSVM_SEGMENT_MEMFD",
538            mp->segment_name);
539       clib_spinlock_lock (&em->segment_handles_lock);
540       hash_set (em->shared_segment_handles, segment_handle, 1);
541       clib_spinlock_unlock (&em->segment_handles_lock);
542       vec_free (fds);
543       DBG ("Mapped new segment %lx", segment_handle);
544       return;
545     }
546
547   clib_memset (a, 0, sizeof (*a));
548   a->segment_name = (char *) mp->segment_name;
549   a->segment_size = mp->segment_size;
550   /* Attach to the segment vpp created */
551   rv = fifo_segment_attach (sm, a);
552   if (rv)
553     {
554       clib_warning ("svm_fifo_segment_attach ('%s') failed",
555                     mp->segment_name);
556       return;
557     }
558   clib_spinlock_lock (&em->segment_handles_lock);
559   hash_set (em->shared_segment_handles, mp->segment_name, 1);
560   clib_spinlock_unlock (&em->segment_handles_lock);
561   clib_warning ("Mapped new segment '%s' size %d", mp->segment_name,
562                 mp->segment_size);
563 }
564
565 static void
566 session_print_stats (echo_main_t * em, echo_session_t * session)
567 {
568   f64 deltat;
569   u64 bytes;
570
571   deltat = clib_time_now (&em->clib_time) - session->start;
572   bytes = em->i_am_master ? session->bytes_received : em->bytes_to_send;
573   fformat (stdout, "Finished in %.6f\n", deltat);
574   fformat (stdout, "%.4f Gbit/second\n", (bytes * 8.0) / deltat / 1e9);
575 }
576
577 static void
578 test_recv_bytes (echo_main_t * em, echo_session_t * s, u8 * rx_buf,
579                  u32 n_read)
580 {
581   int i;
582   for (i = 0; i < n_read; i++)
583     {
584       if (rx_buf[i] != ((s->bytes_received + i) & 0xff)
585           && em->max_test_msg > 0)
586         {
587           clib_warning ("error at byte %lld, 0x%x not 0x%x",
588                         s->bytes_received + i, rx_buf[i],
589                         ((s->bytes_received + i) & 0xff));
590           em->max_test_msg--;
591           if (em->max_test_msg == 0)
592             clib_warning ("Too many errors, hiding next ones");
593         }
594     }
595 }
596
597 static void
598 recv_data_chunk (echo_main_t * em, echo_session_t * s, u8 * rx_buf)
599 {
600   int n_to_read, n_read;
601
602   n_to_read = svm_fifo_max_dequeue (s->rx_fifo);
603   if (!n_to_read)
604     return;
605
606   do
607     {
608       n_read = app_recv_stream ((app_session_t *) s, rx_buf,
609                                 vec_len (rx_buf));
610
611       if (n_read > 0)
612         {
613           if (em->test_return_packets)
614             test_recv_bytes (em, s, rx_buf, n_read);
615
616           n_to_read -= n_read;
617
618           s->bytes_received += n_read;
619           ASSERT (s->bytes_to_receive >= n_read);
620           s->bytes_to_receive -= n_read;
621         }
622       else
623         break;
624     }
625   while (n_to_read > 0);
626 }
627
628 static void
629 send_data_chunk (echo_main_t * em, echo_session_t * s)
630 {
631   u64 test_buf_len, bytes_this_chunk, test_buf_offset;
632   u8 *test_data = em->connect_test_data;
633   int n_sent;
634
635   test_buf_len = vec_len (test_data);
636   test_buf_offset = s->bytes_sent % test_buf_len;
637   bytes_this_chunk = clib_min (test_buf_len - test_buf_offset,
638                                s->bytes_to_send);
639
640   n_sent = app_send_stream ((app_session_t *) s, test_data + test_buf_offset,
641                             bytes_this_chunk, 0);
642
643   if (n_sent > 0)
644     {
645       s->bytes_to_send -= n_sent;
646       s->bytes_sent += n_sent;
647     }
648 }
649
650 /*
651  * Rx/Tx polling thread per connection
652  */
653 static void *
654 client_thread_fn (void *arg)
655 {
656   echo_main_t *em = &echo_main;
657   static u8 *rx_buf = 0;
658   u32 session_index = *(u32 *) arg;
659   echo_session_t *s;
660
661   vec_validate (rx_buf, 1 << 20);
662
663   while (!em->time_to_stop && em->state != STATE_READY)
664     ;
665
666   s = pool_elt_at_index (em->sessions, session_index);
667   while (!em->time_to_stop)
668     {
669       send_data_chunk (em, s);
670       recv_data_chunk (em, s, rx_buf);
671       if (!s->bytes_to_send && !s->bytes_to_receive)
672         break;
673     }
674
675   DBG ("session %d done send %lu to do, %lu done || recv %lu to do, %lu done",
676        session_index, s->bytes_to_send, s->bytes_sent, s->bytes_to_receive,
677        s->bytes_received);
678   em->tx_total += s->bytes_sent;
679   em->rx_total += s->bytes_received;
680   em->n_active_clients--;
681
682   pthread_exit (0);
683 }
684
685 void
686 client_send_connect (echo_main_t * em, u8 * uri, u32 opaque)
687 {
688   vl_api_connect_uri_t *cmp;
689   cmp = vl_msg_api_alloc (sizeof (*cmp));
690   clib_memset (cmp, 0, sizeof (*cmp));
691
692   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_URI);
693   cmp->client_index = em->my_client_index;
694   cmp->context = ntohl (opaque);
695   memcpy (cmp->uri, uri, vec_len (uri));
696   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & cmp);
697 }
698
699 void
700 client_send_disconnect (echo_main_t * em, echo_session_t * s)
701 {
702   vl_api_disconnect_session_t *dmp;
703   dmp = vl_msg_api_alloc (sizeof (*dmp));
704   clib_memset (dmp, 0, sizeof (*dmp));
705   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
706   dmp->client_index = em->my_client_index;
707   dmp->handle = s->vpp_session_handle;
708   DBG ("Sending Session disonnect handle %lu", dmp->handle);
709   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & dmp);
710 }
711
712 int
713 client_disconnect (echo_main_t * em, echo_session_t * s)
714 {
715   client_send_disconnect (em, s);
716   pool_put (em->sessions, s);
717   clib_memset (s, 0xfe, sizeof (*s));
718   return 0;
719 }
720
721 static void
722 session_bound_handler (session_bound_msg_t * mp)
723 {
724   echo_main_t *em = &echo_main;
725
726   if (mp->retval)
727     {
728       clib_warning ("bind failed: %U", format_api_error,
729                     clib_net_to_host_u32 (mp->retval));
730       em->state = STATE_FAILED;
731       return;
732     }
733
734   clib_warning ("listening on %U:%u", format_ip46_address, mp->lcl_ip,
735                 mp->lcl_is_ip4 ? IP46_TYPE_IP4 : IP46_TYPE_IP6,
736                 clib_net_to_host_u16 (mp->lcl_port));
737   em->state = STATE_READY;
738 }
739
740 static void
741 quic_qsession_accepted_handler (session_accepted_msg_t * mp)
742 {
743   DBG ("Accept on QSession index %u", mp->handle);
744 }
745
746
747 static void
748 session_accepted_handler (session_accepted_msg_t * mp)
749 {
750   app_session_evt_t _app_evt, *app_evt = &_app_evt;
751   session_accepted_reply_msg_t *rmp;
752   svm_fifo_t *rx_fifo, *tx_fifo;
753   echo_main_t *em = &echo_main;
754   echo_session_t *session;
755   static f64 start_time;
756   u32 session_index;
757   u64 segment_handle;
758   u8 *ip_str;
759
760   segment_handle = mp->segment_handle;
761
762   if (start_time == 0.0)
763     start_time = clib_time_now (&em->clib_time);
764
765   ip_str = format (0, "%U", format_ip46_address, &mp->rmt.ip, mp->rmt.is_ip4);
766   clib_warning ("Accepted session from: %s:%d", ip_str,
767                 clib_net_to_host_u16 (mp->rmt.port));
768
769   /* Allocate local session and set it up */
770   pool_get (em->sessions, session);
771   session_index = session - em->sessions;
772
773   if (wait_for_segment_allocation (segment_handle))
774     {
775       clib_warning ("timeout waiting for segment allocation %lu",
776                     segment_handle);
777       return;
778     }
779   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
780   rx_fifo->client_session_index = session_index;
781   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
782   tx_fifo->client_session_index = session_index;
783
784   session->rx_fifo = rx_fifo;
785   session->tx_fifo = tx_fifo;
786   session->vpp_session_handle = mp->handle;
787   session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
788                                          svm_msg_q_t *);
789
790   /* Add it to lookup table */
791   DBG ("Accepted session handle %lx, idx %lu", mp->handle, session_index);
792   hash_set (em->session_index_by_vpp_handles, mp->handle, session_index);
793
794   /*
795    * Send accept reply to vpp
796    */
797   app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt,
798                              SESSION_CTRL_EVT_ACCEPTED_REPLY);
799   rmp = (session_accepted_reply_msg_t *) app_evt->evt->data;
800   rmp->handle = mp->handle;
801   rmp->context = mp->context;
802   app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt);
803
804   /* TODO : this is very ugly */
805   if (mp->rmt.is_ip4 != 255)
806     return quic_qsession_accepted_handler (mp);
807   DBG ("SSession handle is %lu", mp->handle);
808
809   em->state = STATE_READY;
810
811   /* Stats printing */
812   if (pool_elts (em->sessions) && (pool_elts (em->sessions) % 20000) == 0)
813     {
814       f64 now = clib_time_now (&em->clib_time);
815       fformat (stdout, "%d active sessions in %.2f seconds, %.2f/sec...\n",
816                pool_elts (em->sessions), now - start_time,
817                (f64) pool_elts (em->sessions) / (now - start_time));
818     }
819
820   session->bytes_received = 0;
821   session->start = clib_time_now (&em->clib_time);
822 }
823
824 static void
825 quic_session_connected_handler (session_connected_msg_t * mp)
826 {
827   echo_main_t *em = &echo_main;
828   u8 *uri = format (0, "QUIC://session/%lu", mp->handle);
829   DBG ("QSession Connect : %s", uri);
830   client_send_connect (em, uri, QUIC_SESSION_TYPE_STREAM);
831 }
832
833 static void
834 session_connected_handler (session_connected_msg_t * mp)
835 {
836   echo_main_t *em = &echo_main;
837   echo_session_t *session;
838   u32 session_index;
839   svm_fifo_t *rx_fifo, *tx_fifo;
840   int rv;
841   u64 segment_handle;
842   segment_handle = mp->segment_handle;
843
844   if (mp->retval)
845     {
846       clib_warning ("connection failed with code: %U", format_api_error,
847                     clib_net_to_host_u32 (mp->retval));
848       em->state = STATE_FAILED;
849       return;
850     }
851
852   /*
853    * Setup session
854    */
855
856   pool_get (em->sessions, session);
857   clib_memset (session, 0, sizeof (*session));
858   session_index = session - em->sessions;
859   DBG ("Setting session_index %lu", session_index);
860
861   if (wait_for_segment_allocation (segment_handle))
862     {
863       clib_warning ("timeout waiting for segment allocation %lu",
864                     segment_handle);
865       return;
866     }
867   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
868   rx_fifo->client_session_index = session_index;
869   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
870   tx_fifo->client_session_index = session_index;
871
872   session->rx_fifo = rx_fifo;
873   session->tx_fifo = tx_fifo;
874   session->vpp_session_handle = mp->handle;
875   session->start = clib_time_now (&em->clib_time);
876   session->vpp_evt_q = uword_to_pointer (mp->vpp_event_queue_address,
877                                          svm_msg_q_t *);
878
879   DBG ("Connected session handle %lx, idx %lu", mp->handle, session_index);
880   hash_set (em->session_index_by_vpp_handles, mp->handle, session_index);
881
882   if (mp->context == QUIC_SESSION_TYPE_QUIC)
883     return quic_session_connected_handler (mp);
884
885   DBG ("SSession Connected");
886
887   /*
888    * Start RX thread
889    */
890   em->thread_args[em->n_clients_connected] = session_index;
891   rv = pthread_create (&em->client_thread_handles[em->n_clients_connected],
892                        NULL /*attr */ , client_thread_fn,
893                        (void *) &em->thread_args[em->n_clients_connected]);
894   if (rv)
895     {
896       clib_warning ("pthread_create returned %d", rv);
897       return;
898     }
899
900   em->n_clients_connected += 1;
901   clib_warning ("session %u (0x%llx) connected with local ip %U port %d",
902                 session_index, mp->handle, format_ip46_address, &mp->lcl.ip,
903                 mp->lcl.is_ip4, clib_net_to_host_u16 (mp->lcl.port));
904 }
905
906 static void
907 session_disconnected_handler (session_disconnected_msg_t * mp)
908 {
909   app_session_evt_t _app_evt, *app_evt = &_app_evt;
910   session_disconnected_reply_msg_t *rmp;
911   echo_main_t *em = &echo_main;
912   echo_session_t *session = 0;
913   uword *p;
914   int rv = 0;
915   DBG ("Disonnected session handle %lx", mp->handle);
916   p = hash_get (em->session_index_by_vpp_handles, mp->handle);
917   if (!p)
918     {
919       clib_warning ("couldn't find session key %llx", mp->handle);
920       return;
921     }
922
923   session = pool_elt_at_index (em->sessions, p[0]);
924   hash_unset (em->session_index_by_vpp_handles, mp->handle);
925
926   pool_put (em->sessions, session);
927
928   app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt,
929                              SESSION_CTRL_EVT_DISCONNECTED_REPLY);
930   rmp = (session_disconnected_reply_msg_t *) app_evt->evt->data;
931   rmp->retval = rv;
932   rmp->handle = mp->handle;
933   rmp->context = mp->context;
934   app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt);
935
936   session_print_stats (em, session);
937 }
938
939 static void
940 session_reset_handler (session_reset_msg_t * mp)
941 {
942   app_session_evt_t _app_evt, *app_evt = &_app_evt;
943   echo_main_t *em = &echo_main;
944   session_reset_reply_msg_t *rmp;
945   echo_session_t *session = 0;
946   uword *p;
947   int rv = 0;
948
949   DBG ("Reset session handle %lx", mp->handle);
950   p = hash_get (em->session_index_by_vpp_handles, mp->handle);
951
952   if (p)
953     {
954       session = pool_elt_at_index (em->sessions, p[0]);
955       clib_warning ("got reset");
956       /* Cleanup later */
957       em->time_to_stop = 1;
958     }
959   else
960     {
961       clib_warning ("couldn't find session key %llx", mp->handle);
962       return;
963     }
964
965   app_alloc_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt,
966                              SESSION_CTRL_EVT_RESET_REPLY);
967   rmp = (session_reset_reply_msg_t *) app_evt->evt->data;
968   rmp->retval = rv;
969   rmp->handle = mp->handle;
970   app_send_ctrl_evt_to_vpp (session->vpp_evt_q, app_evt);
971 }
972
973 static void
974 handle_mq_event (session_event_t * e)
975 {
976   switch (e->event_type)
977     {
978     case SESSION_CTRL_EVT_BOUND:
979       DBG ("SESSION_CTRL_EVT_BOUND");
980       session_bound_handler ((session_bound_msg_t *) e->data);
981       break;
982     case SESSION_CTRL_EVT_ACCEPTED:
983       DBG ("SESSION_CTRL_EVT_ACCEPTED");
984       session_accepted_handler ((session_accepted_msg_t *) e->data);
985       break;
986     case SESSION_CTRL_EVT_CONNECTED:
987       DBG ("SESSION_CTRL_EVT_CONNECTED");
988       session_connected_handler ((session_connected_msg_t *) e->data);
989       break;
990     case SESSION_CTRL_EVT_DISCONNECTED:
991       DBG ("SESSION_CTRL_EVT_DISCONNECTED");
992       session_disconnected_handler ((session_disconnected_msg_t *) e->data);
993       break;
994     case SESSION_CTRL_EVT_RESET:
995       DBG ("SESSION_CTRL_EVT_RESET");
996       session_reset_handler ((session_reset_msg_t *) e->data);
997       break;
998     default:
999       clib_warning ("unhandled %u", e->event_type);
1000     }
1001 }
1002
1003 static void
1004 clients_run (echo_main_t * em)
1005 {
1006   f64 start_time, deltat, timeout = 100.0;
1007   svm_msg_q_msg_t msg;
1008   session_event_t *e;
1009   echo_session_t *s;
1010   hash_pair_t *p;
1011   int i;
1012
1013   /* Init test data */
1014   vec_validate (em->connect_test_data, 1024 * 1024 - 1);
1015   for (i = 0; i < vec_len (em->connect_test_data); i++)
1016     em->connect_test_data[i] = i & 0xff;
1017
1018   /*
1019    * Attach and connect the clients
1020    */
1021   if (application_attach (em))
1022     return;
1023
1024   for (i = 0; i < em->n_clients; i++)
1025     client_send_connect (em, em->connect_uri, QUIC_SESSION_TYPE_QUIC);
1026
1027   start_time = clib_time_now (&em->clib_time);
1028   while (em->n_clients_connected < em->n_clients
1029          && (clib_time_now (&em->clib_time) - start_time < timeout)
1030          && em->state != STATE_FAILED && em->time_to_stop != 1)
1031
1032     {
1033       int rc = svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_TIMEDWAIT, 1);
1034       if (rc == ETIMEDOUT && em->time_to_stop)
1035         break;
1036       if (rc == ETIMEDOUT)
1037         continue;
1038       e = svm_msg_q_msg_data (em->our_event_queue, &msg);
1039       handle_mq_event (e);
1040       svm_msg_q_free_msg (em->our_event_queue, &msg);
1041     }
1042
1043   if (em->n_clients_connected != em->n_clients)
1044     {
1045       clib_warning ("failed to initialize all connections");
1046       return;
1047     }
1048
1049   /*
1050    * Initialize connections
1051    */
1052   DBG ("Initialize connections on %u clients", em->n_clients);
1053
1054   /* *INDENT-OFF* */
1055   hash_foreach_pair (p, em->session_index_by_vpp_handles,
1056                 ({
1057       s = pool_elt_at_index (em->sessions, p->value[0]);
1058       s->bytes_to_send = em->bytes_to_send;
1059       if (!em->no_return)
1060         s->bytes_to_receive = em->bytes_to_send;
1061                 }));
1062   /* *INDENT-ON* */
1063   em->n_active_clients = em->n_clients_connected;
1064
1065   /*
1066    * Wait for client threads to send the data
1067    */
1068   DBG ("Waiting for data on %u clients", em->n_active_clients);
1069   start_time = clib_time_now (&em->clib_time);
1070   em->state = STATE_READY;
1071   while (em->n_active_clients)
1072     if (!svm_msg_q_is_empty (em->our_event_queue))
1073       {
1074         if (svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_TIMEDWAIT, 0))
1075           {
1076             clib_warning ("svm msg q returned");
1077             continue;
1078           }
1079         e = svm_msg_q_msg_data (em->our_event_queue, &msg);
1080         if (e->event_type != FIFO_EVENT_APP_RX)
1081           handle_mq_event (e);
1082         svm_msg_q_free_msg (em->our_event_queue, &msg);
1083       }
1084
1085   /* *INDENT-OFF* */
1086   hash_foreach_pair (p, em->session_index_by_vpp_handles,
1087                 ({
1088       s = pool_elt_at_index (em->sessions, p->value[0]);
1089       DBG ("Sending disconnect on session %lu", p->key);
1090       client_disconnect (em, s);
1091                 }));
1092   /* *INDENT-ON* */
1093
1094   /*
1095    * Stats and detach
1096    */
1097   deltat = clib_time_now (&em->clib_time) - start_time;
1098   fformat (stdout, "%lld bytes (%lld mbytes, %lld gbytes) in %.2f seconds\n",
1099            em->tx_total, em->tx_total / (1ULL << 20),
1100            em->tx_total / (1ULL << 30), deltat);
1101   fformat (stdout, "%.4f Gbit/second\n", (em->tx_total * 8.0) / deltat / 1e9);
1102
1103   wait_for_disconnected_sessions (em);
1104   application_detach (em);
1105 }
1106
1107 static void
1108 vl_api_bind_uri_reply_t_handler (vl_api_bind_uri_reply_t * mp)
1109 {
1110   echo_main_t *em = &echo_main;
1111
1112   if (mp->retval)
1113     {
1114       clib_warning ("bind failed: %U", format_api_error,
1115                     clib_net_to_host_u32 (mp->retval));
1116       em->state = STATE_FAILED;
1117       return;
1118     }
1119
1120   em->state = STATE_READY;
1121 }
1122
1123 static void
1124 vl_api_unbind_uri_reply_t_handler (vl_api_unbind_uri_reply_t * mp)
1125 {
1126   echo_main_t *em = &echo_main;
1127
1128   if (mp->retval != 0)
1129     clib_warning ("returned %d", ntohl (mp->retval));
1130
1131   em->state = STATE_START;
1132 }
1133
1134 u8 *
1135 format_ip4_address (u8 * s, va_list * args)
1136 {
1137   u8 *a = va_arg (*args, u8 *);
1138   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
1139 }
1140
1141 u8 *
1142 format_ip6_address (u8 * s, va_list * args)
1143 {
1144   ip6_address_t *a = va_arg (*args, ip6_address_t *);
1145   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
1146
1147   i_max_n_zero = ARRAY_LEN (a->as_u16);
1148   max_n_zeros = 0;
1149   i_first_zero = i_max_n_zero;
1150   n_zeros = 0;
1151   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
1152     {
1153       u32 is_zero = a->as_u16[i] == 0;
1154       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
1155         {
1156           i_first_zero = i;
1157           n_zeros = 0;
1158         }
1159       n_zeros += is_zero;
1160       if ((!is_zero && n_zeros > max_n_zeros)
1161           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
1162         {
1163           i_max_n_zero = i_first_zero;
1164           max_n_zeros = n_zeros;
1165           i_first_zero = ARRAY_LEN (a->as_u16);
1166           n_zeros = 0;
1167         }
1168     }
1169
1170   last_double_colon = 0;
1171   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
1172     {
1173       if (i == i_max_n_zero && max_n_zeros > 1)
1174         {
1175           s = format (s, "::");
1176           i += max_n_zeros - 1;
1177           last_double_colon = 1;
1178         }
1179       else
1180         {
1181           s = format (s, "%s%x",
1182                       (last_double_colon || i == 0) ? "" : ":",
1183                       clib_net_to_host_u16 (a->as_u16[i]));
1184           last_double_colon = 0;
1185         }
1186     }
1187
1188   return s;
1189 }
1190
1191 /* Format an IP46 address. */
1192 u8 *
1193 format_ip46_address (u8 * s, va_list * args)
1194 {
1195   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
1196   ip46_type_t type = va_arg (*args, ip46_type_t);
1197   int is_ip4 = 1;
1198
1199   switch (type)
1200     {
1201     case IP46_TYPE_ANY:
1202       is_ip4 = ip46_address_is_ip4 (ip46);
1203       break;
1204     case IP46_TYPE_IP4:
1205       is_ip4 = 1;
1206       break;
1207     case IP46_TYPE_IP6:
1208       is_ip4 = 0;
1209       break;
1210     }
1211
1212   return is_ip4 ?
1213     format (s, "%U", format_ip4_address, &ip46->ip4) :
1214     format (s, "%U", format_ip6_address, &ip46->ip6);
1215 }
1216
1217 static void
1218 server_handle_rx (echo_main_t * em, session_event_t * e)
1219 {
1220   int n_read, max_dequeue, n_sent;
1221   u32 offset, to_dequeue;
1222   echo_session_t *s;
1223   s = pool_elt_at_index (em->sessions, e->session_index);
1224
1225   /* Clear event only once. Otherwise, if we do it in the loop by calling
1226    * app_recv_stream, we may end up with a lot of unhandled rx events on the
1227    * message queue */
1228   svm_fifo_unset_event (s->rx_fifo);
1229
1230   max_dequeue = svm_fifo_max_dequeue (s->rx_fifo);
1231   if (PREDICT_FALSE (!max_dequeue))
1232     return;
1233   do
1234     {
1235       /* The options here are to limit ourselves to max_dequeue or read
1236        * even the data that was enqueued while we were dequeueing and which
1237        * now has an rx event in the mq. Either of the two work. */
1238       to_dequeue = clib_min (max_dequeue, vec_len (em->rx_buf));
1239       n_read = app_recv_stream_raw (s->rx_fifo, em->rx_buf, to_dequeue,
1240                                     0 /* clear evt */ , 0 /* peek */ );
1241
1242       if (n_read > 0)
1243         {
1244           if (em->test_return_packets)
1245             test_recv_bytes (em, s, em->rx_buf, n_read);
1246
1247           max_dequeue -= n_read;
1248           s->bytes_received += n_read;
1249         }
1250       else
1251         break;
1252
1253       /* Reflect if a non-drop session */
1254       if (!em->no_return && n_read > 0)
1255         {
1256           offset = 0;
1257           do
1258             {
1259               n_sent = app_send_stream ((app_session_t *) s,
1260                                         &em->rx_buf[offset],
1261                                         n_read, SVM_Q_WAIT);
1262               if (n_sent > 0)
1263                 {
1264                   n_read -= n_sent;
1265                   offset += n_sent;
1266                 }
1267             }
1268           while ((n_sent <= 0 || n_read > 0) && !em->time_to_stop);
1269         }
1270     }
1271   while (max_dequeue > 0 && !em->time_to_stop);
1272 }
1273
1274 static void
1275 server_handle_mq (echo_main_t * em)
1276 {
1277   svm_msg_q_msg_t msg;
1278   session_event_t *e;
1279
1280   while (1)
1281     {
1282       int rc = svm_msg_q_sub (em->our_event_queue, &msg, SVM_Q_TIMEDWAIT, 1);
1283       if (PREDICT_FALSE (rc == ETIMEDOUT && em->time_to_stop))
1284         break;
1285       if (PREDICT_FALSE (em->time_to_print_stats == 1))
1286         {
1287           em->time_to_print_stats = 0;
1288           fformat (stdout, "%d connections\n", pool_elts (em->sessions));
1289         }
1290       if (rc == ETIMEDOUT)
1291         continue;
1292       e = svm_msg_q_msg_data (em->our_event_queue, &msg);
1293       switch (e->event_type)
1294         {
1295         case SESSION_IO_EVT_RX:
1296           DBG ("SESSION_IO_EVT_RX");
1297           server_handle_rx (em, e);
1298           break;
1299         default:
1300           handle_mq_event (e);
1301           break;
1302         }
1303       svm_msg_q_free_msg (em->our_event_queue, &msg);
1304     }
1305 }
1306
1307 void
1308 server_send_listen (echo_main_t * em)
1309 {
1310   vl_api_bind_uri_t *bmp;
1311   bmp = vl_msg_api_alloc (sizeof (*bmp));
1312   clib_memset (bmp, 0, sizeof (*bmp));
1313
1314   bmp->_vl_msg_id = ntohs (VL_API_BIND_URI);
1315   bmp->client_index = em->my_client_index;
1316   bmp->context = ntohl (0xfeedface);
1317   memcpy (bmp->uri, em->uri, vec_len (em->uri));
1318   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & bmp);
1319 }
1320
1321 int
1322 server_listen (echo_main_t * em)
1323 {
1324   server_send_listen (em);
1325   if (wait_for_state_change (em, STATE_READY))
1326     {
1327       clib_warning ("timeout waiting for STATE_READY");
1328       return -1;
1329     }
1330   return 0;
1331 }
1332
1333 void
1334 server_send_unbind (echo_main_t * em)
1335 {
1336   vl_api_unbind_uri_t *ump;
1337
1338   ump = vl_msg_api_alloc (sizeof (*ump));
1339   clib_memset (ump, 0, sizeof (*ump));
1340
1341   ump->_vl_msg_id = ntohs (VL_API_UNBIND_URI);
1342   ump->client_index = em->my_client_index;
1343   memcpy (ump->uri, em->uri, vec_len (em->uri));
1344   vl_msg_api_send_shmem (em->vl_input_queue, (u8 *) & ump);
1345 }
1346
1347 void
1348 server_run (echo_main_t * em)
1349 {
1350   echo_session_t *session;
1351   int i;
1352
1353   /* $$$$ hack preallocation */
1354   for (i = 0; i < 200000; i++)
1355     {
1356       pool_get (em->sessions, session);
1357       clib_memset (session, 0, sizeof (*session));
1358     }
1359   for (i = 0; i < 200000; i++)
1360     pool_put_index (em->sessions, i);
1361
1362   if (application_attach (em))
1363     return;
1364
1365   /* Bind to uri */
1366   if (server_listen (em))
1367     return;
1368
1369   /* Enter handle event loop */
1370   server_handle_mq (em);
1371
1372   /* Cleanup */
1373   server_send_unbind (em);
1374
1375   application_detach (em);
1376
1377   fformat (stdout, "Test complete...\n");
1378 }
1379
1380 static void
1381 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
1382                                            mp)
1383 {
1384   echo_main_t *em = &echo_main;
1385   uword *p;
1386   DBG ("Got disonnected reply for session handle %lu", mp->handle);
1387
1388   if (mp->retval)
1389     {
1390       clib_warning ("vpp complained about disconnect: %d",
1391                     ntohl (mp->retval));
1392       return;
1393     }
1394
1395   em->state = STATE_START;
1396
1397   p = hash_get (em->session_index_by_vpp_handles, mp->handle);
1398   if (p)
1399     {
1400       hash_unset (em->session_index_by_vpp_handles, mp->handle);
1401     }
1402   else
1403     {
1404       clib_warning ("couldn't find session key %llx", mp->handle);
1405     }
1406 }
1407
1408 static void
1409   vl_api_application_tls_cert_add_reply_t_handler
1410   (vl_api_application_tls_cert_add_reply_t * mp)
1411 {
1412   if (mp->retval)
1413     clib_warning ("failed to add tls cert");
1414 }
1415
1416 static void
1417   vl_api_application_tls_key_add_reply_t_handler
1418   (vl_api_application_tls_key_add_reply_t * mp)
1419 {
1420   if (mp->retval)
1421     clib_warning ("failed to add tls key");
1422 }
1423
1424 #define foreach_quic_echo_msg                                           \
1425 _(BIND_URI_REPLY, bind_uri_reply)                                       \
1426 _(UNBIND_URI_REPLY, unbind_uri_reply)                                   \
1427 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)                   \
1428 _(APPLICATION_ATTACH_REPLY, application_attach_reply)                   \
1429 _(APPLICATION_DETACH_REPLY, application_detach_reply)                   \
1430 _(MAP_ANOTHER_SEGMENT, map_another_segment)                             \
1431 _(APPLICATION_TLS_CERT_ADD_REPLY, application_tls_cert_add_reply)       \
1432 _(APPLICATION_TLS_KEY_ADD_REPLY, application_tls_key_add_reply)         \
1433
1434 void
1435 quic_echo_api_hookup (echo_main_t * em)
1436 {
1437 #define _(N,n)                                                  \
1438     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1439                            vl_api_##n##_t_handler,              \
1440                            vl_noop_handler,                     \
1441                            vl_api_##n##_t_endian,               \
1442                            vl_api_##n##_t_print,                \
1443                            sizeof(vl_api_##n##_t), 1);
1444   foreach_quic_echo_msg;
1445 #undef _
1446 }
1447
1448 int
1449 main (int argc, char **argv)
1450 {
1451   int i_am_server = 1, test_return_packets = 0;
1452   echo_main_t *em = &echo_main;
1453   fifo_segment_main_t *sm = &em->segment_main;
1454   unformat_input_t _argv, *a = &_argv;
1455   u8 *chroot_prefix;
1456   u8 *uri = 0;
1457   u8 *bind_uri = (u8 *) "quic://0.0.0.0/1234";
1458   u8 *connect_uri = (u8 *) "quic://6.0.1.1/1234";
1459   u64 bytes_to_send = 64 << 10, mbytes;
1460   char *app_name;
1461   u32 tmp;
1462
1463   clib_mem_init_thread_safe (0, 256 << 20);
1464
1465   clib_memset (em, 0, sizeof (*em));
1466   em->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1467   em->shared_segment_handles = hash_create (0, sizeof (uword));
1468   clib_spinlock_init (&em->segment_handles_lock);
1469   em->my_pid = getpid ();
1470   em->socket_name = 0;
1471   em->use_sock_api = 1;
1472   em->fifo_size = 64 << 10;
1473   em->n_clients = 1;
1474   em->max_test_msg = 50;
1475   em->quic_streams = 1;
1476
1477   clib_time_init (&em->clib_time);
1478   init_error_string_table (em);
1479   fifo_segment_main_init (sm, HIGH_SEGMENT_BASEVA, 20);
1480   unformat_init_command_line (a, argv);
1481
1482   while (unformat_check_input (a) != UNFORMAT_END_OF_INPUT)
1483     {
1484       if (unformat (a, "chroot prefix %s", &chroot_prefix))
1485         {
1486           vl_set_memory_root_path ((char *) chroot_prefix);
1487         }
1488       else if (unformat (a, "uri %s", &uri))
1489         ;
1490       else if (unformat (a, "server"))
1491         i_am_server = 1;
1492       else if (unformat (a, "client"))
1493         i_am_server = 0;
1494       else if (unformat (a, "no-return"))
1495         em->no_return = 1;
1496       else if (unformat (a, "test-bytes"))
1497         test_return_packets = 1;
1498       else if (unformat (a, "bytes %lld", &mbytes))
1499         {
1500           bytes_to_send = mbytes;
1501         }
1502       else if (unformat (a, "mbytes %lld", &mbytes))
1503         {
1504           bytes_to_send = mbytes << 20;
1505         }
1506       else if (unformat (a, "gbytes %lld", &mbytes))
1507         {
1508           bytes_to_send = mbytes << 30;
1509         }
1510       else if (unformat (a, "socket-name %s", &em->socket_name))
1511         ;
1512       else if (unformat (a, "use-svm-api"))
1513         em->use_sock_api = 0;
1514       else if (unformat (a, "fifo-size %d", &tmp))
1515         em->fifo_size = tmp << 10;
1516       else if (unformat (a, "nclients %d", &em->n_clients))
1517         ;
1518       else if (unformat (a, "appns %_%v%_", &em->appns_id))
1519         ;
1520       else if (unformat (a, "all-scope"))
1521         em->appns_flags |= (APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE
1522                             | APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE);
1523       else if (unformat (a, "local-scope"))
1524         em->appns_flags = APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE;
1525       else if (unformat (a, "global-scope"))
1526         em->appns_flags = APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1527       else if (unformat (a, "secret %lu", &em->appns_secret))
1528         ;
1529       else if (unformat (a, "quic-streams %d", &em->quic_streams))
1530         ;
1531       else
1532         {
1533           fformat (stderr, "%s: usage [master|slave]\n", argv[0]);
1534           exit (1);
1535         }
1536     }
1537
1538   if (!em->socket_name)
1539     em->socket_name = format (0, "%s%c", API_SOCKET_FILE, 0);
1540
1541   if (uri)
1542     {
1543       em->uri = format (0, "%s%c", uri, 0);
1544       em->connect_uri = format (0, "%s%c", uri, 0);
1545     }
1546   else
1547     {
1548       em->uri = format (0, "%s%c", bind_uri, 0);
1549       em->connect_uri = format (0, "%s%c", connect_uri, 0);
1550     }
1551
1552   em->i_am_master = i_am_server;
1553   em->test_return_packets = test_return_packets;
1554   em->bytes_to_send = bytes_to_send;
1555   em->time_to_stop = 0;
1556   vec_validate (em->rx_buf, 4 << 20);
1557   vec_validate (em->client_thread_handles, em->n_clients - 1);
1558   vec_validate (em->thread_args, em->n_clients - 1);
1559
1560   setup_signal_handlers ();
1561   quic_echo_api_hookup (em);
1562
1563   app_name = i_am_server ? "quic_echo_server" : "quic_echo_client";
1564   if (connect_to_vpp (app_name) < 0)
1565     {
1566       svm_region_exit ();
1567       fformat (stderr, "Couldn't connect to vpe, exiting...\n");
1568       exit (1);
1569     }
1570
1571   if (i_am_server == 0)
1572     clients_run (em);
1573   else
1574     server_run (em);
1575
1576   /* Make sure detach finishes */
1577   wait_for_state_change (em, STATE_DETACHED);
1578
1579   disconnect_from_vpp (em);
1580   exit (0);
1581 }
1582
1583 /*
1584  * fd.io coding-style-patch-verification: ON
1585  *
1586  * Local Variables:
1587  * eval: (c-set-style "gnu")
1588  * End:
1589  */