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