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