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