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