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