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