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