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