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