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