Integrate first QUIC protocol implementation
[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/streambuf.h>
30 #include <picotls/openssl.h>
31 #include <picotls/pembase64.h>
32
33 static quic_main_t quic_main;
34
35 static void quic_update_timer (quic_ctx_t * ctx);
36 static int64_t quic_get_time (quicly_now_cb * self);
37 static void quic_connection_closed (u32 conn_index);
38 static void quic_disconnect (u32 ctx_index, u32 thread_index);
39
40 #define QUIC_INT_MAX  0x3FFFFFFFFFFFFFFF
41
42 u32
43 quic_ctx_half_open_alloc (void)
44 {
45   quic_main_t *qm = &quic_main;
46   u8 will_expand = 0;
47   quic_ctx_t *ctx;
48   u32 ctx_index;
49
50   pool_get_aligned_will_expand (qm->half_open_ctx_pool, will_expand, 0);
51   if (PREDICT_FALSE (will_expand && vlib_num_workers ()))
52     {
53       clib_rwlock_writer_lock (&qm->half_open_rwlock);
54       pool_get (qm->half_open_ctx_pool, ctx);
55       ctx_index = ctx - qm->half_open_ctx_pool;
56       clib_rwlock_writer_unlock (&qm->half_open_rwlock);
57     }
58   else
59     {
60       /* reader lock assumption: only main thread will call pool_get */
61       clib_rwlock_reader_lock (&qm->half_open_rwlock);
62       pool_get (qm->half_open_ctx_pool, ctx);
63       ctx_index = ctx - qm->half_open_ctx_pool;
64       clib_rwlock_reader_unlock (&qm->half_open_rwlock);
65     }
66   memset (ctx, 0, sizeof (*ctx));
67   return ctx_index;
68 }
69
70 void
71 quic_ctx_half_open_free (u32 ho_index)
72 {
73   quic_main_t *qm = &quic_main;
74   clib_rwlock_writer_lock (&qm->half_open_rwlock);
75   pool_put_index (qm->half_open_ctx_pool, ho_index);
76   clib_rwlock_writer_unlock (&qm->half_open_rwlock);
77 }
78
79 quic_ctx_t *
80 quic_ctx_half_open_get (u32 ctx_index)
81 {
82   quic_main_t *qm = &quic_main;
83   clib_rwlock_reader_lock (&qm->half_open_rwlock);
84   return pool_elt_at_index (qm->half_open_ctx_pool, ctx_index);
85 }
86
87 void
88 quic_ctx_half_open_reader_unlock ()
89 {
90   clib_rwlock_reader_unlock (&quic_main.half_open_rwlock);
91 }
92
93 u32
94 quic_ctx_half_open_index (quic_ctx_t * ctx)
95 {
96   return (ctx - quic_main.half_open_ctx_pool);
97 }
98
99 u32
100 quic_ctx_alloc ()
101 {
102   u8 thread_index = vlib_get_thread_index ();
103   quic_main_t *qm = &quic_main;
104   quic_ctx_t *ctx;
105
106   pool_get (qm->ctx_pool[thread_index], ctx);
107
108   memset (ctx, 0, sizeof (quic_ctx_t));
109   ctx->c_thread_index = thread_index;
110   return ctx - qm->ctx_pool[thread_index];
111 }
112
113 static void
114 quic_ctx_free (quic_ctx_t * ctx)
115 {
116   QUIC_DBG (2, "Free ctx %u", ctx->c_c_index);
117   u32 thread_index = ctx->c_thread_index;
118   if (CLIB_DEBUG)
119     memset (ctx, 0xfb, sizeof (*ctx));
120   pool_put (quic_main.ctx_pool[thread_index], ctx);
121 }
122
123 static quic_ctx_t *
124 quic_ctx_get (u32 ctx_index)
125 {
126   return pool_elt_at_index (quic_main.ctx_pool[vlib_get_thread_index ()],
127                             ctx_index);
128 }
129
130 static quic_ctx_t *
131 quic_ctx_get_w_thread (u32 ctx_index, u8 thread_index)
132 {
133   return pool_elt_at_index (quic_main.ctx_pool[thread_index], ctx_index);
134 }
135
136 static void
137 quic_disconnect_transport (quic_ctx_t * ctx)
138 {
139   QUIC_DBG (2, "Called quic_disconnect_transport");
140   vnet_disconnect_args_t a = {
141     .handle = ctx->c_quic_ctx_id.quic_session,
142     .app_index = quic_main.app_index,
143   };
144
145   if (vnet_disconnect_session (&a))
146     clib_warning ("UDP session disconnect errored");
147 }
148
149 static int
150 quic_send_datagram (session_t * session, quicly_datagram_t * packet)
151 {
152   QUIC_DBG (2, "Called quic_send_datagram at %ld", quic_get_time (NULL));
153   u32 max_enqueue;
154   session_dgram_hdr_t hdr;
155   int rv;
156   u32 len;
157   svm_fifo_t *f;
158   transport_connection_t *tc;
159
160   len = packet->data.len;
161   f = session->tx_fifo;
162   tc = session_get_transport (session);
163
164   max_enqueue = svm_fifo_max_enqueue (f);
165   if (max_enqueue <= sizeof (session_dgram_hdr_t))
166     return 1;
167
168   max_enqueue -= sizeof (session_dgram_hdr_t);
169
170   if (max_enqueue < len)
171     return 1;
172
173   // Build packet header for fifo
174   hdr.data_length = len;
175   hdr.data_offset = 0;
176   hdr.is_ip4 = tc->is_ip4;
177   clib_memcpy (&hdr.lcl_ip, &tc->lcl_ip, sizeof (ip46_address_t));
178   hdr.lcl_port = tc->lcl_port;
179
180   // Read dest address from quicly-provided sockaddr
181   if (hdr.is_ip4)
182     {
183       ASSERT (packet->sa.sa_family == AF_INET);
184       struct sockaddr_in *sa4 = (struct sockaddr_in *) &packet->sa;
185       hdr.rmt_port = sa4->sin_port;
186       hdr.rmt_ip.ip4.as_u32 = sa4->sin_addr.s_addr;
187     }
188   else
189     {
190       ASSERT (packet->sa.sa_family == AF_INET6);
191       struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) &packet->sa;
192       hdr.rmt_port = sa6->sin6_port;
193       clib_memcpy (&hdr.rmt_ip.ip6, &sa6->sin6_addr, 16);
194     }
195
196   rv = svm_fifo_enqueue_nowait (f, sizeof (hdr), (u8 *) & hdr);
197   ASSERT (rv == sizeof (hdr));
198   if (svm_fifo_enqueue_nowait (f, len, packet->data.base) != len)
199     return 1;
200   return 0;
201 }
202
203 static int
204 quic_send_packets (quic_ctx_t * ctx)
205 {
206   //QUIC_DBG (2, "Called quic_send_packets");
207   quicly_datagram_t *packets[16];
208   session_t *quic_session;
209   quicly_conn_t *conn;
210   size_t num_packets, i;
211   int ret;
212
213   quic_session = session_get_from_handle (ctx->c_quic_ctx_id.quic_session);
214   conn = ctx->c_quic_ctx_id.conn;
215
216   if (!conn)
217     return 0;
218
219   do
220     {
221       num_packets = sizeof (packets) / sizeof (packets[0]);
222       if ((ret = quicly_send (conn, packets, &num_packets)) == 0)
223         {
224           for (i = 0; i != num_packets; ++i)
225             {
226               if (quic_send_datagram (quic_session, packets[i]))
227                 {
228                   QUIC_DBG (2, "quic_send_datagram failed");
229                   goto stop_sending;
230                 }
231               ret = 0;
232               quicly_default_free_packet_cb.cb
233                 (&quicly_default_free_packet_cb, packets[i]);
234             }
235         }
236       else
237         {
238           QUIC_DBG (2, "quicly_send returned %d, closing connection\n", ret);
239           return ret;
240         }
241     }
242   while (ret == 0 && num_packets == sizeof (packets) / sizeof (packets[0]));
243
244 stop_sending:
245   if (svm_fifo_set_event (quic_session->tx_fifo))
246     session_send_io_evt_to_thread (quic_session->tx_fifo, FIFO_EVENT_APP_TX);
247
248   quic_update_timer (ctx);
249   return 0;
250 }
251
252 /*****************************************************************************
253  * START QUICLY CALLBACKS
254  * Called from QUIC lib
255  *****************************************************************************/
256
257 static int
258 quic_on_stop_sending (quicly_stream_t * stream, int error_code)
259 {
260   QUIC_DBG (2, "received STOP_SENDING: %d", error_code);
261   return 0;
262 }
263
264 static int
265 quic_on_receive_reset (quicly_stream_t * stream, int error_code)
266 {
267   QUIC_DBG (2, "received RESET_STREAM: %d", error_code);
268   return 0;
269 }
270
271 static int
272 quic_on_receive (quicly_stream_t * stream, size_t off, const void *src,
273                  size_t len)
274 {
275   QUIC_DBG (2, "received data: %lu bytes", len);
276   u32 to_enqueue, ctx_id;
277   quic_ctx_t *ctx;
278   session_t *app_session;
279   svm_fifo_t *rx_fifo;
280   app_worker_t *app_wrk;
281
282   ctx_id = (u64) * quicly_get_data (stream->conn);
283   ctx = quic_ctx_get (ctx_id);
284   app_session = session_get_from_handle (ctx->c_quic_ctx_id.app_session);
285   rx_fifo = app_session->rx_fifo;
286   to_enqueue = svm_fifo_max_enqueue (rx_fifo);
287   if (to_enqueue > len)
288     to_enqueue = len;
289   // TODO what happens to the excess bytes?
290
291   svm_fifo_enqueue_nowait (rx_fifo, to_enqueue, src);
292
293   // Notify app
294   app_wrk = app_worker_get_if_valid (app_session->app_wrk_index);
295   if (PREDICT_TRUE (app_wrk != 0))
296     app_worker_lock_and_send_event (app_wrk, app_session, SESSION_IO_EVT_RX);
297   return 0;
298 }
299
300 static const quicly_stream_callbacks_t quic_stream_callbacks = {
301   .on_destroy = quicly_streambuf_destroy,
302   .on_send_shift = quicly_streambuf_egress_shift,
303   .on_send_emit = quicly_streambuf_egress_emit,
304   .on_send_stop = quic_on_stop_sending,
305   .on_receive = quic_on_receive,
306   .on_receive_reset = quic_on_receive_reset
307 };
308
309 static int
310 quic_on_stream_open (quicly_stream_open_cb * self, quicly_stream_t * stream)
311 {
312   QUIC_DBG (2, "on_stream_open called");
313   int ret;
314   if ((ret =
315        quicly_streambuf_create (stream, sizeof (quicly_streambuf_t))) != 0)
316     {
317       return ret;
318     }
319   stream->callbacks = &quic_stream_callbacks;
320   return 0;
321 }
322
323 static quicly_stream_open_cb on_stream_open = { &quic_on_stream_open };
324
325 static void
326 quic_on_conn_close (quicly_closed_by_peer_cb * self, quicly_conn_t * conn,
327                     int code, uint64_t frame_type,
328                     const char *reason, size_t reason_len)
329 {
330   QUIC_DBG (2, "connection closed, reason: %s", reason);
331   u32 ctx_index = (u64) * quicly_get_data (conn);
332   quic_connection_closed (ctx_index);
333 }
334
335 static quicly_closed_by_peer_cb on_closed_by_peer = { &quic_on_conn_close };
336
337
338 /*****************************************************************************
339  * END QUICLY CALLBACKS
340  *****************************************************************************/
341
342 /* single-entry session cache */
343 struct st_util_session_cache_t
344 {
345   ptls_encrypt_ticket_t super;
346   uint8_t id[32];
347   ptls_iovec_t data;
348 };
349
350 static int
351 encrypt_ticket_cb (ptls_encrypt_ticket_t * _self, ptls_t * tls,
352                    int is_encrypt, ptls_buffer_t * dst, ptls_iovec_t src)
353 {
354   struct st_util_session_cache_t *self = (void *) _self;
355   int ret;
356
357   if (is_encrypt)
358     {
359
360       /* replace the cached entry along with a newly generated session id */
361       free (self->data.base);
362       if ((self->data.base = malloc (src.len)) == NULL)
363         return PTLS_ERROR_NO_MEMORY;
364
365       ptls_get_context (tls)->random_bytes (self->id, sizeof (self->id));
366       memcpy (self->data.base, src.base, src.len);
367       self->data.len = src.len;
368
369       /* store the session id in buffer */
370       if ((ret = ptls_buffer_reserve (dst, sizeof (self->id))) != 0)
371         return ret;
372       memcpy (dst->base + dst->off, self->id, sizeof (self->id));
373       dst->off += sizeof (self->id);
374
375     }
376   else
377     {
378
379       /* check if session id is the one stored in cache */
380       if (src.len != sizeof (self->id))
381         return PTLS_ERROR_SESSION_NOT_FOUND;
382       if (memcmp (self->id, src.base, sizeof (self->id)) != 0)
383         return PTLS_ERROR_SESSION_NOT_FOUND;
384
385       /* return the cached value */
386       if ((ret = ptls_buffer_reserve (dst, self->data.len)) != 0)
387         return ret;
388       memcpy (dst->base + dst->off, self->data.base, self->data.len);
389       dst->off += self->data.len;
390     }
391
392   return 0;
393 }
394
395 static struct st_util_session_cache_t sc = {
396   .super = {
397             .cb = encrypt_ticket_cb,
398             },
399 };
400
401 /* *INDENT-OFF* */
402 static ptls_context_t quic_tlsctx = {
403   .random_bytes = ptls_openssl_random_bytes,
404   .get_time = &ptls_get_time,
405   .key_exchanges = ptls_openssl_key_exchanges,
406   .cipher_suites = ptls_openssl_cipher_suites,
407   .certificates = {
408     .list = NULL,
409     .count = 0
410   },
411   .esni = NULL,
412   .on_client_hello = NULL,
413   .emit_certificate = NULL,
414   .sign_certificate = NULL,
415   .verify_certificate = NULL,
416   .ticket_lifetime = 86400,
417   .max_early_data_size = 8192,
418   .hkdf_label_prefix__obsolete = NULL,
419   .require_dhe_on_psk = 1,
420   .encrypt_ticket = &sc.super,
421 };
422 /* *INDENT-ON* */
423
424 static int
425 ptls_compare_separator_line (const char *line, const char *begin_or_end,
426                              const char *label)
427 {
428   int ret = strncmp (line, "-----", 5);
429   size_t text_index = 5;
430
431   if (ret == 0)
432     {
433       size_t begin_or_end_length = strlen (begin_or_end);
434       ret = strncmp (line + text_index, begin_or_end, begin_or_end_length);
435       text_index += begin_or_end_length;
436     }
437
438   if (ret == 0)
439     {
440       ret = line[text_index] - ' ';
441       text_index++;
442     }
443
444   if (ret == 0)
445     {
446       size_t label_length = strlen (label);
447       ret = strncmp (line + text_index, label, label_length);
448       text_index += label_length;
449     }
450
451   if (ret == 0)
452     {
453       ret = strncmp (line + text_index, "-----", 5);
454     }
455
456   return ret;
457 }
458
459 static int
460 ptls_get_bio_pem_object (BIO * bio, const char *label, ptls_buffer_t * buf)
461 {
462   int ret = PTLS_ERROR_PEM_LABEL_NOT_FOUND;
463   char line[256];
464   ptls_base64_decode_state_t state;
465
466   /* Get the label on a line by itself */
467   while (BIO_gets (bio, line, 256))
468     {
469       if (ptls_compare_separator_line (line, "BEGIN", label) == 0)
470         {
471           ret = 0;
472           ptls_base64_decode_init (&state);
473           break;
474         }
475     }
476   /* Get the data in the buffer */
477   while (ret == 0 && BIO_gets (bio, line, 256))
478     {
479       if (ptls_compare_separator_line (line, "END", label) == 0)
480         {
481           if (state.status == PTLS_BASE64_DECODE_DONE
482               || (state.status == PTLS_BASE64_DECODE_IN_PROGRESS
483                   && state.nbc == 0))
484             {
485               ret = 0;
486             }
487           else
488             {
489               ret = PTLS_ERROR_INCORRECT_BASE64;
490             }
491           break;
492         }
493       else
494         {
495           ret = ptls_base64_decode (line, &state, buf);
496         }
497     }
498
499   return ret;
500 }
501
502 int
503 ptls_load_bio_pem_objects (BIO * bio, const char *label, ptls_iovec_t * list,
504                            size_t list_max, size_t * nb_objects)
505 {
506   int ret = 0;
507   size_t count = 0;
508
509   *nb_objects = 0;
510
511   if (ret == 0)
512     {
513       while (count < list_max)
514         {
515           ptls_buffer_t buf;
516
517           ptls_buffer_init (&buf, "", 0);
518
519           ret = ptls_get_bio_pem_object (bio, label, &buf);
520
521           if (ret == 0)
522             {
523               if (buf.off > 0 && buf.is_allocated)
524                 {
525                   list[count].base = buf.base;
526                   list[count].len = buf.off;
527                   count++;
528                 }
529               else
530                 {
531                   ptls_buffer_dispose (&buf);
532                 }
533             }
534           else
535             {
536               ptls_buffer_dispose (&buf);
537               break;
538             }
539         }
540     }
541
542   if (ret == PTLS_ERROR_PEM_LABEL_NOT_FOUND && count > 0)
543     {
544       ret = 0;
545     }
546
547   *nb_objects = count;
548
549   return ret;
550 }
551
552 #define PTLS_MAX_CERTS_IN_CONTEXT 16
553
554 int
555 ptls_load_bio_certificates (ptls_context_t * ctx, BIO * bio)
556 {
557   int ret = 0;
558
559   ctx->certificates.list =
560     (ptls_iovec_t *) malloc (PTLS_MAX_CERTS_IN_CONTEXT *
561                              sizeof (ptls_iovec_t));
562
563   if (ctx->certificates.list == NULL)
564     {
565       ret = PTLS_ERROR_NO_MEMORY;
566     }
567   else
568     {
569       ret =
570         ptls_load_bio_pem_objects (bio, "CERTIFICATE", ctx->certificates.list,
571                                    PTLS_MAX_CERTS_IN_CONTEXT,
572                                    &ctx->certificates.count);
573     }
574
575   return ret;
576 }
577
578 static inline void
579 load_bio_certificate_chain (ptls_context_t * ctx, const char *cert_data)
580 {
581   BIO *cert_bio;
582   cert_bio = BIO_new_mem_buf (cert_data, -1);
583   if (ptls_load_bio_certificates (ctx, cert_bio) != 0)
584     {
585       BIO_free (cert_bio);
586       fprintf (stderr, "failed to load certificate:%s\n", strerror (errno));
587       exit (1);
588     }
589   BIO_free (cert_bio);
590 }
591
592 static inline void
593 load_bio_private_key (ptls_context_t * ctx, const char *pk_data)
594 {
595   static ptls_openssl_sign_certificate_t sc;
596   EVP_PKEY *pkey;
597   BIO *key_bio;
598
599   key_bio = BIO_new_mem_buf (pk_data, -1);
600   pkey = PEM_read_bio_PrivateKey (key_bio, NULL, NULL, NULL);
601   BIO_free (key_bio);
602
603   if (pkey == NULL)
604     {
605       fprintf (stderr, "failed to read private key from app configuration\n");
606       exit (1);
607     }
608
609   ptls_openssl_init_sign_certificate (&sc, pkey);
610   EVP_PKEY_free (pkey);
611
612   ctx->sign_certificate = &sc.super;
613 }
614
615 static void
616 quic_connection_closed (u32 ctx_index)
617 {
618   QUIC_DBG (2, "QUIC connection closed");
619   quic_ctx_t *ctx;
620
621   ctx = quic_ctx_get (ctx_index);
622   // TODO if connection is not established, just delete the session
623
624   // Do not try to send anything anymore
625   ctx->stream = NULL;
626   quicly_free (ctx->c_quic_ctx_id.conn);
627   ctx->c_quic_ctx_id.conn = NULL;
628   session_transport_closing_notify (&ctx->connection);
629 }
630
631 static int64_t
632 quic_get_time (quicly_now_cb * self)
633 {
634   // TODO read value set by set_time_now?
635   // (needs to change it not to call this function)
636   vlib_main_t *vlib_main = vlib_get_main ();
637   f64 time = vlib_time_now (vlib_main);
638   return (int64_t) (time * 1000.f);
639 }
640 quicly_now_cb quicly_vpp_now_cb = { quic_get_time };
641
642 static void
643 allocate_quicly_ctx (application_t * app, u8 is_client)
644 {
645   QUIC_DBG (2, "Called allocate_quicly_ctx");
646   struct
647   {
648     quicly_context_t _;
649     char cid_key[17];
650   } *ctx_data;
651   quicly_context_t *quicly_ctx;
652   char *cid_key;
653
654   ctx_data = malloc (sizeof (*ctx_data));
655   quicly_ctx = &ctx_data->_;
656   app->quicly_ctx = (u64 *) quicly_ctx;
657   memcpy (quicly_ctx, &quicly_default_context, sizeof (quicly_context_t));
658
659   quicly_ctx->tls = &quic_tlsctx;
660   quicly_ctx->stream_open = &on_stream_open;
661   quicly_ctx->closed_by_peer = &on_closed_by_peer;
662   quicly_ctx->now = &quicly_vpp_now_cb;
663
664   quicly_amend_ptls_context (quicly_ctx->tls);
665
666   quicly_ctx->event_log.mask = INT64_MAX;
667   quicly_ctx->event_log.cb = quicly_new_default_event_log_cb (stderr);
668
669   quicly_ctx->transport_params.max_data = QUIC_INT_MAX;
670   quicly_ctx->transport_params.max_streams_uni = QUIC_INT_MAX;
671   quicly_ctx->transport_params.max_streams_bidi = QUIC_INT_MAX;
672   quicly_ctx->transport_params.max_stream_data.bidi_local = QUIC_INT_MAX;
673   quicly_ctx->transport_params.max_stream_data.bidi_remote = QUIC_INT_MAX;
674   quicly_ctx->transport_params.max_stream_data.uni = QUIC_INT_MAX;
675
676   if (!is_client)
677     {
678       load_bio_private_key (quicly_ctx->tls, (char *) app->tls_key);
679       load_bio_certificate_chain (quicly_ctx->tls, (char *) app->tls_cert);
680       cid_key = ctx_data->cid_key;
681       quicly_ctx->tls->random_bytes (cid_key, 16);
682       cid_key[16] = 0;
683       quicly_ctx->encrypt_cid =
684         quicly_new_default_encrypt_cid_cb (&ptls_openssl_bfecb,
685                                            &ptls_openssl_sha256,
686                                            ptls_iovec_init (cid_key,
687                                                             strlen
688                                                             (cid_key)));
689       quicly_ctx->decrypt_cid =
690         quicly_new_default_decrypt_cid_cb (&ptls_openssl_bfecb,
691                                            &ptls_openssl_sha256,
692                                            ptls_iovec_init (cid_key,
693                                                             strlen
694                                                             (cid_key)));
695     }
696 }
697
698
699 /*****************************************************************************
700  * BEGIN TIMERS HANDLING
701  *****************************************************************************/
702
703 static u32
704 quic_set_time_now (u32 thread_index)
705 {
706   quic_main.wrk_ctx[thread_index].time_now = quic_get_time (NULL);
707   return quic_main.wrk_ctx[thread_index].time_now;
708 }
709
710 static void
711 quic_timer_expired (u32 conn_index)
712 {
713   quic_ctx_t *ctx;
714   QUIC_DBG (2, "Timer expired for conn %u at %ld", conn_index,
715             quic_get_time (NULL));
716   ctx = quic_ctx_get (conn_index);
717   ctx->c_quic_ctx_id.timer_handle = QUIC_TIMER_HANDLE_INVALID;
718   if (quic_send_packets (ctx))
719     {
720       quic_connection_closed (conn_index);
721     }
722 }
723
724 static void
725 quic_update_timer (quic_ctx_t * ctx)
726 {
727   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
728   int64_t next_timeout;
729
730   // This timeout is in ms which is the unit of our timer
731   next_timeout = quicly_get_first_timeout (ctx->c_quic_ctx_id.conn);
732   tw = &quic_main.wrk_ctx[vlib_get_thread_index ()].timer_wheel;
733   f64 next_timeout_f = ((f64) next_timeout) / 1000.f;
734
735   clib_warning ("Timer set to %ld (%lf)", next_timeout, next_timeout_f);
736
737   if (ctx->c_quic_ctx_id.timer_handle == QUIC_TIMER_HANDLE_INVALID)
738     {
739       if (next_timeout == INT64_MAX)
740         return;
741       ctx->c_quic_ctx_id.timer_handle =
742         tw_timer_start_1t_3w_1024sl_ov (tw, ctx->c_c_index, 0,
743                                         next_timeout_f);
744     }
745   else
746     {
747       if (next_timeout == INT64_MAX)
748         {
749           tw_timer_stop_1t_3w_1024sl_ov (tw, ctx->c_quic_ctx_id.timer_handle);
750           ctx->c_quic_ctx_id.timer_handle = QUIC_TIMER_HANDLE_INVALID;
751         }
752       else
753         tw_timer_update_1t_3w_1024sl_ov (tw, ctx->c_quic_ctx_id.timer_handle,
754                                          next_timeout_f);
755     }
756 }
757
758 static void
759 quic_expired_timers_dispatch (u32 * expired_timers)
760 {
761   int i;
762
763   for (i = 0; i < vec_len (expired_timers); i++)
764     {
765       quic_timer_expired (expired_timers[i]);
766     }
767 }
768
769
770 /*****************************************************************************
771  * END TIMERS HANDLING
772  *
773  * BEGIN TRANSPORT PROTO FUNCTIONS
774  *****************************************************************************/
775
776 int
777 quic_connect (transport_endpoint_cfg_t * tep)
778 {
779   QUIC_DBG (2, "Called quic_connect");
780   vnet_connect_args_t _cargs = { {}, }, *cargs = &_cargs;
781   session_endpoint_cfg_t *sep;
782   quic_main_t *qm = &quic_main;
783   quic_ctx_t *ctx;
784   app_worker_t *app_wrk;
785   application_t *app;
786   u32 ctx_index;
787   int error;
788
789   sep = (session_endpoint_cfg_t *) tep;
790   ctx_index = quic_ctx_half_open_alloc ();
791   ctx = quic_ctx_half_open_get (ctx_index);
792   ctx->c_quic_ctx_id.parent_app_wrk_idx = sep->app_wrk_index;
793   ctx->c_s_index = 0xFAFAFAFA;
794   ctx->c_quic_ctx_id.udp_is_ip4 = sep->is_ip4;
795   ctx->c_quic_ctx_id.timer_handle = QUIC_TIMER_HANDLE_INVALID;
796   ctx->c_quic_ctx_id.conn_state = QUIC_CONN_STATE_HANDSHAKE;
797   ctx->client_opaque = sep->opaque;
798   if (sep->hostname)
799     {
800       ctx->srv_hostname = format (0, "%v", sep->hostname);
801       vec_terminate_c_string (ctx->srv_hostname);
802     }
803   else
804     {
805       // needed by quic for crypto + determining client / server
806       ctx->srv_hostname =
807         format (0, "%U", format_ip46_address, &sep->ip, sep->is_ip4);
808     }
809
810   quic_ctx_half_open_reader_unlock ();
811
812   clib_memcpy (&cargs->sep, sep, sizeof (session_endpoint_cfg_t));
813   cargs->sep.transport_proto = TRANSPORT_PROTO_UDP;
814   cargs->app_index = qm->app_index;
815   cargs->api_context = ctx_index;
816
817   app_wrk = app_worker_get (sep->app_wrk_index);
818   app = application_get (app_wrk->app_index);
819   ctx->c_quic_ctx_id.parent_app_id = app_wrk->app_index;
820
821   allocate_quicly_ctx (app, 1 /* is client */ );
822
823   if ((error = vnet_connect (cargs)))
824     return error;
825
826   QUIC_DBG (1, "New connect request %u", ctx_index);
827   return 0;
828 }
829
830 static void
831 quic_disconnect (u32 ctx_index, u32 thread_index)
832 {
833   QUIC_DBG (2, "Called quic_disconnect");
834   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
835   quic_ctx_t *ctx;
836
837   QUIC_DBG (1, "Disconnecting %x", ctx_index);
838
839   ctx = quic_ctx_get (ctx_index);
840   if (ctx->c_quic_ctx_id.timer_handle != QUIC_TIMER_HANDLE_INVALID)
841     {
842       tw = &quic_main.wrk_ctx[vlib_get_thread_index ()].timer_wheel;
843       tw_timer_stop_1t_3w_1024sl_ov (tw, ctx->c_quic_ctx_id.timer_handle);
844     }
845   quic_disconnect_transport (ctx);
846   // This removes the session from the lookup table and frees it.
847   session_transport_delete_notify (&ctx->connection);
848   quic_ctx_free (ctx);
849 }
850
851 u32
852 quic_start_listen (u32 app_listen_session_index, transport_endpoint_t * tep)
853 {
854   QUIC_DBG (2, "Called quic_start_listen");
855   vnet_listen_args_t _bargs, *args = &_bargs;
856   quic_main_t *qm = &quic_main;
857   session_handle_t udp_handle;
858   session_endpoint_cfg_t *sep;
859   session_t *quic_listen_session, *app_listen_session;
860   app_worker_t *app_wrk;
861   application_t *app;
862   quic_ctx_t *lctx;
863   u32 lctx_index;
864   app_listener_t *app_listener;
865
866   sep = (session_endpoint_cfg_t *) tep;
867   app_wrk = app_worker_get (sep->app_wrk_index);
868   app = application_get (app_wrk->app_index);
869
870   allocate_quicly_ctx (app, 0 /* is_client */ );
871
872   sep->transport_proto = TRANSPORT_PROTO_UDP;
873   memset (args, 0, sizeof (*args));
874   args->app_index = qm->app_index;
875   args->sep_ext = *sep;
876   args->sep_ext.ns_index = app->ns_index;
877   if (vnet_listen (args))
878     return -1;
879
880   lctx_index = quic_ctx_alloc ();       // listener
881   udp_handle = args->handle;
882   app_listener = app_listener_get_w_handle (udp_handle);
883   quic_listen_session = app_listener_get_session (app_listener);
884   quic_listen_session->opaque = lctx_index;
885
886   app_listen_session = listen_session_get (app_listen_session_index);
887
888   lctx = quic_ctx_get (lctx_index);     // listener
889   lctx->is_listener = 1;
890   lctx->c_quic_ctx_id.parent_app_wrk_idx = sep->app_wrk_index;
891   lctx->c_quic_ctx_id.parent_app_id = app_wrk->app_index;
892   lctx->c_quic_ctx_id.quic_session = udp_handle;
893   lctx->c_quic_ctx_id.app_session =
894     listen_session_get_handle (app_listen_session);
895   lctx->c_quic_ctx_id.udp_is_ip4 = sep->is_ip4;
896
897   QUIC_DBG (1, "Started listening %d", lctx_index);
898   return lctx_index;
899 }
900
901 u32
902 quic_stop_listen (u32 lctx_index)
903 {
904   QUIC_DBG (2, "Called quic_stop_listen");
905   quic_ctx_t *lctx;
906
907   lctx = quic_ctx_get (lctx_index);     // listener
908   vnet_unlisten_args_t a = {
909     .handle = lctx->c_quic_ctx_id.quic_session,
910     .app_index = quic_main.app_index,
911     .wrk_map_index = 0          /* default wrk */
912   };
913   if (vnet_unlisten (&a))
914     clib_warning ("unlisten errored");
915
916   // TODO: crypto state cleanup
917
918   quic_ctx_free (lctx);         // listener
919   return 0;
920 }
921
922 transport_connection_t *
923 quic_connection_get (u32 ctx_index, u32 thread_index)
924 {
925   QUIC_DBG (2, "Called quic_connection_get");
926   quic_ctx_t *ctx;
927   ctx = quic_ctx_get_w_thread (ctx_index, thread_index);
928   return &ctx->connection;
929 }
930
931 transport_connection_t *
932 quic_listener_get (u32 listener_index)
933 {
934   QUIC_DBG (2, "Called quic_listener_get");
935   quic_ctx_t *ctx;
936   ctx = quic_ctx_get (listener_index);
937   return &ctx->connection;
938 }
939
940 static void
941 quic_update_time (f64 now, u8 thread_index)
942 {
943   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
944
945   tw = &quic_main.wrk_ctx[thread_index].timer_wheel;
946   quic_set_time_now (thread_index);
947   tw_timer_expire_timers_1t_3w_1024sl_ov (tw, now);
948 }
949
950 static u8 *
951 format_quic_connection (u8 * s, va_list * args)
952 {
953   s = format (s, "[QUIC] connection");
954   return s;
955 }
956
957 static u8 *
958 format_quic_half_open (u8 * s, va_list * args)
959 {
960   u32 qc_index = va_arg (*args, u32);
961   quic_ctx_t *ctx = quic_ctx_half_open_get (qc_index);
962   s = format (s, "[QUIC] half-open app %u", ctx->c_quic_ctx_id.parent_app_id);
963   quic_ctx_half_open_reader_unlock ();
964   return s;
965 }
966
967 // TODO improve
968 static u8 *
969 format_quic_listener (u8 * s, va_list * args)
970 {
971   s = format (s, "[QUIC] listener");
972   return s;
973 }
974
975 /*****************************************************************************
976  * END TRANSPORT PROTO FUNCTIONS
977  *
978  * START SESSION CALLBACKS
979  * Called from UDP layer
980  *****************************************************************************/
981
982 static inline void
983 quic_build_sockaddr (struct sockaddr *sa, socklen_t * salen,
984                      ip46_address_t * addr, u16 port, u8 is_ip4)
985 {
986   if (is_ip4)
987     {
988       struct sockaddr_in *sa4 = (struct sockaddr_in *) sa;
989       sa4->sin_family = AF_INET;
990       sa4->sin_port = port;
991       sa4->sin_addr.s_addr = addr->ip4.as_u32;
992       *salen = sizeof (struct sockaddr_in);
993     }
994   else
995     {
996       struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) sa;
997       sa6->sin6_family = AF_INET6;
998       sa6->sin6_port = port;
999       clib_memcpy (&sa6->sin6_addr, &addr->ip6, 16);
1000       *salen = sizeof (struct sockaddr_in6);
1001     }
1002 }
1003
1004 static int
1005 quic_delayed_notify_app_connected (void *ctx_index)
1006 {
1007   QUIC_DBG (1, "quic_notify_app_connected");
1008   session_t *app_session;
1009   app_worker_t *app_wrk;
1010   quic_ctx_t *ctx;
1011   ctx = quic_ctx_get ((u32) (u64) ctx_index);
1012
1013   app_wrk = app_worker_get_if_valid (ctx->c_quic_ctx_id.parent_app_wrk_idx);
1014   if (!app_wrk)
1015     {
1016       quic_disconnect_transport (ctx);
1017       return -1;
1018     }
1019
1020   app_session = session_alloc (ctx->c_thread_index);
1021   QUIC_DBG (1, "Created app_session, id %u", app_session->session_index);
1022   ctx->c_s_index = app_session->session_index;
1023   app_session->app_wrk_index = ctx->c_quic_ctx_id.parent_app_wrk_idx;
1024   app_session->connection_index = ctx->c_c_index;
1025   app_session->session_type =
1026     session_type_from_proto_and_ip (TRANSPORT_PROTO_QUIC,
1027                                     ctx->c_quic_ctx_id.udp_is_ip4);
1028
1029   if (app_worker_init_connected (app_wrk, app_session)) // TODO dont allocate fifos
1030     {
1031       quic_disconnect (ctx->c_c_index, vlib_get_thread_index ());
1032       return app_worker_connect_notify (app_wrk, NULL, ctx->client_opaque);
1033     }
1034
1035   app_session->session_state = SESSION_STATE_CONNECTING;
1036   if (app_worker_connect_notify (app_wrk, app_session, ctx->client_opaque))
1037     {
1038       QUIC_DBG (1, "failed to notify app");
1039       quic_disconnect (ctx->c_c_index, vlib_get_thread_index ());
1040       return -1;
1041     }
1042
1043   ctx->c_quic_ctx_id.app_session = session_handle (app_session);
1044   app_session->session_state = SESSION_STATE_LISTENING;
1045   session_lookup_add_connection (&ctx->connection,
1046                                  session_handle (app_session));
1047
1048   return 0;
1049 }
1050
1051 int
1052 quic_session_connected_callback (u32 quic_app_index, u32 ho_ctx_idx,
1053                                  session_t * s, u8 is_fail)
1054 {
1055   QUIC_DBG (2, "Called quic_session_connected_callback");
1056   // This should always be called before quic_connect returns since UDP always
1057   // connects instantly.
1058   struct sockaddr_in6 sa6;
1059   struct sockaddr *sa = (struct sockaddr *) &sa6;
1060   socklen_t salen;
1061   transport_connection_t *tc;
1062   quic_ctx_t *ho_ctx, *ctx;
1063   u32 ctx_index;
1064   int ret;
1065   application_t *app;
1066   app_worker_t *app_wrk;
1067
1068   ho_ctx = quic_ctx_half_open_get (ho_ctx_idx);
1069   if (is_fail)
1070     {
1071       int (*cb_fn) (u32, u32, session_t *, u8), rv = 0;
1072       u32 wrk_index, api_context;
1073
1074       wrk_index = ho_ctx->c_quic_ctx_id.parent_app_wrk_idx;
1075       app_wrk =
1076         app_worker_get_if_valid (ho_ctx->c_quic_ctx_id.parent_app_wrk_idx);
1077       if (app_wrk)
1078         {
1079           api_context = ho_ctx->c_s_index;
1080           app = application_get (app_wrk->app_index);
1081           cb_fn = app->cb_fns.session_connected_callback;
1082           rv = cb_fn (wrk_index, api_context, 0, 1 /* failed */ );
1083         }
1084       quic_ctx_half_open_reader_unlock ();
1085       quic_ctx_half_open_free (ho_ctx_idx);
1086       return rv;
1087     }
1088
1089   app_wrk =
1090     app_worker_get_if_valid (ho_ctx->c_quic_ctx_id.parent_app_wrk_idx);
1091   if (!app_wrk)
1092     {
1093       QUIC_DBG (1, "Appwrk not found");
1094       return -1;
1095     }
1096   app = application_get (app_wrk->app_index);
1097
1098   ctx_index = quic_ctx_alloc ();
1099   ctx = quic_ctx_get (ctx_index);
1100   clib_memcpy (ctx, ho_ctx, sizeof (*ctx));
1101   quic_ctx_half_open_reader_unlock ();  // TODO: this is a race
1102   quic_ctx_half_open_free (ho_ctx_idx);
1103
1104   ctx->c_thread_index = vlib_get_thread_index ();
1105   ctx->c_c_index = ctx_index;
1106
1107   QUIC_DBG (1, "Quic connect for returned %u. New connection [%u]%x",
1108             is_fail, vlib_get_thread_index (), (ctx) ? ctx_index : ~0);
1109
1110   ctx->c_quic_ctx_id.quic_session = session_handle (s);
1111   s->opaque = ctx_index;
1112   s->session_state = SESSION_STATE_READY;
1113
1114   // Init QUIC lib connection
1115   // Generate required sockaddr & salen
1116   tc = session_get_transport (s);
1117   quic_build_sockaddr (sa, &salen, &tc->rmt_ip, tc->rmt_port, tc->is_ip4);
1118
1119   ret =
1120     quicly_connect (&ctx->c_quic_ctx_id.conn,
1121                     (quicly_context_t *) app->quicly_ctx,
1122                     (char *) ctx->srv_hostname, sa, salen,
1123                     &quic_main.next_cid, &quic_main.hs_properties, NULL);
1124   ++quic_main.next_cid.master_id;
1125   // Save context handle in quicly connection
1126   *quicly_get_data (ctx->c_quic_ctx_id.conn) = (void *) (u64) ctx_index;
1127   assert (ret == 0);
1128
1129   if (quic_send_packets (ctx))
1130     {
1131       quic_connection_closed (ctx_index);
1132     }
1133   return ret;
1134 }
1135
1136 void
1137 quic_session_disconnect_callback (session_t * s)
1138 {
1139   clib_warning ("UDP session disconnected???");
1140 }
1141
1142 void
1143 quic_session_reset_callback (session_t * s)
1144 {
1145   clib_warning ("UDP session reset???");
1146 }
1147
1148 static int
1149 quic_add_segment_callback (u32 client_index, u64 seg_handle)
1150 {
1151   QUIC_DBG (2, "Called quic_add_segment_callback");
1152   QUIC_DBG (2, "NOT IMPLEMENTED");
1153   /* No-op for builtin */
1154   return 0;
1155 }
1156
1157 static int
1158 quic_del_segment_callback (u32 client_index, u64 seg_handle)
1159 {
1160   QUIC_DBG (2, "Called quic_del_segment_callback");
1161   QUIC_DBG (2, "NOT IMPLEMENTED");
1162   /* No-op for builtin */
1163   return 0;
1164 }
1165
1166 int
1167 quic_add_vpp_q_builtin_tx_evt (session_t * s)
1168 {
1169   if (svm_fifo_set_event (s->tx_fifo))
1170     session_send_io_evt_to_thread_custom (s, s->thread_index,
1171                                           FIFO_EVENT_BUILTIN_TX);
1172   return 0;
1173 }
1174
1175 void
1176 quic_open_stream_if_ready (quic_ctx_t * ctx)
1177 {
1178   quicly_conn_t *conn = ctx->c_quic_ctx_id.conn;
1179   if (ctx->stream)
1180     {
1181       QUIC_DBG (2, "----------- > FOUND Stream id %d",
1182                 ctx->stream->stream_id);
1183       QUIC_DBG (2, "----------- > FOUND Stream is_open %d",
1184                 ctx->stream->sendstate.is_open);
1185       return;
1186     }
1187   if (quicly_connection_is_ready (conn))
1188     assert (!quicly_open_stream (conn, &ctx->stream, 0));
1189   QUIC_DBG (2, "Stream id %d", ctx->stream->stream_id);
1190   QUIC_DBG (2, "Stream is_open %d", ctx->stream->sendstate.is_open);
1191 }
1192
1193 int
1194 quic_custom_tx_callback (void *session)
1195 {
1196   QUIC_DBG (2, "Called quic_custom_tx_callback");
1197   session_t *app_session = (session_t *) session;
1198   quic_ctx_t *ctx;
1199   svm_fifo_t *f;
1200   u32 deq_max;
1201   u8 *data;
1202
1203   if (PREDICT_FALSE
1204       (app_session->session_state >= SESSION_STATE_TRANSPORT_CLOSING))
1205     return 0;
1206   ctx = quic_ctx_get (app_session->connection_index);
1207   quic_open_stream_if_ready (ctx);
1208   if (!ctx->stream)
1209     {
1210       quic_add_vpp_q_builtin_tx_evt (app_session);
1211       return 0;
1212     }
1213
1214   f = app_session->tx_fifo;
1215   deq_max = svm_fifo_max_dequeue (f);
1216   if (!deq_max)
1217     return 0;
1218
1219   data = svm_fifo_head (f);
1220   if (quicly_streambuf_egress_write (ctx->stream, data, deq_max))
1221     {
1222       assert (0);
1223       return 0;
1224     }
1225   QUIC_DBG (2, "Sent %u bytes", deq_max);
1226   svm_fifo_dequeue_drop (f, deq_max);
1227   if (quic_send_packets (ctx))
1228     {
1229       quic_connection_closed (ctx->c_c_index);
1230     }
1231   return 0;
1232 }
1233
1234 int
1235 quic_find_packet_ctx (quic_ctx_t ** ctx, quicly_conn_t ** conn,
1236                       struct sockaddr *sa, socklen_t salen,
1237                       quicly_decoded_packet_t packet)
1238 {
1239   quic_ctx_t *ctx_;
1240   quicly_conn_t *conn_;
1241   /* *INDENT-OFF* */
1242   pool_foreach (ctx_, quic_main.ctx_pool[vlib_get_thread_index()],
1243   ({
1244     conn_ = ctx_->c_quic_ctx_id.conn;
1245     if (conn_ && !ctx_->is_listener)
1246       {
1247         if (quicly_is_destination(conn_, sa, salen, &packet))
1248           {
1249             *conn = conn_;
1250             *ctx = ctx_;
1251             QUIC_DBG (2, "connection_found");
1252             return 0;
1253           }
1254       }
1255   }));
1256   /* *INDENT-ON* */
1257   return 0;
1258 }
1259
1260 static int
1261 quic_receive (quic_ctx_t * ctx, quicly_conn_t * conn,
1262               quicly_decoded_packet_t packet)
1263 {
1264   quicly_receive (conn, &packet);
1265   // Conn may be set to null if the connection is terminated
1266   if (ctx->c_quic_ctx_id.conn
1267       && ctx->c_quic_ctx_id.conn_state == QUIC_CONN_STATE_HANDSHAKE)
1268     {
1269       if (quicly_connection_is_ready (conn))
1270         {
1271           ctx->c_quic_ctx_id.conn_state = QUIC_CONN_STATE_READY;
1272           if (quicly_is_client (conn))
1273             session_send_rpc_evt_to_thread_force (vlib_get_thread_index (),
1274                                                   &quic_delayed_notify_app_connected,
1275                                                   (void *) (u64)
1276                                                   ctx->c_c_index);
1277         }
1278     }
1279   if (quic_send_packets (ctx))
1280     {
1281       quic_connection_closed (ctx->c_c_index);
1282     }
1283   return 0;
1284 }
1285
1286 static int
1287 quic_delayed_create_app_session (void *ctx_index)
1288 {
1289   quic_ctx_t *lctx, *ctx;
1290   session_t *app_session, *app_listen_session;
1291   app_worker_t *app_wrk;
1292   int rv;
1293
1294   ctx = quic_ctx_get ((u32) (u64) ctx_index);
1295   app_session = session_alloc (ctx->c_thread_index);
1296   app_session->session_state = SESSION_STATE_LISTENING;
1297   ctx->c_s_index = app_session->session_index;
1298
1299   lctx = quic_ctx_get (ctx->c_quic_ctx_id.listener_ctx_id);
1300
1301   app_listen_session =
1302     listen_session_get_from_handle (lctx->c_quic_ctx_id.app_session);
1303   app_session->app_wrk_index = lctx->c_quic_ctx_id.parent_app_wrk_idx;
1304   app_session->connection_index = ctx->c_c_index;
1305   app_session->session_type = app_listen_session->session_type;
1306   app_session->listener_index = app_listen_session->session_index;
1307   app_session->app_index = quic_main.app_index;
1308
1309   // TODO: don't alloc fifos when we don't transfer data on this session
1310   if ((rv = app_worker_init_accepted (app_session)))
1311     {
1312       QUIC_DBG (1, "failed to allocate fifos");
1313       session_free (app_session);
1314       return rv;
1315     }
1316   ctx->c_quic_ctx_id.app_session = session_handle (app_session);
1317   ctx->c_quic_ctx_id.parent_app_id = lctx->c_quic_ctx_id.parent_app_id;
1318   ctx->c_quic_ctx_id.udp_is_ip4 = lctx->c_quic_ctx_id.udp_is_ip4;
1319   ctx->c_quic_ctx_id.parent_app_wrk_idx = app_session->app_wrk_index;
1320   session_lookup_add_connection (&ctx->connection,
1321                                  session_handle (app_session));
1322   app_wrk = app_worker_get (app_session->app_wrk_index);
1323   rv = app_worker_accept_notify (app_wrk, app_session);
1324   if (rv)
1325     {
1326       QUIC_DBG (1, "failed to notify accept worker app");
1327       return rv;
1328     }
1329   return 0;
1330 }
1331
1332 static int
1333 quic_create_connection (quicly_context_t * quicly_ctx,
1334                         u64 quic_session_handle, u32 lctx_index,
1335                         quicly_conn_t * conn, struct sockaddr *sa,
1336                         socklen_t salen, quicly_decoded_packet_t packet)
1337 {
1338   quic_ctx_t *ctx;
1339   u32 ctx_index;
1340
1341   /* new connection, accept and create context if packet is valid */
1342   // TODO: check if socket is actually listening?
1343   QUIC_DBG (2, "New connection created");
1344   if (quicly_accept (&conn, quicly_ctx, sa, salen,
1345                      &packet, ptls_iovec_init (NULL, 0),
1346                      &quic_main.next_cid, NULL) != 0)
1347     {
1348       // Invalid packet, pass
1349       assert (conn == NULL);
1350       QUIC_DBG (2, "Accept failed");
1351       return 0;
1352     }
1353   assert (conn != NULL);
1354
1355   ++quic_main.next_cid.master_id;
1356   // Create context
1357   ctx_index = quic_ctx_alloc ();
1358   ctx = quic_ctx_get (ctx_index);
1359   // Save ctx handle in quicly connection
1360   *quicly_get_data (conn) = (void *) (u64) ctx_index;
1361
1362   ctx->c_thread_index = vlib_get_thread_index ();
1363   ctx->c_c_index = ctx_index;
1364   ctx->c_quic_ctx_id.quic_session = quic_session_handle;
1365   ctx->c_quic_ctx_id.listener_ctx_id = lctx_index;
1366   ctx->c_quic_ctx_id.timer_handle = QUIC_TIMER_HANDLE_INVALID;
1367   ctx->c_quic_ctx_id.conn = conn;
1368
1369   session_send_rpc_evt_to_thread_force (vlib_get_thread_index (),
1370                                         &quic_delayed_create_app_session,
1371                                         (void *) (u64) ctx_index);
1372   if (quic_send_packets (ctx))
1373     {
1374       quic_connection_closed (ctx_index);
1375     }
1376   return 0;
1377 }
1378
1379 static int
1380 quic_reset_connection (quicly_context_t * quicly_ctx, u64 quic_session_handle,
1381                        struct sockaddr *sa, socklen_t salen,
1382                        quicly_decoded_packet_t packet)
1383 {
1384   /* short header packet; potentially a dead connection. No need to check the length of the incoming packet,
1385    * because loop is prevented by authenticating the CID (by checking node_id and thread_id). If the peer is also
1386    * sending a reset, then the next CID is highly likely to contain a non-authenticating CID, ... */
1387   QUIC_DBG (2, "Sending stateless reset");
1388   quicly_datagram_t *dgram;
1389   session_t *quic_session;
1390   if (packet.cid.dest.plaintext.node_id == 0
1391       && packet.cid.dest.plaintext.thread_id == 0)
1392     {
1393       dgram = quicly_send_stateless_reset (quicly_ctx, sa, salen,
1394                                            &packet.cid.dest.plaintext);
1395       quic_session = session_get_from_handle (quic_session_handle);
1396       if (quic_send_datagram (quic_session, dgram))     // TODO : missing event on fifo
1397         QUIC_DBG (2, "Send reset failed");
1398     }
1399   return 0;
1400 }
1401
1402 int
1403 quic_app_rx_callback (session_t * quic_session)
1404 {
1405   // Read data from UDP rx_fifo and pass it to the quicly conn.
1406   QUIC_DBG (2, "Called quic_app_rx_callback");
1407
1408   quicly_decoded_packet_t packet;
1409   session_dgram_hdr_t ph;
1410   application_t *app;
1411   quicly_conn_t *conn = NULL;
1412   quic_ctx_t *lctx, *ctx = NULL;
1413   svm_fifo_t *f;
1414   size_t plen;
1415   struct sockaddr_in6 sa6;
1416   struct sockaddr *sa = (struct sockaddr *) &sa6;
1417   socklen_t salen;
1418   u32 max_deq, len;
1419   u8 *data;
1420   u32 lctx_index = quic_session->opaque;
1421   u64 quic_session_handle = session_handle (quic_session);
1422
1423   f = quic_session->rx_fifo;
1424
1425   do
1426     {
1427       conn = NULL;
1428       max_deq = svm_fifo_max_dequeue (f);
1429       if (max_deq < sizeof (session_dgram_hdr_t))
1430         {
1431           svm_fifo_unset_event (f);
1432           return 0;
1433         }
1434       QUIC_DBG (2, "Processing one packet at %ld", quic_get_time (NULL));
1435
1436       svm_fifo_unset_event (f);
1437       svm_fifo_peek (f, 0, sizeof (ph), (u8 *) & ph);
1438       ASSERT (ph.data_length >= ph.data_offset);
1439       len = ph.data_length - ph.data_offset;
1440
1441       quic_build_sockaddr (sa, &salen, &ph.rmt_ip, ph.rmt_port, ph.is_ip4);
1442
1443       // Quicly can read len bytes from the fifo at offset:
1444       // ph.data_offset + SESSION_CONN_HDR_LEN
1445       data = svm_fifo_head (f) + ph.data_offset + SESSION_CONN_HDR_LEN;
1446
1447       lctx = quic_ctx_get (lctx_index);
1448       app = application_get (lctx->c_quic_ctx_id.parent_app_id);
1449
1450       plen =
1451         quicly_decode_packet ((quicly_context_t *) app->quicly_ctx, &packet,
1452                               data, len);
1453       if (plen != SIZE_MAX)
1454         {
1455           quic_find_packet_ctx (&ctx, &conn, sa, salen, packet);
1456           if (conn != NULL)
1457             quic_receive (ctx, conn, packet);
1458           else if (QUICLY_PACKET_IS_LONG_HEADER (packet.octets.base[0]))
1459             quic_create_connection ((quicly_context_t *) app->quicly_ctx,
1460                                     quic_session_handle, lctx_index, conn,
1461                                     sa, salen, packet);
1462           else if (((quicly_context_t *) app->quicly_ctx)->encrypt_cid)
1463             quic_reset_connection ((quicly_context_t *) app->quicly_ctx,
1464                                    quic_session_handle, sa, salen, packet);
1465         }
1466       svm_fifo_dequeue_drop (f,
1467                              ph.data_length + ph.data_offset +
1468                              SESSION_CONN_HDR_LEN);
1469     }
1470   while (1);
1471   return 0;
1472 }
1473
1474 /*****************************************************************************
1475  * END TRANSPORT PROTO FUNCTIONS
1476 *****************************************************************************/
1477
1478 /* *INDENT-OFF* */
1479 static session_cb_vft_t quic_app_cb_vft = {
1480   .session_accept_callback = NULL,
1481   .session_disconnect_callback = quic_session_disconnect_callback,
1482   .session_connected_callback = quic_session_connected_callback,
1483   .session_reset_callback = quic_session_reset_callback,
1484   .add_segment_callback = quic_add_segment_callback,
1485   .del_segment_callback = quic_del_segment_callback,
1486   .builtin_app_rx_callback = quic_app_rx_callback,
1487 };
1488
1489 const static transport_proto_vft_t quic_proto = {
1490   .connect = quic_connect,
1491   .close = quic_disconnect,
1492   .start_listen = quic_start_listen,
1493   .stop_listen = quic_stop_listen,
1494   .get_connection = quic_connection_get,
1495   .get_listener = quic_listener_get,
1496   .update_time = quic_update_time,
1497   .custom_tx = quic_custom_tx_callback,
1498   .tx_type = TRANSPORT_TX_INTERNAL,
1499   .service_type = TRANSPORT_SERVICE_APP,
1500   .format_connection = format_quic_connection,
1501   .format_half_open = format_quic_half_open,
1502   .format_listener = format_quic_listener,
1503 };
1504 /* *INDENT-ON* */
1505
1506 static clib_error_t *
1507 quic_init (vlib_main_t * vm)
1508 {
1509   QUIC_DBG (2, "Called quic_init");
1510   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1511   vnet_app_attach_args_t _a, *a = &_a;
1512   u64 options[APP_OPTIONS_N_OPTIONS];
1513   u32 segment_size = 512 << 20;
1514   quic_main_t *qm = &quic_main;
1515   u32 fifo_size = 64 << 10;
1516   u32 num_threads;
1517
1518   num_threads = 1 /* main thread */  + vtm->n_threads;
1519
1520   memset (a, 0, sizeof (*a));
1521   memset (options, 0, sizeof (options));
1522
1523   a->session_cb_vft = &quic_app_cb_vft;
1524   a->api_client_index = APP_INVALID_INDEX;
1525   a->options = options;
1526   a->name = format (0, "quic");
1527   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
1528   a->options[APP_OPTIONS_RX_FIFO_SIZE] = fifo_size;
1529   a->options[APP_OPTIONS_TX_FIFO_SIZE] = fifo_size;
1530   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1531   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1532   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
1533
1534   if (vnet_application_attach (a))
1535     {
1536       clib_warning ("failed to attach quic app");
1537       return clib_error_return (0, "failed to attach quic app");
1538     }
1539
1540   vec_validate (qm->ctx_pool, num_threads - 1);
1541   vec_validate (qm->wrk_ctx, num_threads - 1);
1542   // Timers, one per thread.
1543   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
1544   /* *INDENT-OFF* */
1545   foreach_vlib_main (({
1546     tw = &qm->wrk_ctx[ii].timer_wheel;
1547     tw_timer_wheel_init_1t_3w_1024sl_ov (tw, quic_expired_timers_dispatch,
1548                                          10e-3 /* timer period 1ms */ , ~0);
1549     tw->last_run_time = vlib_time_now (this_vlib_main);
1550   }));
1551   /* *INDENT-ON* */
1552
1553   if (!qm->ca_cert_path)
1554     qm->ca_cert_path = QUIC_DEFAULT_CA_CERT_PATH;
1555
1556   qm->app_index = a->app_index;
1557   clib_rwlock_init (&qm->half_open_rwlock);
1558   qm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
1559     / QUIC_TSTAMP_RESOLUTION;
1560
1561   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
1562                                FIB_PROTOCOL_IP4, ~0);
1563   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
1564                                FIB_PROTOCOL_IP6, ~0);
1565
1566   vec_free (a->name);
1567   return 0;
1568 }
1569
1570 quic_main_t *
1571 vnet_quic_get_main (void)
1572 {
1573   return &quic_main;
1574 }
1575
1576 VLIB_INIT_FUNCTION (quic_init);
1577
1578 /* *INDENT-OFF* */
1579 VLIB_PLUGIN_REGISTER () =
1580 {
1581   .version = VPP_BUILD_VER,
1582   .description = "Quic transport protocol",
1583 };
1584 /* *INDENT-ON* */
1585
1586 /*
1587  * fd.io coding-style-patch-verification: ON
1588  *
1589  * Local Variables:
1590  * eval: (c-set-style "gnu")
1591  * End:
1592  */