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