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