quic: clean accept/connect error codepath
[vpp.git] / src / plugins / quic / quic.c
1 /*
2  * Copyright (c) 2019 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 #include <quic/quic_crypto.h>
30
31 #include <quicly/defaults.h>
32
33 static char *quic_error_strings[] = {
34 #define quic_error(n,s) s,
35 #include <quic/quic_error.def>
36 #undef quic_error
37 };
38
39 static quic_main_t quic_main;
40 static void quic_update_timer (quic_ctx_t * ctx);
41 static void quic_check_quic_session_connected (quic_ctx_t * ctx);
42 static int quic_reset_connection (u64 udp_session_handle,
43                                   quic_rx_packet_ctx_t * pctx);
44 static void quic_proto_on_close (u32 ctx_index, u32 thread_index);
45
46 static quicly_stream_open_t on_stream_open;
47 static quicly_closed_by_peer_t on_closed_by_peer;
48 static quicly_now_t quicly_vpp_now_cb;
49
50 static int
51 quic_store_quicly_ctx (application_t * app, u32 ckpair_index,
52                        u8 crypto_engine)
53 {
54   quic_main_t *qm = &quic_main;
55   quicly_context_t *quicly_ctx;
56   ptls_iovec_t key_vec;
57   app_cert_key_pair_t *ckpair;
58   u64 max_enq;
59   if (app->quicly_ctx)
60     return 0;
61
62   if (crypto_engine == CRYPTO_ENGINE_NONE)
63     {
64       QUIC_DBG (2, "No crypto engine specified, using %d", crypto_engine);
65       crypto_engine = qm->default_crypto_engine;
66     }
67   if (!clib_bitmap_get (qm->available_crypto_engines, crypto_engine))
68     {
69       QUIC_DBG (1, "Quic does not support crypto engine %d", crypto_engine);
70       return VNET_API_ERROR_MISSING_CERT_KEY;
71     }
72
73   quicly_ctx_data_t *quicly_ctx_data =
74     clib_mem_alloc (sizeof (quicly_ctx_data_t));
75   clib_memset (quicly_ctx_data, 0, sizeof (*quicly_ctx_data));  /* picotls depends on this */
76   quicly_ctx = &quicly_ctx_data->quicly_ctx;
77   ptls_context_t *ptls_ctx = &quicly_ctx_data->ptls_ctx;
78   ptls_ctx->random_bytes = ptls_openssl_random_bytes;
79   ptls_ctx->get_time = &ptls_get_time;
80   ptls_ctx->key_exchanges = ptls_openssl_key_exchanges;
81   ptls_ctx->cipher_suites = qm->quic_ciphers[crypto_engine];
82   ptls_ctx->certificates.list = NULL;
83   ptls_ctx->certificates.count = 0;
84   ptls_ctx->esni = NULL;
85   ptls_ctx->on_client_hello = NULL;
86   ptls_ctx->emit_certificate = NULL;
87   ptls_ctx->sign_certificate = NULL;
88   ptls_ctx->verify_certificate = NULL;
89   ptls_ctx->ticket_lifetime = 86400;
90   ptls_ctx->max_early_data_size = 8192;
91   ptls_ctx->hkdf_label_prefix__obsolete = NULL;
92   ptls_ctx->require_dhe_on_psk = 1;
93   ptls_ctx->encrypt_ticket = &qm->session_cache.super;
94
95   app->quicly_ctx = (u64 *) quicly_ctx;
96   clib_memcpy (quicly_ctx, &quicly_spec_context, sizeof (quicly_context_t));
97
98   quicly_ctx->max_packet_size = QUIC_MAX_PACKET_SIZE;
99   quicly_ctx->tls = ptls_ctx;
100   quicly_ctx->stream_open = &on_stream_open;
101   quicly_ctx->closed_by_peer = &on_closed_by_peer;
102   quicly_ctx->now = &quicly_vpp_now_cb;
103   quicly_amend_ptls_context (quicly_ctx->tls);
104
105   quicly_ctx->transport_params.max_data = QUIC_INT_MAX;
106   quicly_ctx->transport_params.max_streams_uni = (uint64_t) 1 << 60;
107   quicly_ctx->transport_params.max_streams_bidi = (uint64_t) 1 << 60;
108   quicly_ctx->transport_params.idle_timeout = qm->connection_timeout;
109
110   /* max_enq is FIFO_SIZE - 1 */
111   max_enq = app->sm_properties.rx_fifo_size - 1;
112   quicly_ctx->transport_params.max_stream_data.bidi_local = max_enq;
113   max_enq = app->sm_properties.tx_fifo_size - 1;
114   quicly_ctx->transport_params.max_stream_data.bidi_remote = max_enq;
115   quicly_ctx->transport_params.max_stream_data.uni = QUIC_INT_MAX;
116
117   quicly_ctx->tls->random_bytes (quicly_ctx_data->cid_key, 16);
118   quicly_ctx_data->cid_key[16] = 0;
119   key_vec = ptls_iovec_init (quicly_ctx_data->cid_key,
120                              strlen (quicly_ctx_data->cid_key));
121   quicly_ctx->cid_encryptor =
122     quicly_new_default_cid_encryptor (&ptls_openssl_bfecb,
123                                       &ptls_openssl_aes128ecb,
124                                       &ptls_openssl_sha256, key_vec);
125
126   ckpair = app_cert_key_pair_get_if_valid (ckpair_index);
127   if (!ckpair || !ckpair->key || !ckpair->cert)
128     {
129       QUIC_DBG (1, "Wrong ckpair id %d\n", ckpair_index);
130       goto error;
131     }
132   if (load_bio_private_key (quicly_ctx->tls, (char *) ckpair->key))
133     {
134       QUIC_DBG (1, "failed to read private key from app configuration\n");
135       goto error;
136     }
137   if (load_bio_certificate_chain (quicly_ctx->tls, (char *) ckpair->cert))
138     {
139       QUIC_DBG (1, "failed to load certificate\n");
140       goto error;
141     }
142   return 0;
143
144 error:
145   clib_mem_free (quicly_ctx_data);
146   return VNET_API_ERROR_MISSING_CERT_KEY;
147 }
148
149 /*  Helper functions */
150
151 static u32
152 quic_ctx_alloc (u32 thread_index)
153 {
154   quic_main_t *qm = &quic_main;
155   quic_ctx_t *ctx;
156
157   pool_get (qm->ctx_pool[thread_index], ctx);
158
159   clib_memset (ctx, 0, sizeof (quic_ctx_t));
160   ctx->c_thread_index = thread_index;
161   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
162   QUIC_DBG (3, "Allocated quic_ctx %u on thread %u",
163             ctx - qm->ctx_pool[thread_index], thread_index);
164   return ctx - qm->ctx_pool[thread_index];
165 }
166
167 static void
168 quic_ctx_free (quic_ctx_t * ctx)
169 {
170   QUIC_DBG (2, "Free ctx %u %x", ctx->c_thread_index, ctx->c_c_index);
171   u32 thread_index = ctx->c_thread_index;
172   ASSERT (ctx->timer_handle == QUIC_TIMER_HANDLE_INVALID);
173   if (CLIB_DEBUG)
174     clib_memset (ctx, 0xfb, sizeof (*ctx));
175   pool_put (quic_main.ctx_pool[thread_index], ctx);
176 }
177
178 static quic_ctx_t *
179 quic_ctx_get (u32 ctx_index, u32 thread_index)
180 {
181   return pool_elt_at_index (quic_main.ctx_pool[thread_index], ctx_index);
182 }
183
184 static quic_ctx_t *
185 quic_ctx_get_if_valid (u32 ctx_index, u32 thread_index)
186 {
187   if (pool_is_free_index (quic_main.ctx_pool[thread_index], ctx_index))
188     return 0;
189   return pool_elt_at_index (quic_main.ctx_pool[thread_index], ctx_index);
190 }
191
192 static quic_ctx_t *
193 quic_get_conn_ctx (quicly_conn_t * conn)
194 {
195   u64 conn_data;
196   conn_data = (u64) * quicly_get_data (conn);
197   return quic_ctx_get (conn_data & UINT32_MAX, conn_data >> 32);
198 }
199
200 static void
201 quic_store_conn_ctx (quicly_conn_t * conn, quic_ctx_t * ctx)
202 {
203   *quicly_get_data (conn) =
204     (void *) (((u64) ctx->c_thread_index) << 32 | (u64) ctx->c_c_index);
205 }
206
207 static inline int
208 quic_ctx_is_stream (quic_ctx_t * ctx)
209 {
210   return (ctx->flags & QUIC_F_IS_STREAM);
211 }
212
213 static inline int
214 quic_ctx_is_listener (quic_ctx_t * ctx)
215 {
216   return (ctx->flags & QUIC_F_IS_LISTENER);
217 }
218
219 static session_t *
220 get_stream_session_from_stream (quicly_stream_t * stream)
221 {
222   quic_ctx_t *ctx;
223   quic_stream_data_t *stream_data;
224
225   stream_data = (quic_stream_data_t *) stream->data;
226   ctx = quic_ctx_get (stream_data->ctx_id, stream_data->thread_index);
227   return session_get (ctx->c_s_index, stream_data->thread_index);
228 }
229
230 static inline void
231 quic_make_connection_key (clib_bihash_kv_16_8_t * kv,
232                           const quicly_cid_plaintext_t * id)
233 {
234   kv->key[0] = ((u64) id->master_id) << 32 | (u64) id->thread_id;
235   kv->key[1] = id->node_id;
236 }
237
238 static int
239 quic_sendable_packet_count (session_t * udp_session)
240 {
241   u32 max_enqueue;
242   u32 packet_size = QUIC_MAX_PACKET_SIZE + SESSION_CONN_HDR_LEN;
243   max_enqueue = svm_fifo_max_enqueue (udp_session->tx_fifo);
244   return clib_min (max_enqueue / packet_size, QUIC_SEND_PACKET_VEC_SIZE);
245 }
246
247 static quicly_context_t *
248 quic_get_quicly_ctx_from_ctx (quic_ctx_t * ctx)
249 {
250   return ctx->quicly_ctx;
251 }
252
253 static quicly_context_t *
254 quic_get_quicly_ctx_from_udp (u64 udp_session_handle)
255 {
256   session_t *udp_session = session_get_from_handle (udp_session_handle);
257   quic_ctx_t *ctx =
258     quic_ctx_get (udp_session->opaque, udp_session->thread_index);
259   return ctx->quicly_ctx;
260 }
261
262 static inline void
263 quic_set_udp_tx_evt (session_t * udp_session)
264 {
265   int rv = 0;
266   if (svm_fifo_set_event (udp_session->tx_fifo))
267     rv = session_send_io_evt_to_thread (udp_session->tx_fifo,
268                                         SESSION_IO_EVT_TX);
269   if (PREDICT_FALSE (rv))
270     clib_warning ("Event enqueue errored %d", rv);
271 }
272
273 static inline void
274 quic_stop_ctx_timer (quic_ctx_t * ctx)
275 {
276   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
277   if (ctx->timer_handle == QUIC_TIMER_HANDLE_INVALID)
278     return;
279   tw = &quic_main.wrk_ctx[ctx->c_thread_index].timer_wheel;
280   tw_timer_stop_1t_3w_1024sl_ov (tw, ctx->timer_handle);
281   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
282   QUIC_DBG (4, "Stopping timer for ctx %u", ctx->c_c_index);
283 }
284
285 /* QUIC protocol actions */
286
287 static void
288 quic_ack_rx_data (session_t * stream_session)
289 {
290   u32 max_deq;
291   quic_ctx_t *sctx;
292   svm_fifo_t *f;
293   quicly_stream_t *stream;
294   quic_stream_data_t *stream_data;
295
296   sctx = quic_ctx_get (stream_session->connection_index,
297                        stream_session->thread_index);
298   ASSERT (quic_ctx_is_stream (sctx));
299   stream = sctx->stream;
300   stream_data = (quic_stream_data_t *) stream->data;
301
302   f = stream_session->rx_fifo;
303   max_deq = svm_fifo_max_dequeue (f);
304
305   ASSERT (stream_data->app_rx_data_len >= max_deq);
306   quicly_stream_sync_recvbuf (stream, stream_data->app_rx_data_len - max_deq);
307   QUIC_DBG (3, "Acking %u bytes", stream_data->app_rx_data_len - max_deq);
308   stream_data->app_rx_data_len = max_deq;
309 }
310
311 static void
312 quic_disconnect_transport (quic_ctx_t * ctx)
313 {
314   QUIC_DBG (2, "Disconnecting transport 0x%lx", ctx->udp_session_handle);
315   vnet_disconnect_args_t a = {
316     .handle = ctx->udp_session_handle,
317     .app_index = quic_main.app_index,
318   };
319
320   if (vnet_disconnect_session (&a))
321     clib_warning ("UDP session 0x%lx disconnect errored",
322                   ctx->udp_session_handle);
323 }
324
325 static void
326 quic_connection_delete (quic_ctx_t * ctx)
327 {
328   clib_bihash_kv_16_8_t kv;
329   quicly_conn_t *conn;
330
331   QUIC_DBG (2, "Deleting connection %u", ctx->c_c_index);
332
333   ASSERT (!quic_ctx_is_stream (ctx));
334   quic_stop_ctx_timer (ctx);
335
336   /*  Delete the connection from the connection map */
337   conn = ctx->conn;
338   quic_make_connection_key (&kv, quicly_get_master_id (conn));
339   QUIC_DBG (2, "Deleting conn with id %lu %lu from map", kv.key[0],
340             kv.key[1]);
341   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 0 /* is_add */ );
342
343   quic_disconnect_transport (ctx);
344
345   if (ctx->conn)
346     quicly_free (ctx->conn);
347   ctx->conn = NULL;
348   session_transport_delete_notify (&ctx->connection);
349 }
350
351 void
352 quic_increment_counter (u8 evt, u8 val)
353 {
354   vlib_main_t *vm = vlib_get_main ();
355   vlib_node_increment_counter (vm, quic_input_node.index, evt, val);
356 }
357
358 /**
359  * Called when quicly return an error
360  * This function interacts tightly with quic_proto_on_close
361  */
362 static void
363 quic_connection_closed (quic_ctx_t * ctx)
364 {
365   QUIC_DBG (2, "QUIC connection %u/%u closed", ctx->c_thread_index,
366             ctx->c_c_index);
367
368   /* TODO if connection is not established, just delete the session? */
369   /* Actually should send connect or accept error */
370
371   switch (ctx->conn_state)
372     {
373     case QUIC_CONN_STATE_READY:
374       /* Error on an opened connection (timeout...)
375          This puts the session in closing state, we should receive a notification
376          when the app has closed its session */
377       session_transport_reset_notify (&ctx->connection);
378       /* This ensures we delete the connection when the app confirms the close */
379       ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING_QUIC_CLOSED;
380       break;
381     case QUIC_CONN_STATE_PASSIVE_CLOSING:
382       ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING_QUIC_CLOSED;
383       /* quic_proto_on_close will eventually be called when the app confirms the close
384          , we delete the connection at that point */
385       break;
386     case QUIC_CONN_STATE_PASSIVE_CLOSING_APP_CLOSED:
387       /* App already confirmed close, we can delete the connection */
388       quic_connection_delete (ctx);
389       break;
390     case QUIC_CONN_STATE_OPENED:
391     case QUIC_CONN_STATE_HANDSHAKE:
392     case QUIC_CONN_STATE_ACTIVE_CLOSING:
393       quic_connection_delete (ctx);
394       break;
395     default:
396       QUIC_DBG (0, "BUG %d", ctx->conn_state);
397       break;
398     }
399 }
400
401 static int
402 quic_send_datagram (session_t * udp_session, quicly_datagram_t * packet)
403 {
404   u32 max_enqueue;
405   session_dgram_hdr_t hdr;
406   u32 len, ret;
407   svm_fifo_t *f;
408   transport_connection_t *tc;
409
410   len = packet->data.len;
411   f = udp_session->tx_fifo;
412   tc = session_get_transport (udp_session);
413   max_enqueue = svm_fifo_max_enqueue (f);
414   if (max_enqueue < SESSION_CONN_HDR_LEN + len)
415     {
416       QUIC_ERR ("Too much data to send, max_enqueue %u, len %u",
417                 max_enqueue, len + SESSION_CONN_HDR_LEN);
418       return QUIC_ERROR_FULL_FIFO;
419     }
420
421   /*  Build packet header for fifo */
422   hdr.data_length = len;
423   hdr.data_offset = 0;
424   hdr.is_ip4 = tc->is_ip4;
425   clib_memcpy (&hdr.lcl_ip, &tc->lcl_ip, sizeof (ip46_address_t));
426   hdr.lcl_port = tc->lcl_port;
427
428   /*  Read dest address from quicly-provided sockaddr */
429   if (hdr.is_ip4)
430     {
431       ASSERT (packet->dest.sa.sa_family == AF_INET);
432       struct sockaddr_in *sa4 = (struct sockaddr_in *) &packet->dest.sa;
433       hdr.rmt_port = sa4->sin_port;
434       hdr.rmt_ip.ip4.as_u32 = sa4->sin_addr.s_addr;
435     }
436   else
437     {
438       ASSERT (packet->dest.sa.sa_family == AF_INET6);
439       struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) &packet->dest.sa;
440       hdr.rmt_port = sa6->sin6_port;
441       clib_memcpy (&hdr.rmt_ip.ip6, &sa6->sin6_addr, 16);
442     }
443
444   ret = svm_fifo_enqueue (f, sizeof (hdr), (u8 *) & hdr);
445   if (ret != sizeof (hdr))
446     {
447       QUIC_ERR ("Not enough space to enqueue header");
448       return QUIC_ERROR_FULL_FIFO;
449     }
450   ret = svm_fifo_enqueue (f, len, packet->data.base);
451   if (ret != len)
452     {
453       QUIC_ERR ("Not enough space to enqueue payload");
454       return QUIC_ERROR_FULL_FIFO;
455     }
456
457   quic_increment_counter (QUIC_ERROR_TX_PACKETS, 1);
458
459   return 0;
460 }
461
462 static int
463 quic_send_packets (quic_ctx_t * ctx)
464 {
465   quicly_datagram_t *packets[QUIC_SEND_PACKET_VEC_SIZE];
466   session_t *udp_session;
467   quicly_conn_t *conn;
468   size_t num_packets, i, max_packets;
469   quicly_packet_allocator_t *pa;
470   quicly_context_t *quicly_context;
471   int err = 0;
472
473   /* We have sctx, get qctx */
474   if (quic_ctx_is_stream (ctx))
475     ctx = quic_ctx_get (ctx->quic_connection_ctx_id, ctx->c_thread_index);
476
477   ASSERT (!quic_ctx_is_stream (ctx));
478
479   udp_session = session_get_from_handle_if_valid (ctx->udp_session_handle);
480   if (!udp_session)
481     goto quicly_error;
482
483   conn = ctx->conn;
484
485   if (!conn)
486     return 0;
487
488   /* TODO : quicly can assert it can send min_packets up to 2 */
489   if (quic_sendable_packet_count (udp_session) < 2)
490     goto stop_sending;
491
492   quicly_context = quic_get_quicly_ctx_from_ctx (ctx);
493   if (!quicly_context)
494     {
495       clib_warning ("Tried to send packets on non existing app worker %u",
496                     ctx->parent_app_wrk_id);
497       quic_connection_delete (ctx);
498       return 1;
499     }
500   pa = quicly_context->packet_allocator;
501   do
502     {
503       max_packets = quic_sendable_packet_count (udp_session);
504       if (max_packets < 2)
505         break;
506       num_packets = max_packets;
507       if ((err = quicly_send (conn, packets, &num_packets)))
508         goto quicly_error;
509
510       for (i = 0; i != num_packets; ++i)
511         {
512           if ((err = quic_send_datagram (udp_session, packets[i])))
513             goto quicly_error;
514
515           pa->free_packet (pa, packets[i]);
516         }
517     }
518   while (num_packets > 0 && num_packets == max_packets);
519
520 stop_sending:
521   quic_set_udp_tx_evt (udp_session);
522
523   QUIC_DBG (3, "%u[TX] %u[RX]", svm_fifo_max_dequeue (udp_session->tx_fifo),
524             svm_fifo_max_dequeue (udp_session->rx_fifo));
525   quic_update_timer (ctx);
526   return 0;
527
528 quicly_error:
529   if (err && err != QUICLY_ERROR_PACKET_IGNORED
530       && err != QUICLY_ERROR_FREE_CONNECTION)
531     clib_warning ("Quic error '%U'.", quic_format_err, err);
532   quic_connection_closed (ctx);
533   return 1;
534 }
535
536 /* Quicly callbacks */
537
538 static void
539 quic_on_stream_destroy (quicly_stream_t * stream, int err)
540 {
541   quic_stream_data_t *stream_data = (quic_stream_data_t *) stream->data;
542   quic_ctx_t *sctx = quic_ctx_get (stream_data->ctx_id,
543                                    stream_data->thread_index);
544   session_t *stream_session = session_get (sctx->c_s_index,
545                                            sctx->c_thread_index);
546   QUIC_DBG (2, "DESTROYED_STREAM: session 0x%lx (%U)",
547             session_handle (stream_session), quic_format_err, err);
548
549   stream_session->session_state = SESSION_STATE_CLOSED;
550   session_transport_delete_notify (&sctx->connection);
551
552   quic_ctx_free (sctx);
553   clib_mem_free (stream->data);
554 }
555
556 static int
557 quic_on_stop_sending (quicly_stream_t * stream, int err)
558 {
559 #if QUIC_DEBUG >= 2
560   quic_stream_data_t *stream_data = (quic_stream_data_t *) stream->data;
561   quic_ctx_t *sctx = quic_ctx_get (stream_data->ctx_id,
562                                    stream_data->thread_index);
563   session_t *stream_session = session_get (sctx->c_s_index,
564                                            sctx->c_thread_index);
565   clib_warning ("(NOT IMPLEMENTD) STOP_SENDING: session 0x%lx (%U)",
566                 session_handle (stream_session), quic_format_err, err);
567 #endif
568   /* TODO : handle STOP_SENDING */
569   return 0;
570 }
571
572 static int
573 quic_on_receive_reset (quicly_stream_t * stream, int err)
574 {
575   quic_stream_data_t *stream_data = (quic_stream_data_t *) stream->data;
576   quic_ctx_t *sctx = quic_ctx_get (stream_data->ctx_id,
577                                    stream_data->thread_index);
578 #if QUIC_DEBUG >= 2
579   session_t *stream_session = session_get (sctx->c_s_index,
580                                            sctx->c_thread_index);
581   clib_warning ("RESET_STREAM: session 0x%lx (%U)",
582                 session_handle (stream_session), quic_format_err, err);
583 #endif
584   session_transport_closing_notify (&sctx->connection);
585   return 0;
586 }
587
588 static int
589 quic_on_receive (quicly_stream_t * stream, size_t off, const void *src,
590                  size_t len)
591 {
592   QUIC_DBG (3, "received data: %lu bytes, offset %lu", len, off);
593   u32 max_enq;
594   quic_ctx_t *sctx;
595   session_t *stream_session;
596   app_worker_t *app_wrk;
597   svm_fifo_t *f;
598   quic_stream_data_t *stream_data;
599   int rlen, rv;
600
601   stream_data = (quic_stream_data_t *) stream->data;
602   sctx = quic_ctx_get (stream_data->ctx_id, stream_data->thread_index);
603   stream_session = session_get (sctx->c_s_index, stream_data->thread_index);
604   f = stream_session->rx_fifo;
605
606   max_enq = svm_fifo_max_enqueue_prod (f);
607   QUIC_DBG (3, "Enqueuing %u at off %u in %u space", len, off, max_enq);
608   /* Handle duplicate packet/chunk from quicly */
609   if (off < stream_data->app_rx_data_len)
610     {
611       QUIC_DBG (3, "Session [idx %u, app_wrk %u, thread %u, rx-fifo 0x%llx]: "
612                 "DUPLICATE PACKET (max_enq %u, len %u, "
613                 "app_rx_data_len %u, off %u, ToBeNQ %u)",
614                 stream_session->session_index,
615                 stream_session->app_wrk_index,
616                 stream_session->thread_index, f,
617                 max_enq, len, stream_data->app_rx_data_len, off,
618                 off - stream_data->app_rx_data_len + len);
619       return 0;
620     }
621   if (PREDICT_FALSE ((off - stream_data->app_rx_data_len + len) > max_enq))
622     {
623       QUIC_ERR ("Session [idx %u, app_wrk %u, thread %u, rx-fifo 0x%llx]: "
624                 "RX FIFO IS FULL (max_enq %u, len %u, "
625                 "app_rx_data_len %u, off %u, ToBeNQ %u)",
626                 stream_session->session_index,
627                 stream_session->app_wrk_index,
628                 stream_session->thread_index, f,
629                 max_enq, len, stream_data->app_rx_data_len, off,
630                 off - stream_data->app_rx_data_len + len);
631       return 1;
632     }
633   if (off == stream_data->app_rx_data_len)
634     {
635       /* Streams live on the same thread so (f, stream_data) should stay consistent */
636       rlen = svm_fifo_enqueue (f, len, (u8 *) src);
637       QUIC_DBG (3, "Session [idx %u, app_wrk %u, ti %u, rx-fifo 0x%llx]: "
638                 "Enqueuing %u (rlen %u) at off %u in %u space, ",
639                 stream_session->session_index,
640                 stream_session->app_wrk_index,
641                 stream_session->thread_index, f, len, rlen, off, max_enq);
642       stream_data->app_rx_data_len += rlen;
643       ASSERT (rlen >= len);
644       app_wrk = app_worker_get_if_valid (stream_session->app_wrk_index);
645       if (PREDICT_TRUE (app_wrk != 0))
646         {
647           rv = app_worker_lock_and_send_event (app_wrk, stream_session,
648                                                SESSION_IO_EVT_RX);
649           if (rv)
650             QUIC_ERR ("Failed to ping app for RX");
651         }
652       quic_ack_rx_data (stream_session);
653     }
654   else
655     {
656       rlen = svm_fifo_enqueue_with_offset (f,
657                                            off - stream_data->app_rx_data_len,
658                                            len, (u8 *) src);
659       ASSERT (rlen == 0);
660     }
661   return 0;
662 }
663
664 void
665 quic_fifo_egress_shift (quicly_stream_t * stream, size_t delta)
666 {
667   session_t *stream_session;
668   svm_fifo_t *f;
669   int rv;
670
671   stream_session = get_stream_session_from_stream (stream);
672   f = stream_session->tx_fifo;
673
674   rv = svm_fifo_dequeue_drop (f, delta);
675   ASSERT (rv == delta);
676   quicly_stream_sync_sendbuf (stream, 0);
677 }
678
679 int
680 quic_fifo_egress_emit (quicly_stream_t * stream, size_t off, void *dst,
681                        size_t * len, int *wrote_all)
682 {
683   u32 deq_max, first_deq, max_rd_chunk, rem_offset;
684   session_t *stream_session;
685   svm_fifo_t *f;
686
687   stream_session = get_stream_session_from_stream (stream);
688   f = stream_session->tx_fifo;
689
690   QUIC_DBG (3, "Emitting %u, offset %u", *len, off);
691
692   deq_max = svm_fifo_max_dequeue_cons (f);
693   ASSERT (off <= deq_max);
694   if (off + *len < deq_max)
695     {
696       *wrote_all = 0;
697     }
698   else
699     {
700       *wrote_all = 1;
701       *len = deq_max - off;
702       QUIC_DBG (3, "Wrote ALL, %u", *len);
703     }
704
705   /* TODO, use something like : return svm_fifo_peek (f, off, *len, dst); */
706   max_rd_chunk = svm_fifo_max_read_chunk (f);
707
708   first_deq = 0;
709   if (off < max_rd_chunk)
710     {
711       first_deq = clib_min (*len, max_rd_chunk - off);
712       clib_memcpy_fast (dst, svm_fifo_head (f) + off, first_deq);
713     }
714
715   if (max_rd_chunk < off + *len)
716     {
717       rem_offset = max_rd_chunk < off ? off - max_rd_chunk : 0;
718       clib_memcpy_fast (dst + first_deq, f->head_chunk->data + rem_offset,
719                         *len - first_deq);
720     }
721
722   return 0;
723 }
724
725 static const quicly_stream_callbacks_t quic_stream_callbacks = {
726   .on_destroy = quic_on_stream_destroy,
727   .on_send_shift = quic_fifo_egress_shift,
728   .on_send_emit = quic_fifo_egress_emit,
729   .on_send_stop = quic_on_stop_sending,
730   .on_receive = quic_on_receive,
731   .on_receive_reset = quic_on_receive_reset
732 };
733
734 static int
735 quic_on_stream_open (quicly_stream_open_t * self, quicly_stream_t * stream)
736 {
737   /* Return code for this function ends either
738    * - in quicly_receive : if not QUICLY_ERROR_PACKET_IGNORED, will close connection
739    * - in quicly_open_stream, returned directly
740    */
741
742   session_t *stream_session, *quic_session;
743   quic_stream_data_t *stream_data;
744   app_worker_t *app_wrk;
745   quic_ctx_t *qctx, *sctx;
746   u32 sctx_id;
747   int rv;
748
749   QUIC_DBG (2, "on_stream_open called");
750   stream->data = clib_mem_alloc (sizeof (quic_stream_data_t));
751   stream->callbacks = &quic_stream_callbacks;
752   /* Notify accept on parent qsession, but only if this is not a locally
753    * initiated stream */
754   if (quicly_stream_is_self_initiated (stream))
755     return 0;
756
757   sctx_id = quic_ctx_alloc (vlib_get_thread_index ());
758   qctx = quic_get_conn_ctx (stream->conn);
759
760   /* Might need to signal that the connection is ready if the first thing the
761    * server does is open a stream */
762   quic_check_quic_session_connected (qctx);
763   /* ctx might be invalidated */
764   qctx = quic_get_conn_ctx (stream->conn);
765
766   stream_session = session_alloc (qctx->c_thread_index);
767   QUIC_DBG (2, "ACCEPTED stream_session 0x%lx ctx %u",
768             session_handle (stream_session), sctx_id);
769   sctx = quic_ctx_get (sctx_id, qctx->c_thread_index);
770   sctx->parent_app_wrk_id = qctx->parent_app_wrk_id;
771   sctx->parent_app_id = qctx->parent_app_id;
772   sctx->quic_connection_ctx_id = qctx->c_c_index;
773   sctx->c_c_index = sctx_id;
774   sctx->c_s_index = stream_session->session_index;
775   sctx->stream = stream;
776   sctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
777   sctx->flags |= QUIC_F_IS_STREAM;
778
779   stream_data = (quic_stream_data_t *) stream->data;
780   stream_data->ctx_id = sctx_id;
781   stream_data->thread_index = sctx->c_thread_index;
782   stream_data->app_rx_data_len = 0;
783
784   sctx->c_s_index = stream_session->session_index;
785   stream_session->session_state = SESSION_STATE_CREATED;
786   stream_session->app_wrk_index = sctx->parent_app_wrk_id;
787   stream_session->connection_index = sctx->c_c_index;
788   stream_session->session_type =
789     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, qctx->udp_is_ip4);
790   quic_session = session_get (qctx->c_s_index, qctx->c_thread_index);
791   stream_session->listener_handle = listen_session_get_handle (quic_session);
792
793   app_wrk = app_worker_get (stream_session->app_wrk_index);
794   if ((rv = app_worker_init_connected (app_wrk, stream_session)))
795     {
796       QUIC_ERR ("failed to allocate fifos");
797       quicly_reset_stream (stream, QUIC_APP_ALLOCATION_ERROR);
798       return 0;                 /* Frame is still valid */
799     }
800   svm_fifo_add_want_deq_ntf (stream_session->rx_fifo,
801                              SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL |
802                              SVM_FIFO_WANT_DEQ_NOTIF_IF_EMPTY);
803
804   if ((rv = app_worker_accept_notify (app_wrk, stream_session)))
805     {
806       QUIC_ERR ("failed to notify accept worker app");
807       quicly_reset_stream (stream, QUIC_APP_ACCEPT_NOTIFY_ERROR);
808       return 0;                 /* Frame is still valid */
809     }
810
811   return 0;
812 }
813
814 static void
815 quic_on_closed_by_peer (quicly_closed_by_peer_t * self, quicly_conn_t * conn,
816                         int code, uint64_t frame_type,
817                         const char *reason, size_t reason_len)
818 {
819   quic_ctx_t *ctx = quic_get_conn_ctx (conn);
820 #if QUIC_DEBUG >= 2
821   session_t *quic_session = session_get (ctx->c_s_index, ctx->c_thread_index);
822   clib_warning ("Session 0x%lx closed by peer (%U) %.*s ",
823                 session_handle (quic_session), quic_format_err, code,
824                 reason_len, reason);
825 #endif
826   ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING;
827   session_transport_closing_notify (&ctx->connection);
828 }
829
830 /* Timer handling */
831
832 static int64_t
833 quic_get_thread_time (u8 thread_index)
834 {
835   return quic_main.wrk_ctx[thread_index].time_now;
836 }
837
838 static int64_t
839 quic_get_time (quicly_now_t * self)
840 {
841   u8 thread_index = vlib_get_thread_index ();
842   return quic_get_thread_time (thread_index);
843 }
844
845 static u32
846 quic_set_time_now (u32 thread_index)
847 {
848   vlib_main_t *vlib_main = vlib_get_main ();
849   f64 time = vlib_time_now (vlib_main);
850   quic_main.wrk_ctx[thread_index].time_now = (int64_t) (time * 1000.f);
851   return quic_main.wrk_ctx[thread_index].time_now;
852 }
853
854 /* Transport proto callback */
855 static void
856 quic_update_time (f64 now, u8 thread_index)
857 {
858   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
859
860   tw = &quic_main.wrk_ctx[thread_index].timer_wheel;
861   quic_set_time_now (thread_index);
862   tw_timer_expire_timers_1t_3w_1024sl_ov (tw, now);
863 }
864
865 static void
866 quic_timer_expired (u32 conn_index)
867 {
868   quic_ctx_t *ctx;
869   QUIC_DBG (4, "Timer expired for conn %u at %ld", conn_index,
870             quic_get_time (NULL));
871   ctx = quic_ctx_get (conn_index, vlib_get_thread_index ());
872   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
873   quic_send_packets (ctx);
874 }
875
876 static void
877 quic_update_timer (quic_ctx_t * ctx)
878 {
879   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
880   int64_t next_timeout, next_interval;
881   session_t *quic_session;
882   int rv;
883
884   /*  This timeout is in ms which is the unit of our timer */
885   next_timeout = quicly_get_first_timeout (ctx->conn);
886   next_interval = next_timeout - quic_get_time (NULL);
887
888   if (next_timeout == 0 || next_interval <= 0)
889     {
890       if (ctx->c_s_index == QUIC_SESSION_INVALID)
891         {
892           next_interval = 1;
893         }
894       else
895         {
896           quic_session = session_get (ctx->c_s_index, ctx->c_thread_index);
897           if (svm_fifo_set_event (quic_session->tx_fifo))
898             {
899               rv = session_send_io_evt_to_thread_custom (quic_session,
900                                                          quic_session->thread_index,
901                                                          SESSION_IO_EVT_BUILTIN_TX);
902               if (PREDICT_FALSE (rv))
903                 QUIC_ERR ("Failed to enqueue builtin_tx %d", rv);
904             }
905           return;
906         }
907     }
908
909   tw = &quic_main.wrk_ctx[vlib_get_thread_index ()].timer_wheel;
910
911   QUIC_DBG (4, "Timer set to %ld (int %ld) for ctx %u", next_timeout,
912             next_interval, ctx->c_c_index);
913
914   if (ctx->timer_handle == QUIC_TIMER_HANDLE_INVALID)
915     {
916       if (next_timeout == INT64_MAX)
917         {
918           QUIC_DBG (4, "timer for ctx %u already stopped", ctx->c_c_index);
919           return;
920         }
921       ctx->timer_handle = tw_timer_start_1t_3w_1024sl_ov (tw, ctx->c_c_index,
922                                                           0, next_interval);
923     }
924   else
925     {
926       if (next_timeout == INT64_MAX)
927         {
928           quic_stop_ctx_timer (ctx);
929         }
930       else
931         tw_timer_update_1t_3w_1024sl_ov (tw, ctx->timer_handle,
932                                          next_interval);
933     }
934   return;
935 }
936
937 static void
938 quic_expired_timers_dispatch (u32 * expired_timers)
939 {
940   int i;
941
942   for (i = 0; i < vec_len (expired_timers); i++)
943     {
944       quic_timer_expired (expired_timers[i]);
945     }
946 }
947
948 /* Transport proto functions */
949
950 static int
951 quic_connect_stream (session_t * quic_session, u32 opaque)
952 {
953   uint64_t quic_session_handle;
954   session_t *stream_session;
955   quic_stream_data_t *stream_data;
956   quicly_stream_t *stream;
957   quicly_conn_t *conn;
958   app_worker_t *app_wrk;
959   quic_ctx_t *qctx, *sctx;
960   u32 sctx_index;
961   int rv;
962
963   /*  Find base session to which the user want to attach a stream */
964   quic_session_handle = session_handle (quic_session);
965   QUIC_DBG (2, "Opening new stream (qsession %u)", quic_session_handle);
966
967   if (session_type_transport_proto (quic_session->session_type) !=
968       TRANSPORT_PROTO_QUIC)
969     {
970       QUIC_ERR ("received incompatible session");
971       return -1;
972     }
973
974   app_wrk = app_worker_get_if_valid (quic_session->app_wrk_index);
975   if (!app_wrk)
976     {
977       QUIC_ERR ("Invalid app worker :(");
978       return -1;
979     }
980
981   sctx_index = quic_ctx_alloc (quic_session->thread_index);     /*  Allocate before we get pointers */
982   sctx = quic_ctx_get (sctx_index, quic_session->thread_index);
983   qctx = quic_ctx_get (quic_session->connection_index,
984                        quic_session->thread_index);
985   if (quic_ctx_is_stream (qctx))
986     {
987       QUIC_ERR ("session is a stream");
988       quic_ctx_free (sctx);
989       return -1;
990     }
991
992   sctx->parent_app_wrk_id = qctx->parent_app_wrk_id;
993   sctx->parent_app_id = qctx->parent_app_id;
994   sctx->quic_connection_ctx_id = qctx->c_c_index;
995   sctx->c_c_index = sctx_index;
996   sctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
997   sctx->flags |= QUIC_F_IS_STREAM;
998
999   conn = qctx->conn;
1000
1001   if (!conn || !quicly_connection_is_ready (conn))
1002     return -1;
1003
1004   if ((rv = quicly_open_stream (conn, &stream, 0 /* uni */ )))
1005     {
1006       QUIC_DBG (2, "Stream open failed with %d", rv);
1007       return -1;
1008     }
1009   sctx->stream = stream;
1010
1011   QUIC_DBG (2, "Opened stream %d, creating session", stream->stream_id);
1012
1013   stream_session = session_alloc (qctx->c_thread_index);
1014   QUIC_DBG (2, "Allocated stream_session 0x%lx ctx %u",
1015             session_handle (stream_session), sctx_index);
1016   stream_session->app_wrk_index = app_wrk->wrk_index;
1017   stream_session->connection_index = sctx_index;
1018   stream_session->listener_handle = quic_session_handle;
1019   stream_session->session_type =
1020     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, qctx->udp_is_ip4);
1021
1022   sctx->c_s_index = stream_session->session_index;
1023   stream_data = (quic_stream_data_t *) stream->data;
1024   stream_data->ctx_id = sctx->c_c_index;
1025   stream_data->thread_index = sctx->c_thread_index;
1026   stream_data->app_rx_data_len = 0;
1027   stream_session->session_state = SESSION_STATE_READY;
1028
1029   /* For now we only reset streams. Cleanup will be triggered by timers */
1030   if (app_worker_init_connected (app_wrk, stream_session))
1031     {
1032       QUIC_ERR ("failed to app_worker_init_connected");
1033       quicly_reset_stream (stream, QUIC_APP_CONNECT_NOTIFY_ERROR);
1034       return app_worker_connect_notify (app_wrk, NULL, opaque);
1035     }
1036
1037   svm_fifo_add_want_deq_ntf (stream_session->rx_fifo,
1038                              SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL |
1039                              SVM_FIFO_WANT_DEQ_NOTIF_IF_EMPTY);
1040
1041   if (app_worker_connect_notify (app_wrk, stream_session, opaque))
1042     {
1043       QUIC_ERR ("failed to notify app");
1044       quicly_reset_stream (stream, QUIC_APP_CONNECT_NOTIFY_ERROR);
1045       return -1;
1046     }
1047
1048   return 0;
1049 }
1050
1051 static int
1052 quic_connect_connection (session_endpoint_cfg_t * sep)
1053 {
1054   vnet_connect_args_t _cargs, *cargs = &_cargs;
1055   quic_main_t *qm = &quic_main;
1056   quic_ctx_t *ctx;
1057   app_worker_t *app_wrk;
1058   application_t *app;
1059   u32 ctx_index;
1060   u32 thread_index = vlib_get_thread_index ();
1061   int error;
1062
1063   clib_memset (cargs, 0, sizeof (*cargs));
1064   ctx_index = quic_ctx_alloc (thread_index);
1065   ctx = quic_ctx_get (ctx_index, thread_index);
1066   ctx->parent_app_wrk_id = sep->app_wrk_index;
1067   ctx->c_s_index = QUIC_SESSION_INVALID;
1068   ctx->c_c_index = ctx_index;
1069   ctx->udp_is_ip4 = sep->is_ip4;
1070   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1071   ctx->conn_state = QUIC_CONN_STATE_HANDSHAKE;
1072   ctx->client_opaque = sep->opaque;
1073   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1074   if (sep->hostname)
1075     ctx->srv_hostname = format (0, "%v", sep->hostname);
1076   else
1077     /*  needed by quic for crypto + determining client / server */
1078     ctx->srv_hostname = format (0, "%U", format_ip46_address,
1079                                 &sep->ip, sep->is_ip4);
1080   vec_terminate_c_string (ctx->srv_hostname);
1081
1082   clib_memcpy (&cargs->sep, sep, sizeof (session_endpoint_cfg_t));
1083   cargs->sep.transport_proto = TRANSPORT_PROTO_UDPC;
1084   cargs->app_index = qm->app_index;
1085   cargs->api_context = ctx_index;
1086
1087   app_wrk = app_worker_get (sep->app_wrk_index);
1088   app = application_get (app_wrk->app_index);
1089   ctx->parent_app_id = app_wrk->app_index;
1090   cargs->sep_ext.ns_index = app->ns_index;
1091
1092   if ((error =
1093        quic_store_quicly_ctx (app, sep->ckpair_index, sep->crypto_engine)))
1094     return error;
1095   /* Also store it in ctx for convenience
1096    * Waiting for crypto_ctx logic */
1097   ctx->quicly_ctx = (quicly_context_t *) app->quicly_ctx;
1098
1099   if ((error = vnet_connect (cargs)))
1100     return error;
1101
1102   return 0;
1103 }
1104
1105 static int
1106 quic_connect (transport_endpoint_cfg_t * tep)
1107 {
1108   QUIC_DBG (2, "Called quic_connect");
1109   session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) tep;
1110   session_t *quic_session;
1111   sep = (session_endpoint_cfg_t *) tep;
1112
1113   quic_session = session_get_from_handle_if_valid (sep->parent_handle);
1114   if (quic_session)
1115     return quic_connect_stream (quic_session, sep->opaque);
1116   else
1117     return quic_connect_connection (sep);
1118 }
1119
1120 static void
1121 quic_proto_on_close (u32 ctx_index, u32 thread_index)
1122 {
1123   quic_ctx_t *ctx = quic_ctx_get_if_valid (ctx_index, thread_index);
1124   if (!ctx)
1125     return;
1126 #if QUIC_DEBUG >= 2
1127   session_t *stream_session = session_get (ctx->c_s_index,
1128                                            ctx->c_thread_index);
1129   clib_warning ("Closing session 0x%lx", session_handle (stream_session));
1130 #endif
1131   if (quic_ctx_is_stream (ctx))
1132     {
1133       quicly_stream_t *stream = ctx->stream;
1134       quicly_reset_stream (stream, QUIC_APP_ERROR_CLOSE_NOTIFY);
1135       quic_send_packets (ctx);
1136       return;
1137     }
1138
1139   switch (ctx->conn_state)
1140     {
1141     case QUIC_CONN_STATE_OPENED:
1142     case QUIC_CONN_STATE_HANDSHAKE:
1143     case QUIC_CONN_STATE_READY:
1144       ctx->conn_state = QUIC_CONN_STATE_ACTIVE_CLOSING;
1145       quicly_conn_t *conn = ctx->conn;
1146       /* Start connection closing. Keep sending packets until quicly_send
1147          returns QUICLY_ERROR_FREE_CONNECTION */
1148       quicly_close (conn, QUIC_APP_ERROR_CLOSE_NOTIFY, "Closed by peer");
1149       /* This also causes all streams to be closed (and the cb called) */
1150       quic_send_packets (ctx);
1151       break;
1152     case QUIC_CONN_STATE_PASSIVE_CLOSING:
1153       ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING_APP_CLOSED;
1154       /* send_packets will eventually return an error, we delete the conn at
1155          that point */
1156       break;
1157     case QUIC_CONN_STATE_PASSIVE_CLOSING_QUIC_CLOSED:
1158       quic_connection_delete (ctx);
1159       break;
1160     case QUIC_CONN_STATE_ACTIVE_CLOSING:
1161       break;
1162     default:
1163       QUIC_ERR ("Trying to close conn in state %d", ctx->conn_state);
1164       break;
1165     }
1166 }
1167
1168 static u32
1169 quic_start_listen (u32 quic_listen_session_index, transport_endpoint_t * tep)
1170 {
1171   vnet_listen_args_t _bargs, *args = &_bargs;
1172   quic_main_t *qm = &quic_main;
1173   session_handle_t udp_handle;
1174   session_endpoint_cfg_t *sep;
1175   session_t *udp_listen_session;
1176   app_worker_t *app_wrk;
1177   application_t *app;
1178   quic_ctx_t *lctx;
1179   u32 lctx_index;
1180   app_listener_t *app_listener;
1181   int rv;
1182
1183   sep = (session_endpoint_cfg_t *) tep;
1184   app_wrk = app_worker_get (sep->app_wrk_index);
1185   /* We need to call this because we call app_worker_init_connected in
1186    * quic_accept_stream, which assumes the connect segment manager exists */
1187   app_worker_alloc_connects_segment_manager (app_wrk);
1188   app = application_get (app_wrk->app_index);
1189   QUIC_DBG (2, "Called quic_start_listen for app %d", app_wrk->app_index);
1190
1191   if (quic_store_quicly_ctx (app, sep->ckpair_index, sep->crypto_engine))
1192     return -1;
1193
1194   sep->transport_proto = TRANSPORT_PROTO_UDPC;
1195   clib_memset (args, 0, sizeof (*args));
1196   args->app_index = qm->app_index;
1197   args->sep_ext = *sep;
1198   args->sep_ext.ns_index = app->ns_index;
1199   if ((rv = vnet_listen (args)))
1200     return rv;
1201
1202   lctx_index = quic_ctx_alloc (0);
1203   udp_handle = args->handle;
1204   app_listener = app_listener_get_w_handle (udp_handle);
1205   udp_listen_session = app_listener_get_session (app_listener);
1206   udp_listen_session->opaque = lctx_index;
1207
1208   lctx = quic_ctx_get (lctx_index, 0);
1209   lctx->flags |= QUIC_F_IS_LISTENER;
1210   /* Also store it in ctx for convenience
1211    * Waiting for crypto_ctx logic */
1212   lctx->quicly_ctx = (quicly_context_t *) app->quicly_ctx;
1213
1214   clib_memcpy (&lctx->c_rmt_ip, &args->sep.peer.ip, sizeof (ip46_address_t));
1215   clib_memcpy (&lctx->c_lcl_ip, &args->sep.ip, sizeof (ip46_address_t));
1216   lctx->c_rmt_port = args->sep.peer.port;
1217   lctx->c_lcl_port = args->sep.port;
1218   lctx->c_is_ip4 = args->sep.is_ip4;
1219   lctx->c_fib_index = args->sep.fib_index;
1220   lctx->c_proto = TRANSPORT_PROTO_QUIC;
1221   lctx->parent_app_wrk_id = sep->app_wrk_index;
1222   lctx->parent_app_id = app_wrk->app_index;
1223   lctx->udp_session_handle = udp_handle;
1224   lctx->c_s_index = quic_listen_session_index;
1225
1226   QUIC_DBG (2, "Listening UDP session 0x%lx",
1227             session_handle (udp_listen_session));
1228   QUIC_DBG (2, "Listening QUIC session 0x%lx", quic_listen_session_index);
1229   return lctx_index;
1230 }
1231
1232 static u32
1233 quic_stop_listen (u32 lctx_index)
1234 {
1235   QUIC_DBG (2, "Called quic_stop_listen");
1236   quic_ctx_t *lctx;
1237   lctx = quic_ctx_get (lctx_index, 0);
1238   ASSERT (quic_ctx_is_listener (lctx));
1239   vnet_unlisten_args_t a = {
1240     .handle = lctx->udp_session_handle,
1241     .app_index = quic_main.app_index,
1242     .wrk_map_index = 0          /* default wrk */
1243   };
1244   if (vnet_unlisten (&a))
1245     clib_warning ("unlisten errored");
1246
1247   /*  TODO: crypto state cleanup */
1248
1249   quic_ctx_free (lctx);
1250   return 0;
1251 }
1252
1253 static transport_connection_t *
1254 quic_connection_get (u32 ctx_index, u32 thread_index)
1255 {
1256   quic_ctx_t *ctx;
1257   ctx = quic_ctx_get (ctx_index, thread_index);
1258   return &ctx->connection;
1259 }
1260
1261 static transport_connection_t *
1262 quic_listener_get (u32 listener_index)
1263 {
1264   QUIC_DBG (2, "Called quic_listener_get");
1265   quic_ctx_t *ctx;
1266   ctx = quic_ctx_get (listener_index, 0);
1267   return &ctx->connection;
1268 }
1269
1270 static u8 *
1271 format_quic_ctx (u8 * s, va_list * args)
1272 {
1273   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
1274   u32 verbose = va_arg (*args, u32);
1275   u8 *str = 0;
1276
1277   if (!ctx)
1278     return s;
1279   str = format (str, "[#%d][Q] ", ctx->c_thread_index);
1280
1281   if (quic_ctx_is_listener (ctx))
1282     str = format (str, "Listener, UDP %ld", ctx->udp_session_handle);
1283   else if (quic_ctx_is_stream (ctx))
1284     str = format (str, "Stream %ld conn %d",
1285                   ctx->stream->stream_id, ctx->quic_connection_ctx_id);
1286   else                          /* connection */
1287     str = format (str, "Conn %d UDP %d", ctx->c_c_index,
1288                   ctx->udp_session_handle);
1289
1290   str = format (str, " app %d wrk %d", ctx->parent_app_id,
1291                 ctx->parent_app_wrk_id);
1292
1293   if (verbose == 1)
1294     s = format (s, "%-50s%-15d", str, ctx->conn_state);
1295   else
1296     s = format (s, "%s\n", str);
1297   vec_free (str);
1298   return s;
1299 }
1300
1301 static u8 *
1302 format_quic_connection (u8 * s, va_list * args)
1303 {
1304   u32 qc_index = va_arg (*args, u32);
1305   u32 thread_index = va_arg (*args, u32);
1306   u32 verbose = va_arg (*args, u32);
1307   quic_ctx_t *ctx = quic_ctx_get (qc_index, thread_index);
1308   s = format (s, "%U", format_quic_ctx, ctx, verbose);
1309   return s;
1310 }
1311
1312 static u8 *
1313 format_quic_half_open (u8 * s, va_list * args)
1314 {
1315   u32 qc_index = va_arg (*args, u32);
1316   u32 thread_index = va_arg (*args, u32);
1317   quic_ctx_t *ctx = quic_ctx_get (qc_index, thread_index);
1318   s = format (s, "[#%d][Q] half-open app %u", thread_index,
1319               ctx->parent_app_id);
1320   return s;
1321 }
1322
1323 /*  TODO improve */
1324 static u8 *
1325 format_quic_listener (u8 * s, va_list * args)
1326 {
1327   u32 tci = va_arg (*args, u32);
1328   u32 thread_index = va_arg (*args, u32);
1329   u32 verbose = va_arg (*args, u32);
1330   quic_ctx_t *ctx = quic_ctx_get (tci, thread_index);
1331   s = format (s, "%U", format_quic_ctx, ctx, verbose);
1332   return s;
1333 }
1334
1335 /* Session layer callbacks */
1336
1337 static inline void
1338 quic_build_sockaddr (struct sockaddr *sa, socklen_t * salen,
1339                      ip46_address_t * addr, u16 port, u8 is_ip4)
1340 {
1341   if (is_ip4)
1342     {
1343       struct sockaddr_in *sa4 = (struct sockaddr_in *) sa;
1344       sa4->sin_family = AF_INET;
1345       sa4->sin_port = port;
1346       sa4->sin_addr.s_addr = addr->ip4.as_u32;
1347       *salen = sizeof (struct sockaddr_in);
1348     }
1349   else
1350     {
1351       struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) sa;
1352       sa6->sin6_family = AF_INET6;
1353       sa6->sin6_port = port;
1354       clib_memcpy (&sa6->sin6_addr, &addr->ip6, 16);
1355       *salen = sizeof (struct sockaddr_in6);
1356     }
1357 }
1358
1359 static void
1360 quic_on_quic_session_connected (quic_ctx_t * ctx)
1361 {
1362   session_t *quic_session;
1363   app_worker_t *app_wrk;
1364   u32 ctx_id = ctx->c_c_index;
1365   u32 thread_index = ctx->c_thread_index;
1366   int rv;
1367
1368   quic_session = session_alloc (thread_index);
1369
1370   QUIC_DBG (2, "Allocated quic session 0x%lx", session_handle (quic_session));
1371   ctx->c_s_index = quic_session->session_index;
1372   quic_session->app_wrk_index = ctx->parent_app_wrk_id;
1373   quic_session->connection_index = ctx->c_c_index;
1374   quic_session->listener_handle = SESSION_INVALID_HANDLE;
1375   quic_session->session_type =
1376     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, ctx->udp_is_ip4);
1377
1378   /* If quic session connected fails, immediatly close connection */
1379   app_wrk = app_worker_get (ctx->parent_app_wrk_id);
1380   if (app_worker_init_connected (app_wrk, quic_session))
1381     {
1382       QUIC_ERR ("failed to app_worker_init_connected");
1383       quic_proto_on_close (ctx_id, thread_index);
1384       app_worker_connect_notify (app_wrk, NULL, ctx->client_opaque);
1385       return;
1386     }
1387
1388   quic_session->session_state = SESSION_STATE_CONNECTING;
1389   if ((rv = app_worker_connect_notify (app_wrk, quic_session,
1390                                        ctx->client_opaque)))
1391     {
1392       QUIC_ERR ("failed to notify app %d", rv);
1393       quic_proto_on_close (ctx_id, thread_index);
1394       return;
1395     }
1396
1397   /*  If the app opens a stream in its callback it may invalidate ctx */
1398   ctx = quic_ctx_get (ctx_id, thread_index);
1399   /*
1400    * app_worker_connect_notify() might have reallocated pool, reload
1401    * quic_session pointer
1402    */
1403   quic_session = session_get (ctx->c_s_index, thread_index);
1404   quic_session->session_state = SESSION_STATE_LISTENING;
1405 }
1406
1407 static void
1408 quic_check_quic_session_connected (quic_ctx_t * ctx)
1409 {
1410   /* Called when we need to trigger quic session connected
1411    * we may call this function on the server side / at
1412    * stream opening */
1413
1414   /* Conn may be set to null if the connection is terminated */
1415   if (!ctx->conn || ctx->conn_state != QUIC_CONN_STATE_HANDSHAKE)
1416     return;
1417   if (!quicly_connection_is_ready (ctx->conn))
1418     return;
1419   ctx->conn_state = QUIC_CONN_STATE_READY;
1420   if (!quicly_is_client (ctx->conn))
1421     return;
1422   quic_on_quic_session_connected (ctx);
1423 }
1424
1425 static void
1426 quic_receive_connection (void *arg)
1427 {
1428   u32 new_ctx_id, thread_index = vlib_get_thread_index ();
1429   quic_ctx_t *temp_ctx, *new_ctx;
1430   clib_bihash_kv_16_8_t kv;
1431   quicly_conn_t *conn;
1432   session_t *udp_session;
1433
1434   temp_ctx = arg;
1435   new_ctx_id = quic_ctx_alloc (thread_index);
1436   new_ctx = quic_ctx_get (new_ctx_id, thread_index);
1437
1438   QUIC_DBG (2, "Received conn %u (now %u)", temp_ctx->c_thread_index,
1439             new_ctx_id);
1440
1441   clib_memcpy (new_ctx, temp_ctx, sizeof (quic_ctx_t));
1442   clib_mem_free (temp_ctx);
1443
1444   new_ctx->c_thread_index = thread_index;
1445   new_ctx->c_c_index = new_ctx_id;
1446
1447   conn = new_ctx->conn;
1448   quic_store_conn_ctx (conn, new_ctx);
1449   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1450   kv.value = ((u64) thread_index) << 32 | (u64) new_ctx_id;
1451   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1452   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1453   new_ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1454   quic_update_timer (new_ctx);
1455
1456   /*  Trigger write on this connection if necessary */
1457   udp_session = session_get_from_handle (new_ctx->udp_session_handle);
1458   udp_session->opaque = new_ctx_id;
1459   udp_session->flags &= ~SESSION_F_IS_MIGRATING;
1460   if (svm_fifo_max_dequeue (udp_session->tx_fifo))
1461     quic_set_udp_tx_evt (udp_session);
1462 }
1463
1464 static void
1465 quic_transfer_connection (u32 ctx_index, u32 dest_thread)
1466 {
1467   quic_ctx_t *ctx, *temp_ctx;
1468   u32 thread_index = vlib_get_thread_index ();
1469
1470   QUIC_DBG (2, "Transferring conn %u to thread %u", ctx_index, dest_thread);
1471
1472   temp_ctx = clib_mem_alloc (sizeof (quic_ctx_t));
1473   ASSERT (temp_ctx);
1474   ctx = quic_ctx_get (ctx_index, thread_index);
1475
1476   clib_memcpy (temp_ctx, ctx, sizeof (quic_ctx_t));
1477
1478   quic_stop_ctx_timer (ctx);
1479   quic_ctx_free (ctx);
1480
1481   /*  Send connection to destination thread */
1482   session_send_rpc_evt_to_thread (dest_thread, quic_receive_connection,
1483                                   (void *) temp_ctx);
1484 }
1485
1486 static int
1487 quic_udp_session_connected_callback (u32 quic_app_index, u32 ctx_index,
1488                                      session_t * udp_session, u8 is_fail)
1489 {
1490   QUIC_DBG (2, "QSession is now connected (id %u)",
1491             udp_session->session_index);
1492   /* This should always be called before quic_connect returns since UDP always
1493    * connects instantly. */
1494   clib_bihash_kv_16_8_t kv;
1495   struct sockaddr_in6 sa6;
1496   struct sockaddr *sa = (struct sockaddr *) &sa6;
1497   socklen_t salen;
1498   transport_connection_t *tc;
1499   app_worker_t *app_wrk;
1500   quicly_conn_t *conn;
1501   quic_ctx_t *ctx;
1502   u32 thread_index = vlib_get_thread_index ();
1503   int ret;
1504   quicly_context_t *quicly_ctx;
1505
1506
1507   ctx = quic_ctx_get (ctx_index, thread_index);
1508   if (is_fail)
1509     {
1510       u32 api_context;
1511       app_wrk = app_worker_get_if_valid (ctx->parent_app_wrk_id);
1512       if (app_wrk)
1513         {
1514           api_context = ctx->c_s_index;
1515           app_worker_connect_notify (app_wrk, 0, api_context);
1516         }
1517       return 0;
1518     }
1519
1520   ctx->c_thread_index = thread_index;
1521   ctx->c_c_index = ctx_index;
1522
1523   QUIC_DBG (2, "Quic connect returned %u. New ctx [%u]%x",
1524             is_fail, thread_index, (ctx) ? ctx_index : ~0);
1525
1526   ctx->udp_session_handle = session_handle (udp_session);
1527   udp_session->opaque = ctx_index;
1528
1529   /* Init QUIC lib connection
1530    * Generate required sockaddr & salen */
1531   tc = session_get_transport (udp_session);
1532   quic_build_sockaddr (sa, &salen, &tc->rmt_ip, tc->rmt_port, tc->is_ip4);
1533
1534   quicly_ctx = quic_get_quicly_ctx_from_ctx (ctx);
1535   ret = quicly_connect (&ctx->conn, quicly_ctx, (char *) ctx->srv_hostname,
1536                         sa, NULL, &quic_main.next_cid, ptls_iovec_init (NULL,
1537                                                                         0),
1538                         &quic_main.hs_properties, NULL);
1539   ++quic_main.next_cid.master_id;
1540   /*  Save context handle in quicly connection */
1541   quic_store_conn_ctx (ctx->conn, ctx);
1542   assert (ret == 0);
1543
1544   /*  Register connection in connections map */
1545   conn = ctx->conn;
1546   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1547   kv.value = ((u64) thread_index) << 32 | (u64) ctx_index;
1548   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1549   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1550
1551   /*  UDP stack quirk? preemptively transfer connection if that happens */
1552   if (udp_session->thread_index != thread_index)
1553     quic_transfer_connection (ctx_index, udp_session->thread_index);
1554   else
1555     quic_send_packets (ctx);
1556
1557   return ret;
1558 }
1559
1560 static void
1561 quic_udp_session_disconnect_callback (session_t * s)
1562 {
1563   clib_warning ("UDP session disconnected???");
1564 }
1565
1566 static void
1567 quic_udp_session_cleanup_callback (session_t * udp_session,
1568                                    session_cleanup_ntf_t ntf)
1569 {
1570   quic_ctx_t *ctx;
1571
1572   if (ntf != SESSION_CLEANUP_SESSION)
1573     return;
1574
1575   ctx = quic_ctx_get (udp_session->opaque, udp_session->thread_index);
1576   quic_stop_ctx_timer (ctx);
1577   quic_ctx_free (ctx);
1578 }
1579
1580 static void
1581 quic_udp_session_reset_callback (session_t * s)
1582 {
1583   clib_warning ("UDP session reset???");
1584 }
1585
1586 static void
1587 quic_udp_session_migrate_callback (session_t * s, session_handle_t new_sh)
1588 {
1589   u32 new_thread = session_thread_from_handle (new_sh);
1590   quic_ctx_t *ctx;
1591
1592   QUIC_ERR ("Session %x migrated to %lx", s->session_index, new_sh);
1593   ASSERT (vlib_get_thread_index () == s->thread_index);
1594   ctx = quic_ctx_get (s->opaque, s->thread_index);
1595   ASSERT (ctx->udp_session_handle == session_handle (s));
1596
1597   ctx->udp_session_handle = new_sh;
1598 #if QUIC_DEBUG >= 1
1599   s->opaque = 0xfeedface;
1600 #endif
1601   quic_transfer_connection (ctx->c_c_index, new_thread);
1602 }
1603
1604 int
1605 quic_udp_session_accepted_callback (session_t * udp_session)
1606 {
1607   /* New UDP connection, try to accept it */
1608   u32 ctx_index;
1609   quic_ctx_t *ctx, *lctx;
1610   session_t *udp_listen_session;
1611   u32 thread_index = vlib_get_thread_index ();
1612
1613   udp_listen_session =
1614     listen_session_get_from_handle (udp_session->listener_handle);
1615
1616   ctx_index = quic_ctx_alloc (thread_index);
1617   ctx = quic_ctx_get (ctx_index, thread_index);
1618   ctx->c_thread_index = udp_session->thread_index;
1619   ctx->c_c_index = ctx_index;
1620   ctx->c_s_index = QUIC_SESSION_INVALID;
1621   ctx->udp_session_handle = session_handle (udp_session);
1622   QUIC_DBG (2, "ACCEPTED UDP 0x%lx", ctx->udp_session_handle);
1623   ctx->listener_ctx_id = udp_listen_session->opaque;
1624   lctx = quic_ctx_get (udp_listen_session->opaque,
1625                        udp_listen_session->thread_index);
1626   ctx->udp_is_ip4 = lctx->c_is_ip4;
1627   ctx->parent_app_id = lctx->parent_app_id;
1628   ctx->parent_app_wrk_id = lctx->parent_app_wrk_id;
1629   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1630   ctx->conn_state = QUIC_CONN_STATE_OPENED;
1631   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1632
1633   /* Also store it in ctx for convenience
1634    * Waiting for crypto_ctx logic */
1635   ctx->quicly_ctx = lctx->quicly_ctx;
1636
1637   udp_session->opaque = ctx_index;
1638
1639   /* TODO timeout to delete these if they never connect */
1640   return 0;
1641 }
1642
1643 static int
1644 quic_add_segment_callback (u32 client_index, u64 seg_handle)
1645 {
1646   /* No-op for builtin */
1647   return 0;
1648 }
1649
1650 static int
1651 quic_del_segment_callback (u32 client_index, u64 seg_handle)
1652 {
1653   /* No-op for builtin */
1654   return 0;
1655 }
1656
1657 static int
1658 quic_custom_app_rx_callback (transport_connection_t * tc)
1659 {
1660   quic_ctx_t *ctx;
1661   session_t *stream_session = session_get (tc->s_index, tc->thread_index);
1662   QUIC_DBG (3, "Received app READ notification");
1663   quic_ack_rx_data (stream_session);
1664   svm_fifo_reset_has_deq_ntf (stream_session->rx_fifo);
1665
1666   /* Need to send packets (acks may never be sent otherwise) */
1667   ctx = quic_ctx_get (stream_session->connection_index,
1668                       stream_session->thread_index);
1669   quic_send_packets (ctx);
1670   return 0;
1671 }
1672
1673 static int
1674 quic_custom_tx_callback (void *s, u32 max_burst_size)
1675 {
1676   session_t *stream_session = (session_t *) s;
1677   quicly_stream_t *stream;
1678   quic_ctx_t *ctx;
1679   int rv;
1680
1681   if (PREDICT_FALSE
1682       (stream_session->session_state >= SESSION_STATE_TRANSPORT_CLOSING))
1683     return 0;
1684   ctx = quic_ctx_get (stream_session->connection_index,
1685                       stream_session->thread_index);
1686   if (PREDICT_FALSE (!quic_ctx_is_stream (ctx)))
1687     {
1688       goto tx_end;              /* Most probably a reschedule */
1689     }
1690
1691   QUIC_DBG (3, "Stream TX event");
1692   quic_ack_rx_data (stream_session);
1693   if (!svm_fifo_max_dequeue (stream_session->tx_fifo))
1694     return 0;
1695
1696   stream = ctx->stream;
1697   if (!quicly_sendstate_is_open (&stream->sendstate))
1698     {
1699       QUIC_ERR ("Warning: tried to send on closed stream");
1700       return -1;
1701     }
1702
1703   if ((rv = quicly_stream_sync_sendbuf (stream, 1)) != 0)
1704     return rv;
1705
1706 tx_end:
1707   quic_send_packets (ctx);
1708   return 0;
1709 }
1710
1711 /*
1712  * Returns 0 if a matching connection is found and is on the right thread.
1713  * Otherwise returns -1.
1714  * If a connection is found, even on the wrong thread, ctx_thread and ctx_index
1715  * will be set.
1716  */
1717 static inline int
1718 quic_find_packet_ctx (quic_rx_packet_ctx_t * pctx, u32 caller_thread_index)
1719 {
1720   clib_bihash_kv_16_8_t kv;
1721   clib_bihash_16_8_t *h;
1722   quic_ctx_t *ctx;
1723   u32 index, thread_id;
1724
1725   h = &quic_main.connection_hash;
1726   quic_make_connection_key (&kv, &pctx->packet.cid.dest.plaintext);
1727   QUIC_DBG (3, "Searching conn with id %lu %lu", kv.key[0], kv.key[1]);
1728
1729   if (clib_bihash_search_16_8 (h, &kv, &kv))
1730     {
1731       QUIC_DBG (3, "connection not found");
1732       return QUIC_PACKET_TYPE_NONE;
1733     }
1734
1735   index = kv.value & UINT32_MAX;
1736   thread_id = kv.value >> 32;
1737   /* Check if this connection belongs to this thread, otherwise
1738    * ask for it to be moved */
1739   if (thread_id != caller_thread_index)
1740     {
1741       QUIC_DBG (2, "Connection is on wrong thread");
1742       /* Cannot make full check with quicly_is_destination... */
1743       pctx->ctx_index = index;
1744       pctx->thread_index = thread_id;
1745       return QUIC_PACKET_TYPE_MIGRATE;
1746     }
1747   ctx = quic_ctx_get (index, vlib_get_thread_index ());
1748   if (!ctx->conn)
1749     {
1750       QUIC_ERR ("ctx has no conn");
1751       return QUIC_PACKET_TYPE_NONE;
1752     }
1753   if (!quicly_is_destination (ctx->conn, NULL, &pctx->sa, &pctx->packet))
1754     return QUIC_PACKET_TYPE_NONE;
1755
1756   QUIC_DBG (3, "Connection found");
1757   pctx->ctx_index = index;
1758   pctx->thread_index = thread_id;
1759   return QUIC_PACKET_TYPE_RECEIVE;
1760 }
1761
1762 static int
1763 quic_accept_connection (u32 ctx_index, quic_rx_packet_ctx_t * pctx)
1764 {
1765   u32 thread_index = vlib_get_thread_index ();
1766   quicly_context_t *quicly_ctx;
1767   session_t *quic_session;
1768   clib_bihash_kv_16_8_t kv;
1769   app_worker_t *app_wrk;
1770   quicly_conn_t *conn;
1771   quic_ctx_t *ctx;
1772   quic_ctx_t *lctx;
1773   int rv;
1774
1775   /* new connection, accept and create context if packet is valid
1776    * TODO: check if socket is actually listening? */
1777   ctx = quic_ctx_get (ctx_index, thread_index);
1778   if (ctx->c_s_index != QUIC_SESSION_INVALID)
1779     {
1780       QUIC_DBG (2, "already accepted ctx 0x%x", ctx_index);
1781       return 0;
1782     }
1783
1784   quicly_ctx = quic_get_quicly_ctx_from_ctx (ctx);
1785   if ((rv = quicly_accept (&conn, quicly_ctx, NULL, &pctx->sa,
1786                            &pctx->packet, NULL, &quic_main.next_cid, NULL)))
1787     {
1788       /* Invalid packet, pass */
1789       assert (conn == NULL);
1790       QUIC_ERR ("Accept failed with %U", quic_format_err, rv);
1791       /* TODO: cleanup created quic ctx and UDP session */
1792       return 0;
1793     }
1794   assert (conn != NULL);
1795
1796   ++quic_main.next_cid.master_id;
1797   /* Save ctx handle in quicly connection */
1798   quic_store_conn_ctx (conn, ctx);
1799   ctx->conn = conn;
1800
1801   quic_session = session_alloc (ctx->c_thread_index);
1802   QUIC_DBG (2, "Allocated quic_session, 0x%lx ctx %u",
1803             session_handle (quic_session), ctx->c_c_index);
1804   quic_session->session_state = SESSION_STATE_LISTENING;
1805   ctx->c_s_index = quic_session->session_index;
1806
1807   lctx = quic_ctx_get (ctx->listener_ctx_id, 0);
1808
1809   quic_session->app_wrk_index = lctx->parent_app_wrk_id;
1810   quic_session->connection_index = ctx->c_c_index;
1811   quic_session->session_type =
1812     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, ctx->udp_is_ip4);
1813   quic_session->listener_handle = lctx->c_s_index;
1814
1815   /* Register connection in connections map */
1816   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1817   kv.value = ((u64) thread_index) << 32 | (u64) ctx_index;
1818   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1819   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1820
1821   /* If notify fails, reset connection immediatly */
1822   if ((rv = app_worker_init_accepted (quic_session)))
1823     {
1824       QUIC_ERR ("failed to allocate fifos");
1825       quic_proto_on_close (ctx_index, thread_index);
1826       return rv;
1827     }
1828
1829   app_wrk = app_worker_get (quic_session->app_wrk_index);
1830   if ((rv = app_worker_accept_notify (app_wrk, quic_session)))
1831     {
1832       QUIC_ERR ("failed to notify accept worker app");
1833       quic_proto_on_close (ctx_index, thread_index);
1834       return rv;
1835     }
1836   ctx->conn_state = QUIC_CONN_STATE_HANDSHAKE;
1837
1838   return quic_send_packets (ctx);
1839 }
1840
1841 static int
1842 quic_reset_connection (u64 udp_session_handle, quic_rx_packet_ctx_t * pctx)
1843 {
1844   /* short header packet; potentially a dead connection. No need to check the
1845    * length of the incoming packet, because loop is prevented by authenticating
1846    * the CID (by checking node_id and thread_id). If the peer is also sending a
1847    * reset, then the next CID is highly likely to contain a non-authenticating
1848    * CID, ... */
1849   QUIC_DBG (2, "Sending stateless reset");
1850   int rv;
1851   quicly_datagram_t *dgram;
1852   session_t *udp_session;
1853   quicly_context_t *quicly_ctx;
1854   if (pctx->packet.cid.dest.plaintext.node_id != 0
1855       || pctx->packet.cid.dest.plaintext.thread_id != 0)
1856     return 0;
1857   quicly_ctx = quic_get_quicly_ctx_from_udp (udp_session_handle);
1858   dgram = quicly_send_stateless_reset (quicly_ctx, &pctx->sa, NULL,
1859                                        &pctx->packet.cid.dest.plaintext);
1860   if (dgram == NULL)
1861     return 1;
1862   udp_session = session_get_from_handle (udp_session_handle);
1863   rv = quic_send_datagram (udp_session, dgram);
1864   quic_set_udp_tx_evt (udp_session);
1865   return rv;
1866 }
1867
1868 static int
1869 quic_process_one_rx_packet (u64 udp_session_handle, svm_fifo_t * f,
1870                             u32 fifo_offset, quic_rx_packet_ctx_t * pctx)
1871 {
1872   size_t plen;
1873   u32 full_len, ret;
1874   u32 thread_index = vlib_get_thread_index ();
1875   u32 cur_deq = svm_fifo_max_dequeue (f) - fifo_offset;
1876   quicly_context_t *quicly_ctx;
1877   int rv;
1878
1879   ret = svm_fifo_peek (f, fifo_offset,
1880                        SESSION_CONN_HDR_LEN, (u8 *) & pctx->ph);
1881   ASSERT (ret == SESSION_CONN_HDR_LEN);
1882   ASSERT (pctx->ph.data_offset == 0);
1883   full_len = pctx->ph.data_length + SESSION_CONN_HDR_LEN;
1884   if (full_len > cur_deq)
1885     {
1886       QUIC_ERR ("Not enough data in fifo RX");
1887       return 1;
1888     }
1889
1890   /* Quicly can read len bytes from the fifo at offset:
1891    * ph.data_offset + SESSION_CONN_HDR_LEN */
1892   ret = svm_fifo_peek (f, SESSION_CONN_HDR_LEN + fifo_offset,
1893                        pctx->ph.data_length, pctx->data);
1894   if (ret != pctx->ph.data_length)
1895     {
1896       QUIC_ERR ("Not enough data peeked in RX");
1897       return 1;
1898     }
1899
1900   quic_increment_counter (QUIC_ERROR_RX_PACKETS, 1);
1901   quic_build_sockaddr (&pctx->sa, &pctx->salen, &pctx->ph.rmt_ip,
1902                        pctx->ph.rmt_port, pctx->ph.is_ip4);
1903   quicly_ctx = quic_get_quicly_ctx_from_udp (udp_session_handle);
1904   plen = quicly_decode_packet (quicly_ctx, &pctx->packet,
1905                                pctx->data, pctx->ph.data_length);
1906
1907   if (plen == SIZE_MAX)
1908     {
1909       return 1;
1910     }
1911
1912   rv = quic_find_packet_ctx (pctx, thread_index);
1913   if (rv == QUIC_PACKET_TYPE_RECEIVE)
1914     {
1915       pctx->ptype = QUIC_PACKET_TYPE_RECEIVE;
1916       return 0;
1917     }
1918   else if (rv == QUIC_PACKET_TYPE_MIGRATE)
1919     {
1920       pctx->ptype = QUIC_PACKET_TYPE_MIGRATE;
1921       /*  Connection found but on wrong thread, ask move */
1922     }
1923   else if (QUICLY_PACKET_IS_LONG_HEADER (pctx->packet.octets.base[0]))
1924     {
1925       pctx->ptype = QUIC_PACKET_TYPE_ACCEPT;
1926     }
1927   else
1928     {
1929       pctx->ptype = QUIC_PACKET_TYPE_RESET;
1930     }
1931   return 1;
1932 }
1933
1934 static int
1935 quic_udp_session_rx_callback (session_t * udp_session)
1936 {
1937   /*  Read data from UDP rx_fifo and pass it to the quicly conn. */
1938   quic_ctx_t *ctx = NULL;
1939   svm_fifo_t *f = udp_session->rx_fifo;
1940   u32 max_deq;
1941   u64 udp_session_handle = session_handle (udp_session);
1942   int rv = 0;
1943   u32 thread_index = vlib_get_thread_index ();
1944   u32 cur_deq, fifo_offset, max_packets, i;
1945
1946   quic_rx_packet_ctx_t packets_ctx[QUIC_RCV_MAX_BATCH_PACKETS];
1947
1948   if (udp_session->flags & SESSION_F_IS_MIGRATING)
1949     {
1950       QUIC_DBG (3, "RX on migrating udp session");
1951       return 0;
1952     }
1953
1954 rx_start:
1955   max_deq = svm_fifo_max_dequeue (f);
1956   if (max_deq == 0)
1957     return 0;
1958
1959   fifo_offset = 0;
1960   max_packets = QUIC_RCV_MAX_BATCH_PACKETS;
1961
1962   for (i = 0; i < max_packets; i++)
1963     {
1964       packets_ctx[i].thread_index = UINT32_MAX;
1965       packets_ctx[i].ctx_index = UINT32_MAX;
1966       packets_ctx[i].ptype = QUIC_PACKET_TYPE_DROP;
1967
1968       cur_deq = max_deq - fifo_offset;
1969       if (cur_deq == 0)
1970         {
1971           max_packets = i + 1;
1972           break;
1973         }
1974       if (cur_deq < SESSION_CONN_HDR_LEN)
1975         {
1976           fifo_offset = max_deq;
1977           max_packets = i + 1;
1978           QUIC_ERR ("Fifo %d < header size in RX", cur_deq);
1979           break;
1980         }
1981       rv = quic_process_one_rx_packet (udp_session_handle, f,
1982                                        fifo_offset, &packets_ctx[i]);
1983       if (packets_ctx[i].ptype != QUIC_PACKET_TYPE_MIGRATE)
1984         fifo_offset += SESSION_CONN_HDR_LEN + packets_ctx[i].ph.data_length;
1985       if (rv)
1986         {
1987           max_packets = i + 1;
1988           break;
1989         }
1990     }
1991
1992   for (i = 0; i < max_packets; i++)
1993     {
1994       switch (packets_ctx[i].ptype)
1995         {
1996         case QUIC_PACKET_TYPE_RECEIVE:
1997           ctx = quic_ctx_get (packets_ctx[i].ctx_index, thread_index);
1998           rv = quicly_receive (ctx->conn, NULL, &packets_ctx[i].sa,
1999                                &packets_ctx[i].packet);
2000           if (rv && rv != QUICLY_ERROR_PACKET_IGNORED)
2001             {
2002               QUIC_ERR ("quicly_receive return error %U",
2003                         quic_format_err, rv);
2004             }
2005           break;
2006         case QUIC_PACKET_TYPE_ACCEPT:
2007           udp_session = session_get_from_handle (udp_session_handle);
2008           if ((rv = quic_accept_connection (udp_session->opaque,
2009                                             &packets_ctx[i])))
2010             {
2011               QUIC_ERR ("quic accept errored with %d", rv);
2012             }
2013           break;
2014         case QUIC_PACKET_TYPE_RESET:
2015           quic_reset_connection (udp_session_handle, &packets_ctx[i]);
2016           break;
2017         }
2018     }
2019   for (i = 0; i < max_packets; i++)
2020     {
2021       if (packets_ctx[i].ptype != QUIC_PACKET_TYPE_RECEIVE)
2022         continue;
2023       ctx = quic_ctx_get (packets_ctx[i].ctx_index,
2024                           packets_ctx[i].thread_index);
2025       quic_check_quic_session_connected (ctx);
2026       ctx = quic_ctx_get (packets_ctx[i].ctx_index,
2027                           packets_ctx[i].thread_index);
2028       quic_send_packets (ctx);
2029     }
2030
2031   udp_session = session_get_from_handle (udp_session_handle);   /*  session alloc might have happened */
2032   f = udp_session->rx_fifo;
2033   svm_fifo_dequeue_drop (f, fifo_offset);
2034
2035   if (svm_fifo_max_dequeue (f))
2036     goto rx_start;
2037
2038   return 0;
2039 }
2040
2041 always_inline void
2042 quic_common_get_transport_endpoint (quic_ctx_t * ctx,
2043                                     transport_endpoint_t * tep, u8 is_lcl)
2044 {
2045   session_t *udp_session;
2046   if (!quic_ctx_is_stream (ctx))
2047     {
2048       udp_session = session_get_from_handle (ctx->udp_session_handle);
2049       session_get_endpoint (udp_session, tep, is_lcl);
2050     }
2051 }
2052
2053 static void
2054 quic_get_transport_listener_endpoint (u32 listener_index,
2055                                       transport_endpoint_t * tep, u8 is_lcl)
2056 {
2057   quic_ctx_t *ctx;
2058   app_listener_t *app_listener;
2059   session_t *udp_listen_session;
2060   ctx = quic_ctx_get (listener_index, vlib_get_thread_index ());
2061   if (quic_ctx_is_listener (ctx))
2062     {
2063       app_listener = app_listener_get_w_handle (ctx->udp_session_handle);
2064       udp_listen_session = app_listener_get_session (app_listener);
2065       return session_get_endpoint (udp_listen_session, tep, is_lcl);
2066     }
2067   quic_common_get_transport_endpoint (ctx, tep, is_lcl);
2068 }
2069
2070 static void
2071 quic_get_transport_endpoint (u32 ctx_index, u32 thread_index,
2072                              transport_endpoint_t * tep, u8 is_lcl)
2073 {
2074   quic_ctx_t *ctx;
2075   ctx = quic_ctx_get (ctx_index, thread_index);
2076   quic_common_get_transport_endpoint (ctx, tep, is_lcl);
2077 }
2078
2079 /* *INDENT-OFF* */
2080 static session_cb_vft_t quic_app_cb_vft = {
2081   .session_accept_callback = quic_udp_session_accepted_callback,
2082   .session_disconnect_callback = quic_udp_session_disconnect_callback,
2083   .session_connected_callback = quic_udp_session_connected_callback,
2084   .session_reset_callback = quic_udp_session_reset_callback,
2085   .session_migrate_callback = quic_udp_session_migrate_callback,
2086   .add_segment_callback = quic_add_segment_callback,
2087   .del_segment_callback = quic_del_segment_callback,
2088   .builtin_app_rx_callback = quic_udp_session_rx_callback,
2089   .session_cleanup_callback = quic_udp_session_cleanup_callback,
2090 };
2091
2092 static const transport_proto_vft_t quic_proto = {
2093   .connect = quic_connect,
2094   .close = quic_proto_on_close,
2095   .start_listen = quic_start_listen,
2096   .stop_listen = quic_stop_listen,
2097   .get_connection = quic_connection_get,
2098   .get_listener = quic_listener_get,
2099   .update_time = quic_update_time,
2100   .app_rx_evt = quic_custom_app_rx_callback,
2101   .custom_tx = quic_custom_tx_callback,
2102   .format_connection = format_quic_connection,
2103   .format_half_open = format_quic_half_open,
2104   .format_listener = format_quic_listener,
2105   .get_transport_endpoint = quic_get_transport_endpoint,
2106   .get_transport_listener_endpoint = quic_get_transport_listener_endpoint,
2107   .transport_options = {
2108     .tx_type = TRANSPORT_TX_INTERNAL,
2109     .service_type = TRANSPORT_SERVICE_APP,
2110   },
2111 };
2112 /* *INDENT-ON* */
2113
2114 static quicly_stream_open_t on_stream_open = { quic_on_stream_open };
2115 static quicly_closed_by_peer_t on_closed_by_peer = { quic_on_closed_by_peer };
2116 static quicly_now_t quicly_vpp_now_cb = { quic_get_time };
2117
2118 static void
2119 quic_register_cipher_suite (crypto_engine_type_t type,
2120                             ptls_cipher_suite_t ** ciphers)
2121 {
2122   quic_main_t *qm = &quic_main;
2123   vec_validate (qm->quic_ciphers, type);
2124   clib_bitmap_set (qm->available_crypto_engines, type, 1);
2125   qm->quic_ciphers[type] = ciphers;
2126 }
2127
2128 static void
2129 quic_update_fifo_size ()
2130 {
2131   quic_main_t *qm = &quic_main;
2132   segment_manager_props_t *seg_mgr_props =
2133     application_get_segment_manager_properties (qm->app_index);
2134
2135   if (!seg_mgr_props)
2136     {
2137       clib_warning
2138         ("error while getting segment_manager_props_t, can't update fifo-size");
2139       return;
2140     }
2141
2142   seg_mgr_props->tx_fifo_size = qm->udp_fifo_size;
2143   seg_mgr_props->rx_fifo_size = qm->udp_fifo_size;
2144 }
2145
2146 static clib_error_t *
2147 quic_init (vlib_main_t * vm)
2148 {
2149   u32 segment_size = 256 << 20;
2150   vlib_thread_main_t *vtm = vlib_get_thread_main ();
2151   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
2152   vnet_app_attach_args_t _a, *a = &_a;
2153   u64 options[APP_OPTIONS_N_OPTIONS];
2154   quic_main_t *qm = &quic_main;
2155   u32 num_threads, i;
2156
2157   num_threads = 1 /* main thread */  + vtm->n_threads;
2158
2159   clib_memset (a, 0, sizeof (*a));
2160   clib_memset (options, 0, sizeof (options));
2161
2162   a->session_cb_vft = &quic_app_cb_vft;
2163   a->api_client_index = APP_INVALID_INDEX;
2164   a->options = options;
2165   a->name = format (0, "quic");
2166   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
2167   a->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = segment_size;
2168   a->options[APP_OPTIONS_RX_FIFO_SIZE] = qm->udp_fifo_size;
2169   a->options[APP_OPTIONS_TX_FIFO_SIZE] = qm->udp_fifo_size;
2170   a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = qm->udp_fifo_prealloc;
2171   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
2172   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
2173   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
2174
2175   if (vnet_application_attach (a))
2176     {
2177       clib_warning ("failed to attach quic app");
2178       return clib_error_return (0, "failed to attach quic app");
2179     }
2180
2181   vec_validate (qm->ctx_pool, num_threads - 1);
2182   vec_validate (qm->wrk_ctx, num_threads - 1);
2183   /*  Timer wheels, one per thread. */
2184   for (i = 0; i < num_threads; i++)
2185     {
2186       tw = &qm->wrk_ctx[i].timer_wheel;
2187       tw_timer_wheel_init_1t_3w_1024sl_ov (tw, quic_expired_timers_dispatch,
2188                                            1e-3 /* timer period 1ms */ , ~0);
2189       tw->last_run_time = vlib_time_now (vlib_get_main ());
2190     }
2191
2192   clib_bihash_init_16_8 (&qm->connection_hash, "quic connections", 1024,
2193                          4 << 20);
2194
2195
2196   qm->app_index = a->app_index;
2197   qm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
2198     / QUIC_TSTAMP_RESOLUTION;
2199   qm->session_cache.super.cb = quic_encrypt_ticket_cb;
2200
2201   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
2202                                FIB_PROTOCOL_IP4, ~0);
2203   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
2204                                FIB_PROTOCOL_IP6, ~0);
2205
2206   clib_bitmap_alloc (qm->available_crypto_engines,
2207                      app_crypto_engine_n_types ());
2208   quic_register_cipher_suite (CRYPTO_ENGINE_VPP, quic_crypto_cipher_suites);
2209   quic_register_cipher_suite (CRYPTO_ENGINE_PICOTLS,
2210                               ptls_openssl_cipher_suites);
2211   qm->default_crypto_engine = CRYPTO_ENGINE_PICOTLS;
2212   vec_free (a->name);
2213   return 0;
2214 }
2215
2216 VLIB_INIT_FUNCTION (quic_init);
2217
2218 static clib_error_t *
2219 quic_plugin_crypto_command_fn (vlib_main_t * vm,
2220                                unformat_input_t * input,
2221                                vlib_cli_command_t * cmd)
2222 {
2223   quic_main_t *qm = &quic_main;
2224   if (unformat_check_input (input) == UNFORMAT_END_OF_INPUT)
2225     return clib_error_return (0, "unknown input '%U'",
2226                               format_unformat_error, input);
2227   if (unformat (input, "vpp"))
2228     qm->default_crypto_engine = CRYPTO_ENGINE_VPP;
2229   else if (unformat (input, "picotls"))
2230     qm->default_crypto_engine = CRYPTO_ENGINE_PICOTLS;
2231   else
2232     return clib_error_return (0, "unknown input '%U'",
2233                               format_unformat_error, input);
2234   return 0;
2235 }
2236
2237 u64 quic_fifosize = 0;
2238 static clib_error_t *
2239 quic_plugin_set_fifo_size_command_fn (vlib_main_t * vm,
2240                                       unformat_input_t * input,
2241                                       vlib_cli_command_t * cmd)
2242 {
2243   quic_main_t *qm = &quic_main;
2244   unformat_input_t _line_input, *line_input = &_line_input;
2245   uword tmp;
2246
2247   if (!unformat_user (input, unformat_line_input, line_input))
2248     return 0;
2249
2250   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2251     {
2252       if (unformat (line_input, "%U", unformat_memory_size, &tmp))
2253         {
2254           if (tmp >= 0x100000000ULL)
2255             {
2256               return clib_error_return
2257                 (0, "fifo-size %llu (0x%llx) too large", tmp, tmp);
2258             }
2259           qm->udp_fifo_size = tmp;
2260           quic_update_fifo_size ();
2261         }
2262       else
2263         return clib_error_return (0, "unknown input '%U'",
2264                                   format_unformat_error, line_input);
2265     }
2266
2267   return 0;
2268 }
2269
2270 static u8 *
2271 quic_format_ctx_stat (u8 * s, va_list * args)
2272 {
2273   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
2274   quicly_stats_t quicly_stats;
2275
2276   quicly_get_stats (ctx->conn, &quicly_stats);
2277
2278   s = format (s, "\n\rQUIC conn stats \n\r");
2279
2280   s =
2281     format (s, "RTT: min:%d, smoothed:%d, variance:%d, latest:%d \n\r",
2282             quicly_stats.rtt.minimum, quicly_stats.rtt.smoothed,
2283             quicly_stats.rtt.variance, quicly_stats.rtt.latest);
2284   s = format (s, "Packet loss:%d \n\r", quicly_stats.num_packets.lost);
2285
2286   return s;
2287 }
2288
2289 static clib_error_t *
2290 quic_plugin_showstats_command_fn (vlib_main_t * vm,
2291                                   unformat_input_t * input,
2292                                   vlib_cli_command_t * cmd)
2293 {
2294   quic_main_t *qm = &quic_main;
2295   quic_ctx_t *ctx = NULL;
2296   u32 num_workers = vlib_num_workers ();
2297
2298   for (int i = 0; i < num_workers + 1; i++)
2299     {
2300       /* *INDENT-OFF* */
2301       pool_foreach (ctx, qm->ctx_pool[i],
2302       ({
2303         if(!(ctx->flags & QUIC_F_IS_LISTENER) && !(ctx->flags & QUIC_F_IS_STREAM))
2304           vlib_cli_output (vm, "%U", quic_format_ctx_stat, ctx);
2305       }));
2306       /* *INDENT-ON* */
2307     }
2308   return 0;
2309 }
2310
2311 static clib_error_t *
2312 quic_show_ctx_command_fn (vlib_main_t * vm, unformat_input_t * input,
2313                           vlib_cli_command_t * cmd)
2314 {
2315   quic_main_t *qm = &quic_main;
2316   quic_ctx_t *ctx = NULL;
2317   u32 num_workers = vlib_num_workers ();
2318
2319   for (int i = 0; i < num_workers + 1; i++)
2320     {
2321       /* *INDENT-OFF* */
2322       pool_foreach (ctx, qm->ctx_pool[i],
2323       ({
2324         vlib_cli_output (vm, "%U", format_quic_ctx, ctx, 1);
2325       }));
2326       /* *INDENT-ON* */
2327     }
2328   return 0;
2329 }
2330
2331 /* *INDENT-OFF* */
2332 VLIB_CLI_COMMAND (quic_plugin_crypto_command, static) =
2333 {
2334   .path = "quic set crypto api",
2335   .short_help = "quic set crypto api [picotls, vpp]",
2336   .function = quic_plugin_crypto_command_fn,
2337 };
2338 VLIB_CLI_COMMAND(quic_plugin_set_fifo_size_command, static)=
2339 {
2340   .path = "quic set fifo-size",
2341   .short_help = "quic set fifo-size N[K|M|G] (default 64K)",
2342   .function = quic_plugin_set_fifo_size_command_fn,
2343 };
2344 VLIB_CLI_COMMAND(quic_plugin_stats_command, static)=
2345 {
2346   .path = "show quic stats",
2347   .short_help = "show quic stats",
2348   .function = quic_plugin_showstats_command_fn,
2349 };
2350 VLIB_CLI_COMMAND(quic_show_ctx_command, static)=
2351 {
2352   .path = "show quic ctx",
2353   .short_help = "show quic ctx",
2354   .function = quic_show_ctx_command_fn,
2355 };
2356 VLIB_PLUGIN_REGISTER () =
2357 {
2358   .version = VPP_BUILD_VER,
2359   .description = "Quic transport protocol",
2360   .default_disabled = 1,
2361 };
2362 /* *INDENT-ON* */
2363
2364 static clib_error_t *
2365 quic_config_fn (vlib_main_t * vm, unformat_input_t * input)
2366 {
2367   quic_main_t *qm = &quic_main;
2368   uword tmp;
2369   u32 i;
2370
2371   qm->udp_fifo_size = QUIC_DEFAULT_FIFO_SIZE;
2372   qm->udp_fifo_prealloc = 0;
2373   qm->connection_timeout = QUIC_DEFAULT_CONN_TIMEOUT;
2374   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2375     {
2376       if (unformat (input, "fifo-size %U", unformat_memory_size, &tmp))
2377         {
2378           if (tmp >= 0x100000000ULL)
2379             {
2380               return clib_error_return (0,
2381                                         "fifo-size %llu (0x%llx) too large",
2382                                         tmp, tmp);
2383             }
2384           qm->udp_fifo_size = tmp;
2385         }
2386       else if (unformat (input, "conn-timeout %u", &i))
2387         qm->connection_timeout = i;
2388       else if (unformat (input, "fifo-prealloc %u", &i))
2389         qm->udp_fifo_prealloc = i;
2390       else
2391         return clib_error_return (0, "unknown input '%U'",
2392                                   format_unformat_error, input);
2393     }
2394
2395   return 0;
2396 }
2397
2398 VLIB_EARLY_CONFIG_FUNCTION (quic_config_fn, "quic");
2399
2400 static uword
2401 quic_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
2402               vlib_frame_t * frame)
2403 {
2404   return 0;
2405 }
2406
2407 /* *INDENT-OFF* */
2408 VLIB_REGISTER_NODE (quic_input_node) =
2409 {
2410   .function = quic_node_fn,
2411   .name = "quic-input",
2412   .vector_size = sizeof (u32),
2413   .type = VLIB_NODE_TYPE_INTERNAL,
2414   .n_errors = ARRAY_LEN (quic_error_strings),
2415   .error_strings = quic_error_strings,
2416 };
2417 /* *INDENT-ON* */
2418
2419 /*
2420  * fd.io coding-style-patch-verification: ON
2421  *
2422  * Local Variables:
2423  * eval: (c-set-style "gnu")
2424  * End:
2425  */