quic: fix stream tx_fifo race condition
[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   QUIC_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   QUIC_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   QUIC_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   QUIC_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       QUIC_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       QUIC_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   QUIC_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, rlen, rv;
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
600   stream_data = (quic_stream_data_t *) stream->data;
601   sctx = quic_ctx_get (stream_data->ctx_id, stream_data->thread_index);
602   stream_session = session_get (sctx->c_s_index, stream_data->thread_index);
603   f = stream_session->rx_fifo;
604
605   max_enq = svm_fifo_max_enqueue_prod (f);
606   QUIC_DBG (3, "Enqueuing %u at off %u in %u space", len, off, max_enq);
607   /* Handle duplicate packet/chunk from quicly */
608   if (off < stream_data->app_rx_data_len)
609     {
610       QUIC_DBG (3, "Session [idx %u, app_wrk %u, thread %u, rx-fifo 0x%llx]: "
611                 "DUPLICATE PACKET (max_enq %u, len %u, "
612                 "app_rx_data_len %u, off %u, ToBeNQ %u)",
613                 stream_session->session_index,
614                 stream_session->app_wrk_index,
615                 stream_session->thread_index, f,
616                 max_enq, len, stream_data->app_rx_data_len, off,
617                 off - stream_data->app_rx_data_len + len);
618       return 0;
619     }
620   if (PREDICT_FALSE ((off - stream_data->app_rx_data_len + len) > max_enq))
621     {
622       QUIC_ERR ("Session [idx %u, app_wrk %u, thread %u, rx-fifo 0x%llx]: "
623                 "RX FIFO IS FULL (max_enq %u, len %u, "
624                 "app_rx_data_len %u, off %u, ToBeNQ %u)",
625                 stream_session->session_index,
626                 stream_session->app_wrk_index,
627                 stream_session->thread_index, f,
628                 max_enq, len, stream_data->app_rx_data_len, off,
629                 off - stream_data->app_rx_data_len + len);
630       return 1;
631     }
632   if (off == stream_data->app_rx_data_len)
633     {
634       /* Streams live on the same thread so (f, stream_data) should stay consistent */
635       rlen = svm_fifo_enqueue (f, len, (u8 *) src);
636       QUIC_DBG (3, "Session [idx %u, app_wrk %u, ti %u, rx-fifo 0x%llx]: "
637                 "Enqueuing %u (rlen %u) at off %u in %u space, ",
638                 stream_session->session_index,
639                 stream_session->app_wrk_index,
640                 stream_session->thread_index, f, len, rlen, off, max_enq);
641       stream_data->app_rx_data_len += rlen;
642       QUIC_ASSERT (rlen >= len);
643       app_wrk = app_worker_get_if_valid (stream_session->app_wrk_index);
644       if (PREDICT_TRUE (app_wrk != 0))
645         {
646           rv = app_worker_lock_and_send_event (app_wrk, stream_session,
647                                                SESSION_IO_EVT_RX);
648           if (rv)
649             QUIC_ERR ("Failed to ping app for RX");
650         }
651       quic_ack_rx_data (stream_session);
652     }
653   else
654     {
655       rlen = svm_fifo_enqueue_with_offset (f,
656                                            off - stream_data->app_rx_data_len,
657                                            len, (u8 *) src);
658       QUIC_ASSERT (rlen == 0);
659     }
660   return 0;
661 }
662
663 void
664 quic_fifo_egress_shift (quicly_stream_t * stream, size_t delta)
665 {
666   quic_stream_data_t *stream_data;
667   session_t *stream_session;
668   svm_fifo_t *f;
669   u32 rv;
670
671   stream_data = (quic_stream_data_t *) stream->data;
672   stream_session = get_stream_session_from_stream (stream);
673   f = stream_session->tx_fifo;
674
675   QUIC_ASSERT (stream_data->app_tx_data_len >= delta);
676   stream_data->app_tx_data_len -= delta;
677   rv = svm_fifo_dequeue_drop (f, delta);
678   QUIC_ASSERT (rv == delta);
679
680   rv = quicly_stream_sync_sendbuf (stream, 0);
681   QUIC_ASSERT (!rv);
682 }
683
684 int
685 quic_fifo_egress_emit (quicly_stream_t * stream, size_t off, void *dst,
686                        size_t * len, int *wrote_all)
687 {
688   u32 deq_max, first_deq, max_rd_chunk, rem_offset;
689   quic_stream_data_t *stream_data;
690   session_t *stream_session;
691   svm_fifo_t *f;
692
693   stream_data = (quic_stream_data_t *) stream->data;
694   stream_session = get_stream_session_from_stream (stream);
695   f = stream_session->tx_fifo;
696
697   QUIC_DBG (3, "Emitting %u, offset %u", *len, off);
698
699   deq_max = svm_fifo_max_dequeue_cons (f);
700   QUIC_ASSERT (off <= deq_max);
701   if (off + *len < deq_max)
702     {
703       *wrote_all = 0;
704     }
705   else
706     {
707       *wrote_all = 1;
708       *len = deq_max - off;
709     }
710   QUIC_ASSERT (*len > 0);
711
712   if (off + *len > stream_data->app_tx_data_len)
713     stream_data->app_tx_data_len = off + *len;
714
715   /* TODO, use something like : return svm_fifo_peek (f, off, *len, dst); */
716   max_rd_chunk = svm_fifo_max_read_chunk (f);
717
718   first_deq = 0;
719   if (off < max_rd_chunk)
720     {
721       first_deq = clib_min (*len, max_rd_chunk - off);
722       clib_memcpy_fast (dst, svm_fifo_head (f) + off, first_deq);
723     }
724
725   if (max_rd_chunk < off + *len)
726     {
727       rem_offset = max_rd_chunk < off ? off - max_rd_chunk : 0;
728       clib_memcpy_fast (dst + first_deq, f->head_chunk->data + rem_offset,
729                         *len - first_deq);
730     }
731
732   return 0;
733 }
734
735 static const quicly_stream_callbacks_t quic_stream_callbacks = {
736   .on_destroy = quic_on_stream_destroy,
737   .on_send_shift = quic_fifo_egress_shift,
738   .on_send_emit = quic_fifo_egress_emit,
739   .on_send_stop = quic_on_stop_sending,
740   .on_receive = quic_on_receive,
741   .on_receive_reset = quic_on_receive_reset
742 };
743
744 static int
745 quic_on_stream_open (quicly_stream_open_t * self, quicly_stream_t * stream)
746 {
747   /* Return code for this function ends either
748    * - in quicly_receive : if not QUICLY_ERROR_PACKET_IGNORED, will close connection
749    * - in quicly_open_stream, returned directly
750    */
751
752   session_t *stream_session, *quic_session;
753   quic_stream_data_t *stream_data;
754   app_worker_t *app_wrk;
755   quic_ctx_t *qctx, *sctx;
756   u32 sctx_id;
757   int rv;
758
759   QUIC_DBG (2, "on_stream_open called");
760   stream->data = clib_mem_alloc (sizeof (quic_stream_data_t));
761   stream->callbacks = &quic_stream_callbacks;
762   /* Notify accept on parent qsession, but only if this is not a locally
763    * initiated stream */
764   if (quicly_stream_is_self_initiated (stream))
765     return 0;
766
767   sctx_id = quic_ctx_alloc (vlib_get_thread_index ());
768   qctx = quic_get_conn_ctx (stream->conn);
769
770   /* Might need to signal that the connection is ready if the first thing the
771    * server does is open a stream */
772   quic_check_quic_session_connected (qctx);
773   /* ctx might be invalidated */
774   qctx = quic_get_conn_ctx (stream->conn);
775
776   stream_session = session_alloc (qctx->c_thread_index);
777   QUIC_DBG (2, "ACCEPTED stream_session 0x%lx ctx %u",
778             session_handle (stream_session), sctx_id);
779   sctx = quic_ctx_get (sctx_id, qctx->c_thread_index);
780   sctx->parent_app_wrk_id = qctx->parent_app_wrk_id;
781   sctx->parent_app_id = qctx->parent_app_id;
782   sctx->quic_connection_ctx_id = qctx->c_c_index;
783   sctx->c_c_index = sctx_id;
784   sctx->c_s_index = stream_session->session_index;
785   sctx->stream = stream;
786   sctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
787   sctx->flags |= QUIC_F_IS_STREAM;
788
789   stream_data = (quic_stream_data_t *) stream->data;
790   stream_data->ctx_id = sctx_id;
791   stream_data->thread_index = sctx->c_thread_index;
792   stream_data->app_rx_data_len = 0;
793   stream_data->app_tx_data_len = 0;
794
795   sctx->c_s_index = stream_session->session_index;
796   stream_session->session_state = SESSION_STATE_CREATED;
797   stream_session->app_wrk_index = sctx->parent_app_wrk_id;
798   stream_session->connection_index = sctx->c_c_index;
799   stream_session->session_type =
800     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, qctx->udp_is_ip4);
801   quic_session = session_get (qctx->c_s_index, qctx->c_thread_index);
802   stream_session->listener_handle = listen_session_get_handle (quic_session);
803
804   app_wrk = app_worker_get (stream_session->app_wrk_index);
805   if ((rv = app_worker_init_connected (app_wrk, stream_session)))
806     {
807       QUIC_ERR ("failed to allocate fifos");
808       quicly_reset_stream (stream, QUIC_APP_ALLOCATION_ERROR);
809       return 0;                 /* Frame is still valid */
810     }
811   svm_fifo_add_want_deq_ntf (stream_session->rx_fifo,
812                              SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL |
813                              SVM_FIFO_WANT_DEQ_NOTIF_IF_EMPTY);
814
815   if ((rv = app_worker_accept_notify (app_wrk, stream_session)))
816     {
817       QUIC_ERR ("failed to notify accept worker app");
818       quicly_reset_stream (stream, QUIC_APP_ACCEPT_NOTIFY_ERROR);
819       return 0;                 /* Frame is still valid */
820     }
821
822   return 0;
823 }
824
825 static void
826 quic_on_closed_by_peer (quicly_closed_by_peer_t * self, quicly_conn_t * conn,
827                         int code, uint64_t frame_type,
828                         const char *reason, size_t reason_len)
829 {
830   quic_ctx_t *ctx = quic_get_conn_ctx (conn);
831 #if QUIC_DEBUG >= 2
832   session_t *quic_session = session_get (ctx->c_s_index, ctx->c_thread_index);
833   clib_warning ("Session 0x%lx closed by peer (%U) %.*s ",
834                 session_handle (quic_session), quic_format_err, code,
835                 reason_len, reason);
836 #endif
837   ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING;
838   session_transport_closing_notify (&ctx->connection);
839 }
840
841 /* Timer handling */
842
843 static int64_t
844 quic_get_thread_time (u8 thread_index)
845 {
846   return quic_main.wrk_ctx[thread_index].time_now;
847 }
848
849 static int64_t
850 quic_get_time (quicly_now_t * self)
851 {
852   u8 thread_index = vlib_get_thread_index ();
853   return quic_get_thread_time (thread_index);
854 }
855
856 static u32
857 quic_set_time_now (u32 thread_index)
858 {
859   vlib_main_t *vlib_main = vlib_get_main ();
860   f64 time = vlib_time_now (vlib_main);
861   quic_main.wrk_ctx[thread_index].time_now = (int64_t) (time * 1000.f);
862   return quic_main.wrk_ctx[thread_index].time_now;
863 }
864
865 /* Transport proto callback */
866 static void
867 quic_update_time (f64 now, u8 thread_index)
868 {
869   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
870
871   tw = &quic_main.wrk_ctx[thread_index].timer_wheel;
872   quic_set_time_now (thread_index);
873   tw_timer_expire_timers_1t_3w_1024sl_ov (tw, now);
874 }
875
876 static void
877 quic_timer_expired (u32 conn_index)
878 {
879   quic_ctx_t *ctx;
880   QUIC_DBG (4, "Timer expired for conn %u at %ld", conn_index,
881             quic_get_time (NULL));
882   ctx = quic_ctx_get (conn_index, vlib_get_thread_index ());
883   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
884   quic_send_packets (ctx);
885 }
886
887 static void
888 quic_update_timer (quic_ctx_t * ctx)
889 {
890   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
891   int64_t next_timeout, next_interval;
892   session_t *quic_session;
893   int rv;
894
895   /*  This timeout is in ms which is the unit of our timer */
896   next_timeout = quicly_get_first_timeout (ctx->conn);
897   next_interval = next_timeout - quic_get_time (NULL);
898
899   if (next_timeout == 0 || next_interval <= 0)
900     {
901       if (ctx->c_s_index == QUIC_SESSION_INVALID)
902         {
903           next_interval = 1;
904         }
905       else
906         {
907           quic_session = session_get (ctx->c_s_index, ctx->c_thread_index);
908           if (svm_fifo_set_event (quic_session->tx_fifo))
909             {
910               rv = session_send_io_evt_to_thread_custom (quic_session,
911                                                          quic_session->thread_index,
912                                                          SESSION_IO_EVT_BUILTIN_TX);
913               if (PREDICT_FALSE (rv))
914                 QUIC_ERR ("Failed to enqueue builtin_tx %d", rv);
915             }
916           return;
917         }
918     }
919
920   tw = &quic_main.wrk_ctx[vlib_get_thread_index ()].timer_wheel;
921
922   QUIC_DBG (4, "Timer set to %ld (int %ld) for ctx %u", next_timeout,
923             next_interval, ctx->c_c_index);
924
925   if (ctx->timer_handle == QUIC_TIMER_HANDLE_INVALID)
926     {
927       if (next_timeout == INT64_MAX)
928         {
929           QUIC_DBG (4, "timer for ctx %u already stopped", ctx->c_c_index);
930           return;
931         }
932       ctx->timer_handle = tw_timer_start_1t_3w_1024sl_ov (tw, ctx->c_c_index,
933                                                           0, next_interval);
934     }
935   else
936     {
937       if (next_timeout == INT64_MAX)
938         {
939           quic_stop_ctx_timer (ctx);
940         }
941       else
942         tw_timer_update_1t_3w_1024sl_ov (tw, ctx->timer_handle,
943                                          next_interval);
944     }
945   return;
946 }
947
948 static void
949 quic_expired_timers_dispatch (u32 * expired_timers)
950 {
951   int i;
952
953   for (i = 0; i < vec_len (expired_timers); i++)
954     {
955       quic_timer_expired (expired_timers[i]);
956     }
957 }
958
959 /* Transport proto functions */
960
961 static int
962 quic_connect_stream (session_t * quic_session, u32 opaque)
963 {
964   uint64_t quic_session_handle;
965   session_t *stream_session;
966   quic_stream_data_t *stream_data;
967   quicly_stream_t *stream;
968   quicly_conn_t *conn;
969   app_worker_t *app_wrk;
970   quic_ctx_t *qctx, *sctx;
971   u32 sctx_index;
972   int rv;
973
974   /*  Find base session to which the user want to attach a stream */
975   quic_session_handle = session_handle (quic_session);
976   QUIC_DBG (2, "Opening new stream (qsession %u)", quic_session_handle);
977
978   if (session_type_transport_proto (quic_session->session_type) !=
979       TRANSPORT_PROTO_QUIC)
980     {
981       QUIC_ERR ("received incompatible session");
982       return -1;
983     }
984
985   app_wrk = app_worker_get_if_valid (quic_session->app_wrk_index);
986   if (!app_wrk)
987     {
988       QUIC_ERR ("Invalid app worker :(");
989       return -1;
990     }
991
992   sctx_index = quic_ctx_alloc (quic_session->thread_index);     /*  Allocate before we get pointers */
993   sctx = quic_ctx_get (sctx_index, quic_session->thread_index);
994   qctx = quic_ctx_get (quic_session->connection_index,
995                        quic_session->thread_index);
996   if (quic_ctx_is_stream (qctx))
997     {
998       QUIC_ERR ("session is a stream");
999       quic_ctx_free (sctx);
1000       return -1;
1001     }
1002
1003   sctx->parent_app_wrk_id = qctx->parent_app_wrk_id;
1004   sctx->parent_app_id = qctx->parent_app_id;
1005   sctx->quic_connection_ctx_id = qctx->c_c_index;
1006   sctx->c_c_index = sctx_index;
1007   sctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1008   sctx->flags |= QUIC_F_IS_STREAM;
1009
1010   conn = qctx->conn;
1011
1012   if (!conn || !quicly_connection_is_ready (conn))
1013     return -1;
1014
1015   if ((rv = quicly_open_stream (conn, &stream, 0 /* uni */ )))
1016     {
1017       QUIC_DBG (2, "Stream open failed with %d", rv);
1018       return -1;
1019     }
1020   sctx->stream = stream;
1021
1022   QUIC_DBG (2, "Opened stream %d, creating session", stream->stream_id);
1023
1024   stream_session = session_alloc (qctx->c_thread_index);
1025   QUIC_DBG (2, "Allocated stream_session 0x%lx ctx %u",
1026             session_handle (stream_session), sctx_index);
1027   stream_session->app_wrk_index = app_wrk->wrk_index;
1028   stream_session->connection_index = sctx_index;
1029   stream_session->listener_handle = quic_session_handle;
1030   stream_session->session_type =
1031     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, qctx->udp_is_ip4);
1032
1033   sctx->c_s_index = stream_session->session_index;
1034   stream_data = (quic_stream_data_t *) stream->data;
1035   stream_data->ctx_id = sctx->c_c_index;
1036   stream_data->thread_index = sctx->c_thread_index;
1037   stream_data->app_rx_data_len = 0;
1038   stream_data->app_tx_data_len = 0;
1039   stream_session->session_state = SESSION_STATE_READY;
1040
1041   /* For now we only reset streams. Cleanup will be triggered by timers */
1042   if (app_worker_init_connected (app_wrk, stream_session))
1043     {
1044       QUIC_ERR ("failed to app_worker_init_connected");
1045       quicly_reset_stream (stream, QUIC_APP_CONNECT_NOTIFY_ERROR);
1046       return app_worker_connect_notify (app_wrk, NULL, opaque);
1047     }
1048
1049   svm_fifo_add_want_deq_ntf (stream_session->rx_fifo,
1050                              SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL |
1051                              SVM_FIFO_WANT_DEQ_NOTIF_IF_EMPTY);
1052
1053   if (app_worker_connect_notify (app_wrk, stream_session, opaque))
1054     {
1055       QUIC_ERR ("failed to notify app");
1056       quicly_reset_stream (stream, QUIC_APP_CONNECT_NOTIFY_ERROR);
1057       return -1;
1058     }
1059
1060   return 0;
1061 }
1062
1063 static int
1064 quic_connect_connection (session_endpoint_cfg_t * sep)
1065 {
1066   vnet_connect_args_t _cargs, *cargs = &_cargs;
1067   quic_main_t *qm = &quic_main;
1068   quic_ctx_t *ctx;
1069   app_worker_t *app_wrk;
1070   application_t *app;
1071   u32 ctx_index;
1072   u32 thread_index = vlib_get_thread_index ();
1073   int error;
1074
1075   clib_memset (cargs, 0, sizeof (*cargs));
1076   ctx_index = quic_ctx_alloc (thread_index);
1077   ctx = quic_ctx_get (ctx_index, thread_index);
1078   ctx->parent_app_wrk_id = sep->app_wrk_index;
1079   ctx->c_s_index = QUIC_SESSION_INVALID;
1080   ctx->c_c_index = ctx_index;
1081   ctx->udp_is_ip4 = sep->is_ip4;
1082   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1083   ctx->conn_state = QUIC_CONN_STATE_HANDSHAKE;
1084   ctx->client_opaque = sep->opaque;
1085   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1086   if (sep->hostname)
1087     ctx->srv_hostname = format (0, "%v", sep->hostname);
1088   else
1089     /*  needed by quic for crypto + determining client / server */
1090     ctx->srv_hostname = format (0, "%U", format_ip46_address,
1091                                 &sep->ip, sep->is_ip4);
1092   vec_terminate_c_string (ctx->srv_hostname);
1093
1094   clib_memcpy (&cargs->sep, sep, sizeof (session_endpoint_cfg_t));
1095   cargs->sep.transport_proto = TRANSPORT_PROTO_UDPC;
1096   cargs->app_index = qm->app_index;
1097   cargs->api_context = ctx_index;
1098
1099   app_wrk = app_worker_get (sep->app_wrk_index);
1100   app = application_get (app_wrk->app_index);
1101   ctx->parent_app_id = app_wrk->app_index;
1102   cargs->sep_ext.ns_index = app->ns_index;
1103
1104   if ((error =
1105        quic_store_quicly_ctx (app, sep->ckpair_index, sep->crypto_engine)))
1106     return error;
1107   /* Also store it in ctx for convenience
1108    * Waiting for crypto_ctx logic */
1109   ctx->quicly_ctx = (quicly_context_t *) app->quicly_ctx;
1110
1111   if ((error = vnet_connect (cargs)))
1112     return error;
1113
1114   return 0;
1115 }
1116
1117 static int
1118 quic_connect (transport_endpoint_cfg_t * tep)
1119 {
1120   QUIC_DBG (2, "Called quic_connect");
1121   session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) tep;
1122   session_t *quic_session;
1123   sep = (session_endpoint_cfg_t *) tep;
1124
1125   quic_session = session_get_from_handle_if_valid (sep->parent_handle);
1126   if (quic_session)
1127     return quic_connect_stream (quic_session, sep->opaque);
1128   else
1129     return quic_connect_connection (sep);
1130 }
1131
1132 static void
1133 quic_proto_on_close (u32 ctx_index, u32 thread_index)
1134 {
1135   quic_ctx_t *ctx = quic_ctx_get_if_valid (ctx_index, thread_index);
1136   if (!ctx)
1137     return;
1138 #if QUIC_DEBUG >= 2
1139   session_t *stream_session = session_get (ctx->c_s_index,
1140                                            ctx->c_thread_index);
1141   clib_warning ("Closing session 0x%lx", session_handle (stream_session));
1142 #endif
1143   if (quic_ctx_is_stream (ctx))
1144     {
1145       quicly_stream_t *stream = ctx->stream;
1146       quicly_reset_stream (stream, QUIC_APP_ERROR_CLOSE_NOTIFY);
1147       quic_send_packets (ctx);
1148       return;
1149     }
1150
1151   switch (ctx->conn_state)
1152     {
1153     case QUIC_CONN_STATE_OPENED:
1154     case QUIC_CONN_STATE_HANDSHAKE:
1155     case QUIC_CONN_STATE_READY:
1156       ctx->conn_state = QUIC_CONN_STATE_ACTIVE_CLOSING;
1157       quicly_conn_t *conn = ctx->conn;
1158       /* Start connection closing. Keep sending packets until quicly_send
1159          returns QUICLY_ERROR_FREE_CONNECTION */
1160       quicly_close (conn, QUIC_APP_ERROR_CLOSE_NOTIFY, "Closed by peer");
1161       /* This also causes all streams to be closed (and the cb called) */
1162       quic_send_packets (ctx);
1163       break;
1164     case QUIC_CONN_STATE_PASSIVE_CLOSING:
1165       ctx->conn_state = QUIC_CONN_STATE_PASSIVE_CLOSING_APP_CLOSED;
1166       /* send_packets will eventually return an error, we delete the conn at
1167          that point */
1168       break;
1169     case QUIC_CONN_STATE_PASSIVE_CLOSING_QUIC_CLOSED:
1170       quic_connection_delete (ctx);
1171       break;
1172     case QUIC_CONN_STATE_ACTIVE_CLOSING:
1173       break;
1174     default:
1175       QUIC_ERR ("Trying to close conn in state %d", ctx->conn_state);
1176       break;
1177     }
1178 }
1179
1180 static u32
1181 quic_start_listen (u32 quic_listen_session_index, transport_endpoint_t * tep)
1182 {
1183   vnet_listen_args_t _bargs, *args = &_bargs;
1184   quic_main_t *qm = &quic_main;
1185   session_handle_t udp_handle;
1186   session_endpoint_cfg_t *sep;
1187   session_t *udp_listen_session;
1188   app_worker_t *app_wrk;
1189   application_t *app;
1190   quic_ctx_t *lctx;
1191   u32 lctx_index;
1192   app_listener_t *app_listener;
1193   int rv;
1194
1195   sep = (session_endpoint_cfg_t *) tep;
1196   app_wrk = app_worker_get (sep->app_wrk_index);
1197   /* We need to call this because we call app_worker_init_connected in
1198    * quic_accept_stream, which assumes the connect segment manager exists */
1199   app_worker_alloc_connects_segment_manager (app_wrk);
1200   app = application_get (app_wrk->app_index);
1201   QUIC_DBG (2, "Called quic_start_listen for app %d", app_wrk->app_index);
1202
1203   if (quic_store_quicly_ctx (app, sep->ckpair_index, sep->crypto_engine))
1204     return -1;
1205
1206   sep->transport_proto = TRANSPORT_PROTO_UDPC;
1207   clib_memset (args, 0, sizeof (*args));
1208   args->app_index = qm->app_index;
1209   args->sep_ext = *sep;
1210   args->sep_ext.ns_index = app->ns_index;
1211   if ((rv = vnet_listen (args)))
1212     return rv;
1213
1214   lctx_index = quic_ctx_alloc (0);
1215   udp_handle = args->handle;
1216   app_listener = app_listener_get_w_handle (udp_handle);
1217   udp_listen_session = app_listener_get_session (app_listener);
1218   udp_listen_session->opaque = lctx_index;
1219
1220   lctx = quic_ctx_get (lctx_index, 0);
1221   lctx->flags |= QUIC_F_IS_LISTENER;
1222   /* Also store it in ctx for convenience
1223    * Waiting for crypto_ctx logic */
1224   lctx->quicly_ctx = (quicly_context_t *) app->quicly_ctx;
1225
1226   clib_memcpy (&lctx->c_rmt_ip, &args->sep.peer.ip, sizeof (ip46_address_t));
1227   clib_memcpy (&lctx->c_lcl_ip, &args->sep.ip, sizeof (ip46_address_t));
1228   lctx->c_rmt_port = args->sep.peer.port;
1229   lctx->c_lcl_port = args->sep.port;
1230   lctx->c_is_ip4 = args->sep.is_ip4;
1231   lctx->c_fib_index = args->sep.fib_index;
1232   lctx->c_proto = TRANSPORT_PROTO_QUIC;
1233   lctx->parent_app_wrk_id = sep->app_wrk_index;
1234   lctx->parent_app_id = app_wrk->app_index;
1235   lctx->udp_session_handle = udp_handle;
1236   lctx->c_s_index = quic_listen_session_index;
1237
1238   QUIC_DBG (2, "Listening UDP session 0x%lx",
1239             session_handle (udp_listen_session));
1240   QUIC_DBG (2, "Listening QUIC session 0x%lx", quic_listen_session_index);
1241   return lctx_index;
1242 }
1243
1244 static u32
1245 quic_stop_listen (u32 lctx_index)
1246 {
1247   QUIC_DBG (2, "Called quic_stop_listen");
1248   quic_ctx_t *lctx;
1249   lctx = quic_ctx_get (lctx_index, 0);
1250   QUIC_ASSERT (quic_ctx_is_listener (lctx));
1251   vnet_unlisten_args_t a = {
1252     .handle = lctx->udp_session_handle,
1253     .app_index = quic_main.app_index,
1254     .wrk_map_index = 0          /* default wrk */
1255   };
1256   if (vnet_unlisten (&a))
1257     clib_warning ("unlisten errored");
1258
1259   /*  TODO: crypto state cleanup */
1260
1261   quic_ctx_free (lctx);
1262   return 0;
1263 }
1264
1265 static transport_connection_t *
1266 quic_connection_get (u32 ctx_index, u32 thread_index)
1267 {
1268   quic_ctx_t *ctx;
1269   ctx = quic_ctx_get (ctx_index, thread_index);
1270   return &ctx->connection;
1271 }
1272
1273 static transport_connection_t *
1274 quic_listener_get (u32 listener_index)
1275 {
1276   QUIC_DBG (2, "Called quic_listener_get");
1277   quic_ctx_t *ctx;
1278   ctx = quic_ctx_get (listener_index, 0);
1279   return &ctx->connection;
1280 }
1281
1282 static u8 *
1283 format_quic_ctx (u8 * s, va_list * args)
1284 {
1285   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
1286   u32 verbose = va_arg (*args, u32);
1287   u8 *str = 0;
1288
1289   if (!ctx)
1290     return s;
1291   str = format (str, "[#%d][Q] ", ctx->c_thread_index);
1292
1293   if (quic_ctx_is_listener (ctx))
1294     str = format (str, "Listener, UDP %ld", ctx->udp_session_handle);
1295   else if (quic_ctx_is_stream (ctx))
1296     str = format (str, "Stream %ld conn %d",
1297                   ctx->stream->stream_id, ctx->quic_connection_ctx_id);
1298   else                          /* connection */
1299     str = format (str, "Conn %d UDP %d", ctx->c_c_index,
1300                   ctx->udp_session_handle);
1301
1302   str = format (str, " app %d wrk %d", ctx->parent_app_id,
1303                 ctx->parent_app_wrk_id);
1304
1305   if (verbose == 1)
1306     s = format (s, "%-50s%-15d", str, ctx->conn_state);
1307   else
1308     s = format (s, "%s\n", str);
1309   vec_free (str);
1310   return s;
1311 }
1312
1313 static u8 *
1314 format_quic_connection (u8 * s, va_list * args)
1315 {
1316   u32 qc_index = va_arg (*args, u32);
1317   u32 thread_index = va_arg (*args, u32);
1318   u32 verbose = va_arg (*args, u32);
1319   quic_ctx_t *ctx = quic_ctx_get (qc_index, thread_index);
1320   s = format (s, "%U", format_quic_ctx, ctx, verbose);
1321   return s;
1322 }
1323
1324 static u8 *
1325 format_quic_half_open (u8 * s, va_list * args)
1326 {
1327   u32 qc_index = va_arg (*args, u32);
1328   u32 thread_index = va_arg (*args, u32);
1329   quic_ctx_t *ctx = quic_ctx_get (qc_index, thread_index);
1330   s = format (s, "[#%d][Q] half-open app %u", thread_index,
1331               ctx->parent_app_id);
1332   return s;
1333 }
1334
1335 /*  TODO improve */
1336 static u8 *
1337 format_quic_listener (u8 * s, va_list * args)
1338 {
1339   u32 tci = va_arg (*args, u32);
1340   u32 thread_index = va_arg (*args, u32);
1341   u32 verbose = va_arg (*args, u32);
1342   quic_ctx_t *ctx = quic_ctx_get (tci, thread_index);
1343   s = format (s, "%U", format_quic_ctx, ctx, verbose);
1344   return s;
1345 }
1346
1347 /* Session layer callbacks */
1348
1349 static inline void
1350 quic_build_sockaddr (struct sockaddr *sa, socklen_t * salen,
1351                      ip46_address_t * addr, u16 port, u8 is_ip4)
1352 {
1353   if (is_ip4)
1354     {
1355       struct sockaddr_in *sa4 = (struct sockaddr_in *) sa;
1356       sa4->sin_family = AF_INET;
1357       sa4->sin_port = port;
1358       sa4->sin_addr.s_addr = addr->ip4.as_u32;
1359       *salen = sizeof (struct sockaddr_in);
1360     }
1361   else
1362     {
1363       struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) sa;
1364       sa6->sin6_family = AF_INET6;
1365       sa6->sin6_port = port;
1366       clib_memcpy (&sa6->sin6_addr, &addr->ip6, 16);
1367       *salen = sizeof (struct sockaddr_in6);
1368     }
1369 }
1370
1371 static void
1372 quic_on_quic_session_connected (quic_ctx_t * ctx)
1373 {
1374   session_t *quic_session;
1375   app_worker_t *app_wrk;
1376   u32 ctx_id = ctx->c_c_index;
1377   u32 thread_index = ctx->c_thread_index;
1378   int rv;
1379
1380   quic_session = session_alloc (thread_index);
1381
1382   QUIC_DBG (2, "Allocated quic session 0x%lx", session_handle (quic_session));
1383   ctx->c_s_index = quic_session->session_index;
1384   quic_session->app_wrk_index = ctx->parent_app_wrk_id;
1385   quic_session->connection_index = ctx->c_c_index;
1386   quic_session->listener_handle = SESSION_INVALID_HANDLE;
1387   quic_session->session_type =
1388     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, ctx->udp_is_ip4);
1389
1390   /* If quic session connected fails, immediatly close connection */
1391   app_wrk = app_worker_get (ctx->parent_app_wrk_id);
1392   if (app_worker_init_connected (app_wrk, quic_session))
1393     {
1394       QUIC_ERR ("failed to app_worker_init_connected");
1395       quic_proto_on_close (ctx_id, thread_index);
1396       app_worker_connect_notify (app_wrk, NULL, ctx->client_opaque);
1397       return;
1398     }
1399
1400   quic_session->session_state = SESSION_STATE_CONNECTING;
1401   if ((rv = app_worker_connect_notify (app_wrk, quic_session,
1402                                        ctx->client_opaque)))
1403     {
1404       QUIC_ERR ("failed to notify app %d", rv);
1405       quic_proto_on_close (ctx_id, thread_index);
1406       return;
1407     }
1408
1409   /*  If the app opens a stream in its callback it may invalidate ctx */
1410   ctx = quic_ctx_get (ctx_id, thread_index);
1411   /*
1412    * app_worker_connect_notify() might have reallocated pool, reload
1413    * quic_session pointer
1414    */
1415   quic_session = session_get (ctx->c_s_index, thread_index);
1416   quic_session->session_state = SESSION_STATE_LISTENING;
1417 }
1418
1419 static void
1420 quic_check_quic_session_connected (quic_ctx_t * ctx)
1421 {
1422   /* Called when we need to trigger quic session connected
1423    * we may call this function on the server side / at
1424    * stream opening */
1425
1426   /* Conn may be set to null if the connection is terminated */
1427   if (!ctx->conn || ctx->conn_state != QUIC_CONN_STATE_HANDSHAKE)
1428     return;
1429   if (!quicly_connection_is_ready (ctx->conn))
1430     return;
1431   ctx->conn_state = QUIC_CONN_STATE_READY;
1432   if (!quicly_is_client (ctx->conn))
1433     return;
1434   quic_on_quic_session_connected (ctx);
1435 }
1436
1437 static void
1438 quic_receive_connection (void *arg)
1439 {
1440   u32 new_ctx_id, thread_index = vlib_get_thread_index ();
1441   quic_ctx_t *temp_ctx, *new_ctx;
1442   clib_bihash_kv_16_8_t kv;
1443   quicly_conn_t *conn;
1444   session_t *udp_session;
1445
1446   temp_ctx = arg;
1447   new_ctx_id = quic_ctx_alloc (thread_index);
1448   new_ctx = quic_ctx_get (new_ctx_id, thread_index);
1449
1450   QUIC_DBG (2, "Received conn %u (now %u)", temp_ctx->c_thread_index,
1451             new_ctx_id);
1452
1453   clib_memcpy (new_ctx, temp_ctx, sizeof (quic_ctx_t));
1454   clib_mem_free (temp_ctx);
1455
1456   new_ctx->c_thread_index = thread_index;
1457   new_ctx->c_c_index = new_ctx_id;
1458
1459   conn = new_ctx->conn;
1460   quic_store_conn_ctx (conn, new_ctx);
1461   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1462   kv.value = ((u64) thread_index) << 32 | (u64) new_ctx_id;
1463   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1464   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1465   new_ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1466   quic_update_timer (new_ctx);
1467
1468   /*  Trigger write on this connection if necessary */
1469   udp_session = session_get_from_handle (new_ctx->udp_session_handle);
1470   udp_session->opaque = new_ctx_id;
1471   udp_session->flags &= ~SESSION_F_IS_MIGRATING;
1472   if (svm_fifo_max_dequeue (udp_session->tx_fifo))
1473     quic_set_udp_tx_evt (udp_session);
1474 }
1475
1476 static void
1477 quic_transfer_connection (u32 ctx_index, u32 dest_thread)
1478 {
1479   quic_ctx_t *ctx, *temp_ctx;
1480   u32 thread_index = vlib_get_thread_index ();
1481
1482   QUIC_DBG (2, "Transferring conn %u to thread %u", ctx_index, dest_thread);
1483
1484   temp_ctx = clib_mem_alloc (sizeof (quic_ctx_t));
1485   QUIC_ASSERT (temp_ctx != NULL);
1486   ctx = quic_ctx_get (ctx_index, thread_index);
1487
1488   clib_memcpy (temp_ctx, ctx, sizeof (quic_ctx_t));
1489
1490   quic_stop_ctx_timer (ctx);
1491   quic_ctx_free (ctx);
1492
1493   /*  Send connection to destination thread */
1494   session_send_rpc_evt_to_thread (dest_thread, quic_receive_connection,
1495                                   (void *) temp_ctx);
1496 }
1497
1498 static int
1499 quic_udp_session_connected_callback (u32 quic_app_index, u32 ctx_index,
1500                                      session_t * udp_session, u8 is_fail)
1501 {
1502   QUIC_DBG (2, "QSession is now connected (id %u)",
1503             udp_session->session_index);
1504   /* This should always be called before quic_connect returns since UDP always
1505    * connects instantly. */
1506   clib_bihash_kv_16_8_t kv;
1507   struct sockaddr_in6 sa6;
1508   struct sockaddr *sa = (struct sockaddr *) &sa6;
1509   socklen_t salen;
1510   transport_connection_t *tc;
1511   app_worker_t *app_wrk;
1512   quicly_conn_t *conn;
1513   quic_ctx_t *ctx;
1514   u32 thread_index = vlib_get_thread_index ();
1515   int ret;
1516   quicly_context_t *quicly_ctx;
1517
1518
1519   ctx = quic_ctx_get (ctx_index, thread_index);
1520   if (is_fail)
1521     {
1522       u32 api_context;
1523       app_wrk = app_worker_get_if_valid (ctx->parent_app_wrk_id);
1524       if (app_wrk)
1525         {
1526           api_context = ctx->c_s_index;
1527           app_worker_connect_notify (app_wrk, 0, api_context);
1528         }
1529       return 0;
1530     }
1531
1532   ctx->c_thread_index = thread_index;
1533   ctx->c_c_index = ctx_index;
1534
1535   QUIC_DBG (2, "Quic connect returned %u. New ctx [%u]%x",
1536             is_fail, thread_index, (ctx) ? ctx_index : ~0);
1537
1538   ctx->udp_session_handle = session_handle (udp_session);
1539   udp_session->opaque = ctx_index;
1540
1541   /* Init QUIC lib connection
1542    * Generate required sockaddr & salen */
1543   tc = session_get_transport (udp_session);
1544   quic_build_sockaddr (sa, &salen, &tc->rmt_ip, tc->rmt_port, tc->is_ip4);
1545
1546   quicly_ctx = quic_get_quicly_ctx_from_ctx (ctx);
1547   ret = quicly_connect (&ctx->conn, quicly_ctx, (char *) ctx->srv_hostname,
1548                         sa, NULL, &quic_main.next_cid, ptls_iovec_init (NULL,
1549                                                                         0),
1550                         &quic_main.hs_properties, NULL);
1551   ++quic_main.next_cid.master_id;
1552   /*  Save context handle in quicly connection */
1553   quic_store_conn_ctx (ctx->conn, ctx);
1554   assert (ret == 0);
1555
1556   /*  Register connection in connections map */
1557   conn = ctx->conn;
1558   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1559   kv.value = ((u64) thread_index) << 32 | (u64) ctx_index;
1560   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1561   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1562
1563   /*  UDP stack quirk? preemptively transfer connection if that happens */
1564   if (udp_session->thread_index != thread_index)
1565     quic_transfer_connection (ctx_index, udp_session->thread_index);
1566   else
1567     quic_send_packets (ctx);
1568
1569   return ret;
1570 }
1571
1572 static void
1573 quic_udp_session_disconnect_callback (session_t * s)
1574 {
1575   clib_warning ("UDP session disconnected???");
1576 }
1577
1578 static void
1579 quic_udp_session_cleanup_callback (session_t * udp_session,
1580                                    session_cleanup_ntf_t ntf)
1581 {
1582   quic_ctx_t *ctx;
1583
1584   if (ntf != SESSION_CLEANUP_SESSION)
1585     return;
1586
1587   ctx = quic_ctx_get (udp_session->opaque, udp_session->thread_index);
1588   quic_stop_ctx_timer (ctx);
1589   quic_ctx_free (ctx);
1590 }
1591
1592 static void
1593 quic_udp_session_reset_callback (session_t * s)
1594 {
1595   clib_warning ("UDP session reset???");
1596 }
1597
1598 static void
1599 quic_udp_session_migrate_callback (session_t * s, session_handle_t new_sh)
1600 {
1601   u32 new_thread = session_thread_from_handle (new_sh);
1602   quic_ctx_t *ctx;
1603
1604   QUIC_ERR ("Session %x migrated to %lx", s->session_index, new_sh);
1605   QUIC_ASSERT (vlib_get_thread_index () == s->thread_index);
1606   ctx = quic_ctx_get (s->opaque, s->thread_index);
1607   QUIC_ASSERT (ctx->udp_session_handle == session_handle (s));
1608
1609   ctx->udp_session_handle = new_sh;
1610 #if QUIC_DEBUG >= 1
1611   s->opaque = 0xfeedface;
1612 #endif
1613   quic_transfer_connection (ctx->c_c_index, new_thread);
1614 }
1615
1616 int
1617 quic_udp_session_accepted_callback (session_t * udp_session)
1618 {
1619   /* New UDP connection, try to accept it */
1620   u32 ctx_index;
1621   quic_ctx_t *ctx, *lctx;
1622   session_t *udp_listen_session;
1623   u32 thread_index = vlib_get_thread_index ();
1624
1625   udp_listen_session =
1626     listen_session_get_from_handle (udp_session->listener_handle);
1627
1628   ctx_index = quic_ctx_alloc (thread_index);
1629   ctx = quic_ctx_get (ctx_index, thread_index);
1630   ctx->c_thread_index = udp_session->thread_index;
1631   ctx->c_c_index = ctx_index;
1632   ctx->c_s_index = QUIC_SESSION_INVALID;
1633   ctx->udp_session_handle = session_handle (udp_session);
1634   QUIC_DBG (2, "ACCEPTED UDP 0x%lx", ctx->udp_session_handle);
1635   ctx->listener_ctx_id = udp_listen_session->opaque;
1636   lctx = quic_ctx_get (udp_listen_session->opaque,
1637                        udp_listen_session->thread_index);
1638   ctx->udp_is_ip4 = lctx->c_is_ip4;
1639   ctx->parent_app_id = lctx->parent_app_id;
1640   ctx->parent_app_wrk_id = lctx->parent_app_wrk_id;
1641   ctx->timer_handle = QUIC_TIMER_HANDLE_INVALID;
1642   ctx->conn_state = QUIC_CONN_STATE_OPENED;
1643   ctx->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1644
1645   /* Also store it in ctx for convenience
1646    * Waiting for crypto_ctx logic */
1647   ctx->quicly_ctx = lctx->quicly_ctx;
1648
1649   udp_session->opaque = ctx_index;
1650
1651   /* TODO timeout to delete these if they never connect */
1652   return 0;
1653 }
1654
1655 static int
1656 quic_add_segment_callback (u32 client_index, u64 seg_handle)
1657 {
1658   /* No-op for builtin */
1659   return 0;
1660 }
1661
1662 static int
1663 quic_del_segment_callback (u32 client_index, u64 seg_handle)
1664 {
1665   /* No-op for builtin */
1666   return 0;
1667 }
1668
1669 static int
1670 quic_custom_app_rx_callback (transport_connection_t * tc)
1671 {
1672   quic_ctx_t *ctx;
1673   session_t *stream_session = session_get (tc->s_index, tc->thread_index);
1674   QUIC_DBG (3, "Received app READ notification");
1675   quic_ack_rx_data (stream_session);
1676   svm_fifo_reset_has_deq_ntf (stream_session->rx_fifo);
1677
1678   /* Need to send packets (acks may never be sent otherwise) */
1679   ctx = quic_ctx_get (stream_session->connection_index,
1680                       stream_session->thread_index);
1681   quic_send_packets (ctx);
1682   return 0;
1683 }
1684
1685 static int
1686 quic_custom_tx_callback (void *s, u32 max_burst_size)
1687 {
1688   session_t *stream_session = (session_t *) s;
1689   quic_stream_data_t *stream_data;
1690   quicly_stream_t *stream;
1691   quic_ctx_t *ctx;
1692   u32 max_deq;
1693   int rv;
1694
1695   if (PREDICT_FALSE
1696       (stream_session->session_state >= SESSION_STATE_TRANSPORT_CLOSING))
1697     return 0;
1698   ctx = quic_ctx_get (stream_session->connection_index,
1699                       stream_session->thread_index);
1700   if (PREDICT_FALSE (!quic_ctx_is_stream (ctx)))
1701     {
1702       goto tx_end;              /* Most probably a reschedule */
1703     }
1704
1705   QUIC_DBG (3, "Stream TX event");
1706   quic_ack_rx_data (stream_session);
1707   stream = ctx->stream;
1708   if (!quicly_sendstate_is_open (&stream->sendstate))
1709     {
1710       QUIC_ERR ("Warning: tried to send on closed stream");
1711       return -1;
1712     }
1713
1714   stream_data = (quic_stream_data_t *) stream->data;
1715   max_deq = svm_fifo_max_dequeue (stream_session->tx_fifo);
1716   QUIC_ASSERT (max_deq >= stream_data->app_tx_data_len);
1717   if (max_deq == stream_data->app_tx_data_len)
1718     {
1719       QUIC_DBG (3, "TX but no data %d / %d", max_deq,
1720                 stream_data->app_tx_data_len);
1721       return 0;
1722     }
1723   stream_data->app_tx_data_len = max_deq;
1724   rv = quicly_stream_sync_sendbuf (stream, 1);
1725   QUIC_ASSERT (!rv);
1726
1727 tx_end:
1728   quic_send_packets (ctx);
1729   return 0;
1730 }
1731
1732 /*
1733  * Returns 0 if a matching connection is found and is on the right thread.
1734  * Otherwise returns -1.
1735  * If a connection is found, even on the wrong thread, ctx_thread and ctx_index
1736  * will be set.
1737  */
1738 static inline int
1739 quic_find_packet_ctx (quic_rx_packet_ctx_t * pctx, u32 caller_thread_index)
1740 {
1741   clib_bihash_kv_16_8_t kv;
1742   clib_bihash_16_8_t *h;
1743   quic_ctx_t *ctx;
1744   u32 index, thread_id;
1745
1746   h = &quic_main.connection_hash;
1747   quic_make_connection_key (&kv, &pctx->packet.cid.dest.plaintext);
1748   QUIC_DBG (3, "Searching conn with id %lu %lu", kv.key[0], kv.key[1]);
1749
1750   if (clib_bihash_search_16_8 (h, &kv, &kv))
1751     {
1752       QUIC_DBG (3, "connection not found");
1753       return QUIC_PACKET_TYPE_NONE;
1754     }
1755
1756   index = kv.value & UINT32_MAX;
1757   thread_id = kv.value >> 32;
1758   /* Check if this connection belongs to this thread, otherwise
1759    * ask for it to be moved */
1760   if (thread_id != caller_thread_index)
1761     {
1762       QUIC_DBG (2, "Connection is on wrong thread");
1763       /* Cannot make full check with quicly_is_destination... */
1764       pctx->ctx_index = index;
1765       pctx->thread_index = thread_id;
1766       return QUIC_PACKET_TYPE_MIGRATE;
1767     }
1768   ctx = quic_ctx_get (index, vlib_get_thread_index ());
1769   if (!ctx->conn)
1770     {
1771       QUIC_ERR ("ctx has no conn");
1772       return QUIC_PACKET_TYPE_NONE;
1773     }
1774   if (!quicly_is_destination (ctx->conn, NULL, &pctx->sa, &pctx->packet))
1775     return QUIC_PACKET_TYPE_NONE;
1776
1777   QUIC_DBG (3, "Connection found");
1778   pctx->ctx_index = index;
1779   pctx->thread_index = thread_id;
1780   return QUIC_PACKET_TYPE_RECEIVE;
1781 }
1782
1783 static int
1784 quic_accept_connection (u32 ctx_index, quic_rx_packet_ctx_t * pctx)
1785 {
1786   u32 thread_index = vlib_get_thread_index ();
1787   quicly_context_t *quicly_ctx;
1788   session_t *quic_session;
1789   clib_bihash_kv_16_8_t kv;
1790   app_worker_t *app_wrk;
1791   quicly_conn_t *conn;
1792   quic_ctx_t *ctx;
1793   quic_ctx_t *lctx;
1794   int rv;
1795
1796   /* new connection, accept and create context if packet is valid
1797    * TODO: check if socket is actually listening? */
1798   ctx = quic_ctx_get (ctx_index, thread_index);
1799   if (ctx->c_s_index != QUIC_SESSION_INVALID)
1800     {
1801       QUIC_DBG (2, "already accepted ctx 0x%x", ctx_index);
1802       return 0;
1803     }
1804
1805   quicly_ctx = quic_get_quicly_ctx_from_ctx (ctx);
1806   if ((rv = quicly_accept (&conn, quicly_ctx, NULL, &pctx->sa,
1807                            &pctx->packet, NULL, &quic_main.next_cid, NULL)))
1808     {
1809       /* Invalid packet, pass */
1810       assert (conn == NULL);
1811       QUIC_ERR ("Accept failed with %U", quic_format_err, rv);
1812       /* TODO: cleanup created quic ctx and UDP session */
1813       return 0;
1814     }
1815   assert (conn != NULL);
1816
1817   ++quic_main.next_cid.master_id;
1818   /* Save ctx handle in quicly connection */
1819   quic_store_conn_ctx (conn, ctx);
1820   ctx->conn = conn;
1821
1822   quic_session = session_alloc (ctx->c_thread_index);
1823   QUIC_DBG (2, "Allocated quic_session, 0x%lx ctx %u",
1824             session_handle (quic_session), ctx->c_c_index);
1825   quic_session->session_state = SESSION_STATE_LISTENING;
1826   ctx->c_s_index = quic_session->session_index;
1827
1828   lctx = quic_ctx_get (ctx->listener_ctx_id, 0);
1829
1830   quic_session->app_wrk_index = lctx->parent_app_wrk_id;
1831   quic_session->connection_index = ctx->c_c_index;
1832   quic_session->session_type =
1833     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC, ctx->udp_is_ip4);
1834   quic_session->listener_handle = lctx->c_s_index;
1835
1836   /* Register connection in connections map */
1837   quic_make_connection_key (&kv, quicly_get_master_id (conn));
1838   kv.value = ((u64) thread_index) << 32 | (u64) ctx_index;
1839   clib_bihash_add_del_16_8 (&quic_main.connection_hash, &kv, 1 /* is_add */ );
1840   QUIC_DBG (2, "Registering conn with id %lu %lu", kv.key[0], kv.key[1]);
1841
1842   /* If notify fails, reset connection immediatly */
1843   if ((rv = app_worker_init_accepted (quic_session)))
1844     {
1845       QUIC_ERR ("failed to allocate fifos");
1846       quic_proto_on_close (ctx_index, thread_index);
1847       return rv;
1848     }
1849
1850   app_wrk = app_worker_get (quic_session->app_wrk_index);
1851   if ((rv = app_worker_accept_notify (app_wrk, quic_session)))
1852     {
1853       QUIC_ERR ("failed to notify accept worker app");
1854       quic_proto_on_close (ctx_index, thread_index);
1855       return rv;
1856     }
1857   ctx->conn_state = QUIC_CONN_STATE_HANDSHAKE;
1858
1859   return quic_send_packets (ctx);
1860 }
1861
1862 static int
1863 quic_reset_connection (u64 udp_session_handle, quic_rx_packet_ctx_t * pctx)
1864 {
1865   /* short header packet; potentially a dead connection. No need to check the
1866    * length of the incoming packet, because loop is prevented by authenticating
1867    * the CID (by checking node_id and thread_id). If the peer is also sending a
1868    * reset, then the next CID is highly likely to contain a non-authenticating
1869    * CID, ... */
1870   QUIC_DBG (2, "Sending stateless reset");
1871   int rv;
1872   quicly_datagram_t *dgram;
1873   session_t *udp_session;
1874   quicly_context_t *quicly_ctx;
1875   if (pctx->packet.cid.dest.plaintext.node_id != 0
1876       || pctx->packet.cid.dest.plaintext.thread_id != 0)
1877     return 0;
1878   quicly_ctx = quic_get_quicly_ctx_from_udp (udp_session_handle);
1879   dgram = quicly_send_stateless_reset (quicly_ctx, &pctx->sa, NULL,
1880                                        &pctx->packet.cid.dest.plaintext);
1881   if (dgram == NULL)
1882     return 1;
1883   udp_session = session_get_from_handle (udp_session_handle);
1884   rv = quic_send_datagram (udp_session, dgram);
1885   quic_set_udp_tx_evt (udp_session);
1886   return rv;
1887 }
1888
1889 static int
1890 quic_process_one_rx_packet (u64 udp_session_handle, svm_fifo_t * f,
1891                             u32 fifo_offset, quic_rx_packet_ctx_t * pctx)
1892 {
1893   size_t plen;
1894   u32 full_len, ret;
1895   u32 thread_index = vlib_get_thread_index ();
1896   u32 cur_deq = svm_fifo_max_dequeue (f) - fifo_offset;
1897   quicly_context_t *quicly_ctx;
1898   int rv;
1899
1900   ret = svm_fifo_peek (f, fifo_offset,
1901                        SESSION_CONN_HDR_LEN, (u8 *) & pctx->ph);
1902   QUIC_ASSERT (ret == SESSION_CONN_HDR_LEN);
1903   QUIC_ASSERT (pctx->ph.data_offset == 0);
1904   full_len = pctx->ph.data_length + SESSION_CONN_HDR_LEN;
1905   if (full_len > cur_deq)
1906     {
1907       QUIC_ERR ("Not enough data in fifo RX");
1908       return 1;
1909     }
1910
1911   /* Quicly can read len bytes from the fifo at offset:
1912    * ph.data_offset + SESSION_CONN_HDR_LEN */
1913   ret = svm_fifo_peek (f, SESSION_CONN_HDR_LEN + fifo_offset,
1914                        pctx->ph.data_length, pctx->data);
1915   if (ret != pctx->ph.data_length)
1916     {
1917       QUIC_ERR ("Not enough data peeked in RX");
1918       return 1;
1919     }
1920
1921   quic_increment_counter (QUIC_ERROR_RX_PACKETS, 1);
1922   quic_build_sockaddr (&pctx->sa, &pctx->salen, &pctx->ph.rmt_ip,
1923                        pctx->ph.rmt_port, pctx->ph.is_ip4);
1924   quicly_ctx = quic_get_quicly_ctx_from_udp (udp_session_handle);
1925   plen = quicly_decode_packet (quicly_ctx, &pctx->packet,
1926                                pctx->data, pctx->ph.data_length);
1927
1928   if (plen == SIZE_MAX)
1929     {
1930       return 1;
1931     }
1932
1933   rv = quic_find_packet_ctx (pctx, thread_index);
1934   if (rv == QUIC_PACKET_TYPE_RECEIVE)
1935     {
1936       pctx->ptype = QUIC_PACKET_TYPE_RECEIVE;
1937       return 0;
1938     }
1939   else if (rv == QUIC_PACKET_TYPE_MIGRATE)
1940     {
1941       pctx->ptype = QUIC_PACKET_TYPE_MIGRATE;
1942       /*  Connection found but on wrong thread, ask move */
1943     }
1944   else if (QUICLY_PACKET_IS_LONG_HEADER (pctx->packet.octets.base[0]))
1945     {
1946       pctx->ptype = QUIC_PACKET_TYPE_ACCEPT;
1947     }
1948   else
1949     {
1950       pctx->ptype = QUIC_PACKET_TYPE_RESET;
1951     }
1952   return 1;
1953 }
1954
1955 static int
1956 quic_udp_session_rx_callback (session_t * udp_session)
1957 {
1958   /*  Read data from UDP rx_fifo and pass it to the quicly conn. */
1959   quic_ctx_t *ctx = NULL;
1960   svm_fifo_t *f = udp_session->rx_fifo;
1961   u32 max_deq;
1962   u64 udp_session_handle = session_handle (udp_session);
1963   int rv = 0;
1964   u32 thread_index = vlib_get_thread_index ();
1965   u32 cur_deq, fifo_offset, max_packets, i;
1966
1967   quic_rx_packet_ctx_t packets_ctx[QUIC_RCV_MAX_BATCH_PACKETS];
1968
1969   if (udp_session->flags & SESSION_F_IS_MIGRATING)
1970     {
1971       QUIC_DBG (3, "RX on migrating udp session");
1972       return 0;
1973     }
1974
1975 rx_start:
1976   max_deq = svm_fifo_max_dequeue (f);
1977   if (max_deq == 0)
1978     return 0;
1979
1980   fifo_offset = 0;
1981   max_packets = QUIC_RCV_MAX_BATCH_PACKETS;
1982
1983   for (i = 0; i < max_packets; i++)
1984     {
1985       packets_ctx[i].thread_index = UINT32_MAX;
1986       packets_ctx[i].ctx_index = UINT32_MAX;
1987       packets_ctx[i].ptype = QUIC_PACKET_TYPE_DROP;
1988
1989       cur_deq = max_deq - fifo_offset;
1990       if (cur_deq == 0)
1991         {
1992           max_packets = i + 1;
1993           break;
1994         }
1995       if (cur_deq < SESSION_CONN_HDR_LEN)
1996         {
1997           fifo_offset = max_deq;
1998           max_packets = i + 1;
1999           QUIC_ERR ("Fifo %d < header size in RX", cur_deq);
2000           break;
2001         }
2002       rv = quic_process_one_rx_packet (udp_session_handle, f,
2003                                        fifo_offset, &packets_ctx[i]);
2004       if (packets_ctx[i].ptype != QUIC_PACKET_TYPE_MIGRATE)
2005         fifo_offset += SESSION_CONN_HDR_LEN + packets_ctx[i].ph.data_length;
2006       if (rv)
2007         {
2008           max_packets = i + 1;
2009           break;
2010         }
2011     }
2012
2013   for (i = 0; i < max_packets; i++)
2014     {
2015       switch (packets_ctx[i].ptype)
2016         {
2017         case QUIC_PACKET_TYPE_RECEIVE:
2018           ctx = quic_ctx_get (packets_ctx[i].ctx_index, thread_index);
2019           rv = quicly_receive (ctx->conn, NULL, &packets_ctx[i].sa,
2020                                &packets_ctx[i].packet);
2021           if (rv && rv != QUICLY_ERROR_PACKET_IGNORED)
2022             {
2023               QUIC_ERR ("quicly_receive return error %U",
2024                         quic_format_err, rv);
2025             }
2026           break;
2027         case QUIC_PACKET_TYPE_ACCEPT:
2028           udp_session = session_get_from_handle (udp_session_handle);
2029           if ((rv = quic_accept_connection (udp_session->opaque,
2030                                             &packets_ctx[i])))
2031             {
2032               QUIC_ERR ("quic accept errored with %d", rv);
2033             }
2034           break;
2035         case QUIC_PACKET_TYPE_RESET:
2036           quic_reset_connection (udp_session_handle, &packets_ctx[i]);
2037           break;
2038         }
2039     }
2040   for (i = 0; i < max_packets; i++)
2041     {
2042       if (packets_ctx[i].ptype != QUIC_PACKET_TYPE_RECEIVE)
2043         continue;
2044       ctx = quic_ctx_get (packets_ctx[i].ctx_index,
2045                           packets_ctx[i].thread_index);
2046       quic_check_quic_session_connected (ctx);
2047       ctx = quic_ctx_get (packets_ctx[i].ctx_index,
2048                           packets_ctx[i].thread_index);
2049       quic_send_packets (ctx);
2050     }
2051
2052   udp_session = session_get_from_handle (udp_session_handle);   /*  session alloc might have happened */
2053   f = udp_session->rx_fifo;
2054   svm_fifo_dequeue_drop (f, fifo_offset);
2055
2056   if (svm_fifo_max_dequeue (f))
2057     goto rx_start;
2058
2059   return 0;
2060 }
2061
2062 always_inline void
2063 quic_common_get_transport_endpoint (quic_ctx_t * ctx,
2064                                     transport_endpoint_t * tep, u8 is_lcl)
2065 {
2066   session_t *udp_session;
2067   if (!quic_ctx_is_stream (ctx))
2068     {
2069       udp_session = session_get_from_handle (ctx->udp_session_handle);
2070       session_get_endpoint (udp_session, tep, is_lcl);
2071     }
2072 }
2073
2074 static void
2075 quic_get_transport_listener_endpoint (u32 listener_index,
2076                                       transport_endpoint_t * tep, u8 is_lcl)
2077 {
2078   quic_ctx_t *ctx;
2079   app_listener_t *app_listener;
2080   session_t *udp_listen_session;
2081   ctx = quic_ctx_get (listener_index, vlib_get_thread_index ());
2082   if (quic_ctx_is_listener (ctx))
2083     {
2084       app_listener = app_listener_get_w_handle (ctx->udp_session_handle);
2085       udp_listen_session = app_listener_get_session (app_listener);
2086       return session_get_endpoint (udp_listen_session, tep, is_lcl);
2087     }
2088   quic_common_get_transport_endpoint (ctx, tep, is_lcl);
2089 }
2090
2091 static void
2092 quic_get_transport_endpoint (u32 ctx_index, u32 thread_index,
2093                              transport_endpoint_t * tep, u8 is_lcl)
2094 {
2095   quic_ctx_t *ctx;
2096   ctx = quic_ctx_get (ctx_index, thread_index);
2097   quic_common_get_transport_endpoint (ctx, tep, is_lcl);
2098 }
2099
2100 /* *INDENT-OFF* */
2101 static session_cb_vft_t quic_app_cb_vft = {
2102   .session_accept_callback = quic_udp_session_accepted_callback,
2103   .session_disconnect_callback = quic_udp_session_disconnect_callback,
2104   .session_connected_callback = quic_udp_session_connected_callback,
2105   .session_reset_callback = quic_udp_session_reset_callback,
2106   .session_migrate_callback = quic_udp_session_migrate_callback,
2107   .add_segment_callback = quic_add_segment_callback,
2108   .del_segment_callback = quic_del_segment_callback,
2109   .builtin_app_rx_callback = quic_udp_session_rx_callback,
2110   .session_cleanup_callback = quic_udp_session_cleanup_callback,
2111 };
2112
2113 static const transport_proto_vft_t quic_proto = {
2114   .connect = quic_connect,
2115   .close = quic_proto_on_close,
2116   .start_listen = quic_start_listen,
2117   .stop_listen = quic_stop_listen,
2118   .get_connection = quic_connection_get,
2119   .get_listener = quic_listener_get,
2120   .update_time = quic_update_time,
2121   .app_rx_evt = quic_custom_app_rx_callback,
2122   .custom_tx = quic_custom_tx_callback,
2123   .format_connection = format_quic_connection,
2124   .format_half_open = format_quic_half_open,
2125   .format_listener = format_quic_listener,
2126   .get_transport_endpoint = quic_get_transport_endpoint,
2127   .get_transport_listener_endpoint = quic_get_transport_listener_endpoint,
2128   .transport_options = {
2129     .tx_type = TRANSPORT_TX_INTERNAL,
2130     .service_type = TRANSPORT_SERVICE_APP,
2131   },
2132 };
2133 /* *INDENT-ON* */
2134
2135 static quicly_stream_open_t on_stream_open = { quic_on_stream_open };
2136 static quicly_closed_by_peer_t on_closed_by_peer = { quic_on_closed_by_peer };
2137 static quicly_now_t quicly_vpp_now_cb = { quic_get_time };
2138
2139 static void
2140 quic_register_cipher_suite (crypto_engine_type_t type,
2141                             ptls_cipher_suite_t ** ciphers)
2142 {
2143   quic_main_t *qm = &quic_main;
2144   vec_validate (qm->quic_ciphers, type);
2145   clib_bitmap_set (qm->available_crypto_engines, type, 1);
2146   qm->quic_ciphers[type] = ciphers;
2147 }
2148
2149 static void
2150 quic_update_fifo_size ()
2151 {
2152   quic_main_t *qm = &quic_main;
2153   segment_manager_props_t *seg_mgr_props =
2154     application_get_segment_manager_properties (qm->app_index);
2155
2156   if (!seg_mgr_props)
2157     {
2158       clib_warning
2159         ("error while getting segment_manager_props_t, can't update fifo-size");
2160       return;
2161     }
2162
2163   seg_mgr_props->tx_fifo_size = qm->udp_fifo_size;
2164   seg_mgr_props->rx_fifo_size = qm->udp_fifo_size;
2165 }
2166
2167 static clib_error_t *
2168 quic_init (vlib_main_t * vm)
2169 {
2170   u32 segment_size = 256 << 20;
2171   vlib_thread_main_t *vtm = vlib_get_thread_main ();
2172   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
2173   vnet_app_attach_args_t _a, *a = &_a;
2174   u64 options[APP_OPTIONS_N_OPTIONS];
2175   quic_main_t *qm = &quic_main;
2176   u32 num_threads, i;
2177
2178   num_threads = 1 /* main thread */  + vtm->n_threads;
2179
2180   clib_memset (a, 0, sizeof (*a));
2181   clib_memset (options, 0, sizeof (options));
2182
2183   a->session_cb_vft = &quic_app_cb_vft;
2184   a->api_client_index = APP_INVALID_INDEX;
2185   a->options = options;
2186   a->name = format (0, "quic");
2187   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
2188   a->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = segment_size;
2189   a->options[APP_OPTIONS_RX_FIFO_SIZE] = qm->udp_fifo_size;
2190   a->options[APP_OPTIONS_TX_FIFO_SIZE] = qm->udp_fifo_size;
2191   a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = qm->udp_fifo_prealloc;
2192   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
2193   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
2194   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
2195
2196   if (vnet_application_attach (a))
2197     {
2198       clib_warning ("failed to attach quic app");
2199       return clib_error_return (0, "failed to attach quic app");
2200     }
2201
2202   vec_validate (qm->ctx_pool, num_threads - 1);
2203   vec_validate (qm->wrk_ctx, num_threads - 1);
2204   /*  Timer wheels, one per thread. */
2205   for (i = 0; i < num_threads; i++)
2206     {
2207       tw = &qm->wrk_ctx[i].timer_wheel;
2208       tw_timer_wheel_init_1t_3w_1024sl_ov (tw, quic_expired_timers_dispatch,
2209                                            1e-3 /* timer period 1ms */ , ~0);
2210       tw->last_run_time = vlib_time_now (vlib_get_main ());
2211     }
2212
2213   clib_bihash_init_16_8 (&qm->connection_hash, "quic connections", 1024,
2214                          4 << 20);
2215
2216
2217   qm->app_index = a->app_index;
2218   qm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
2219     / QUIC_TSTAMP_RESOLUTION;
2220   qm->session_cache.super.cb = quic_encrypt_ticket_cb;
2221
2222   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
2223                                FIB_PROTOCOL_IP4, ~0);
2224   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
2225                                FIB_PROTOCOL_IP6, ~0);
2226
2227   clib_bitmap_alloc (qm->available_crypto_engines,
2228                      app_crypto_engine_n_types ());
2229   quic_register_cipher_suite (CRYPTO_ENGINE_VPP, quic_crypto_cipher_suites);
2230   quic_register_cipher_suite (CRYPTO_ENGINE_PICOTLS,
2231                               ptls_openssl_cipher_suites);
2232   qm->default_crypto_engine = CRYPTO_ENGINE_PICOTLS;
2233   vec_free (a->name);
2234   return 0;
2235 }
2236
2237 VLIB_INIT_FUNCTION (quic_init);
2238
2239 static clib_error_t *
2240 quic_plugin_crypto_command_fn (vlib_main_t * vm,
2241                                unformat_input_t * input,
2242                                vlib_cli_command_t * cmd)
2243 {
2244   quic_main_t *qm = &quic_main;
2245   if (unformat_check_input (input) == UNFORMAT_END_OF_INPUT)
2246     return clib_error_return (0, "unknown input '%U'",
2247                               format_unformat_error, input);
2248   if (unformat (input, "vpp"))
2249     qm->default_crypto_engine = CRYPTO_ENGINE_VPP;
2250   else if (unformat (input, "picotls"))
2251     qm->default_crypto_engine = CRYPTO_ENGINE_PICOTLS;
2252   else
2253     return clib_error_return (0, "unknown input '%U'",
2254                               format_unformat_error, input);
2255   return 0;
2256 }
2257
2258 u64 quic_fifosize = 0;
2259 static clib_error_t *
2260 quic_plugin_set_fifo_size_command_fn (vlib_main_t * vm,
2261                                       unformat_input_t * input,
2262                                       vlib_cli_command_t * cmd)
2263 {
2264   quic_main_t *qm = &quic_main;
2265   unformat_input_t _line_input, *line_input = &_line_input;
2266   uword tmp;
2267
2268   if (!unformat_user (input, unformat_line_input, line_input))
2269     return 0;
2270
2271   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
2272     {
2273       if (unformat (line_input, "%U", unformat_memory_size, &tmp))
2274         {
2275           if (tmp >= 0x100000000ULL)
2276             {
2277               return clib_error_return
2278                 (0, "fifo-size %llu (0x%llx) too large", tmp, tmp);
2279             }
2280           qm->udp_fifo_size = tmp;
2281           quic_update_fifo_size ();
2282         }
2283       else
2284         return clib_error_return (0, "unknown input '%U'",
2285                                   format_unformat_error, line_input);
2286     }
2287
2288   return 0;
2289 }
2290
2291 static u8 *
2292 quic_format_ctx_stat (u8 * s, va_list * args)
2293 {
2294   quic_ctx_t *ctx = va_arg (*args, quic_ctx_t *);
2295   quicly_stats_t quicly_stats;
2296
2297   quicly_get_stats (ctx->conn, &quicly_stats);
2298
2299   s = format (s, "\n\rQUIC conn stats \n\r");
2300
2301   s =
2302     format (s, "RTT: min:%d, smoothed:%d, variance:%d, latest:%d \n\r",
2303             quicly_stats.rtt.minimum, quicly_stats.rtt.smoothed,
2304             quicly_stats.rtt.variance, quicly_stats.rtt.latest);
2305   s = format (s, "Packet loss:%d \n\r", quicly_stats.num_packets.lost);
2306
2307   return s;
2308 }
2309
2310 static clib_error_t *
2311 quic_plugin_showstats_command_fn (vlib_main_t * vm,
2312                                   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         if(!(ctx->flags & QUIC_F_IS_LISTENER) && !(ctx->flags & QUIC_F_IS_STREAM))
2325           vlib_cli_output (vm, "%U", quic_format_ctx_stat, ctx);
2326       }));
2327       /* *INDENT-ON* */
2328     }
2329   return 0;
2330 }
2331
2332 static clib_error_t *
2333 quic_show_ctx_command_fn (vlib_main_t * vm, unformat_input_t * input,
2334                           vlib_cli_command_t * cmd)
2335 {
2336   quic_main_t *qm = &quic_main;
2337   quic_ctx_t *ctx = NULL;
2338   u32 num_workers = vlib_num_workers ();
2339
2340   for (int i = 0; i < num_workers + 1; i++)
2341     {
2342       /* *INDENT-OFF* */
2343       pool_foreach (ctx, qm->ctx_pool[i],
2344       ({
2345         vlib_cli_output (vm, "%U", format_quic_ctx, ctx, 1);
2346       }));
2347       /* *INDENT-ON* */
2348     }
2349   return 0;
2350 }
2351
2352 /* *INDENT-OFF* */
2353 VLIB_CLI_COMMAND (quic_plugin_crypto_command, static) =
2354 {
2355   .path = "quic set crypto api",
2356   .short_help = "quic set crypto api [picotls, vpp]",
2357   .function = quic_plugin_crypto_command_fn,
2358 };
2359 VLIB_CLI_COMMAND(quic_plugin_set_fifo_size_command, static)=
2360 {
2361   .path = "quic set fifo-size",
2362   .short_help = "quic set fifo-size N[K|M|G] (default 64K)",
2363   .function = quic_plugin_set_fifo_size_command_fn,
2364 };
2365 VLIB_CLI_COMMAND(quic_plugin_stats_command, static)=
2366 {
2367   .path = "show quic stats",
2368   .short_help = "show quic stats",
2369   .function = quic_plugin_showstats_command_fn,
2370 };
2371 VLIB_CLI_COMMAND(quic_show_ctx_command, static)=
2372 {
2373   .path = "show quic ctx",
2374   .short_help = "show quic ctx",
2375   .function = quic_show_ctx_command_fn,
2376 };
2377 VLIB_PLUGIN_REGISTER () =
2378 {
2379   .version = VPP_BUILD_VER,
2380   .description = "Quic transport protocol",
2381   .default_disabled = 1,
2382 };
2383 /* *INDENT-ON* */
2384
2385 static clib_error_t *
2386 quic_config_fn (vlib_main_t * vm, unformat_input_t * input)
2387 {
2388   quic_main_t *qm = &quic_main;
2389   uword tmp;
2390   u32 i;
2391
2392   qm->udp_fifo_size = QUIC_DEFAULT_FIFO_SIZE;
2393   qm->udp_fifo_prealloc = 0;
2394   qm->connection_timeout = QUIC_DEFAULT_CONN_TIMEOUT;
2395   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
2396     {
2397       if (unformat (input, "fifo-size %U", unformat_memory_size, &tmp))
2398         {
2399           if (tmp >= 0x100000000ULL)
2400             {
2401               return clib_error_return (0,
2402                                         "fifo-size %llu (0x%llx) too large",
2403                                         tmp, tmp);
2404             }
2405           qm->udp_fifo_size = tmp;
2406         }
2407       else if (unformat (input, "conn-timeout %u", &i))
2408         qm->connection_timeout = i;
2409       else if (unformat (input, "fifo-prealloc %u", &i))
2410         qm->udp_fifo_prealloc = i;
2411       else
2412         return clib_error_return (0, "unknown input '%U'",
2413                                   format_unformat_error, input);
2414     }
2415
2416   return 0;
2417 }
2418
2419 VLIB_EARLY_CONFIG_FUNCTION (quic_config_fn, "quic");
2420
2421 static uword
2422 quic_node_fn (vlib_main_t * vm, vlib_node_runtime_t * node,
2423               vlib_frame_t * frame)
2424 {
2425   return 0;
2426 }
2427
2428 /* *INDENT-OFF* */
2429 VLIB_REGISTER_NODE (quic_input_node) =
2430 {
2431   .function = quic_node_fn,
2432   .name = "quic-input",
2433   .vector_size = sizeof (u32),
2434   .type = VLIB_NODE_TYPE_INTERNAL,
2435   .n_errors = ARRAY_LEN (quic_error_strings),
2436   .error_strings = quic_error_strings,
2437 };
2438 /* *INDENT-ON* */
2439
2440 /*
2441  * fd.io coding-style-patch-verification: ON
2442  *
2443  * Local Variables:
2444  * eval: (c-set-style "gnu")
2445  * End:
2446  */