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