3f7a3426069fb1a60edccb088dbd48d4df5fd5c4
[vpp.git] / src / plugins / quic / quic.c
1 /*
2  * Copyright (c) 2021 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 <sys/socket.h>
17 #include <sys/syscall.h>
18
19 #include <openssl/rand.h>
20
21 #include <vnet/session/application.h>
22 #include <vnet/session/transport.h>
23 #include <vnet/session/session.h>
24 #include <vlib/unix/plugin.h>
25 #include <vpp/app/version.h>
26
27 #include <vppinfra/lock.h>
28
29 #include <quic/quic.h>
30 #include <quic/certs.h>
31 #include <quic/error.h>
32
33 #include <quicly/constants.h>
34 #include <quicly/defaults.h>
35 #include <picotls.h>
36
37 #include <quic/quic_crypto.h>
38
39 extern quicly_crypto_engine_t quic_crypto_engine;
40
41 static char *quic_error_strings[] = {
42 #define quic_error(n,s) s,
43 #include <quic/quic_error.def>
44 #undef quic_error
45 };
46
47 #define DEFAULT_MAX_PACKETS_PER_KEY 16777216
48
49 quic_main_t quic_main;
50 static void quic_update_timer (quic_ctx_t * ctx);
51 static void quic_check_quic_session_connected (quic_ctx_t * ctx);
52 static int quic_reset_connection (u64 udp_session_handle,
53                                   quic_rx_packet_ctx_t * pctx);
54 static void quic_proto_on_close (u32 ctx_index, u32 thread_index);
55
56 static quicly_stream_open_t on_stream_open;
57 static quicly_closed_by_remote_t on_closed_by_remote;
58 static quicly_now_t quicly_vpp_now_cb;
59
60 /* Crypto contexts */
61
62 static inline void
63 quic_crypto_context_make_key_from_ctx (clib_bihash_kv_24_8_t * kv,
64                                        quic_ctx_t * ctx)
65 {
66   application_t *app = application_get (ctx->parent_app_id);
67   kv->key[0] = ((u64) ctx->ckpair_index) << 32 | (u64) ctx->crypto_engine;
68   kv->key[1] = app->sm_properties.rx_fifo_size - 1;
69   kv->key[2] = app->sm_properties.tx_fifo_size - 1;
70 }
71
72 static inline void
73 quic_crypto_context_make_key_from_crctx (clib_bihash_kv_24_8_t * kv,
74                                          crypto_context_t * crctx)
75 {
76   quic_crypto_context_data_t *data =
77     (quic_crypto_context_data_t *) crctx->data;
78   kv->key[0] = ((u64) crctx->ckpair_index) << 32 | (u64) crctx->crypto_engine;
79   kv->key[1] = data->quicly_ctx.transport_params.max_stream_data.bidi_local;
80   kv->key[2] = data->quicly_ctx.transport_params.max_stream_data.bidi_remote;
81 }
82
83 static void
84 quic_crypto_context_free_if_needed (crypto_context_t * crctx, u8 thread_index)
85 {
86   quic_main_t *qm = &quic_main;
87   clib_bihash_kv_24_8_t kv;
88   if (crctx->n_subscribers)
89     return;
90   quic_crypto_context_make_key_from_crctx (&kv, crctx);
91   clib_bihash_add_del_24_8 (&qm->wrk_ctx[thread_index].crypto_context_hash,
92                             &kv, 0 /* is_add */ );
93   clib_mem_free (crctx->data);
94   pool_put (qm->wrk_ctx[thread_index].crypto_ctx_pool, crctx);
95 }
96
97 static int
98 quic_app_cert_key_pair_delete_callback (app_cert_key_pair_t * ckpair)
99 {
100   quic_main_t *qm = &quic_main;
101   crypto_context_t *crctx;
102   clib_bihash_kv_24_8_t kv;
103   vlib_thread_main_t *vtm = vlib_get_thread_main ();
104   int num_threads = 1 /* main thread */  + vtm->n_threads;
105   int i;
106
107   for (i = 0; i < num_threads; i++)
108     {
109       pool_foreach (crctx, qm->wrk_ctx[i].crypto_ctx_pool)  {
110         if (crctx->ckpair_index == ckpair->cert_key_index)
111           {
112             quic_crypto_context_make_key_from_crctx (&kv, crctx);
113             clib_bihash_add_del_24_8 (&qm->wrk_ctx[i].crypto_context_hash, &kv, 0 /* is_add */ );
114           }
115       }
116     }
117   return 0;
118 }
119
120 static crypto_context_t *
121 quic_crypto_context_alloc (u8 thread_index)
122 {
123   quic_main_t *qm = &quic_main;
124   crypto_context_t *crctx;
125   u32 idx;
126
127   pool_get (qm->wrk_ctx[thread_index].crypto_ctx_pool, crctx);
128   clib_memset (crctx, 0, sizeof (*crctx));
129   idx = (crctx - qm->wrk_ctx[thread_index].crypto_ctx_pool);
130   crctx->ctx_index = ((u32) thread_index) << 24 | idx;
131
132   return crctx;
133 }
134
135 static crypto_context_t *
136 quic_crypto_context_get (u32 cr_index, u32 thread_index)
137 {
138   quic_main_t *qm = &quic_main;
139   ASSERT (cr_index >> 24 == thread_index);
140   return pool_elt_at_index (qm->wrk_ctx[thread_index].crypto_ctx_pool,
141                             cr_index & 0x00ffffff);
142 }
143
144 static clib_error_t *
145 quic_list_crypto_context_command_fn (vlib_main_t * vm,
146                                      unformat_input_t * input,
147                                      vlib_cli_command_t * cmd)
148 {
149   quic_main_t *qm = &quic_main;
150   crypto_context_t *crctx;
151   vlib_thread_main_t *vtm = vlib_get_thread_main ();
152   int i, num_threads = 1 /* main thread */  + vtm->n_threads;
153   for (i = 0; i < num_threads; i++)
154     {
155       pool_foreach (crctx, qm->wrk_ctx[i].crypto_ctx_pool)  {
156         vlib_cli_output (vm, "[%d][Q]%U", i, format_crypto_context, crctx);
157       }
158     }
159   return 0;
160 }
161
162 static clib_error_t *
163 quic_set_max_packets_per_key_fn (vlib_main_t * vm,
164                                  unformat_input_t * input,
165                                  vlib_cli_command_t * cmd)
166 {
167   quic_main_t *qm = &quic_main;
168   unformat_input_t _line_input, *line_input = &_line_input;
169   u64 tmp;
170
171   if (!unformat_user (input, unformat_line_input, line_input))
172     return 0;
173
174   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
175     {
176       if (unformat (line_input, "%U", unformat_memory_size, &tmp))
177         {
178           qm->max_packets_per_key = tmp;
179         }
180       else
181         return clib_error_return (0, "unknown input '%U'",
182                                   format_unformat_error, line_input);
183     }
184
185   return 0;
186 }
187
188 static clib_error_t *
189 quic_set_cc_fn (vlib_main_t *vm, unformat_input_t *input,
190                 vlib_cli_command_t *cmd)
191 {
192   unformat_input_t _line_input, *line_input = &_line_input;
193   quic_main_t *qm = &quic_main;
194   clib_error_t *e = 0;
195
196   if (!unformat_user (input, unformat_line_input, line_input))
197     return 0;
198
199   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
200     {
201       if (unformat (line_input, "reno"))
202         qm->default_quic_cc = QUIC_CC_RENO;
203       else if (unformat (line_input, "cubic"))
204         qm->default_quic_cc = QUIC_CC_CUBIC;
205       else
206         {
207           e = clib_error_return (0, "unknown input '%U'",
208                                  format_unformat_error, line_input);
209           goto done;
210         }
211     }
212 done:
213   unformat_free (line_input);
214   return e;
215 }
216
217 static void
218 quic_release_crypto_context (u32 crypto_context_index, u8 thread_index)
219 {
220   crypto_context_t *crctx;
221   crctx = quic_crypto_context_get (crypto_context_index, thread_index);
222   crctx->n_subscribers--;
223   quic_crypto_context_free_if_needed (crctx, thread_index);
224 }
225
226 static int
227 quic_init_crypto_context (crypto_context_t * crctx, quic_ctx_t * ctx)
228 {
229   quic_main_t *qm = &quic_main;
230   quicly_context_t *quicly_ctx;
231   ptls_iovec_t key_vec;
232   app_cert_key_pair_t *ckpair;
233   application_t *app;
234   quic_crypto_context_data_t *data;
235   ptls_context_t *ptls_ctx;
236
237   QUIC_DBG (2, "Init quic crctx %d thread %d", crctx->ctx_index,
238             ctx->c_thread_index);
239
240   data = clib_mem_alloc (sizeof (*data));
241   /* picotls depends on data being zeroed */
242   clib_memset (data, 0, sizeof (*data));
243   crctx->data = (void *) data;
244   quicly_ctx = &data->quicly_ctx;
245   ptls_ctx = &data->ptls_ctx;
246
247   ptls_ctx->random_bytes = ptls_openssl_random_bytes;
248   ptls_ctx->get_time = &ptls_get_time;
249   ptls_ctx->key_exchanges = ptls_openssl_key_exchanges;
250   ptls_ctx->cipher_suites = qm->quic_ciphers[ctx->crypto_engine];
251   ptls_ctx->certificates.list = NULL;
252   ptls_ctx->certificates.count = 0;
253   ptls_ctx->esni = NULL;
254   ptls_ctx->on_client_hello = NULL;
255   ptls_ctx->emit_certificate = NULL;
256   ptls_ctx->sign_certificate = NULL;
257   ptls_ctx->verify_certificate = NULL;
258   ptls_ctx->ticket_lifetime = 86400;
259   ptls_ctx->max_early_data_size = 8192;
260   ptls_ctx->hkdf_label_prefix__obsolete = NULL;
261   ptls_ctx->require_dhe_on_psk = 1;
262   ptls_ctx->encrypt_ticket = &qm->session_cache.super;
263   clib_memcpy (quicly_ctx, &quicly_spec_context, sizeof (quicly_context_t));
264
265   quicly_ctx->max_packets_per_key = qm->max_packets_per_key;
266   quicly_ctx->tls = ptls_ctx;
267   quicly_ctx->stream_open = &on_stream_open;
268   quicly_ctx->closed_by_remote = &on_closed_by_remote;
269   quicly_ctx->now = &quicly_vpp_now_cb;
270   quicly_amend_ptls_context (quicly_ctx->tls);
271
272   if (qm->vnet_crypto_enabled &&
273       qm->default_crypto_engine == CRYPTO_ENGINE_VPP)
274     quicly_ctx->crypto_engine = &quic_crypto_engine;
275   else
276     quicly_ctx->crypto_engine = &quicly_default_crypto_engine;
277
278   quicly_ctx->transport_params.max_data = QUIC_INT_MAX;
279   quicly_ctx->transport_params.max_streams_uni = (uint64_t) 1 << 60;
280   quicly_ctx->transport_params.max_streams_bidi = (uint64_t) 1 << 60;
281   quicly_ctx->transport_params.max_idle_timeout = qm->connection_timeout;
282
283   if (qm->default_quic_cc == QUIC_CC_CUBIC)
284     quicly_ctx->init_cc = &quicly_cc_cubic_init;
285   else if (qm->default_quic_cc == QUIC_CC_RENO)
286     quicly_ctx->init_cc = &quicly_cc_reno_init;
287
288   app = application_get (ctx->parent_app_id);
289   quicly_ctx->transport_params.max_stream_data.bidi_local =
290     app->sm_properties.rx_fifo_size - 1;
291   quicly_ctx->transport_params.max_stream_data.bidi_remote =
292     app->sm_properties.tx_fifo_size - 1;
293   quicly_ctx->transport_params.max_stream_data.uni = QUIC_INT_MAX;
294
295   quicly_ctx->transport_params.max_udp_payload_size = QUIC_MAX_PACKET_SIZE;
296   if (!app->quic_iv_set)
297     {
298       ptls_openssl_random_bytes (app->quic_iv, QUIC_IV_LEN - 1);
299       app->quic_iv[QUIC_IV_LEN - 1] = 0;
300       app->quic_iv_set = 1;
301     }
302
303   clib_memcpy (data->cid_key, app->quic_iv, QUIC_IV_LEN);
304   key_vec = ptls_iovec_init (data->cid_key, QUIC_IV_LEN);
305   quicly_ctx->cid_encryptor =
306     quicly_new_default_cid_encryptor (&ptls_openssl_bfecb,
307                                       &ptls_openssl_aes128ecb,
308                                       &ptls_openssl_sha256, key_vec);
309
310   ckpair = app_cert_key_pair_get_if_valid (crctx->ckpair_index);
311   if (!ckpair || !ckpair->key || !ckpair->cert)
312     {
313       QUIC_DBG (1, "Wrong ckpair id %d\n", crctx->ckpair_index);
314       return -1;
315     }
316   if (load_bio_private_key (quicly_ctx->tls, (char *) ckpair->key))
317     {
318       QUIC_DBG (1, "failed to read private key from app configuration\n");
319       return -1;
320     }
321   if (load_bio_certificate_chain (quicly_ctx->tls, (char *) ckpair->cert))
322     {
323       QUIC_DBG (1, "failed to load certificate\n");
324       return -1;
325     }
326   return 0;
327
328 }
329
330 static int
331 quic_acquire_crypto_context (quic_ctx_t * ctx)
332 {
333   quic_main_t *qm = &quic_main;
334   crypto_context_t *crctx;
335   clib_bihash_kv_24_8_t kv;
336
337   if (ctx->crypto_engine == CRYPTO_ENGINE_NONE)
338     {
339       QUIC_DBG (2, "No crypto engine specified, using %d",
340                 qm->default_crypto_engine);
341       ctx->crypto_engine = qm->default_crypto_engine;
342     }
343   if (!clib_bitmap_get (qm->available_crypto_engines, ctx->crypto_engine))
344     {
345       QUIC_DBG (1, "Quic does not support crypto engine %d",
346                 ctx->crypto_engine);
347       return SESSION_E_NOCRYPTOENG;
348     }
349
350   /* Check for exisiting crypto ctx */
351   quic_crypto_context_make_key_from_ctx (&kv, ctx);
352   if (clib_bihash_search_24_8
353       (&qm->wrk_ctx[ctx->c_thread_index].crypto_context_hash, &kv, &kv) == 0)
354     {
355       crctx = quic_crypto_context_get (kv.value, ctx->c_thread_index);
356       QUIC_DBG (2, "Found exisiting crypto context %d", kv.value);
357       ctx->crypto_context_index = kv.value;
358       crctx->n_subscribers++;
359       return 0;
360     }
361
362   crctx = quic_crypto_context_alloc (ctx->c_thread_index);
363   ctx->crypto_context_index = crctx->ctx_index;
364   kv.value = crctx->ctx_index;
365   crctx->crypto_engine = ctx->crypto_engine;
366   crctx->ckpair_index = ctx->ckpair_index;
367   if (quic_init_crypto_context (crctx, ctx))
368     goto error;
369   if (vnet_app_add_cert_key_interest (ctx->ckpair_index, qm->app_index))
370     goto error;
371   crctx->n_subscribers++;
372   clib_bihash_add_del_24_8 (&qm->
373                             wrk_ctx[ctx->c_thread_index].crypto_context_hash,
374                             &kv, 1 /* is_add */ );
375   return 0;
376
377 error:
378   quic_crypto_context_free_if_needed (crctx, ctx->c_thread_index);
379   return SESSION_E_NOCRYPTOCKP;
380 }
381
382 /*  Helper functions */
383
384 static u32
385 quic_ctx_alloc (u32 thread_index)
386 {
387   quic_main_t *qm = &quic_main;
388   quic_ctx_t *ctx;
389
390   pool_get_aligned_safe (qm->ctx_pool[thread_index], ctx,
391                          CLIB_CACHE_LINE_BYTES);
392
393   clib_memset (ctx, 0, sizeof (quic_ctx_t));
394   ctx->c_thread_index = thread_index;
395   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
396   QUIC_DBG (3, "Allocated quic_ctx %u on thread %u",
397             ctx - qm->ctx_pool[thread_index], thread_index);
398   return ctx - qm->ctx_pool[thread_index];
399 }
400
401 static void
402 quic_ctx_free (quic_ctx_t * ctx)
403 {
404   QUIC_DBG (2, "Free ctx %u %x", ctx->c_thread_index, ctx->c_c_index);
405   u32 thread_index = ctx->c_thread_index;
406   QUIC_ASSERT (ctx->timer_handle == QUIC_TIMER_HANDLE_INVALID);
407   if (CLIB_DEBUG)
408     clib_memset (ctx, 0xfb, sizeof (*ctx));
409   pool_put (quic_main.ctx_pool[thread_index], ctx);
410 }
411
412 static quic_ctx_t *
413 quic_ctx_get (u32 ctx_index, u32 thread_index)
414 {
415   return pool_elt_at_index (quic_main.ctx_pool[thread_index], ctx_index);
416 }
417
418 static quic_ctx_t *
419 quic_ctx_get_if_valid (u32 ctx_index, u32 thread_index)
420 {
421   if (pool_is_free_index (quic_main.ctx_pool[thread_index], ctx_index))
422     return 0;
423   return pool_elt_at_index (quic_main.ctx_pool[thread_index], ctx_index);
424 }
425
426 quic_ctx_t *
427 quic_get_conn_ctx (quicly_conn_t * conn)
428 {
429   u64 conn_data;
430   conn_data = (u64) * quicly_get_data (conn);
431   return quic_ctx_get (conn_data & UINT32_MAX, conn_data >> 32);
432 }
433
434 static void
435 quic_store_conn_ctx (quicly_conn_t * conn, quic_ctx_t * ctx)
436 {
437   *quicly_get_data (conn) =
438     (void *) (((u64) ctx->c_thread_index) << 32 | (u64) ctx->c_c_index);
439 }
440
441 static inline int
442 quic_ctx_is_stream (quic_ctx_t * ctx)
443 {
444   return (ctx->flags & QUIC_F_IS_STREAM);
445 }
446
447 static inline int
448 quic_ctx_is_listener (quic_ctx_t * ctx)
449 {
450   return (ctx->flags & QUIC_F_IS_LISTENER);
451 }
452
453 static inline int
454 quic_ctx_is_conn (quic_ctx_t * ctx)
455 {
456   return !(quic_ctx_is_listener (ctx) || quic_ctx_is_stream (ctx));
457 }
458
459 static inline session_t *
460 get_stream_session_and_ctx_from_stream (quicly_stream_t * stream,
461                                         quic_ctx_t ** ctx)
462 {
463   quic_stream_data_t *stream_data;
464
465   stream_data = (quic_stream_data_t *) stream->data;
466   *ctx = quic_ctx_get (stream_data->ctx_id, stream_data->thread_index);
467   return session_get ((*ctx)->c_s_index, stream_data->thread_index);
468 }
469
470 static inline void
471 quic_make_connection_key (clib_bihash_kv_16_8_t * kv,
472                           const quicly_cid_plaintext_t * id)
473 {
474   kv->key[0] = ((u64) id->master_id) << 32 | (u64) id->thread_id;
475   kv->key[1] = id->node_id;
476 }
477
478 static int
479 quic_sendable_packet_count (session_t * udp_session)
480 {
481   u32 max_enqueue;
482   u32 packet_size = QUIC_MAX_PACKET_SIZE + SESSION_CONN_HDR_LEN;
483   max_enqueue = svm_fifo_max_enqueue (udp_session->tx_fifo);
484   return clib_min (max_enqueue / packet_size, QUIC_SEND_PACKET_VEC_SIZE);
485 }
486
487 static quicly_context_t *
488 quic_get_quicly_ctx_from_ctx (quic_ctx_t * ctx)
489 {
490   crypto_context_t *crctx =
491     quic_crypto_context_get (ctx->crypto_context_index, ctx->c_thread_index);
492   quic_crypto_context_data_t *data =
493     (quic_crypto_context_data_t *) crctx->data;
494   return &data->quicly_ctx;
495 }
496
497 static quicly_context_t *
498 quic_get_quicly_ctx_from_udp (u64 udp_session_handle)
499 {
500   session_t *udp_session = session_get_from_handle (udp_session_handle);
501   quic_ctx_t *ctx =
502     quic_ctx_get (udp_session->opaque, udp_session->thread_index);
503   return quic_get_quicly_ctx_from_ctx (ctx);
504 }
505
506 static inline void
507 quic_set_udp_tx_evt (session_t * udp_session)
508 {
509   int rv = 0;
510   if (svm_fifo_set_event (udp_session->tx_fifo))
511     rv = session_send_io_evt_to_thread (udp_session->tx_fifo,
512                                         SESSION_IO_EVT_TX);
513   if (PREDICT_FALSE (rv))
514     clib_warning ("Event enqueue errored %d", rv);
515 }
516
517 static inline void
518 quic_stop_ctx_timer (quic_ctx_t * ctx)
519 {
520   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
521   if (ctx->timer_handle == QUIC_TIMER_HANDLE_INVALID)
522     return;
523   tw = &quic_main.wrk_ctx[ctx->c_thread_index].timer_wheel;
524   tw_timer_stop_1t_3w_1024sl_ov (tw, ctx->timer_handle);
525   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
526   QUIC_DBG (4, "Stopping timer for ctx %u", ctx->c_c_index);
527 }
528
529 /* QUIC protocol actions */
530
531 static void
532 quic_ack_rx_data (session_t * stream_session)
533 {
534   u32 max_deq;
535   quic_ctx_t *sctx;
536   svm_fifo_t *f;
537   quicly_stream_t *stream;
538   quic_stream_data_t *stream_data;
539
540   sctx = quic_ctx_get (stream_session->connection_index,
541                        stream_session->thread_index);
542   QUIC_ASSERT (quic_ctx_is_stream (sctx));
543   stream = sctx->stream;
544   stream_data = (quic_stream_data_t *) stream->data;
545
546   f = stream_session->rx_fifo;
547   max_deq = svm_fifo_max_dequeue (f);
548
549   QUIC_ASSERT (stream_data->app_rx_data_len >= max_deq);
550   quicly_stream_sync_recvbuf (stream, stream_data->app_rx_data_len - max_deq);
551   QUIC_DBG (3, "Acking %u bytes", stream_data->app_rx_data_len - max_deq);
552   stream_data->app_rx_data_len = max_deq;
553 }
554
555 static void
556 quic_disconnect_transport (quic_ctx_t * ctx)
557 {
558   QUIC_DBG (2, "Disconnecting transport 0x%lx", ctx->udp_session_handle);
559   vnet_disconnect_args_t a = {
560     .handle = ctx->udp_session_handle,
561     .app_index = quic_main.app_index,
562   };
563
564   if (vnet_disconnect_session (&a))
565     clib_warning ("UDP session 0x%lx disconnect errored",
566                   ctx->udp_session_handle);
567 }
568
569 static void
570 quic_connection_delete (quic_ctx_t * ctx)
571 {
572   clib_bihash_kv_16_8_t kv;
573   quicly_conn_t *conn;
574
575   if (ctx->conn == NULL)
576     {
577       QUIC_DBG (2, "Skipping redundant delete of connection %u",
578                 ctx->c_c_index);
579       return;
580     }
581   QUIC_DBG (2, "Deleting connection %u", ctx->c_c_index);
582
583   QUIC_ASSERT (!quic_ctx_is_stream (ctx));
584   quic_stop_ctx_timer (ctx);
585
586   /*  Delete the connection from the connection map */
587   conn = ctx->conn;
588   ctx->conn = NULL;
589   quic_make_connection_key (&kv, quicly_get_master_id (conn));
590   QUIC_DBG (2, "Deleting conn with id %lu %lu from map", kv.key[0],
591             kv.key[1]);
592   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 0 /* is_add */ );
593
594   quic_disconnect_transport (ctx);
595
596   if (conn)
597     quicly_free (conn);
598   session_transport_delete_notify (&ctx->connection);
599 }
600
601 void
602 quic_increment_counter (u8 evt, u8 val)
603 {
604   vlib_main_t *vm = vlib_get_main ();
605   vlib_node_increment_counter (vm, quic_input_node.index, evt, val);
606 }
607
608 /**
609  * Called when quicly return an error
610  * This function interacts tightly with quic_proto_on_close
611  */
612 static void
613 quic_connection_closed (quic_ctx_t * ctx)
614 {
615   QUIC_DBG (2, "QUIC connection %u/%u closed", ctx->c_thread_index,
616             ctx->c_c_index);
617
618   /* TODO if connection is not established, just delete the session? */
619   /* Actually should send connect or accept error */
620
621   switch (ctx->conn_state)
622     {
623     case QUIC_CONN_STATE_READY:
624       /* Error on an opened connection (timeout...)
625          This puts the session in closing state, we should receive a notification
626          when the app has closed its session */
627       session_transport_reset_notify (&ctx->connection);
628       /* This ensures we delete the connection when the app confirms the close */
629       ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING_QUIC_CLOSED;
630       break;
631     case QUIC_CONN_STATE_PASSIVE_CLOSING:
632       ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING_QUIC_CLOSED;
633       /* quic_proto_on_close will eventually be called when the app confirms the close
634          , we delete the connection at that point */
635       break;
636     case QUIC_CONN_STATE_PASSIVE_CLOSING_APP_CLOSED:
637       /* App already confirmed close, we can delete the connection */
638       quic_connection_delete (ctx);
639       break;
640     case QUIC_CONN_STATE_OPENED:
641     case QUIC_CONN_STATE_HANDSHAKE:
642     case QUIC_CONN_STATE_ACTIVE_CLOSING:
643       quic_connection_delete (ctx);
644       break;
645     default:
646       QUIC_DBG (0, "BUG %d", ctx->conn_state);
647       break;
648     }
649 }
650
651 static int
652 quic_send_datagram (session_t *udp_session, struct iovec *packet,
653                     quicly_address_t *dest, quicly_address_t *src)
654 {
655   u32 max_enqueue, len;
656   session_dgram_hdr_t hdr;
657   svm_fifo_t *f;
658   transport_connection_t *tc;
659   int ret;
660
661   len = packet->iov_len;
662   f = udp_session->tx_fifo;
663   tc = session_get_transport (udp_session);
664   max_enqueue = svm_fifo_max_enqueue (f);
665   if (max_enqueue < SESSION_CONN_HDR_LEN + len)
666     {
667       QUIC_ERR ("Too much data to send, max_enqueue %u, len %u",
668                 max_enqueue, len + SESSION_CONN_HDR_LEN);
669       return QUIC_ERROR_FULL_FIFO;
670     }
671
672   /*  Build packet header for fifo */
673   hdr.data_length = len;
674   hdr.data_offset = 0;
675   hdr.is_ip4 = tc->is_ip4;
676   clib_memcpy (&hdr.lcl_ip, &tc->lcl_ip, sizeof (ip46_address_t));
677   hdr.lcl_port = tc->lcl_port;
678   hdr.gso_size = 0;
679
680   /*  Read dest address from quicly-provided sockaddr */
681   if (hdr.is_ip4)
682     {
683       QUIC_ASSERT (dest->sa.sa_family == AF_INET);
684       struct sockaddr_in *sa4 = (struct sockaddr_in *) &dest->sa;
685       hdr.rmt_port = sa4->sin_port;
686       hdr.rmt_ip.ip4.as_u32 = sa4->sin_addr.s_addr;
687     }
688   else
689     {
690       QUIC_ASSERT (dest->sa.sa_family == AF_INET6);
691       struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) &dest->sa;
692       hdr.rmt_port = sa6->sin6_port;
693       clib_memcpy_fast (&hdr.rmt_ip.ip6, &sa6->sin6_addr, 16);
694     }
695
696   svm_fifo_seg_t segs[2] = { { (u8 *) &hdr, sizeof (hdr) },
697                              { packet->iov_base, len } };
698
699   ret = svm_fifo_enqueue_segments (f, segs, 2, 0 /* allow partial */);
700   if (PREDICT_FALSE (ret < 0))
701     {
702       QUIC_ERR ("Not enough space to enqueue dgram");
703       return QUIC_ERROR_FULL_FIFO;
704     }
705
706   quic_increment_counter (QUIC_ERROR_TX_PACKETS, 1);
707
708   return 0;
709 }
710
711 static int
712 quic_send_packets (quic_ctx_t * ctx)
713 {
714   struct iovec packets[QUIC_SEND_PACKET_VEC_SIZE];
715   uint8_t
716     buf[QUIC_SEND_PACKET_VEC_SIZE * quic_get_quicly_ctx_from_ctx (ctx)
717                                       ->transport_params.max_udp_payload_size];
718   session_t *udp_session;
719   quicly_conn_t *conn;
720   size_t num_packets, i, max_packets;
721   quicly_address_t dest, src;
722   u32 n_sent = 0;
723   int err = 0;
724
725   /* We have sctx, get qctx */
726   if (quic_ctx_is_stream (ctx))
727     ctx = quic_ctx_get (ctx->quic_connection_ctx_id, ctx->c_thread_index);
728
729   QUIC_ASSERT (!quic_ctx_is_stream (ctx));
730
731   udp_session = session_get_from_handle_if_valid (ctx->udp_session_handle);
732   if (!udp_session)
733     goto quicly_error;
734
735   conn = ctx->conn;
736   if (!conn)
737     return 0;
738
739   do
740     {
741       /* TODO : quicly can assert it can send min_packets up to 2 */
742       max_packets = quic_sendable_packet_count (udp_session);
743       if (max_packets < 2)
744         break;
745
746       num_packets = max_packets;
747       if ((err = quicly_send (conn, &dest, &src, packets, &num_packets, buf,
748                               sizeof (buf))))
749         goto quicly_error;
750
751       for (i = 0; i != num_packets; ++i)
752         {
753
754           if ((err =
755                  quic_send_datagram (udp_session, &packets[i], &dest, &src)))
756             goto quicly_error;
757
758         }
759       n_sent += num_packets;
760     }
761   while (num_packets > 0 && num_packets == max_packets);
762
763   quic_set_udp_tx_evt (udp_session);
764
765   QUIC_DBG (3, "%u[TX] %u[RX]", svm_fifo_max_dequeue (udp_session->tx_fifo),
766             svm_fifo_max_dequeue (udp_session->rx_fifo));
767   quic_update_timer (ctx);
768   return n_sent;
769
770 quicly_error:
771   if (err && err != QUICLY_ERROR_PACKET_IGNORED
772       && err != QUICLY_ERROR_FREE_CONNECTION)
773     clib_warning ("Quic error '%U'.", quic_format_err, err);
774   quic_connection_closed (ctx);
775   return 0;
776 }
777
778 /* Quicly callbacks */
779
780 static void
781 quic_on_stream_destroy (quicly_stream_t * stream, int err)
782 {
783   quic_stream_data_t *stream_data = (quic_stream_data_t *) stream->data;
784   quic_ctx_t *sctx = quic_ctx_get (stream_data->ctx_id,
785                                    stream_data->thread_index);
786   QUIC_DBG (2, "DESTROYED_STREAM: session 0x%lx (%U)",
787             session_handle (stream_session), quic_format_err, err);
788
789   session_transport_closing_notify (&sctx->connection);
790   session_transport_delete_notify (&sctx->connection);
791
792   quic_increment_counter (QUIC_ERROR_CLOSED_STREAM, 1);
793   quic_ctx_free (sctx);
794   clib_mem_free (stream->data);
795 }
796
797 static void
798 quic_on_stop_sending (quicly_stream_t * stream, int err)
799 {
800 #if QUIC_DEBUG >= 2
801   quic_stream_data_t *stream_data = (quic_stream_data_t *) stream->data;
802   quic_ctx_t *sctx = quic_ctx_get (stream_data->ctx_id,
803                                    stream_data->thread_index);
804   session_t *stream_session = session_get (sctx->c_s_index,
805                                            sctx->c_thread_index);
806   clib_warning ("(NOT IMPLEMENTD) STOP_SENDING: session 0x%lx (%U)",
807                 session_handle (stream_session), quic_format_err, err);
808 #endif
809   /* TODO : handle STOP_SENDING */
810 }
811
812 static void
813 quic_on_receive_reset (quicly_stream_t * stream, int err)
814 {
815   quic_stream_data_t *stream_data = (quic_stream_data_t *) stream->data;
816   quic_ctx_t *sctx = quic_ctx_get (stream_data->ctx_id,
817                                    stream_data->thread_index);
818 #if QUIC_DEBUG >= 2
819   session_t *stream_session = session_get (sctx->c_s_index,
820                                            sctx->c_thread_index);
821   clib_warning ("RESET_STREAM: session 0x%lx (%U)",
822                 session_handle (stream_session), quic_format_err, err);
823 #endif
824   session_transport_closing_notify (&sctx->connection);
825 }
826
827 static void
828 quic_on_receive (quicly_stream_t * stream, size_t off, const void *src,
829                  size_t len)
830 {
831   QUIC_DBG (3, "received data: %lu bytes, offset %lu", len, off);
832   u32 max_enq;
833   quic_ctx_t *sctx;
834   session_t *stream_session;
835   app_worker_t *app_wrk;
836   svm_fifo_t *f;
837   quic_stream_data_t *stream_data;
838   int rlen;
839
840   if (!len)
841     return;
842
843   stream_data = (quic_stream_data_t *) stream->data;
844   sctx = quic_ctx_get (stream_data->ctx_id, stream_data->thread_index);
845   stream_session = session_get (sctx->c_s_index, stream_data->thread_index);
846   f = stream_session->rx_fifo;
847
848   max_enq = svm_fifo_max_enqueue_prod (f);
849   QUIC_DBG (3, "Enqueuing %u at off %u in %u space", len, off, max_enq);
850   /* Handle duplicate packet/chunk from quicly */
851   if (off < stream_data->app_rx_data_len)
852     {
853       QUIC_DBG (3, "Session [idx %u, app_wrk %u, thread %u, rx-fifo 0x%llx]: "
854                 "DUPLICATE PACKET (max_enq %u, len %u, "
855                 "app_rx_data_len %u, off %u, ToBeNQ %u)",
856                 stream_session->session_index,
857                 stream_session->app_wrk_index,
858                 stream_session->thread_index, f,
859                 max_enq, len, stream_data->app_rx_data_len, off,
860                 off - stream_data->app_rx_data_len + len);
861       return;
862     }
863   if (PREDICT_FALSE ((off - stream_data->app_rx_data_len + len) > max_enq))
864     {
865       QUIC_ERR ("Session [idx %u, app_wrk %u, thread %u, rx-fifo 0x%llx]: "
866                 "RX FIFO IS FULL (max_enq %u, len %u, "
867                 "app_rx_data_len %u, off %u, ToBeNQ %u)",
868                 stream_session->session_index,
869                 stream_session->app_wrk_index,
870                 stream_session->thread_index, f,
871                 max_enq, len, stream_data->app_rx_data_len, off,
872                 off - stream_data->app_rx_data_len + len);
873       return;                   /* This shouldn't happen */
874     }
875   if (off == stream_data->app_rx_data_len)
876     {
877       /* Streams live on the same thread so (f, stream_data) should stay consistent */
878       rlen = svm_fifo_enqueue (f, len, (u8 *) src);
879       if (PREDICT_FALSE (rlen < 0))
880         {
881           /*
882            * drop, fifo full
883            * drop, fifo grow
884            */
885           return;
886         }
887       QUIC_DBG (3, "Session [idx %u, app_wrk %u, ti %u, rx-fifo 0x%llx]: "
888                 "Enqueuing %u (rlen %u) at off %u in %u space, ",
889                 stream_session->session_index,
890                 stream_session->app_wrk_index,
891                 stream_session->thread_index, f, len, rlen, off, max_enq);
892       stream_data->app_rx_data_len += rlen;
893       QUIC_ASSERT (rlen >= len);
894       app_wrk = app_worker_get_if_valid (stream_session->app_wrk_index);
895       if (PREDICT_TRUE (app_wrk != 0))
896         {
897           app_worker_rx_notify (app_wrk, stream_session);
898         }
899       quic_ack_rx_data (stream_session);
900     }
901   else
902     {
903       rlen = svm_fifo_enqueue_with_offset (f,
904                                            off - stream_data->app_rx_data_len,
905                                            len, (u8 *) src);
906       if (PREDICT_FALSE (rlen < 0))
907         {
908           /*
909            * drop, fifo full
910            * drop, fifo grow
911            */
912           return;
913         }
914       QUIC_ASSERT (rlen == 0);
915     }
916   return;
917 }
918
919 void
920 quic_fifo_egress_shift (quicly_stream_t * stream, size_t delta)
921 {
922   quic_stream_data_t *stream_data;
923   session_t *stream_session;
924   quic_ctx_t *ctx;
925   svm_fifo_t *f;
926   u32 rv;
927
928   stream_data = (quic_stream_data_t *) stream->data;
929   stream_session = get_stream_session_and_ctx_from_stream (stream, &ctx);
930   f = stream_session->tx_fifo;
931
932   QUIC_ASSERT (stream_data->app_tx_data_len >= delta);
933   stream_data->app_tx_data_len -= delta;
934   ctx->bytes_written += delta;
935   rv = svm_fifo_dequeue_drop (f, delta);
936   QUIC_ASSERT (rv == delta);
937
938   rv = quicly_stream_sync_sendbuf (stream, 0);
939   QUIC_ASSERT (!rv);
940 }
941
942 void
943 quic_fifo_egress_emit (quicly_stream_t * stream, size_t off, void *dst,
944                        size_t * len, int *wrote_all)
945 {
946   quic_stream_data_t *stream_data;
947   quic_ctx_t *ctx;
948   session_t *stream_session;
949   svm_fifo_t *f;
950   u32 deq_max;
951
952   stream_data = (quic_stream_data_t *) stream->data;
953   stream_session = get_stream_session_and_ctx_from_stream (stream, &ctx);
954   f = stream_session->tx_fifo;
955
956   QUIC_DBG (3, "Emitting %u, offset %u", *len, off);
957
958   deq_max = svm_fifo_max_dequeue_cons (f);
959   QUIC_ASSERT (off <= deq_max);
960   if (off + *len < deq_max)
961     {
962       *wrote_all = 0;
963     }
964   else
965     {
966       *wrote_all = 1;
967       *len = deq_max - off;
968     }
969   QUIC_ASSERT (*len > 0);
970
971   if (off + *len > stream_data->app_tx_data_len)
972     stream_data->app_tx_data_len = off + *len;
973
974   svm_fifo_peek (f, off, *len, dst);
975 }
976
977 static const quicly_stream_callbacks_t quic_stream_callbacks = {
978   .on_destroy = quic_on_stream_destroy,
979   .on_send_shift = quic_fifo_egress_shift,
980   .on_send_emit = quic_fifo_egress_emit,
981   .on_send_stop = quic_on_stop_sending,
982   .on_receive = quic_on_receive,
983   .on_receive_reset = quic_on_receive_reset
984 };
985
986 static int
987 quic_on_stream_open (quicly_stream_open_t * self, quicly_stream_t * stream)
988 {
989   /* Return code for this function ends either
990    * - in quicly_receive : if not QUICLY_ERROR_PACKET_IGNORED, will close connection
991    * - in quicly_open_stream, returned directly
992    */
993
994   session_t *stream_session, *quic_session;
995   quic_stream_data_t *stream_data;
996   app_worker_t *app_wrk;
997   quic_ctx_t *qctx, *sctx;
998   u32 sctx_id;
999   int rv;
1000
1001   QUIC_DBG (2, "on_stream_open called");
1002   stream->data = clib_mem_alloc (sizeof (quic_stream_data_t));
1003   stream->callbacks = &quic_stream_callbacks;
1004   /* Notify accept on parent qsession, but only if this is not a locally
1005    * initiated stream */
1006   if (quicly_stream_is_self_initiated (stream))
1007     return 0;
1008
1009   sctx_id = quic_ctx_alloc (vlib_get_thread_index ());
1010   qctx = quic_get_conn_ctx (stream->conn);
1011
1012   /* Might need to signal that the connection is ready if the first thing the
1013    * server does is open a stream */
1014   quic_check_quic_session_connected (qctx);
1015   /* ctx might be invalidated */
1016   qctx = quic_get_conn_ctx (stream->conn);
1017
1018   stream_session = session_alloc (qctx->c_thread_index);
1019   QUIC_DBG (2, "ACCEPTED stream_session 0x%lx ctx %u",
1020             session_handle (stream_session), sctx_id);
1021   sctx = quic_ctx_get (sctx_id, qctx->c_thread_index);
1022   sctx->parent_app_wrk_id = qctx->parent_app_wrk_id;
1023   sctx->parent_app_id = qctx->parent_app_id;
1024   sctx->quic_connection_ctx_id = qctx->c_c_index;
1025   sctx->c_c_index = sctx_id;
1026   sctx->c_s_index = stream_session->session_index;
1027   sctx->stream = stream;
1028   sctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1029   sctx->flags |= QUIC_F_IS_STREAM;
1030   sctx->crypto_context_index = qctx->crypto_context_index;
1031   if (quicly_stream_is_unidirectional (stream->stream_id))
1032     stream_session->flags |= SESSION_F_UNIDIRECTIONAL;
1033
1034   stream_data = (quic_stream_data_t *) stream->data;
1035   stream_data->ctx_id = sctx_id;
1036   stream_data->thread_index = sctx->c_thread_index;
1037   stream_data->app_rx_data_len = 0;
1038   stream_data->app_tx_data_len = 0;
1039
1040   sctx->c_s_index = stream_session->session_index;
1041   stream_session->session_state = SESSION_STATE_CREATED;
1042   stream_session->app_wrk_index = sctx->parent_app_wrk_id;
1043   stream_session->connection_index = sctx->c_c_index;
1044   stream_session->session_type =
1045     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, qctx->udp_is_ip4);
1046   quic_session = session_get (qctx->c_s_index, qctx->c_thread_index);
1047   /* Make sure quic session is in listening state */
1048   quic_session->session_state = SESSION_STATE_LISTENING;
1049   stream_session->listener_handle = listen_session_get_handle (quic_session);
1050
1051   app_wrk = app_worker_get (stream_session->app_wrk_index);
1052   if ((rv = app_worker_init_connected (app_wrk, stream_session)))
1053     {
1054       QUIC_ERR ("failed to allocate fifos");
1055       quicly_reset_stream (stream, QUIC_APP_ALLOCATION_ERROR);
1056       return 0;                 /* Frame is still valid */
1057     }
1058   svm_fifo_add_want_deq_ntf (stream_session->rx_fifo,
1059                              SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL |
1060                              SVM_FIFO_WANT_DEQ_NOTIF_IF_EMPTY);
1061   svm_fifo_init_ooo_lookup (stream_session->rx_fifo, 0 /* ooo enq */);
1062   svm_fifo_init_ooo_lookup (stream_session->tx_fifo, 1 /* ooo deq */);
1063
1064   stream_session->session_state = SESSION_STATE_ACCEPTING;
1065   if ((rv = app_worker_accept_notify (app_wrk, stream_session)))
1066     {
1067       QUIC_ERR ("failed to notify accept worker app");
1068       quicly_reset_stream (stream, QUIC_APP_ACCEPT_NOTIFY_ERROR);
1069       return 0;                 /* Frame is still valid */
1070     }
1071
1072   return 0;
1073 }
1074
1075 static void
1076 quic_on_closed_by_remote (quicly_closed_by_remote_t *self, quicly_conn_t *conn,
1077                           int code, uint64_t frame_type, const char *reason,
1078                           size_t reason_len)
1079 {
1080   quic_ctx_t *ctx = quic_get_conn_ctx (conn);
1081 #if QUIC_DEBUG >= 2
1082   session_t *quic_session = session_get (ctx->c_s_index, ctx->c_thread_index);
1083   clib_warning ("Session 0x%lx closed by peer (%U) %.*s ",
1084                 session_handle (quic_session), quic_format_err, code,
1085                 reason_len, reason);
1086 #endif
1087   ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING;
1088   session_transport_closing_notify (&ctx->connection);
1089 }
1090
1091 /* Timer handling */
1092
1093 static int64_t
1094 quic_get_thread_time (u8 thread_index)
1095 {
1096   return quic_main.wrk_ctx[thread_index].time_now;
1097 }
1098
1099 static int64_t
1100 quic_get_time (quicly_now_t * self)
1101 {
1102   u8 thread_index = vlib_get_thread_index ();
1103   return quic_get_thread_time (thread_index);
1104 }
1105
1106 static u32
1107 quic_set_time_now (u32 thread_index)
1108 {
1109   vlib_main_t *vlib_main = vlib_get_main ();
1110   f64 time = vlib_time_now (vlib_main);
1111   quic_main.wrk_ctx[thread_index].time_now = (int64_t) (time * 1000.f);
1112   return quic_main.wrk_ctx[thread_index].time_now;
1113 }
1114
1115 /* Transport proto callback */
1116 static void
1117 quic_update_time (f64 now, u8 thread_index)
1118 {
1119   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
1120
1121   tw = &quic_main.wrk_ctx[thread_index].timer_wheel;
1122   quic_set_time_now (thread_index);
1123   tw_timer_expire_timers_1t_3w_1024sl_ov (tw, now);
1124 }
1125
1126 static void
1127 quic_timer_expired (u32 conn_index)
1128 {
1129   quic_ctx_t *ctx;
1130   QUIC_DBG (4, "Timer expired for conn %u at %ld", conn_index,
1131             quic_get_time (NULL));
1132   ctx = quic_ctx_get (conn_index, vlib_get_thread_index ());
1133   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1134   quic_send_packets (ctx);
1135 }
1136
1137 static void
1138 quic_update_timer (quic_ctx_t * ctx)
1139 {
1140   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
1141   int64_t next_timeout, next_interval;
1142   session_t *quic_session;
1143   int rv;
1144
1145   /*  This timeout is in ms which is the unit of our timer */
1146   next_timeout = quicly_get_first_timeout (ctx->conn);
1147   next_interval = next_timeout - quic_get_time (NULL);
1148
1149   if (next_timeout == 0 || next_interval <= 0)
1150     {
1151       if (ctx->c_s_index == QUIC_SESSION_INVALID)
1152         {
1153           next_interval = 1;
1154         }
1155       else
1156         {
1157           quic_session = session_get (ctx->c_s_index, ctx->c_thread_index);
1158           if (svm_fifo_set_event (quic_session->tx_fifo))
1159             {
1160               rv = session_send_io_evt_to_thread_custom (
1161                 quic_session, quic_session->thread_index, SESSION_IO_EVT_TX);
1162               if (PREDICT_FALSE (rv))
1163                 QUIC_ERR ("Failed to enqueue builtin_tx %d", rv);
1164             }
1165           return;
1166         }
1167     }
1168
1169   ASSERT (vlib_get_thread_index () == ctx->c_thread_index ||
1170           vlib_get_thread_index () == 0);
1171   tw = &quic_main.wrk_ctx[ctx->c_thread_index].timer_wheel;
1172
1173   QUIC_DBG (4, "Timer set to %ld (int %ld) for ctx %u", next_timeout,
1174             next_interval, ctx->c_c_index);
1175
1176   if (ctx->timer_handle == QUIC_TIMER_HANDLE_INVALID)
1177     {
1178       if (next_timeout == INT64_MAX)
1179         {
1180           QUIC_DBG (4, "timer for ctx %u already stopped", ctx->c_c_index);
1181           return;
1182         }
1183       ctx->timer_handle = tw_timer_start_1t_3w_1024sl_ov (tw, ctx->c_c_index,
1184                                                           0, next_interval);
1185     }
1186   else
1187     {
1188       if (next_timeout == INT64_MAX)
1189         {
1190           quic_stop_ctx_timer (ctx);
1191         }
1192       else
1193         tw_timer_update_1t_3w_1024sl_ov (tw, ctx->timer_handle,
1194                                          next_interval);
1195     }
1196   return;
1197 }
1198
1199 static void
1200 quic_expired_timers_dispatch (u32 * expired_timers)
1201 {
1202   int i;
1203
1204   for (i = 0; i < vec_len (expired_timers); i++)
1205     {
1206       quic_timer_expired (expired_timers[i]);
1207     }
1208 }
1209
1210 /* Transport proto functions */
1211 static int
1212 quic_connect_stream (session_t * quic_session, session_endpoint_cfg_t * sep)
1213 {
1214   uint64_t quic_session_handle;
1215   session_t *stream_session;
1216   quic_stream_data_t *stream_data;
1217   quicly_stream_t *stream;
1218   quicly_conn_t *conn;
1219   app_worker_t *app_wrk;
1220   quic_ctx_t *qctx, *sctx;
1221   u32 sctx_index;
1222   u8 is_unidir;
1223   int rv;
1224
1225   /*  Find base session to which the user want to attach a stream */
1226   quic_session_handle = session_handle (quic_session);
1227   QUIC_DBG (2, "Opening new stream (qsession %u)", quic_session_handle);
1228
1229   if (session_type_transport_proto (quic_session->session_type) !=
1230       TRANSPORT_PROTO_QUIC)
1231     {
1232       QUIC_ERR ("received incompatible session");
1233       return -1;
1234     }
1235
1236   app_wrk = app_worker_get_if_valid (quic_session->app_wrk_index);
1237   if (!app_wrk)
1238     {
1239       QUIC_ERR ("Invalid app worker :(");
1240       return -1;
1241     }
1242
1243   sctx_index = quic_ctx_alloc (quic_session->thread_index);     /*  Allocate before we get pointers */
1244   sctx = quic_ctx_get (sctx_index, quic_session->thread_index);
1245   qctx = quic_ctx_get (quic_session->connection_index,
1246                        quic_session->thread_index);
1247   if (quic_ctx_is_stream (qctx))
1248     {
1249       QUIC_ERR ("session is a stream");
1250       quic_ctx_free (sctx);
1251       return -1;
1252     }
1253
1254   sctx->parent_app_wrk_id = qctx->parent_app_wrk_id;
1255   sctx->parent_app_id = qctx->parent_app_id;
1256   sctx->quic_connection_ctx_id = qctx->c_c_index;
1257   sctx->c_c_index = sctx_index;
1258   sctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1259   sctx->flags |= QUIC_F_IS_STREAM;
1260
1261   conn = qctx->conn;
1262
1263   if (!conn || !quicly_connection_is_ready (conn))
1264     return -1;
1265
1266   is_unidir = sep->transport_flags & TRANSPORT_CFG_F_UNIDIRECTIONAL;
1267   if ((rv = quicly_open_stream (conn, &stream, is_unidir)))
1268     {
1269       QUIC_DBG (2, "Stream open failed with %d", rv);
1270       return -1;
1271     }
1272   quic_increment_counter (QUIC_ERROR_OPENED_STREAM, 1);
1273
1274   sctx->stream = stream;
1275   sctx->crypto_context_index = qctx->crypto_context_index;
1276
1277   QUIC_DBG (2, "Opened stream %d, creating session", stream->stream_id);
1278
1279   stream_session = session_alloc (qctx->c_thread_index);
1280   QUIC_DBG (2, "Allocated stream_session 0x%lx ctx %u",
1281             session_handle (stream_session), sctx_index);
1282   stream_session->app_wrk_index = app_wrk->wrk_index;
1283   stream_session->connection_index = sctx_index;
1284   stream_session->listener_handle = quic_session_handle;
1285   stream_session->session_type =
1286     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, qctx->udp_is_ip4);
1287   if (is_unidir)
1288     stream_session->flags |= SESSION_F_UNIDIRECTIONAL;
1289
1290   sctx->c_s_index = stream_session->session_index;
1291   stream_data = (quic_stream_data_t *) stream->data;
1292   stream_data->ctx_id = sctx->c_c_index;
1293   stream_data->thread_index = sctx->c_thread_index;
1294   stream_data->app_rx_data_len = 0;
1295   stream_data->app_tx_data_len = 0;
1296   stream_session->session_state = SESSION_STATE_READY;
1297   stream_session->opaque = sep->opaque;
1298
1299   /* For now we only reset streams. Cleanup will be triggered by timers */
1300   if ((rv = app_worker_init_connected (app_wrk, stream_session)))
1301     {
1302       QUIC_ERR ("failed to app_worker_init_connected");
1303       quicly_reset_stream (stream, QUIC_APP_CONNECT_NOTIFY_ERROR);
1304       return app_worker_connect_notify (app_wrk, NULL, rv, sep->opaque);
1305     }
1306
1307   svm_fifo_init_ooo_lookup (stream_session->rx_fifo, 0 /* ooo enq */);
1308   svm_fifo_init_ooo_lookup (stream_session->tx_fifo, 1 /* ooo deq */);
1309   svm_fifo_add_want_deq_ntf (stream_session->rx_fifo,
1310                              SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL |
1311                              SVM_FIFO_WANT_DEQ_NOTIF_IF_EMPTY);
1312
1313   if (app_worker_connect_notify (app_wrk, stream_session, SESSION_E_NONE,
1314                                  sep->opaque))
1315     {
1316       QUIC_ERR ("failed to notify app");
1317       quic_increment_counter (QUIC_ERROR_CLOSED_STREAM, 1);
1318       quicly_reset_stream (stream, QUIC_APP_CONNECT_NOTIFY_ERROR);
1319       return -1;
1320     }
1321
1322   return 0;
1323 }
1324
1325 static int
1326 quic_connect_connection (session_endpoint_cfg_t * sep)
1327 {
1328   vnet_connect_args_t _cargs, *cargs = &_cargs;
1329   transport_endpt_crypto_cfg_t *ccfg;
1330   quic_main_t *qm = &quic_main;
1331   u32 ctx_index, thread_index;
1332   quic_ctx_t *ctx;
1333   app_worker_t *app_wrk;
1334   application_t *app;
1335   int error;
1336
1337   if (!sep->ext_cfg)
1338     return SESSION_E_NOEXTCFG;
1339
1340   /* Use pool on thread 1 if we have workers because of UDP */
1341   thread_index = transport_cl_thread ();
1342   ccfg = &sep->ext_cfg->crypto;
1343
1344   clib_memset (cargs, 0, sizeof (*cargs));
1345   ctx_index = quic_ctx_alloc (thread_index);
1346   ctx = quic_ctx_get (ctx_index, thread_index);
1347   ctx->parent_app_wrk_id = sep->app_wrk_index;
1348   ctx->c_s_index = QUIC_SESSION_INVALID;
1349   ctx->c_c_index = ctx_index;
1350   ctx->udp_is_ip4 = sep->is_ip4;
1351   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1352   ctx->conn_state = QUIC_CONN_STATE_HANDSHAKE;
1353   ctx->client_opaque = sep->opaque;
1354   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1355   if (ccfg->hostname[0])
1356     ctx->srv_hostname = format (0, "%s", ccfg->hostname);
1357   else
1358     /*  needed by quic for crypto + determining client / server */
1359     ctx->srv_hostname = format (0, "%U", format_ip46_address,
1360                                 &sep->ip, sep->is_ip4);
1361   vec_terminate_c_string (ctx->srv_hostname);
1362
1363   clib_memcpy (&cargs->sep_ext, sep, sizeof (session_endpoint_cfg_t));
1364   cargs->sep.transport_proto = TRANSPORT_PROTO_UDP;
1365   cargs->app_index = qm->app_index;
1366   cargs->api_context = ctx_index;
1367
1368   app_wrk = app_worker_get (sep->app_wrk_index);
1369   app = application_get (app_wrk->app_index);
1370   ctx->parent_app_id = app_wrk->app_index;
1371   cargs->sep_ext.ns_index = app->ns_index;
1372   cargs->sep_ext.transport_flags = TRANSPORT_CFG_F_CONNECTED;
1373
1374   ctx->crypto_engine = ccfg->crypto_engine;
1375   ctx->ckpair_index = ccfg->ckpair_index;
1376   if ((error = quic_acquire_crypto_context (ctx)))
1377     return error;
1378
1379   if ((error = vnet_connect (cargs)))
1380     return error;
1381
1382   return 0;
1383 }
1384
1385 static int
1386 quic_connect (transport_endpoint_cfg_t * tep)
1387 {
1388   QUIC_DBG (2, "Called quic_connect");
1389   session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) tep;
1390   session_t *quic_session;
1391   sep = (session_endpoint_cfg_t *) tep;
1392
1393   quic_session = session_get_from_handle_if_valid (sep->parent_handle);
1394   if (quic_session)
1395     return quic_connect_stream (quic_session, sep);
1396   else
1397     return quic_connect_connection (sep);
1398 }
1399
1400 static void
1401 quic_proto_on_close (u32 ctx_index, u32 thread_index)
1402 {
1403   int err;
1404   quic_ctx_t *ctx = quic_ctx_get_if_valid (ctx_index, thread_index);
1405   if (!ctx)
1406     return;
1407   session_t *stream_session = session_get (ctx->c_s_index,
1408                                            ctx->c_thread_index);
1409 #if QUIC_DEBUG >= 2
1410   clib_warning ("Closing session 0x%lx", session_handle (stream_session));
1411 #endif
1412   if (quic_ctx_is_stream (ctx))
1413     {
1414       quicly_stream_t *stream = ctx->stream;
1415       if (!quicly_stream_has_send_side (quicly_is_client (stream->conn),
1416                                         stream->stream_id))
1417         return;
1418       quicly_sendstate_shutdown (&stream->sendstate, ctx->bytes_written +
1419                                  svm_fifo_max_dequeue
1420                                  (stream_session->tx_fifo));
1421       err = quicly_stream_sync_sendbuf (stream, 1);
1422       if (err)
1423         {
1424           QUIC_DBG (1, "sendstate_shutdown failed for stream session %lu",
1425                     session_handle (stream_session));
1426           quicly_reset_stream (stream, QUIC_APP_ERROR_CLOSE_NOTIFY);
1427         }
1428       quic_send_packets (ctx);
1429       return;
1430     }
1431
1432   switch (ctx->conn_state)
1433     {
1434     case QUIC_CONN_STATE_OPENED:
1435     case QUIC_CONN_STATE_HANDSHAKE:
1436     case QUIC_CONN_STATE_READY:
1437       ctx->conn_state = QUIC_CONN_STATE_ACTIVE_CLOSING;
1438       quicly_conn_t *conn = ctx->conn;
1439       /* Start connection closing. Keep sending packets until quicly_send
1440          returns QUICLY_ERROR_FREE_CONNECTION */
1441
1442       quic_increment_counter (QUIC_ERROR_CLOSED_CONNECTION, 1);
1443       quicly_close (conn, QUIC_APP_ERROR_CLOSE_NOTIFY, "Closed by peer");
1444       /* This also causes all streams to be closed (and the cb called) */
1445       quic_send_packets (ctx);
1446       break;
1447     case QUIC_CONN_STATE_PASSIVE_CLOSING:
1448       ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING_APP_CLOSED;
1449       /* send_packets will eventually return an error, we delete the conn at
1450          that point */
1451       break;
1452     case QUIC_CONN_STATE_PASSIVE_CLOSING_QUIC_CLOSED:
1453       quic_connection_delete (ctx);
1454       break;
1455     case QUIC_CONN_STATE_ACTIVE_CLOSING:
1456       break;
1457     default:
1458       QUIC_ERR ("Trying to close conn in state %d", ctx->conn_state);
1459       break;
1460     }
1461 }
1462
1463 static u32
1464 quic_start_listen (u32 quic_listen_session_index,
1465                    transport_endpoint_cfg_t *tep)
1466 {
1467   vnet_listen_args_t _bargs, *args = &_bargs;
1468   transport_endpt_crypto_cfg_t *ccfg;
1469   quic_main_t *qm = &quic_main;
1470   session_handle_t udp_handle;
1471   session_endpoint_cfg_t *sep;
1472   session_t *udp_listen_session;
1473   app_worker_t *app_wrk;
1474   application_t *app;
1475   quic_ctx_t *lctx;
1476   u32 lctx_index;
1477   app_listener_t *app_listener;
1478   int rv;
1479
1480   sep = (session_endpoint_cfg_t *) tep;
1481   if (!sep->ext_cfg)
1482     return SESSION_E_NOEXTCFG;
1483
1484   ccfg = &sep->ext_cfg->crypto;
1485   app_wrk = app_worker_get (sep->app_wrk_index);
1486   app = application_get (app_wrk->app_index);
1487   QUIC_DBG (2, "Called quic_start_listen for app %d", app_wrk->app_index);
1488
1489   clib_memset (args, 0, sizeof (*args));
1490   args->app_index = qm->app_index;
1491   args->sep_ext = *sep;
1492   args->sep_ext.ns_index = app->ns_index;
1493   args->sep_ext.transport_proto = TRANSPORT_PROTO_UDP;
1494   args->sep_ext.transport_flags = TRANSPORT_CFG_F_CONNECTED;
1495   if ((rv = vnet_listen (args)))
1496     return rv;
1497
1498   lctx_index = quic_ctx_alloc (0);
1499   udp_handle = args->handle;
1500   app_listener = app_listener_get_w_handle (udp_handle);
1501   udp_listen_session = app_listener_get_session (app_listener);
1502   udp_listen_session->opaque = lctx_index;
1503
1504   lctx = quic_ctx_get (lctx_index, 0);
1505   lctx->flags |= QUIC_F_IS_LISTENER;
1506
1507   clib_memcpy (&lctx->c_rmt_ip, &args->sep.peer.ip, sizeof (ip46_address_t));
1508   clib_memcpy (&lctx->c_lcl_ip, &args->sep.ip, sizeof (ip46_address_t));
1509   lctx->c_rmt_port = args->sep.peer.port;
1510   lctx->c_lcl_port = args->sep.port;
1511   lctx->c_is_ip4 = args->sep.is_ip4;
1512   lctx->c_fib_index = args->sep.fib_index;
1513   lctx->c_proto = TRANSPORT_PROTO_QUIC;
1514   lctx->parent_app_wrk_id = sep->app_wrk_index;
1515   lctx->parent_app_id = app_wrk->app_index;
1516   lctx->udp_session_handle = udp_handle;
1517   lctx->c_s_index = quic_listen_session_index;
1518   lctx->crypto_engine = ccfg->crypto_engine;
1519   lctx->ckpair_index = ccfg->ckpair_index;
1520   if ((rv = quic_acquire_crypto_context (lctx)))
1521     return rv;
1522
1523   QUIC_DBG (2, "Listening UDP session 0x%lx",
1524             session_handle (udp_listen_session));
1525   QUIC_DBG (2, "Listening QUIC session 0x%lx", quic_listen_session_index);
1526   return lctx_index;
1527 }
1528
1529 static u32
1530 quic_stop_listen (u32 lctx_index)
1531 {
1532   QUIC_DBG (2, "Called quic_stop_listen");
1533   quic_ctx_t *lctx;
1534   lctx = quic_ctx_get (lctx_index, 0);
1535   QUIC_ASSERT (quic_ctx_is_listener (lctx));
1536   vnet_unlisten_args_t a = {
1537     .handle = lctx->udp_session_handle,
1538     .app_index = quic_main.app_index,
1539     .wrk_map_index = 0          /* default wrk */
1540   };
1541   if (vnet_unlisten (&a))
1542     clib_warning ("unlisten errored");
1543
1544   quic_release_crypto_context (lctx->crypto_context_index,
1545                                0 /* thread_index */ );
1546   quic_ctx_free (lctx);
1547   return 0;
1548 }
1549
1550 static transport_connection_t *
1551 quic_connection_get (u32 ctx_index, u32 thread_index)
1552 {
1553   quic_ctx_t *ctx;
1554   ctx = quic_ctx_get (ctx_index, thread_index);
1555   return &ctx->connection;
1556 }
1557
1558 static transport_connection_t *
1559 quic_listener_get (u32 listener_index)
1560 {
1561   QUIC_DBG (2, "Called quic_listener_get");
1562   quic_ctx_t *ctx;
1563   ctx = quic_ctx_get (listener_index, 0);
1564   return &ctx->connection;
1565 }
1566
1567 static u8 *
1568 format_quic_ctx (u8 * s, va_list * args)
1569 {
1570   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
1571   u32 verbose = va_arg (*args, u32);
1572   u8 *str = 0;
1573
1574   if (!ctx)
1575     return s;
1576   str = format (str, "[%d:%d][Q] ", ctx->c_thread_index, ctx->c_s_index);
1577
1578   if (quic_ctx_is_listener (ctx))
1579     str = format (str, "Listener, UDP %ld", ctx->udp_session_handle);
1580   else if (quic_ctx_is_stream (ctx))
1581     str = format (str, "Stream %ld conn %d",
1582                   ctx->stream->stream_id, ctx->quic_connection_ctx_id);
1583   else                          /* connection */
1584     str = format (str, "Conn %d UDP %d", ctx->c_c_index,
1585                   ctx->udp_session_handle);
1586
1587   str = format (str, " app %d wrk %d", ctx->parent_app_id,
1588                 ctx->parent_app_wrk_id);
1589
1590   if (verbose == 1)
1591     s = format (s, "%-" SESSION_CLI_ID_LEN "s%-" SESSION_CLI_STATE_LEN "d",
1592                 str, ctx->conn_state);
1593   else
1594     s = format (s, "%s\n", str);
1595   vec_free (str);
1596   return s;
1597 }
1598
1599 static u8 *
1600 format_quic_connection (u8 * s, va_list * args)
1601 {
1602   u32 qc_index = va_arg (*args, u32);
1603   u32 thread_index = va_arg (*args, u32);
1604   u32 verbose = va_arg (*args, u32);
1605   quic_ctx_t *ctx = quic_ctx_get (qc_index, thread_index);
1606   s = format (s, "%U", format_quic_ctx, ctx, verbose);
1607   return s;
1608 }
1609
1610 static u8 *
1611 format_quic_half_open (u8 * s, va_list * args)
1612 {
1613   u32 qc_index = va_arg (*args, u32);
1614   u32 thread_index = va_arg (*args, u32);
1615   quic_ctx_t *ctx = quic_ctx_get (qc_index, thread_index);
1616   s = format (s, "[#%d][Q] half-open app %u", thread_index,
1617               ctx->parent_app_id);
1618   return s;
1619 }
1620
1621 /*  TODO improve */
1622 static u8 *
1623 format_quic_listener (u8 * s, va_list * args)
1624 {
1625   u32 tci = va_arg (*args, u32);
1626   u32 thread_index = va_arg (*args, u32);
1627   u32 verbose = va_arg (*args, u32);
1628   quic_ctx_t *ctx = quic_ctx_get (tci, thread_index);
1629   s = format (s, "%U", format_quic_ctx, ctx, verbose);
1630   return s;
1631 }
1632
1633 /* Session layer callbacks */
1634
1635 static inline void
1636 quic_build_sockaddr (struct sockaddr *sa, socklen_t * salen,
1637                      ip46_address_t * addr, u16 port, u8 is_ip4)
1638 {
1639   if (is_ip4)
1640     {
1641       struct sockaddr_in *sa4 = (struct sockaddr_in *) sa;
1642       sa4->sin_family = AF_INET;
1643       sa4->sin_port = port;
1644       sa4->sin_addr.s_addr = addr->ip4.as_u32;
1645       *salen = sizeof (struct sockaddr_in);
1646     }
1647   else
1648     {
1649       struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) sa;
1650       sa6->sin6_family = AF_INET6;
1651       sa6->sin6_port = port;
1652       clib_memcpy (&sa6->sin6_addr, &addr->ip6, 16);
1653       *salen = sizeof (struct sockaddr_in6);
1654     }
1655 }
1656
1657 static void
1658 quic_on_quic_session_connected (quic_ctx_t * ctx)
1659 {
1660   session_t *quic_session;
1661   app_worker_t *app_wrk;
1662   u32 ctx_id = ctx->c_c_index;
1663   u32 thread_index = ctx->c_thread_index;
1664   int rv;
1665
1666   quic_session = session_alloc (thread_index);
1667
1668   QUIC_DBG (2, "Allocated quic session 0x%lx", session_handle (quic_session));
1669   ctx->c_s_index = quic_session->session_index;
1670   quic_session->app_wrk_index = ctx->parent_app_wrk_id;
1671   quic_session->connection_index = ctx->c_c_index;
1672   quic_session->listener_handle = SESSION_INVALID_HANDLE;
1673   quic_session->session_type =
1674     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, ctx->udp_is_ip4);
1675
1676   /* If quic session connected fails, immediatly close connection */
1677   app_wrk = app_worker_get (ctx->parent_app_wrk_id);
1678   if ((rv = app_worker_init_connected (app_wrk, quic_session)))
1679     {
1680       QUIC_ERR ("failed to app_worker_init_connected");
1681       quic_proto_on_close (ctx_id, thread_index);
1682       app_worker_connect_notify (app_wrk, NULL, rv, ctx->client_opaque);
1683       return;
1684     }
1685
1686   svm_fifo_init_ooo_lookup (quic_session->rx_fifo, 0 /* ooo enq */);
1687   svm_fifo_init_ooo_lookup (quic_session->tx_fifo, 1 /* ooo deq */);
1688
1689   quic_session->session_state = SESSION_STATE_CONNECTING;
1690   if ((rv = app_worker_connect_notify (app_wrk, quic_session,
1691                                        SESSION_E_NONE, ctx->client_opaque)))
1692     {
1693       QUIC_ERR ("failed to notify app %d", rv);
1694       quic_proto_on_close (ctx_id, thread_index);
1695       return;
1696     }
1697 }
1698
1699 static void
1700 quic_check_quic_session_connected (quic_ctx_t * ctx)
1701 {
1702   /* Called when we need to trigger quic session connected
1703    * we may call this function on the server side / at
1704    * stream opening */
1705
1706   /* Conn may be set to null if the connection is terminated */
1707   if (!ctx->conn || ctx->conn_state != QUIC_CONN_STATE_HANDSHAKE)
1708     return;
1709   if (!quicly_connection_is_ready (ctx->conn))
1710     return;
1711   ctx->conn_state = QUIC_CONN_STATE_READY;
1712   if (!quicly_is_client (ctx->conn))
1713     return;
1714   quic_on_quic_session_connected (ctx);
1715 }
1716
1717 static inline void
1718 quic_update_conn_ctx (quicly_conn_t * conn, quicly_context_t * quicly_context)
1719 {
1720   /* we need to update the quicly_conn on migrate
1721    * as it contains a pointer to the crypto context */
1722   ptls_context_t **tls;
1723   quicly_context_t **_quicly_context;
1724   _quicly_context = (quicly_context_t **) conn;
1725   *_quicly_context = quicly_context;
1726   tls = (ptls_context_t **) quicly_get_tls (conn);
1727   *tls = quicly_context->tls;
1728 }
1729
1730 static void
1731 quic_receive_connection (void *arg)
1732 {
1733   u32 new_ctx_id, thread_index = vlib_get_thread_index ();
1734   quic_ctx_t *temp_ctx, *new_ctx;
1735   clib_bihash_kv_16_8_t kv;
1736   quicly_conn_t *conn;
1737   quicly_context_t *quicly_context;
1738   session_t *udp_session;
1739
1740   temp_ctx = arg;
1741   new_ctx_id = quic_ctx_alloc (thread_index);
1742   new_ctx = quic_ctx_get (new_ctx_id, thread_index);
1743
1744   QUIC_DBG (2, "Received conn %u (now %u)", temp_ctx->c_thread_index,
1745             new_ctx_id);
1746
1747   clib_memcpy (new_ctx, temp_ctx, sizeof (quic_ctx_t));
1748   clib_mem_free (temp_ctx);
1749
1750   new_ctx->c_thread_index = thread_index;
1751   new_ctx->c_c_index = new_ctx_id;
1752   quic_acquire_crypto_context (new_ctx);
1753
1754   conn = new_ctx->conn;
1755   quicly_context = quic_get_quicly_ctx_from_ctx (new_ctx);
1756   quic_update_conn_ctx (conn, quicly_context);
1757
1758   quic_store_conn_ctx (conn, new_ctx);
1759   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1760   kv.value = ((u64) thread_index) << 32 | (u64) new_ctx_id;
1761   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1762   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1763   new_ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1764   quic_update_timer (new_ctx);
1765
1766   /*  Trigger write on this connection if necessary */
1767   udp_session = session_get_from_handle (new_ctx->udp_session_handle);
1768   udp_session->opaque = new_ctx_id;
1769   udp_session->flags &= ~SESSION_F_IS_MIGRATING;
1770   if (svm_fifo_max_dequeue (udp_session->tx_fifo))
1771     quic_set_udp_tx_evt (udp_session);
1772 }
1773
1774 static void
1775 quic_transfer_connection (u32 ctx_index, u32 dest_thread)
1776 {
1777   quic_ctx_t *ctx, *temp_ctx;
1778   u32 thread_index = vlib_get_thread_index ();
1779
1780   QUIC_DBG (2, "Transferring conn %u to thread %u", ctx_index, dest_thread);
1781
1782   temp_ctx = clib_mem_alloc (sizeof (quic_ctx_t));
1783   QUIC_ASSERT (temp_ctx != NULL);
1784   ctx = quic_ctx_get (ctx_index, thread_index);
1785
1786   clib_memcpy (temp_ctx, ctx, sizeof (quic_ctx_t));
1787
1788   quic_stop_ctx_timer (ctx);
1789   quic_release_crypto_context (ctx->crypto_context_index, thread_index);
1790   quic_ctx_free (ctx);
1791
1792   /*  Send connection to destination thread */
1793   session_send_rpc_evt_to_thread (dest_thread, quic_receive_connection,
1794                                   (void *) temp_ctx);
1795 }
1796
1797 static int
1798 quic_udp_session_connected_callback (u32 quic_app_index, u32 ctx_index,
1799                                      session_t * udp_session,
1800                                      session_error_t err)
1801 {
1802   QUIC_DBG (2, "UDP Session is now connected (id %u)",
1803             udp_session->session_index);
1804   /* This should always be called before quic_connect returns since UDP always
1805    * connects instantly. */
1806   clib_bihash_kv_16_8_t kv;
1807   struct sockaddr_in6 sa6;
1808   struct sockaddr *sa = (struct sockaddr *) &sa6;
1809   socklen_t salen;
1810   transport_connection_t *tc;
1811   app_worker_t *app_wrk;
1812   quicly_conn_t *conn;
1813   quic_ctx_t *ctx;
1814   u32 thread_index;
1815   int ret;
1816   quicly_context_t *quicly_ctx;
1817
1818   /* Allocate session on whatever thread udp used, i.e., probably first
1819    * worker, although this may be main thread. If it is main, it's done
1820    * with a worker barrier */
1821   thread_index = udp_session->thread_index;
1822   ASSERT (thread_index == 0 || thread_index == 1);
1823   ctx = quic_ctx_get (ctx_index, thread_index);
1824   if (err)
1825     {
1826       u32 api_context;
1827       app_wrk = app_worker_get_if_valid (ctx->parent_app_wrk_id);
1828       if (app_wrk)
1829         {
1830           api_context = ctx->c_s_index;
1831           app_worker_connect_notify (app_wrk, 0, SESSION_E_NONE, api_context);
1832         }
1833       return 0;
1834     }
1835
1836   QUIC_DBG (2, "New ctx [%u]%x", thread_index, (ctx) ? ctx_index : ~0);
1837
1838   ctx->udp_session_handle = session_handle (udp_session);
1839   udp_session->opaque = ctx_index;
1840
1841   /* Init QUIC lib connection
1842    * Generate required sockaddr & salen */
1843   tc = session_get_transport (udp_session);
1844   quic_build_sockaddr (sa, &salen, &tc->rmt_ip, tc->rmt_port, tc->is_ip4);
1845
1846   quicly_ctx = quic_get_quicly_ctx_from_ctx (ctx);
1847   ret = quicly_connect (&ctx->conn, quicly_ctx, (char *) ctx->srv_hostname,
1848                         sa, NULL, &quic_main.wrk_ctx[thread_index].next_cid,
1849                         ptls_iovec_init (NULL, 0), &quic_main.hs_properties,
1850                         NULL);
1851   ++quic_main.wrk_ctx[thread_index].next_cid.master_id;
1852   /*  Save context handle in quicly connection */
1853   quic_store_conn_ctx (ctx->conn, ctx);
1854   assert (ret == 0);
1855
1856   /*  Register connection in connections map */
1857   conn = ctx->conn;
1858   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1859   kv.value = ((u64) thread_index) << 32 | (u64) ctx_index;
1860   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1861   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1862
1863   quic_send_packets (ctx);
1864
1865   return ret;
1866 }
1867
1868 static void
1869 quic_udp_session_disconnect_callback (session_t * s)
1870 {
1871   clib_warning ("UDP session disconnected???");
1872 }
1873
1874 static void
1875 quic_udp_session_cleanup_callback (session_t * udp_session,
1876                                    session_cleanup_ntf_t ntf)
1877 {
1878   quic_ctx_t *ctx;
1879
1880   if (ntf != SESSION_CLEANUP_SESSION)
1881     return;
1882
1883   ctx = quic_ctx_get (udp_session->opaque, udp_session->thread_index);
1884   quic_stop_ctx_timer (ctx);
1885   quic_release_crypto_context (ctx->crypto_context_index,
1886                                ctx->c_thread_index);
1887   quic_ctx_free (ctx);
1888 }
1889
1890 static void
1891 quic_udp_session_reset_callback (session_t * s)
1892 {
1893   clib_warning ("UDP session reset???");
1894 }
1895
1896 static void
1897 quic_udp_session_migrate_callback (session_t * s, session_handle_t new_sh)
1898 {
1899   u32 new_thread = session_thread_from_handle (new_sh);
1900   quic_ctx_t *ctx;
1901
1902   QUIC_DBG (2, "Session %x migrated to %lx", s->session_index, new_sh);
1903   QUIC_ASSERT (vlib_get_thread_index () == s->thread_index);
1904   ctx = quic_ctx_get (s->opaque, s->thread_index);
1905   QUIC_ASSERT (ctx->udp_session_handle == session_handle (s));
1906
1907   ctx->udp_session_handle = new_sh;
1908 #if QUIC_DEBUG >= 1
1909   s->opaque = 0xfeedface;
1910 #endif
1911   quic_transfer_connection (ctx->c_c_index, new_thread);
1912 }
1913
1914 int
1915 quic_udp_session_accepted_callback (session_t * udp_session)
1916 {
1917   /* New UDP connection, try to accept it */
1918   u32 ctx_index;
1919   quic_ctx_t *ctx, *lctx;
1920   session_t *udp_listen_session;
1921   u32 thread_index = vlib_get_thread_index ();
1922
1923   udp_listen_session =
1924     listen_session_get_from_handle (udp_session->listener_handle);
1925
1926   ctx_index = quic_ctx_alloc (thread_index);
1927   ctx = quic_ctx_get (ctx_index, thread_index);
1928   ctx->c_thread_index = udp_session->thread_index;
1929   ctx->c_c_index = ctx_index;
1930   ctx->c_s_index = QUIC_SESSION_INVALID;
1931   ctx->udp_session_handle = session_handle (udp_session);
1932   QUIC_DBG (2, "ACCEPTED UDP 0x%lx", ctx->udp_session_handle);
1933   ctx->listener_ctx_id = udp_listen_session->opaque;
1934   lctx = quic_ctx_get (udp_listen_session->opaque,
1935                        udp_listen_session->thread_index);
1936   ctx->udp_is_ip4 = lctx->c_is_ip4;
1937   ctx->parent_app_id = lctx->parent_app_id;
1938   ctx->parent_app_wrk_id = lctx->parent_app_wrk_id;
1939   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1940   ctx->conn_state = QUIC_CONN_STATE_OPENED;
1941   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1942
1943   ctx->crypto_engine = lctx->crypto_engine;
1944   ctx->ckpair_index = lctx->ckpair_index;
1945   quic_acquire_crypto_context (ctx);
1946   udp_session->opaque = ctx_index;
1947   udp_session->session_state = SESSION_STATE_READY;
1948
1949   /* TODO timeout to delete these if they never connect */
1950   return 0;
1951 }
1952
1953 static int
1954 quic_add_segment_callback (u32 client_index, u64 seg_handle)
1955 {
1956   /* No-op for builtin */
1957   return 0;
1958 }
1959
1960 static int
1961 quic_del_segment_callback (u32 client_index, u64 seg_handle)
1962 {
1963   /* No-op for builtin */
1964   return 0;
1965 }
1966
1967 static int
1968 quic_custom_app_rx_callback (transport_connection_t * tc)
1969 {
1970   quic_ctx_t *ctx;
1971   session_t *stream_session = session_get (tc->s_index, tc->thread_index);
1972   QUIC_DBG (3, "Received app READ notification");
1973   quic_ack_rx_data (stream_session);
1974   svm_fifo_reset_has_deq_ntf (stream_session->rx_fifo);
1975
1976   /* Need to send packets (acks may never be sent otherwise) */
1977   ctx = quic_ctx_get (stream_session->connection_index,
1978                       stream_session->thread_index);
1979   quic_send_packets (ctx);
1980   return 0;
1981 }
1982
1983 static int
1984 quic_custom_tx_callback (void *s, transport_send_params_t * sp)
1985 {
1986   session_t *stream_session = (session_t *) s;
1987   quic_stream_data_t *stream_data;
1988   quicly_stream_t *stream;
1989   quic_ctx_t *ctx;
1990   u32 max_deq;
1991   int rv;
1992
1993   if (PREDICT_FALSE
1994       (stream_session->session_state >= SESSION_STATE_TRANSPORT_CLOSING))
1995     return 0;
1996   ctx = quic_ctx_get (stream_session->connection_index,
1997                       stream_session->thread_index);
1998   if (PREDICT_FALSE (!quic_ctx_is_stream (ctx)))
1999     {
2000       goto tx_end;              /* Most probably a reschedule */
2001     }
2002
2003   QUIC_DBG (3, "Stream TX event");
2004   quic_ack_rx_data (stream_session);
2005   stream = ctx->stream;
2006   if (!quicly_sendstate_is_open (&stream->sendstate))
2007     {
2008       QUIC_ERR ("Warning: tried to send on closed stream");
2009       return 0;
2010     }
2011
2012   stream_data = (quic_stream_data_t *) stream->data;
2013   max_deq = svm_fifo_max_dequeue (stream_session->tx_fifo);
2014   QUIC_ASSERT (max_deq >= stream_data->app_tx_data_len);
2015   if (max_deq == stream_data->app_tx_data_len)
2016     {
2017       QUIC_DBG (3, "TX but no data %d / %d", max_deq,
2018                 stream_data->app_tx_data_len);
2019       return 0;
2020     }
2021   stream_data->app_tx_data_len = max_deq;
2022   rv = quicly_stream_sync_sendbuf (stream, 1);
2023   QUIC_ASSERT (!rv);
2024
2025 tx_end:
2026   return quic_send_packets (ctx);
2027 }
2028
2029 /*
2030  * Returns 0 if a matching connection is found and is on the right thread.
2031  * Otherwise returns -1.
2032  * If a connection is found, even on the wrong thread, ctx_thread and ctx_index
2033  * will be set.
2034  */
2035 static inline int
2036 quic_find_packet_ctx (quic_rx_packet_ctx_t * pctx, u32 caller_thread_index)
2037 {
2038   clib_bihash_kv_16_8_t kv;
2039   clib_bihash_16_8_t *h;
2040   quic_ctx_t *ctx;
2041   u32 index, thread_id;
2042
2043   h = &quic_main.connection_hash;
2044   quic_make_connection_key (&kv, &pctx->packet.cid.dest.plaintext);
2045   QUIC_DBG (3, "Searching conn with id %lu %lu", kv.key[0], kv.key[1]);
2046
2047   if (clib_bihash_search_16_8 (h, &kv, &kv))
2048     {
2049       QUIC_DBG (3, "connection not found");
2050       return QUIC_PACKET_TYPE_NONE;
2051     }
2052
2053   index = kv.value & UINT32_MAX;
2054   thread_id = kv.value >> 32;
2055   /* Check if this connection belongs to this thread, otherwise
2056    * ask for it to be moved */
2057   if (thread_id != caller_thread_index)
2058     {
2059       QUIC_DBG (2, "Connection is on wrong thread");
2060       /* Cannot make full check with quicly_is_destination... */
2061       pctx->ctx_index = index;
2062       pctx->thread_index = thread_id;
2063       return QUIC_PACKET_TYPE_MIGRATE;
2064     }
2065   ctx = quic_ctx_get (index, vlib_get_thread_index ());
2066   if (!ctx->conn)
2067     {
2068       QUIC_ERR ("ctx has no conn");
2069       return QUIC_PACKET_TYPE_NONE;
2070     }
2071   if (!quicly_is_destination (ctx->conn, NULL, &pctx->sa, &pctx->packet))
2072     return QUIC_PACKET_TYPE_NONE;
2073
2074   QUIC_DBG (3, "Connection found");
2075   pctx->ctx_index = index;
2076   pctx->thread_index = thread_id;
2077   return QUIC_PACKET_TYPE_RECEIVE;
2078 }
2079
2080 static void
2081 quic_accept_connection (quic_rx_packet_ctx_t * pctx)
2082 {
2083   quicly_context_t *quicly_ctx;
2084   session_t *quic_session;
2085   clib_bihash_kv_16_8_t kv;
2086   app_worker_t *app_wrk;
2087   quicly_conn_t *conn;
2088   quic_ctx_t *ctx;
2089   quic_ctx_t *lctx;
2090   int rv;
2091
2092   /* new connection, accept and create context if packet is valid
2093    * TODO: check if socket is actually listening? */
2094   ctx = quic_ctx_get (pctx->ctx_index, pctx->thread_index);
2095   if (ctx->c_s_index != QUIC_SESSION_INVALID)
2096     {
2097       QUIC_DBG (2, "already accepted ctx 0x%x", ctx->c_s_index);
2098       return;
2099     }
2100
2101   quicly_ctx = quic_get_quicly_ctx_from_ctx (ctx);
2102   if ((rv = quicly_accept (&conn, quicly_ctx, NULL, &pctx->sa,
2103                            &pctx->packet, NULL,
2104                            &quic_main.wrk_ctx[pctx->thread_index].next_cid,
2105                            NULL)))
2106     {
2107       /* Invalid packet, pass */
2108       assert (conn == NULL);
2109       QUIC_ERR ("Accept failed with %U", quic_format_err, rv);
2110       /* TODO: cleanup created quic ctx and UDP session */
2111       return;
2112     }
2113   assert (conn != NULL);
2114
2115   ++quic_main.wrk_ctx[pctx->thread_index].next_cid.master_id;
2116   /* Save ctx handle in quicly connection */
2117   quic_store_conn_ctx (conn, ctx);
2118   ctx->conn = conn;
2119
2120   quic_session = session_alloc (ctx->c_thread_index);
2121   QUIC_DBG (2, "Allocated quic_session, 0x%lx ctx %u",
2122             session_handle (quic_session), ctx->c_c_index);
2123   ctx->c_s_index = quic_session->session_index;
2124
2125   lctx = quic_ctx_get (ctx->listener_ctx_id, 0);
2126
2127   quic_session->app_wrk_index = lctx->parent_app_wrk_id;
2128   quic_session->connection_index = ctx->c_c_index;
2129   quic_session->session_type =
2130     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, ctx->udp_is_ip4);
2131   quic_session->listener_handle = lctx->c_s_index;
2132
2133   /* Register connection in connections map */
2134   quic_make_connection_key (&kv, quicly_get_master_id (conn));
2135   kv.value = ((u64) pctx->thread_index) << 32 | (u64) pctx->ctx_index;
2136   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
2137   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
2138
2139   /* If notify fails, reset connection immediatly */
2140   if ((rv = app_worker_init_accepted (quic_session)))
2141     {
2142       QUIC_ERR ("failed to allocate fifos");
2143       quic_proto_on_close (pctx->ctx_index, pctx->thread_index);
2144       return;
2145     }
2146
2147   svm_fifo_init_ooo_lookup (quic_session->rx_fifo, 0 /* ooo enq */);
2148   svm_fifo_init_ooo_lookup (quic_session->tx_fifo, 1 /* ooo deq */);
2149
2150   app_wrk = app_worker_get (quic_session->app_wrk_index);
2151   quic_session->session_state = SESSION_STATE_ACCEPTING;
2152   if ((rv = app_worker_accept_notify (app_wrk, quic_session)))
2153     {
2154       QUIC_ERR ("failed to notify accept worker app");
2155       quic_proto_on_close (pctx->ctx_index, pctx->thread_index);
2156       return;
2157     }
2158
2159   ctx->conn_state = QUIC_CONN_STATE_READY;
2160 }
2161
2162 static int
2163 quic_reset_connection (u64 udp_session_handle, quic_rx_packet_ctx_t * pctx)
2164 {
2165   /* short header packet; potentially a dead connection. No need to check the
2166    * length of the incoming packet, because loop is prevented by authenticating
2167    * the CID (by checking node_id and thread_id). If the peer is also sending a
2168    * reset, then the next CID is highly likely to contain a non-authenticating
2169    * CID, ... */
2170   QUIC_DBG (2, "Sending stateless reset");
2171   int rv;
2172   session_t *udp_session;
2173   quicly_context_t *quicly_ctx;
2174   if (pctx->packet.cid.dest.plaintext.node_id != 0
2175       || pctx->packet.cid.dest.plaintext.thread_id != 0)
2176     return 0;
2177   quicly_ctx = quic_get_quicly_ctx_from_udp (udp_session_handle);
2178   quic_ctx_t *qctx = quic_ctx_get (pctx->ctx_index, pctx->thread_index);
2179
2180   quicly_address_t src;
2181   uint8_t payload[quicly_ctx->transport_params.max_udp_payload_size];
2182   size_t payload_len =
2183     quicly_send_stateless_reset (quicly_ctx, &src.sa, payload);
2184   if (payload_len == 0)
2185     return 1;
2186
2187   struct iovec packet;
2188   packet.iov_len = payload_len;
2189   packet.iov_base = payload;
2190
2191   struct _st_quicly_conn_public_t *conn =
2192     (struct _st_quicly_conn_public_t *) qctx->conn;
2193
2194   udp_session = session_get_from_handle (udp_session_handle);
2195   rv = quic_send_datagram (udp_session, &packet, &conn->remote.address,
2196                            &conn->local.address);
2197   quic_set_udp_tx_evt (udp_session);
2198   return rv;
2199 }
2200
2201 static int
2202 quic_process_one_rx_packet (u64 udp_session_handle, svm_fifo_t * f,
2203                             u32 fifo_offset, quic_rx_packet_ctx_t * pctx)
2204 {
2205   size_t plen;
2206   u32 full_len, ret;
2207   u32 thread_index = vlib_get_thread_index ();
2208   u32 cur_deq = svm_fifo_max_dequeue (f) - fifo_offset;
2209   quicly_context_t *quicly_ctx;
2210   session_t *udp_session;
2211   int rv;
2212
2213   ret = svm_fifo_peek (f, fifo_offset,
2214                        SESSION_CONN_HDR_LEN, (u8 *) & pctx->ph);
2215   QUIC_ASSERT (ret == SESSION_CONN_HDR_LEN);
2216   QUIC_ASSERT (pctx->ph.data_offset == 0);
2217   full_len = pctx->ph.data_length + SESSION_CONN_HDR_LEN;
2218   if (full_len > cur_deq)
2219     {
2220       QUIC_ERR ("Not enough data in fifo RX");
2221       return 1;
2222     }
2223
2224   /* Quicly can read len bytes from the fifo at offset:
2225    * ph.data_offset + SESSION_CONN_HDR_LEN */
2226   ret = svm_fifo_peek (f, SESSION_CONN_HDR_LEN + fifo_offset,
2227                        pctx->ph.data_length, pctx->data);
2228   if (ret != pctx->ph.data_length)
2229     {
2230       QUIC_ERR ("Not enough data peeked in RX");
2231       return 1;
2232     }
2233
2234   quic_increment_counter (QUIC_ERROR_RX_PACKETS, 1);
2235   quic_build_sockaddr (&pctx->sa, &pctx->salen, &pctx->ph.rmt_ip,
2236                        pctx->ph.rmt_port, pctx->ph.is_ip4);
2237   quicly_ctx = quic_get_quicly_ctx_from_udp (udp_session_handle);
2238
2239   size_t off = 0;
2240   plen = quicly_decode_packet (quicly_ctx, &pctx->packet, pctx->data,
2241                                pctx->ph.data_length, &off);
2242
2243   if (plen == SIZE_MAX)
2244     {
2245       return 1;
2246     }
2247
2248   rv = quic_find_packet_ctx (pctx, thread_index);
2249   if (rv == QUIC_PACKET_TYPE_RECEIVE)
2250     {
2251       pctx->ptype = QUIC_PACKET_TYPE_RECEIVE;
2252
2253       if (quic_main.vnet_crypto_enabled &&
2254           quic_main.default_crypto_engine == CRYPTO_ENGINE_VPP)
2255         {
2256           quic_ctx_t *qctx = quic_ctx_get (pctx->ctx_index, thread_index);
2257           quic_crypto_decrypt_packet (qctx, pctx);
2258         }
2259       return 0;
2260     }
2261   else if (rv == QUIC_PACKET_TYPE_MIGRATE)
2262     {
2263       pctx->ptype = QUIC_PACKET_TYPE_MIGRATE;
2264       /*  Connection found but on wrong thread, ask move */
2265     }
2266   else if (QUICLY_PACKET_IS_LONG_HEADER (pctx->packet.octets.base[0]))
2267     {
2268       pctx->ptype = QUIC_PACKET_TYPE_ACCEPT;
2269       udp_session = session_get_from_handle (udp_session_handle);
2270       pctx->ctx_index = udp_session->opaque;
2271       pctx->thread_index = thread_index;
2272     }
2273   else
2274     {
2275       pctx->ptype = QUIC_PACKET_TYPE_RESET;
2276     }
2277   return 1;
2278 }
2279
2280 static int
2281 quic_udp_session_rx_callback (session_t * udp_session)
2282 {
2283   /*  Read data from UDP rx_fifo and pass it to the quicly conn. */
2284   quic_ctx_t *ctx = NULL, *prev_ctx = NULL;
2285   svm_fifo_t *f = udp_session->rx_fifo;
2286   u32 max_deq;
2287   u64 udp_session_handle = session_handle (udp_session);
2288   int rv = 0;
2289   u32 thread_index = vlib_get_thread_index ();
2290   u32 cur_deq, fifo_offset, max_packets, i;
2291
2292   quic_rx_packet_ctx_t packets_ctx[QUIC_RCV_MAX_PACKETS];
2293
2294   if (udp_session->flags & SESSION_F_IS_MIGRATING)
2295     {
2296       QUIC_DBG (3, "RX on migrating udp session");
2297       return 0;
2298     }
2299
2300 rx_start:
2301   max_deq = svm_fifo_max_dequeue (f);
2302   if (max_deq == 0)
2303     return 0;
2304
2305   fifo_offset = 0;
2306   max_packets = QUIC_RCV_MAX_PACKETS;
2307
2308 #if CLIB_DEBUG > 0
2309   clib_memset (packets_ctx, 0xfa,
2310                QUIC_RCV_MAX_PACKETS * sizeof (quic_rx_packet_ctx_t));
2311 #endif
2312   for (i = 0; i < max_packets; i++)
2313     {
2314       packets_ctx[i].thread_index = UINT32_MAX;
2315       packets_ctx[i].ctx_index = UINT32_MAX;
2316       packets_ctx[i].ptype = QUIC_PACKET_TYPE_DROP;
2317
2318       cur_deq = max_deq - fifo_offset;
2319       if (cur_deq == 0)
2320         {
2321           max_packets = i + 1;
2322           break;
2323         }
2324       if (cur_deq < SESSION_CONN_HDR_LEN)
2325         {
2326           fifo_offset = max_deq;
2327           max_packets = i + 1;
2328           QUIC_ERR ("Fifo %d < header size in RX", cur_deq);
2329           break;
2330         }
2331       rv = quic_process_one_rx_packet (udp_session_handle, f,
2332                                        fifo_offset, &packets_ctx[i]);
2333       if (packets_ctx[i].ptype != QUIC_PACKET_TYPE_MIGRATE)
2334         fifo_offset += SESSION_CONN_HDR_LEN + packets_ctx[i].ph.data_length;
2335       if (rv)
2336         {
2337           max_packets = i + 1;
2338           break;
2339         }
2340     }
2341
2342   for (i = 0; i < max_packets; i++)
2343     {
2344       switch (packets_ctx[i].ptype)
2345         {
2346         case QUIC_PACKET_TYPE_RECEIVE:
2347           ctx = quic_ctx_get (packets_ctx[i].ctx_index, thread_index);
2348           rv = quicly_receive (ctx->conn, NULL, &packets_ctx[i].sa,
2349                                &packets_ctx[i].packet);
2350           if (rv && rv != QUICLY_ERROR_PACKET_IGNORED)
2351             {
2352               QUIC_ERR ("quicly_receive return error %U",
2353                         quic_format_err, rv);
2354             }
2355           break;
2356         case QUIC_PACKET_TYPE_ACCEPT:
2357           quic_accept_connection (&packets_ctx[i]);
2358           break;
2359         case QUIC_PACKET_TYPE_RESET:
2360           quic_reset_connection (udp_session_handle, &packets_ctx[i]);
2361           break;
2362         }
2363     }
2364   ctx = prev_ctx = NULL;
2365   for (i = 0; i < max_packets; i++)
2366     {
2367       prev_ctx = ctx;
2368       switch (packets_ctx[i].ptype)
2369         {
2370         case QUIC_PACKET_TYPE_RECEIVE:
2371           ctx = quic_ctx_get (packets_ctx[i].ctx_index,
2372                               packets_ctx[i].thread_index);
2373           quic_check_quic_session_connected (ctx);
2374           ctx = quic_ctx_get (packets_ctx[i].ctx_index,
2375                               packets_ctx[i].thread_index);
2376           break;
2377         case QUIC_PACKET_TYPE_ACCEPT:
2378           ctx = quic_ctx_get (packets_ctx[i].ctx_index,
2379                               packets_ctx[i].thread_index);
2380           break;
2381         default:
2382           continue;             /* this exits the for loop since other packet types are
2383                                    necessarily the last in the batch */
2384         }
2385       if (ctx != prev_ctx)
2386         quic_send_packets (ctx);
2387     }
2388
2389   udp_session = session_get_from_handle (udp_session_handle);   /*  session alloc might have happened */
2390   f = udp_session->rx_fifo;
2391   svm_fifo_dequeue_drop (f, fifo_offset);
2392
2393   if (svm_fifo_max_dequeue (f))
2394     goto rx_start;
2395
2396   return 0;
2397 }
2398
2399 always_inline void
2400 quic_common_get_transport_endpoint (quic_ctx_t * ctx,
2401                                     transport_endpoint_t * tep, u8 is_lcl)
2402 {
2403   session_t *udp_session;
2404   if (!quic_ctx_is_stream (ctx))
2405     {
2406       udp_session = session_get_from_handle (ctx->udp_session_handle);
2407       session_get_endpoint (udp_session, tep, is_lcl);
2408     }
2409 }
2410
2411 static void
2412 quic_get_transport_listener_endpoint (u32 listener_index,
2413                                       transport_endpoint_t * tep, u8 is_lcl)
2414 {
2415   quic_ctx_t *ctx;
2416   app_listener_t *app_listener;
2417   session_t *udp_listen_session;
2418   ctx = quic_ctx_get (listener_index, vlib_get_thread_index ());
2419   if (quic_ctx_is_listener (ctx))
2420     {
2421       app_listener = app_listener_get_w_handle (ctx->udp_session_handle);
2422       udp_listen_session = app_listener_get_session (app_listener);
2423       return session_get_endpoint (udp_listen_session, tep, is_lcl);
2424     }
2425   quic_common_get_transport_endpoint (ctx, tep, is_lcl);
2426 }
2427
2428 static void
2429 quic_get_transport_endpoint (u32 ctx_index, u32 thread_index,
2430                              transport_endpoint_t * tep, u8 is_lcl)
2431 {
2432   quic_ctx_t *ctx;
2433   ctx = quic_ctx_get (ctx_index, thread_index);
2434   quic_common_get_transport_endpoint (ctx, tep, is_lcl);
2435 }
2436
2437 static session_cb_vft_t quic_app_cb_vft = {
2438   .session_accept_callback = quic_udp_session_accepted_callback,
2439   .session_disconnect_callback = quic_udp_session_disconnect_callback,
2440   .session_connected_callback = quic_udp_session_connected_callback,
2441   .session_reset_callback = quic_udp_session_reset_callback,
2442   .session_migrate_callback = quic_udp_session_migrate_callback,
2443   .add_segment_callback = quic_add_segment_callback,
2444   .del_segment_callback = quic_del_segment_callback,
2445   .builtin_app_rx_callback = quic_udp_session_rx_callback,
2446   .session_cleanup_callback = quic_udp_session_cleanup_callback,
2447   .app_cert_key_pair_delete_callback = quic_app_cert_key_pair_delete_callback,
2448 };
2449
2450 static const transport_proto_vft_t quic_proto = {
2451   .connect = quic_connect,
2452   .close = quic_proto_on_close,
2453   .start_listen = quic_start_listen,
2454   .stop_listen = quic_stop_listen,
2455   .get_connection = quic_connection_get,
2456   .get_listener = quic_listener_get,
2457   .update_time = quic_update_time,
2458   .app_rx_evt = quic_custom_app_rx_callback,
2459   .custom_tx = quic_custom_tx_callback,
2460   .format_connection = format_quic_connection,
2461   .format_half_open = format_quic_half_open,
2462   .format_listener = format_quic_listener,
2463   .get_transport_endpoint = quic_get_transport_endpoint,
2464   .get_transport_listener_endpoint = quic_get_transport_listener_endpoint,
2465   .transport_options = {
2466     .name = "quic",
2467     .short_name = "Q",
2468     .tx_type = TRANSPORT_TX_INTERNAL,
2469     .service_type = TRANSPORT_SERVICE_APP,
2470   },
2471 };
2472
2473 static quicly_stream_open_t on_stream_open = { quic_on_stream_open };
2474 static quicly_closed_by_remote_t on_closed_by_remote = {
2475   quic_on_closed_by_remote
2476 };
2477 static quicly_now_t quicly_vpp_now_cb = { quic_get_time };
2478
2479 static void
2480 quic_register_cipher_suite (crypto_engine_type_t type,
2481                             ptls_cipher_suite_t ** ciphers)
2482 {
2483   quic_main_t *qm = &quic_main;
2484   vec_validate (qm->quic_ciphers, type);
2485   clib_bitmap_set (qm->available_crypto_engines, type, 1);
2486   qm->quic_ciphers[type] = ciphers;
2487 }
2488
2489 static void
2490 quic_update_fifo_size ()
2491 {
2492   quic_main_t *qm = &quic_main;
2493   segment_manager_props_t *seg_mgr_props =
2494     application_get_segment_manager_properties (qm->app_index);
2495
2496   if (!seg_mgr_props)
2497     {
2498       clib_warning
2499         ("error while getting segment_manager_props_t, can't update fifo-size");
2500       return;
2501     }
2502
2503   seg_mgr_props->tx_fifo_size = qm->udp_fifo_size;
2504   seg_mgr_props->rx_fifo_size = qm->udp_fifo_size;
2505 }
2506
2507 static clib_error_t *
2508 quic_init (vlib_main_t * vm)
2509 {
2510   u32 segment_size = 256 << 20;
2511   vlib_thread_main_t *vtm = vlib_get_thread_main ();
2512   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
2513   vnet_app_attach_args_t _a, *a = &_a;
2514   u64 options[APP_OPTIONS_N_OPTIONS];
2515   quic_main_t *qm = &quic_main;
2516   u32 num_threads, i;
2517   u8 seed[32];
2518
2519   if (syscall (SYS_getrandom, &seed, sizeof (seed), 0) != sizeof (seed))
2520     return clib_error_return_unix (0, "getrandom() failed");
2521   RAND_seed (seed, sizeof (seed));
2522
2523   num_threads = 1 /* main thread */  + vtm->n_threads;
2524
2525   clib_memset (a, 0, sizeof (*a));
2526   clib_memset (options, 0, sizeof (options));
2527
2528   a->session_cb_vft = &quic_app_cb_vft;
2529   a->api_client_index = APP_INVALID_INDEX;
2530   a->options = options;
2531   a->name = format (0, "quic");
2532   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
2533   a->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = segment_size;
2534   a->options[APP_OPTIONS_RX_FIFO_SIZE] = qm->udp_fifo_size;
2535   a->options[APP_OPTIONS_TX_FIFO_SIZE] = qm->udp_fifo_size;
2536   a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = qm->udp_fifo_prealloc;
2537   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
2538   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
2539   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
2540
2541   if (vnet_application_attach (a))
2542     {
2543       clib_warning ("failed to attach quic app");
2544       return clib_error_return (0, "failed to attach quic app");
2545     }
2546
2547   vec_validate (qm->ctx_pool, num_threads - 1);
2548   vec_validate (qm->wrk_ctx, num_threads - 1);
2549
2550   for (i = 0; i < num_threads; i++)
2551     {
2552       qm->wrk_ctx[i].next_cid.thread_id = i;
2553       tw = &qm->wrk_ctx[i].timer_wheel;
2554       tw_timer_wheel_init_1t_3w_1024sl_ov (tw, quic_expired_timers_dispatch,
2555                                            1e-3 /* timer period 1ms */ , ~0);
2556       tw->last_run_time = vlib_time_now (vlib_get_main ());
2557       clib_bihash_init_24_8 (&qm->wrk_ctx[i].crypto_context_hash,
2558                              "quic crypto contexts", 64, 128 << 10);
2559     }
2560
2561   clib_bihash_init_16_8 (&qm->connection_hash, "quic connections", 1024,
2562                          4 << 20);
2563
2564   qm->app_index = a->app_index;
2565   qm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
2566     / QUIC_TSTAMP_RESOLUTION;
2567   qm->session_cache.super.cb = quic_encrypt_ticket_cb;
2568
2569   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
2570                                FIB_PROTOCOL_IP4, ~0);
2571   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
2572                                FIB_PROTOCOL_IP6, ~0);
2573
2574   quic_load_openssl3_legacy_provider ();
2575   clib_bitmap_alloc (qm->available_crypto_engines,
2576                      app_crypto_engine_n_types ());
2577   quic_register_cipher_suite (CRYPTO_ENGINE_PICOTLS,
2578                               ptls_openssl_cipher_suites);
2579   qm->default_crypto_engine = CRYPTO_ENGINE_PICOTLS;
2580
2581   vnet_crypto_main_t *cm = &crypto_main;
2582   if (vec_len (cm->engines) == 0)
2583     qm->vnet_crypto_enabled = 0;
2584   else
2585     qm->vnet_crypto_enabled = 1;
2586   if (qm->vnet_crypto_enabled == 1)
2587     {
2588       u8 empty_key[32] = {};
2589       quic_register_cipher_suite (CRYPTO_ENGINE_VPP,
2590                                   quic_crypto_cipher_suites);
2591       qm->default_crypto_engine = CRYPTO_ENGINE_VPP;
2592       vec_validate (qm->per_thread_crypto_key_indices, num_threads);
2593       for (i = 0; i < num_threads; i++)
2594         {
2595           qm->per_thread_crypto_key_indices[i] = vnet_crypto_key_add (
2596             vm, VNET_CRYPTO_ALG_AES_256_CTR, empty_key, 32);
2597         }
2598     }
2599
2600   qm->max_packets_per_key = DEFAULT_MAX_PACKETS_PER_KEY;
2601   qm->default_quic_cc = QUIC_CC_RENO;
2602
2603   vec_free (a->name);
2604   return 0;
2605 }
2606
2607 VLIB_INIT_FUNCTION (quic_init);
2608
2609 static clib_error_t *
2610 quic_plugin_crypto_command_fn (vlib_main_t * vm,
2611                                unformat_input_t * input,
2612                                vlib_cli_command_t * cmd)
2613 {
2614   unformat_input_t _line_input, *line_input = &_line_input;
2615   quic_main_t *qm = &quic_main;
2616   clib_error_t *e = 0;
2617
2618   if (!unformat_user (input, unformat_line_input, line_input))
2619     return 0;
2620
2621   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2622     {
2623       if (unformat (line_input, "vpp"))
2624         qm->default_crypto_engine = CRYPTO_ENGINE_VPP;
2625       else if (unformat (line_input, "picotls"))
2626         qm->default_crypto_engine = CRYPTO_ENGINE_PICOTLS;
2627       else
2628         {
2629           e = clib_error_return (0, "unknown input '%U'",
2630                                  format_unformat_error, line_input);
2631           goto done;
2632         }
2633     }
2634 done:
2635   unformat_free (line_input);
2636   return e;
2637 }
2638
2639 u64 quic_fifosize = 0;
2640 static clib_error_t *
2641 quic_plugin_set_fifo_size_command_fn (vlib_main_t * vm,
2642                                       unformat_input_t * input,
2643                                       vlib_cli_command_t * cmd)
2644 {
2645   quic_main_t *qm = &quic_main;
2646   unformat_input_t _line_input, *line_input = &_line_input;
2647   uword tmp;
2648
2649   if (!unformat_user (input, unformat_line_input, line_input))
2650     return 0;
2651
2652   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2653     {
2654       if (unformat (line_input, "%U", unformat_memory_size, &tmp))
2655         {
2656           if (tmp >= 0x100000000ULL)
2657             {
2658               return clib_error_return
2659                 (0, "fifo-size %llu (0x%llx) too large", tmp, tmp);
2660             }
2661           qm->udp_fifo_size = tmp;
2662           quic_update_fifo_size ();
2663         }
2664       else
2665         return clib_error_return (0, "unknown input '%U'",
2666                                   format_unformat_error, line_input);
2667     }
2668
2669   return 0;
2670 }
2671
2672 static inline u64
2673 quic_get_counter_value (u32 event_code)
2674 {
2675   vlib_node_t *n;
2676   vlib_main_t *vm;
2677   vlib_error_main_t *em;
2678
2679   u32 code, i;
2680   u64 c, sum = 0;
2681
2682   vm = vlib_get_main ();
2683   em = &vm->error_main;
2684   n = vlib_get_node (vm, quic_input_node.index);
2685   code = event_code;
2686   foreach_vlib_main ()
2687     {
2688       em = &this_vlib_main->error_main;
2689       i = n->error_heap_index + code;
2690       c = em->counters[i];
2691
2692       if (i < vec_len (em->counters_last_clear))
2693         c -= em->counters_last_clear[i];
2694       sum += c;
2695     }
2696   return sum;
2697 }
2698
2699 static void
2700 quic_show_aggregated_stats (vlib_main_t * vm)
2701 {
2702   u32 num_workers = vlib_num_workers ();
2703   quic_main_t *qm = &quic_main;
2704   quic_ctx_t *ctx = NULL;
2705   quicly_stats_t st, agg_stats;
2706   u32 i, nconn = 0, nstream = 0;
2707
2708   clib_memset (&agg_stats, 0, sizeof (agg_stats));
2709   for (i = 0; i < num_workers + 1; i++)
2710     {
2711       pool_foreach (ctx, qm->ctx_pool[i])
2712        {
2713         if (quic_ctx_is_conn (ctx) && ctx->conn)
2714           {
2715             quicly_get_stats (ctx->conn, &st);
2716             agg_stats.rtt.smoothed += st.rtt.smoothed;
2717             agg_stats.rtt.minimum += st.rtt.minimum;
2718             agg_stats.rtt.variance += st.rtt.variance;
2719             agg_stats.num_packets.received += st.num_packets.received;
2720             agg_stats.num_packets.sent += st.num_packets.sent;
2721             agg_stats.num_packets.lost += st.num_packets.lost;
2722             agg_stats.num_packets.ack_received += st.num_packets.ack_received;
2723             agg_stats.num_bytes.received += st.num_bytes.received;
2724             agg_stats.num_bytes.sent += st.num_bytes.sent;
2725             nconn++;
2726           }
2727         else if (quic_ctx_is_stream (ctx))
2728           nstream++;
2729       }
2730     }
2731   vlib_cli_output (vm, "-------- Connections --------");
2732   vlib_cli_output (vm, "Current:         %u", nconn);
2733   vlib_cli_output (vm, "Opened:          %d",
2734                    quic_get_counter_value (QUIC_ERROR_OPENED_CONNECTION));
2735   vlib_cli_output (vm, "Closed:          %d",
2736                    quic_get_counter_value (QUIC_ERROR_CLOSED_CONNECTION));
2737   vlib_cli_output (vm, "---------- Streams ----------");
2738   vlib_cli_output (vm, "Current:         %u", nstream);
2739   vlib_cli_output (vm, "Opened:          %d",
2740                    quic_get_counter_value (QUIC_ERROR_OPENED_STREAM));
2741   vlib_cli_output (vm, "Closed:          %d",
2742                    quic_get_counter_value (QUIC_ERROR_CLOSED_STREAM));
2743   vlib_cli_output (vm, "---------- Packets ----------");
2744   vlib_cli_output (vm, "RX Total:        %d",
2745                    quic_get_counter_value (QUIC_ERROR_RX_PACKETS));
2746   vlib_cli_output (vm, "RX 0RTT:         %d",
2747                    quic_get_counter_value (QUIC_ERROR_ZERO_RTT_RX_PACKETS));
2748   vlib_cli_output (vm, "RX 1RTT:         %d",
2749                    quic_get_counter_value (QUIC_ERROR_ONE_RTT_RX_PACKETS));
2750   vlib_cli_output (vm, "TX Total:        %d",
2751                    quic_get_counter_value (QUIC_ERROR_TX_PACKETS));
2752   vlib_cli_output (vm, "----------- Stats -----------");
2753   vlib_cli_output (vm, "Min      RTT     %f",
2754                    nconn > 0 ? agg_stats.rtt.minimum / nconn : 0);
2755   vlib_cli_output (vm, "Smoothed RTT     %f",
2756                    nconn > 0 ? agg_stats.rtt.smoothed / nconn : 0);
2757   vlib_cli_output (vm, "Variance on RTT  %f",
2758                    nconn > 0 ? agg_stats.rtt.variance / nconn : 0);
2759   vlib_cli_output (vm, "Packets Received %lu",
2760                    agg_stats.num_packets.received);
2761   vlib_cli_output (vm, "Packets Sent     %lu", agg_stats.num_packets.sent);
2762   vlib_cli_output (vm, "Packets Lost     %lu", agg_stats.num_packets.lost);
2763   vlib_cli_output (vm, "Packets Acks     %lu",
2764                    agg_stats.num_packets.ack_received);
2765   vlib_cli_output (vm, "RX bytes         %lu", agg_stats.num_bytes.received);
2766   vlib_cli_output (vm, "TX bytes         %lu", agg_stats.num_bytes.sent);
2767 }
2768
2769 static u8 *
2770 quic_format_quicly_conn_id (u8 * s, va_list * args)
2771 {
2772   quicly_cid_plaintext_t *mid = va_arg (*args, quicly_cid_plaintext_t *);
2773   s = format (s, "C%x_%x", mid->master_id, mid->thread_id);
2774   return s;
2775 }
2776
2777 static u8 *
2778 quic_format_quicly_stream_id (u8 * s, va_list * args)
2779 {
2780   quicly_stream_t *stream = va_arg (*args, quicly_stream_t *);
2781   s =
2782     format (s, "%U S%lx", quic_format_quicly_conn_id,
2783             quicly_get_master_id (stream->conn), stream->stream_id);
2784   return s;
2785 }
2786
2787 static u8 *
2788 quic_format_listener_ctx (u8 * s, va_list * args)
2789 {
2790   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
2791   s = format (s, "[#%d][%x][Listener]", ctx->c_thread_index, ctx->c_c_index);
2792   return s;
2793 }
2794
2795 static u8 *
2796 quic_format_connection_ctx (u8 * s, va_list * args)
2797 {
2798   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
2799   quicly_stats_t quicly_stats;
2800
2801   s = format (s, "[#%d][%x]", ctx->c_thread_index, ctx->c_c_index);
2802
2803   if (!ctx->conn)
2804     {
2805       s = format (s, "- no conn -\n");
2806       return s;
2807     }
2808   s = format (s, "[%U]",
2809               quic_format_quicly_conn_id, quicly_get_master_id (ctx->conn));
2810   quicly_get_stats (ctx->conn, &quicly_stats);
2811
2812   s = format (s, "[RTT >%3d, ~%3d, V%3d, last %3d]",
2813               quicly_stats.rtt.minimum, quicly_stats.rtt.smoothed,
2814               quicly_stats.rtt.variance, quicly_stats.rtt.latest);
2815   s = format (s, " TX:%d RX:%d loss:%d ack:%d",
2816               quicly_stats.num_packets.sent,
2817               quicly_stats.num_packets.received,
2818               quicly_stats.num_packets.lost,
2819               quicly_stats.num_packets.ack_received);
2820   s =
2821     format (s, "\ncwnd:%u ssthresh:%u recovery_end:%lu", quicly_stats.cc.cwnd,
2822             quicly_stats.cc.ssthresh, quicly_stats.cc.recovery_end);
2823
2824   quicly_context_t *quicly_ctx = quic_get_quicly_ctx_from_ctx (ctx);
2825   if (quicly_ctx->init_cc == &quicly_cc_cubic_init)
2826     {
2827       s = format (
2828         s,
2829         "\nk:%d w_max:%u w_last_max:%u avoidance_start:%ld last_sent_time:%ld",
2830         quicly_stats.cc.state.cubic.k, quicly_stats.cc.state.cubic.w_max,
2831         quicly_stats.cc.state.cubic.w_last_max,
2832         quicly_stats.cc.state.cubic.avoidance_start,
2833         quicly_stats.cc.state.cubic.last_sent_time);
2834     }
2835   else if (quicly_ctx->init_cc == &quicly_cc_reno_init)
2836     {
2837       s = format (s, " stash:%u", quicly_stats.cc.state.reno.stash);
2838     }
2839
2840   return s;
2841 }
2842
2843 static u8 *
2844 quic_format_stream_ctx (u8 * s, va_list * args)
2845 {
2846   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
2847   session_t *stream_session;
2848   quicly_stream_t *stream = ctx->stream;
2849   u32 txs, rxs;
2850
2851   s = format (s, "[#%d][%x]", ctx->c_thread_index, ctx->c_c_index);
2852   s = format (s, "[%U]", quic_format_quicly_stream_id, stream);
2853
2854   stream_session = session_get_if_valid (ctx->c_s_index, ctx->c_thread_index);
2855   if (!stream_session)
2856     {
2857       s = format (s, "- no session -\n");
2858       return s;
2859     }
2860   txs = svm_fifo_max_dequeue (stream_session->tx_fifo);
2861   rxs = svm_fifo_max_dequeue (stream_session->rx_fifo);
2862   s = format (s, "[rx %d tx %d]\n", rxs, txs);
2863   return s;
2864 }
2865
2866 static clib_error_t *
2867 quic_show_connections_command_fn (vlib_main_t * vm,
2868                                   unformat_input_t * input,
2869                                   vlib_cli_command_t * cmd)
2870 {
2871   unformat_input_t _line_input, *line_input = &_line_input;
2872   u8 show_listeners = 0, show_conn = 0, show_stream = 0;
2873   u32 num_workers = vlib_num_workers ();
2874   quic_main_t *qm = &quic_main;
2875   clib_error_t *error = 0;
2876   quic_ctx_t *ctx = NULL;
2877
2878   session_cli_return_if_not_enabled ();
2879
2880   if (!unformat_user (input, unformat_line_input, line_input))
2881     {
2882       quic_show_aggregated_stats (vm);
2883       return 0;
2884     }
2885
2886   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2887     {
2888       if (unformat (line_input, "listener"))
2889         show_listeners = 1;
2890       else if (unformat (line_input, "conn"))
2891         show_conn = 1;
2892       else if (unformat (line_input, "stream"))
2893         show_stream = 1;
2894       else
2895         {
2896           error = clib_error_return (0, "unknown input `%U'",
2897                                      format_unformat_error, line_input);
2898           goto done;
2899         }
2900     }
2901
2902   for (int i = 0; i < num_workers + 1; i++)
2903     {
2904       pool_foreach (ctx, qm->ctx_pool[i])
2905        {
2906         if (quic_ctx_is_stream (ctx) && show_stream)
2907           vlib_cli_output (vm, "%U", quic_format_stream_ctx, ctx);
2908         else if (quic_ctx_is_listener (ctx) && show_listeners)
2909           vlib_cli_output (vm, "%U", quic_format_listener_ctx, ctx);
2910         else if (quic_ctx_is_conn (ctx) && show_conn)
2911           vlib_cli_output (vm, "%U", quic_format_connection_ctx, ctx);
2912       }
2913     }
2914
2915 done:
2916   unformat_free (line_input);
2917   return error;
2918 }
2919
2920 VLIB_CLI_COMMAND (quic_plugin_crypto_command, static) = {
2921   .path = "quic set crypto api",
2922   .short_help = "quic set crypto api [picotls|vpp]",
2923   .function = quic_plugin_crypto_command_fn,
2924 };
2925 VLIB_CLI_COMMAND(quic_plugin_set_fifo_size_command, static)=
2926 {
2927   .path = "quic set fifo-size",
2928   .short_help = "quic set fifo-size N[K|M|G] (default 64K)",
2929   .function = quic_plugin_set_fifo_size_command_fn,
2930 };
2931 VLIB_CLI_COMMAND(quic_show_ctx_command, static)=
2932 {
2933   .path = "show quic",
2934   .short_help = "show quic",
2935   .function = quic_show_connections_command_fn,
2936 };
2937 VLIB_CLI_COMMAND (quic_list_crypto_context_command, static) =
2938 {
2939   .path = "show quic crypto context",
2940   .short_help = "list quic crypto contextes",
2941   .function = quic_list_crypto_context_command_fn,
2942 };
2943 VLIB_CLI_COMMAND (quic_set_max_packets_per_key, static) =
2944 {
2945   .path = "set quic max_packets_per_key",
2946   .short_help = "set quic max_packets_per_key 16777216",
2947   .function = quic_set_max_packets_per_key_fn,
2948 };
2949 VLIB_CLI_COMMAND (quic_set_cc, static) = {
2950   .path = "set quic cc",
2951   .short_help = "set quic cc [reno|cubic]",
2952   .function = quic_set_cc_fn,
2953 };
2954 VLIB_PLUGIN_REGISTER () =
2955 {
2956   .version = VPP_BUILD_VER,
2957   .description = "Quic transport protocol",
2958   .default_disabled = 1,
2959 };
2960
2961 static clib_error_t *
2962 quic_config_fn (vlib_main_t * vm, unformat_input_t * input)
2963 {
2964   unformat_input_t _line_input, *line_input = &_line_input;
2965   quic_main_t *qm = &quic_main;
2966   clib_error_t *error = 0;
2967   uword tmp;
2968   u32 i;
2969
2970   qm->udp_fifo_size = QUIC_DEFAULT_FIFO_SIZE;
2971   qm->udp_fifo_prealloc = 0;
2972   qm->connection_timeout = QUIC_DEFAULT_CONN_TIMEOUT;
2973
2974   if (!unformat_user (input, unformat_line_input, line_input))
2975     return 0;
2976
2977   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2978     {
2979       if (unformat (line_input, "fifo-size %U", unformat_memory_size, &tmp))
2980         {
2981           if (tmp >= 0x100000000ULL)
2982             {
2983               error = clib_error_return (0,
2984                                          "fifo-size %llu (0x%llx) too large",
2985                                          tmp, tmp);
2986               goto done;
2987             }
2988           qm->udp_fifo_size = tmp;
2989         }
2990       else if (unformat (line_input, "conn-timeout %u", &i))
2991         qm->connection_timeout = i;
2992       else if (unformat (line_input, "fifo-prealloc %u", &i))
2993         qm->udp_fifo_prealloc = i;
2994       else
2995         {
2996           error = clib_error_return (0, "unknown input '%U'",
2997                                      format_unformat_error, line_input);
2998           goto done;
2999         }
3000     }
3001 done:
3002   unformat_free (line_input);
3003   return error;
3004 }
3005
3006 VLIB_EARLY_CONFIG_FUNCTION (quic_config_fn, "quic");
3007
3008 static uword
3009 quic_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
3010               vlib_frame_t * frame)
3011 {
3012   return 0;
3013 }
3014
3015 VLIB_REGISTER_NODE (quic_input_node) =
3016 {
3017   .function = quic_node_fn,
3018   .name = "quic-input",
3019   .vector_size = sizeof (u32),
3020   .type = VLIB_NODE_TYPE_INTERNAL,
3021   .n_errors = ARRAY_LEN (quic_error_strings),
3022   .error_strings = quic_error_strings,
3023 };
3024
3025 /*
3026  * fd.io coding-style-patch-verification: ON
3027  *
3028  * Local Variables:
3029  * eval: (c-set-style "gnu")
3030  * End:
3031  */