session: use app cb function wrappers
[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       u32 api_context;
1072       int rv = 0;
1073
1074       app_wrk =
1075         app_worker_get_if_valid (ho_ctx->c_quic_ctx_id.parent_app_wrk_idx);
1076       if (app_wrk)
1077         {
1078           api_context = ho_ctx->c_s_index;
1079           app_worker_connect_notify (app_wrk, 0, api_context);
1080         }
1081       quic_ctx_half_open_reader_unlock ();
1082       quic_ctx_half_open_free (ho_ctx_idx);
1083       return rv;
1084     }
1085
1086   app_wrk =
1087     app_worker_get_if_valid (ho_ctx->c_quic_ctx_id.parent_app_wrk_idx);
1088   if (!app_wrk)
1089     {
1090       QUIC_DBG (1, "Appwrk not found");
1091       return -1;
1092     }
1093   app = application_get (app_wrk->app_index);
1094
1095   ctx_index = quic_ctx_alloc ();
1096   ctx = quic_ctx_get (ctx_index);
1097   clib_memcpy (ctx, ho_ctx, sizeof (*ctx));
1098   quic_ctx_half_open_reader_unlock ();  // TODO: this is a race
1099   quic_ctx_half_open_free (ho_ctx_idx);
1100
1101   ctx->c_thread_index = vlib_get_thread_index ();
1102   ctx->c_c_index = ctx_index;
1103
1104   QUIC_DBG (1, "Quic connect for returned %u. New connection [%u]%x",
1105             is_fail, vlib_get_thread_index (), (ctx) ? ctx_index : ~0);
1106
1107   ctx->c_quic_ctx_id.quic_session = session_handle (s);
1108   s->opaque = ctx_index;
1109   s->session_state = SESSION_STATE_READY;
1110
1111   // Init QUIC lib connection
1112   // Generate required sockaddr & salen
1113   tc = session_get_transport (s);
1114   quic_build_sockaddr (sa, &salen, &tc->rmt_ip, tc->rmt_port, tc->is_ip4);
1115
1116   ret =
1117     quicly_connect (&ctx->c_quic_ctx_id.conn,
1118                     (quicly_context_t *) app->quicly_ctx,
1119                     (char *) ctx->srv_hostname, sa, salen,
1120                     &quic_main.next_cid, &quic_main.hs_properties, NULL);
1121   ++quic_main.next_cid.master_id;
1122   // Save context handle in quicly connection
1123   *quicly_get_data (ctx->c_quic_ctx_id.conn) = (void *) (u64) ctx_index;
1124   assert (ret == 0);
1125
1126   if (quic_send_packets (ctx))
1127     {
1128       quic_connection_closed (ctx_index);
1129     }
1130   return ret;
1131 }
1132
1133 void
1134 quic_session_disconnect_callback (session_t * s)
1135 {
1136   clib_warning ("UDP session disconnected???");
1137 }
1138
1139 void
1140 quic_session_reset_callback (session_t * s)
1141 {
1142   clib_warning ("UDP session reset???");
1143 }
1144
1145 static int
1146 quic_add_segment_callback (u32 client_index, u64 seg_handle)
1147 {
1148   QUIC_DBG (2, "Called quic_add_segment_callback");
1149   QUIC_DBG (2, "NOT IMPLEMENTED");
1150   /* No-op for builtin */
1151   return 0;
1152 }
1153
1154 static int
1155 quic_del_segment_callback (u32 client_index, u64 seg_handle)
1156 {
1157   QUIC_DBG (2, "Called quic_del_segment_callback");
1158   QUIC_DBG (2, "NOT IMPLEMENTED");
1159   /* No-op for builtin */
1160   return 0;
1161 }
1162
1163 int
1164 quic_add_vpp_q_builtin_tx_evt (session_t * s)
1165 {
1166   if (svm_fifo_set_event (s->tx_fifo))
1167     session_send_io_evt_to_thread_custom (s, s->thread_index,
1168                                           FIFO_EVENT_BUILTIN_TX);
1169   return 0;
1170 }
1171
1172 void
1173 quic_open_stream_if_ready (quic_ctx_t * ctx)
1174 {
1175   quicly_conn_t *conn = ctx->c_quic_ctx_id.conn;
1176   if (ctx->stream)
1177     {
1178       QUIC_DBG (2, "----------- > FOUND Stream id %d",
1179                 ctx->stream->stream_id);
1180       QUIC_DBG (2, "----------- > FOUND Stream is_open %d",
1181                 ctx->stream->sendstate.is_open);
1182       return;
1183     }
1184   if (quicly_connection_is_ready (conn))
1185     assert (!quicly_open_stream (conn, &ctx->stream, 0));
1186   QUIC_DBG (2, "Stream id %d", ctx->stream->stream_id);
1187   QUIC_DBG (2, "Stream is_open %d", ctx->stream->sendstate.is_open);
1188 }
1189
1190 int
1191 quic_custom_tx_callback (void *session)
1192 {
1193   QUIC_DBG (2, "Called quic_custom_tx_callback");
1194   session_t *app_session = (session_t *) session;
1195   quic_ctx_t *ctx;
1196   svm_fifo_t *f;
1197   u32 deq_max;
1198   u8 *data;
1199
1200   if (PREDICT_FALSE
1201       (app_session->session_state >= SESSION_STATE_TRANSPORT_CLOSING))
1202     return 0;
1203   ctx = quic_ctx_get (app_session->connection_index);
1204   quic_open_stream_if_ready (ctx);
1205   if (!ctx->stream)
1206     {
1207       quic_add_vpp_q_builtin_tx_evt (app_session);
1208       return 0;
1209     }
1210
1211   f = app_session->tx_fifo;
1212   deq_max = svm_fifo_max_dequeue (f);
1213   if (!deq_max)
1214     return 0;
1215
1216   data = svm_fifo_head (f);
1217   if (quicly_streambuf_egress_write (ctx->stream, data, deq_max))
1218     {
1219       assert (0);
1220       return 0;
1221     }
1222   QUIC_DBG (2, "Sent %u bytes", deq_max);
1223   svm_fifo_dequeue_drop (f, deq_max);
1224   if (quic_send_packets (ctx))
1225     {
1226       quic_connection_closed (ctx->c_c_index);
1227     }
1228   return 0;
1229 }
1230
1231 int
1232 quic_find_packet_ctx (quic_ctx_t ** ctx, quicly_conn_t ** conn,
1233                       struct sockaddr *sa, socklen_t salen,
1234                       quicly_decoded_packet_t packet)
1235 {
1236   quic_ctx_t *ctx_;
1237   quicly_conn_t *conn_;
1238   /* *INDENT-OFF* */
1239   pool_foreach (ctx_, quic_main.ctx_pool[vlib_get_thread_index()],
1240   ({
1241     conn_ = ctx_->c_quic_ctx_id.conn;
1242     if (conn_ && !ctx_->is_listener)
1243       {
1244         if (quicly_is_destination(conn_, sa, salen, &packet))
1245           {
1246             *conn = conn_;
1247             *ctx = ctx_;
1248             QUIC_DBG (2, "connection_found");
1249             return 0;
1250           }
1251       }
1252   }));
1253   /* *INDENT-ON* */
1254   return 0;
1255 }
1256
1257 static int
1258 quic_receive (quic_ctx_t * ctx, quicly_conn_t * conn,
1259               quicly_decoded_packet_t packet)
1260 {
1261   quicly_receive (conn, &packet);
1262   // Conn may be set to null if the connection is terminated
1263   if (ctx->c_quic_ctx_id.conn
1264       && ctx->c_quic_ctx_id.conn_state == QUIC_CONN_STATE_HANDSHAKE)
1265     {
1266       if (quicly_connection_is_ready (conn))
1267         {
1268           ctx->c_quic_ctx_id.conn_state = QUIC_CONN_STATE_READY;
1269           if (quicly_is_client (conn))
1270             session_send_rpc_evt_to_thread_force (vlib_get_thread_index (),
1271                                                   &quic_delayed_notify_app_connected,
1272                                                   (void *) (u64)
1273                                                   ctx->c_c_index);
1274         }
1275     }
1276   if (quic_send_packets (ctx))
1277     {
1278       quic_connection_closed (ctx->c_c_index);
1279     }
1280   return 0;
1281 }
1282
1283 static int
1284 quic_delayed_create_app_session (void *ctx_index)
1285 {
1286   quic_ctx_t *lctx, *ctx;
1287   session_t *app_session, *app_listen_session;
1288   app_worker_t *app_wrk;
1289   int rv;
1290
1291   ctx = quic_ctx_get ((u32) (u64) ctx_index);
1292   app_session = session_alloc (ctx->c_thread_index);
1293   app_session->session_state = SESSION_STATE_LISTENING;
1294   ctx->c_s_index = app_session->session_index;
1295
1296   lctx = quic_ctx_get (ctx->c_quic_ctx_id.listener_ctx_id);
1297
1298   app_listen_session =
1299     listen_session_get_from_handle (lctx->c_quic_ctx_id.app_session);
1300   app_session->app_wrk_index = lctx->c_quic_ctx_id.parent_app_wrk_idx;
1301   app_session->connection_index = ctx->c_c_index;
1302   app_session->session_type = app_listen_session->session_type;
1303   app_session->listener_index = app_listen_session->session_index;
1304   app_session->app_index = quic_main.app_index;
1305
1306   // TODO: don't alloc fifos when we don't transfer data on this session
1307   if ((rv = app_worker_init_accepted (app_session)))
1308     {
1309       QUIC_DBG (1, "failed to allocate fifos");
1310       session_free (app_session);
1311       return rv;
1312     }
1313   ctx->c_quic_ctx_id.app_session = session_handle (app_session);
1314   ctx->c_quic_ctx_id.parent_app_id = lctx->c_quic_ctx_id.parent_app_id;
1315   ctx->c_quic_ctx_id.udp_is_ip4 = lctx->c_quic_ctx_id.udp_is_ip4;
1316   ctx->c_quic_ctx_id.parent_app_wrk_idx = app_session->app_wrk_index;
1317   session_lookup_add_connection (&ctx->connection,
1318                                  session_handle (app_session));
1319   app_wrk = app_worker_get (app_session->app_wrk_index);
1320   rv = app_worker_accept_notify (app_wrk, app_session);
1321   if (rv)
1322     {
1323       QUIC_DBG (1, "failed to notify accept worker app");
1324       return rv;
1325     }
1326   return 0;
1327 }
1328
1329 static int
1330 quic_create_connection (quicly_context_t * quicly_ctx,
1331                         u64 quic_session_handle, u32 lctx_index,
1332                         quicly_conn_t * conn, struct sockaddr *sa,
1333                         socklen_t salen, quicly_decoded_packet_t packet)
1334 {
1335   quic_ctx_t *ctx;
1336   u32 ctx_index;
1337
1338   /* new connection, accept and create context if packet is valid */
1339   // TODO: check if socket is actually listening?
1340   QUIC_DBG (2, "New connection created");
1341   if (quicly_accept (&conn, quicly_ctx, sa, salen,
1342                      &packet, ptls_iovec_init (NULL, 0),
1343                      &quic_main.next_cid, NULL) != 0)
1344     {
1345       // Invalid packet, pass
1346       assert (conn == NULL);
1347       QUIC_DBG (2, "Accept failed");
1348       return 0;
1349     }
1350   assert (conn != NULL);
1351
1352   ++quic_main.next_cid.master_id;
1353   // Create context
1354   ctx_index = quic_ctx_alloc ();
1355   ctx = quic_ctx_get (ctx_index);
1356   // Save ctx handle in quicly connection
1357   *quicly_get_data (conn) = (void *) (u64) ctx_index;
1358
1359   ctx->c_thread_index = vlib_get_thread_index ();
1360   ctx->c_c_index = ctx_index;
1361   ctx->c_quic_ctx_id.quic_session = quic_session_handle;
1362   ctx->c_quic_ctx_id.listener_ctx_id = lctx_index;
1363   ctx->c_quic_ctx_id.timer_handle = QUIC_TIMER_HANDLE_INVALID;
1364   ctx->c_quic_ctx_id.conn = conn;
1365
1366   session_send_rpc_evt_to_thread_force (vlib_get_thread_index (),
1367                                         &quic_delayed_create_app_session,
1368                                         (void *) (u64) ctx_index);
1369   if (quic_send_packets (ctx))
1370     {
1371       quic_connection_closed (ctx_index);
1372     }
1373   return 0;
1374 }
1375
1376 static int
1377 quic_reset_connection (quicly_context_t * quicly_ctx, u64 quic_session_handle,
1378                        struct sockaddr *sa, socklen_t salen,
1379                        quicly_decoded_packet_t packet)
1380 {
1381   /* short header packet; potentially a dead connection. No need to check the length of the incoming packet,
1382    * because loop is prevented by authenticating the CID (by checking node_id and thread_id). If the peer is also
1383    * sending a reset, then the next CID is highly likely to contain a non-authenticating CID, ... */
1384   QUIC_DBG (2, "Sending stateless reset");
1385   quicly_datagram_t *dgram;
1386   session_t *quic_session;
1387   if (packet.cid.dest.plaintext.node_id == 0
1388       && packet.cid.dest.plaintext.thread_id == 0)
1389     {
1390       dgram = quicly_send_stateless_reset (quicly_ctx, sa, salen,
1391                                            &packet.cid.dest.plaintext);
1392       quic_session = session_get_from_handle (quic_session_handle);
1393       if (quic_send_datagram (quic_session, dgram))     // TODO : missing event on fifo
1394         QUIC_DBG (2, "Send reset failed");
1395     }
1396   return 0;
1397 }
1398
1399 int
1400 quic_app_rx_callback (session_t * quic_session)
1401 {
1402   // Read data from UDP rx_fifo and pass it to the quicly conn.
1403   QUIC_DBG (2, "Called quic_app_rx_callback");
1404
1405   quicly_decoded_packet_t packet;
1406   session_dgram_hdr_t ph;
1407   application_t *app;
1408   quicly_conn_t *conn = NULL;
1409   quic_ctx_t *lctx, *ctx = NULL;
1410   svm_fifo_t *f;
1411   size_t plen;
1412   struct sockaddr_in6 sa6;
1413   struct sockaddr *sa = (struct sockaddr *) &sa6;
1414   socklen_t salen;
1415   u32 max_deq, len;
1416   u8 *data;
1417   u32 lctx_index = quic_session->opaque;
1418   u64 quic_session_handle = session_handle (quic_session);
1419
1420   f = quic_session->rx_fifo;
1421
1422   do
1423     {
1424       conn = NULL;
1425       max_deq = svm_fifo_max_dequeue (f);
1426       if (max_deq < sizeof (session_dgram_hdr_t))
1427         {
1428           svm_fifo_unset_event (f);
1429           return 0;
1430         }
1431       QUIC_DBG (2, "Processing one packet at %ld", quic_get_time (NULL));
1432
1433       svm_fifo_unset_event (f);
1434       svm_fifo_peek (f, 0, sizeof (ph), (u8 *) & ph);
1435       ASSERT (ph.data_length >= ph.data_offset);
1436       len = ph.data_length - ph.data_offset;
1437
1438       quic_build_sockaddr (sa, &salen, &ph.rmt_ip, ph.rmt_port, ph.is_ip4);
1439
1440       // Quicly can read len bytes from the fifo at offset:
1441       // ph.data_offset + SESSION_CONN_HDR_LEN
1442       data = svm_fifo_head (f) + ph.data_offset + SESSION_CONN_HDR_LEN;
1443
1444       lctx = quic_ctx_get (lctx_index);
1445       app = application_get (lctx->c_quic_ctx_id.parent_app_id);
1446
1447       plen =
1448         quicly_decode_packet ((quicly_context_t *) app->quicly_ctx, &packet,
1449                               data, len);
1450       if (plen != SIZE_MAX)
1451         {
1452           quic_find_packet_ctx (&ctx, &conn, sa, salen, packet);
1453           if (conn != NULL)
1454             quic_receive (ctx, conn, packet);
1455           else if (QUICLY_PACKET_IS_LONG_HEADER (packet.octets.base[0]))
1456             quic_create_connection ((quicly_context_t *) app->quicly_ctx,
1457                                     quic_session_handle, lctx_index, conn,
1458                                     sa, salen, packet);
1459           else if (((quicly_context_t *) app->quicly_ctx)->encrypt_cid)
1460             quic_reset_connection ((quicly_context_t *) app->quicly_ctx,
1461                                    quic_session_handle, sa, salen, packet);
1462         }
1463       svm_fifo_dequeue_drop (f,
1464                              ph.data_length + ph.data_offset +
1465                              SESSION_CONN_HDR_LEN);
1466     }
1467   while (1);
1468   return 0;
1469 }
1470
1471 /*****************************************************************************
1472  * END TRANSPORT PROTO FUNCTIONS
1473 *****************************************************************************/
1474
1475 /* *INDENT-OFF* */
1476 static session_cb_vft_t quic_app_cb_vft = {
1477   .session_accept_callback = NULL,
1478   .session_disconnect_callback = quic_session_disconnect_callback,
1479   .session_connected_callback = quic_session_connected_callback,
1480   .session_reset_callback = quic_session_reset_callback,
1481   .add_segment_callback = quic_add_segment_callback,
1482   .del_segment_callback = quic_del_segment_callback,
1483   .builtin_app_rx_callback = quic_app_rx_callback,
1484 };
1485
1486 const static transport_proto_vft_t quic_proto = {
1487   .connect = quic_connect,
1488   .close = quic_disconnect,
1489   .start_listen = quic_start_listen,
1490   .stop_listen = quic_stop_listen,
1491   .get_connection = quic_connection_get,
1492   .get_listener = quic_listener_get,
1493   .update_time = quic_update_time,
1494   .custom_tx = quic_custom_tx_callback,
1495   .tx_type = TRANSPORT_TX_INTERNAL,
1496   .service_type = TRANSPORT_SERVICE_APP,
1497   .format_connection = format_quic_connection,
1498   .format_half_open = format_quic_half_open,
1499   .format_listener = format_quic_listener,
1500 };
1501 /* *INDENT-ON* */
1502
1503 static clib_error_t *
1504 quic_init (vlib_main_t * vm)
1505 {
1506   QUIC_DBG (2, "Called quic_init");
1507   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1508   vnet_app_attach_args_t _a, *a = &_a;
1509   u64 options[APP_OPTIONS_N_OPTIONS];
1510   u32 segment_size = 512 << 20;
1511   quic_main_t *qm = &quic_main;
1512   u32 fifo_size = 64 << 10;
1513   u32 num_threads;
1514
1515   num_threads = 1 /* main thread */  + vtm->n_threads;
1516
1517   memset (a, 0, sizeof (*a));
1518   memset (options, 0, sizeof (options));
1519
1520   a->session_cb_vft = &quic_app_cb_vft;
1521   a->api_client_index = APP_INVALID_INDEX;
1522   a->options = options;
1523   a->name = format (0, "quic");
1524   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
1525   a->options[APP_OPTIONS_RX_FIFO_SIZE] = fifo_size;
1526   a->options[APP_OPTIONS_TX_FIFO_SIZE] = fifo_size;
1527   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1528   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1529   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
1530
1531   if (vnet_application_attach (a))
1532     {
1533       clib_warning ("failed to attach quic app");
1534       return clib_error_return (0, "failed to attach quic app");
1535     }
1536
1537   vec_validate (qm->ctx_pool, num_threads - 1);
1538   vec_validate (qm->wrk_ctx, num_threads - 1);
1539   // Timers, one per thread.
1540   tw_timer_wheel_1t_3w_1024sl_ov_t *tw;
1541   /* *INDENT-OFF* */
1542   foreach_vlib_main (({
1543     tw = &qm->wrk_ctx[ii].timer_wheel;
1544     tw_timer_wheel_init_1t_3w_1024sl_ov (tw, quic_expired_timers_dispatch,
1545                                          10e-3 /* timer period 1ms */ , ~0);
1546     tw->last_run_time = vlib_time_now (this_vlib_main);
1547   }));
1548   /* *INDENT-ON* */
1549
1550   if (!qm->ca_cert_path)
1551     qm->ca_cert_path = QUIC_DEFAULT_CA_CERT_PATH;
1552
1553   qm->app_index = a->app_index;
1554   clib_rwlock_init (&qm->half_open_rwlock);
1555   qm->tstamp_ticks_per_clock = vm->clib_time.seconds_per_clock
1556     / QUIC_TSTAMP_RESOLUTION;
1557
1558   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
1559                                FIB_PROTOCOL_IP4, ~0);
1560   transport_register_protocol (TRANSPORT_PROTO_QUIC, &quic_proto,
1561                                FIB_PROTOCOL_IP6, ~0);
1562
1563   vec_free (a->name);
1564   return 0;
1565 }
1566
1567 quic_main_t *
1568 vnet_quic_get_main (void)
1569 {
1570   return &quic_main;
1571 }
1572
1573 VLIB_INIT_FUNCTION (quic_init);
1574
1575 /* *INDENT-OFF* */
1576 VLIB_PLUGIN_REGISTER () =
1577 {
1578   .version = VPP_BUILD_VER,
1579   .description = "Quic transport protocol",
1580 };
1581 /* *INDENT-ON* */
1582
1583 /*
1584  * fd.io coding-style-patch-verification: ON
1585  *
1586  * Local Variables:
1587  * eval: (c-set-style "gnu")
1588  * End:
1589  */