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