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