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