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