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