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