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