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