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