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