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