aboutsummaryrefslogtreecommitdiff
path: root/lib/vquic/ngtcp2.c
blob: fe8fe8ced67d7f0323fc8731bef4c03526bbf62d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel@haxx.se>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at https://curl.haxx.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ***************************************************************************/

#include "curl_setup.h"

#ifdef USE_NGTCP2
#include <ngtcp2/ngtcp2.h>
#include <nghttp3/nghttp3.h>
#include <openssl/err.h>
#include "urldata.h"
#include "sendf.h"
#include "strdup.h"
#include "rand.h"
#include "ngtcp2.h"
#include "ngtcp2-crypto.h"
#include "multiif.h"
#include "strcase.h"
#include "connect.h"
#include "strerror.h"

/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"

/* #define DEBUG_NGTCP2 1 */
#define DEBUG_HTTP3
#ifdef DEBUG_HTTP3
#define H3BUGF(x) x
#else
#define H3BUGF(x) do { } WHILE_FALSE
#endif

#define QUIC_MAX_STREAMS (256*1024)
#define QUIC_MAX_DATA (1*1024*1024)
#define QUIC_IDLE_TIMEOUT 60000 /* milliseconds */
#define QUIC_CIPHERS                                                          \
  "TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_"               \
  "POLY1305_SHA256:TLS_AES_128_CCM_SHA256"
#define QUIC_GROUPS "P-256:X25519:P-384:P-521"

static CURLcode process_ingress(struct connectdata *conn,
                                curl_socket_t sockfd);
static CURLcode flush_egress(struct connectdata *conn, int sockfd);

static ngtcp2_tstamp timestamp(void)
{
  struct curltime ct = Curl_now();
  return ct.tv_sec * NGTCP2_SECONDS + ct.tv_usec * NGTCP2_MICROSECONDS;
}

#ifdef DEBUG_NGTCP2
static void quic_printf(void *user_data, const char *fmt, ...)
{
  va_list ap;
  (void)user_data; /* TODO, use this to do infof() instead long-term */
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
  fprintf(stderr, "\n");
}
#endif

static int setup_initial_crypto_context(struct connectdata *conn)
{
  int rv;
  uint8_t initial_secret[32];
  uint8_t secret[32];
  const ngtcp2_cid *dcid;
  uint8_t key[16];
  ssize_t keylen;
  uint8_t iv[16];
  ssize_t ivlen;
  uint8_t hp[16];
  ssize_t hplen;

  dcid = ngtcp2_conn_get_dcid(conn->quic.conn);
  rv = Curl_qc_derive_initial_secret(initial_secret, sizeof(initial_secret),
                                     dcid, (uint8_t *)NGTCP2_INITIAL_SALT,
                                     strlen(NGTCP2_INITIAL_SALT));
  if(rv) {
    return -1;
  }

  Curl_qc_prf_sha256(&conn->quic.hs_crypto_ctx);
  Curl_qc_aead_aes_128_gcm(&conn->quic.hs_crypto_ctx);

  rv = Curl_qc_derive_client_initial_secret(secret, sizeof(secret),
                                            initial_secret,
                                            sizeof(initial_secret));
  if(rv) {
    return -1;
  }

  keylen = Curl_qc_derive_packet_protection_key(key, sizeof(key),
                                                secret, sizeof(secret),
                                                &conn->quic.hs_crypto_ctx);
  if(keylen < 0) {
    return -1;
  }

  ivlen = Curl_qc_derive_packet_protection_iv(iv, sizeof(iv),
                                              secret, sizeof(secret),
                                              &conn->quic.hs_crypto_ctx);
  if(ivlen < 0) {
    return -1;
  }

  hplen = Curl_qc_derive_header_protection_key(hp, sizeof(hp),
                                               secret, sizeof(secret),
                                               &conn->quic.hs_crypto_ctx);
  if(hplen < 0) {
    return -1;
  }

  ngtcp2_conn_install_initial_tx_keys(conn->quic.conn, key, keylen, iv, ivlen,
                                      hp, hplen);

  rv = Curl_qc_derive_server_initial_secret(secret, sizeof(secret),
                                            initial_secret,
                                            sizeof(initial_secret));
  if(rv) {
    return -1;
  }

  keylen = Curl_qc_derive_packet_protection_key(key, sizeof(key),
                                                secret, sizeof(secret),
                                                &conn->quic.hs_crypto_ctx);
  if(keylen < 0) {
    return -1;
  }

  ivlen = Curl_qc_derive_packet_protection_iv(iv, sizeof(iv),
                                              secret, sizeof(secret),
                                              &conn->quic.hs_crypto_ctx);
  if(ivlen < 0) {
    return -1;
  }

  hplen = Curl_qc_derive_header_protection_key(hp, sizeof(hp),
                                               secret, sizeof(secret),
                                               &conn->quic.hs_crypto_ctx);
  if(hplen < 0) {
    return -1;
  }

  ngtcp2_conn_install_initial_rx_keys(conn->quic.conn,
                                      key, keylen, iv, ivlen, hp, hplen);

  return 0;
}

static void quic_settings(ngtcp2_settings *s)
{
  ngtcp2_settings_default(s);
#ifdef DEBUG_NGTCP2
  s->log_printf = quic_printf;
#else
  s->log_printf = NULL;
#endif
  s->initial_ts = timestamp();
  s->max_stream_data_bidi_local = QUIC_MAX_STREAMS;
  s->max_stream_data_bidi_remote = QUIC_MAX_STREAMS;
  s->max_stream_data_uni = QUIC_MAX_STREAMS;
  s->max_data = QUIC_MAX_DATA;
  s->max_streams_bidi = 1;
  s->max_streams_uni = 3;
  s->idle_timeout = QUIC_IDLE_TIMEOUT;
}

/* SSL extension functions */
static int transport_params_add_cb(SSL *ssl, unsigned int ext_type,
                                   unsigned int content,
                                   const unsigned char **out,
                                   size_t *outlen, X509 *x,
                                   size_t chainidx, int *al, void *add_arg)
{
  struct connectdata *conn = (struct connectdata *)SSL_get_app_data(ssl);
  ngtcp2_transport_params params;
  uint8_t buf[64];
  ssize_t nwrite;
  (void)ext_type;
  (void)content;
  (void)x;
  (void)chainidx;
  (void)add_arg;

  ngtcp2_conn_get_local_transport_params(conn->quic.conn, &params);

  nwrite = ngtcp2_encode_transport_params(
    buf, sizeof(buf), NGTCP2_TRANSPORT_PARAMS_TYPE_CLIENT_HELLO, &params);
  if(nwrite < 0) {
    fprintf(stderr, "ngtcp2_encode_transport_params: %s\n",
            ngtcp2_strerror((int)nwrite));
    *al = SSL_AD_INTERNAL_ERROR;
    return -1;
  }

  *out = Curl_memdup(buf, nwrite);
  *outlen = nwrite;

  return 1;
}

static void transport_params_free_cb(SSL *ssl, unsigned int ext_type,
                                     unsigned int context,
                                     const unsigned char *out,
                                     void *add_arg)
{
  (void)ssl;
  (void)ext_type;
  (void)context;
  (void)add_arg;
  free((char *)out);
}

static int transport_params_parse_cb(SSL *ssl, unsigned int ext_type,
                                     unsigned int context,
                                     const unsigned char *in,
                                     size_t inlen, X509 *x, size_t chainidx,
                                     int *al, void *parse_arg)
{
  struct connectdata *conn = (struct connectdata *)SSL_get_app_data(ssl);
  int rv;
  ngtcp2_transport_params params;
  (void)ext_type;
  (void)context;
  (void)x;
  (void)chainidx;
  (void)parse_arg;

  rv = ngtcp2_decode_transport_params(
    &params, NGTCP2_TRANSPORT_PARAMS_TYPE_ENCRYPTED_EXTENSIONS, in, inlen);
  if(rv) {
    fprintf(stderr, "ngtcp2_decode_transport_params: %s\n",
            ngtcp2_strerror(rv));
    *al = SSL_AD_ILLEGAL_PARAMETER;
    return -1;
  }

  rv = ngtcp2_conn_set_remote_transport_params(conn->quic.conn, &params);
  if(rv) {
    *al = SSL_AD_ILLEGAL_PARAMETER;
    return -1;
  }

  return 1;
}

static SSL_CTX *quic_ssl_ctx(struct Curl_easy *data)
{
  SSL_CTX *ssl_ctx = SSL_CTX_new(TLS_method());

  SSL_CTX_set_min_proto_version(ssl_ctx, TLS1_3_VERSION);
  SSL_CTX_set_max_proto_version(ssl_ctx, TLS1_3_VERSION);

  /* This makes OpenSSL client not send CCS after an initial ClientHello. */
  SSL_CTX_clear_options(ssl_ctx, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);

  SSL_CTX_set_default_verify_paths(ssl_ctx);

  if(SSL_CTX_set_ciphersuites(ssl_ctx, QUIC_CIPHERS) != 1) {
    failf(data, "SSL_CTX_set_ciphersuites: %s",
          ERR_error_string(ERR_get_error(), NULL));
    return NULL;
  }

  if(SSL_CTX_set1_groups_list(ssl_ctx, QUIC_GROUPS) != 1) {
    failf(data, "SSL_CTX_set1_groups_list failed");
    return NULL;
  }

  SSL_CTX_set_mode(ssl_ctx, SSL_MODE_QUIC_HACK);

  if(SSL_CTX_add_custom_ext(ssl_ctx,
                            NGTCP2_TLSEXT_QUIC_TRANSPORT_PARAMETERS,
                            SSL_EXT_CLIENT_HELLO |
                            SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
                            transport_params_add_cb,
                            transport_params_free_cb, NULL,
                            transport_params_parse_cb, NULL) != 1) {
    failf(data, "SSL_CTX_add_custom_ext(NGTCP2_TLSEXT_QUIC_TRANSPORT_"
          "PARAMETERS) failed: %s\n",
          ERR_error_string(ERR_get_error(), NULL));
    return NULL;
  }

  return ssl_ctx;
}

/** SSL callbacks ***/

static void set_tls_alert(struct connectdata *conn,
                          uint8_t alert)
{
  struct quicsocket *qs = &conn->quic;
  qs->tls_alert = alert;
}

static int ssl_on_key(struct connectdata *conn,
                      int name, const uint8_t *secret, size_t secretlen)
{
  int rv;
  uint8_t hp[64];
  ssize_t hplen;
  uint8_t key[64];
  ssize_t keylen;
  uint8_t iv[64];
  ssize_t ivlen;
  struct Context *crypto_ctx = &conn->quic.crypto_ctx;

  switch(name) {
  case SSL_KEY_CLIENT_EARLY_TRAFFIC:
  case SSL_KEY_CLIENT_HANDSHAKE_TRAFFIC:
  case SSL_KEY_CLIENT_APPLICATION_TRAFFIC:
  case SSL_KEY_SERVER_HANDSHAKE_TRAFFIC:
  case SSL_KEY_SERVER_APPLICATION_TRAFFIC:
    break;
  default:
    return 0;
  }

  /* TODO We don't have to call this everytime we get key generated. */
  rv = Curl_qc_negotiated_prf(crypto_ctx, conn->quic.ssl);
  if(rv != 0) {
    return -1;
  }
  rv = Curl_qc_negotiated_aead(crypto_ctx, conn->quic.ssl);
  if(rv != 0) {
    return -1;
  }

  keylen = Curl_qc_derive_packet_protection_key(key, sizeof(key), secret,
                                                secretlen, crypto_ctx);
  if(keylen < 0) {
    return -1;
  }

  ivlen = Curl_qc_derive_packet_protection_iv(iv, sizeof(iv), secret,
                                              secretlen, crypto_ctx);
  if(ivlen < 0) {
    return -1;
  }

  hplen =
    Curl_qc_derive_header_protection_key(hp, sizeof(hp),
                                         secret, secretlen, crypto_ctx);
  if(hplen < 0)
    return -1;

  /* TODO Just call this once. */
  ngtcp2_conn_set_aead_overhead(conn->quic.conn,
                                Curl_qc_aead_max_overhead(crypto_ctx));

  switch(name) {
  case SSL_KEY_CLIENT_EARLY_TRAFFIC:
    ngtcp2_conn_install_early_keys(conn->quic.conn, key, keylen, iv, ivlen,
                                   hp, hplen);
    break;
  case SSL_KEY_CLIENT_HANDSHAKE_TRAFFIC:
    ngtcp2_conn_install_handshake_tx_keys(conn->quic.conn, key, keylen,
                                          iv, ivlen, hp, hplen);
    conn->quic.tx_crypto_level = NGTCP2_CRYPTO_LEVEL_HANDSHAKE;
    break;
  case SSL_KEY_CLIENT_APPLICATION_TRAFFIC:
    ngtcp2_conn_install_tx_keys(conn->quic.conn, key, keylen, iv, ivlen,
                                hp, hplen);
    break;
  case SSL_KEY_SERVER_HANDSHAKE_TRAFFIC:
    ngtcp2_conn_install_handshake_rx_keys(conn->quic.conn, key, keylen,
                                          iv, ivlen,
                                          hp, hplen);
    conn->quic.rx_crypto_level = NGTCP2_CRYPTO_LEVEL_HANDSHAKE;
    break;
  case SSL_KEY_SERVER_APPLICATION_TRAFFIC:
    ngtcp2_conn_install_rx_keys(conn->quic.conn, key, keylen, iv, ivlen,
                                hp, hplen);
    conn->quic.rx_crypto_level = NGTCP2_CRYPTO_LEVEL_APP;
    break;
  }
  return 0;
}

static void ssl_msg_cb(int write_p, int version, int content_type,
                       const void *buf, size_t len, SSL *ssl, void *user_data)
{
  int rv;
  struct connectdata *conn = (struct connectdata *)user_data;
  uint8_t *msg = (uint8_t *)buf;
  struct quic_handshake *crypto_data;
  (void)version;
  (void)ssl;

  if(!write_p)
    return;

  switch(content_type) {
  case SSL3_RT_HANDSHAKE:
    break;
  case SSL3_RT_ALERT:
    assert(len == 2);
    if(msg[0] != 2 /* FATAL */) {
      return;
    }
    set_tls_alert(conn, msg[1]);
    return;
  default:
    return;
  }

  crypto_data = &conn->quic.client_crypto_data[conn->quic.tx_crypto_level];
  if(crypto_data->buf == NULL) {
    crypto_data->buf = malloc(4096);
    crypto_data->alloclen = 4096;
    /* TODO Explode if malloc failed */
  }

  /* TODO Just pretend that handshake does not grow more than 4KiB for
     now */
  assert(crypto_data->len + len <= crypto_data->alloclen);

  memcpy(&crypto_data->buf[crypto_data->len], buf, len);
  crypto_data->len += len;

  rv = ngtcp2_conn_submit_crypto_data(
      conn->quic.conn, conn->quic.tx_crypto_level,
      (uint8_t *)(&crypto_data->buf[crypto_data->len] - len), len);
  if(rv) {
    fprintf(stderr, "write_client_handshake failed\n");
  }
  assert(0 == rv);
}

static int ssl_key_cb(SSL *ssl, int name,
                      const unsigned char *secret,
                      size_t secretlen,
                      void *arg)
{
  struct connectdata *conn = (struct connectdata *)arg;
  (void)ssl;

  if(ssl_on_key(conn, name, secret, secretlen) != 0)
    return 0;

  /* log_secret(ssl, name, secret, secretlen); */

  return 1;
}

static int read_server_handshake(struct connectdata *conn,
                                 char *buf, int buflen)
{
  struct quic_handshake *hs = &conn->quic.handshake;
  int avail = (int)(hs->len - hs->nread);
  int n = CURLMIN(buflen, avail);
  memcpy(buf, &hs->buf[hs->nread], n);
  infof(conn->data, "read %d bytes of handshake data\n", n);
  hs->nread += n;
  return n;
}

static void write_server_handshake(struct connectdata *conn,
                                   const uint8_t *ptr, size_t datalen)
{
  char *p;
  struct quic_handshake *hs = &conn->quic.handshake;
  size_t alloclen = datalen + hs->alloclen;
  infof(conn->data, "store %zd bytes of handshake data\n", datalen);
  if(alloclen > hs->alloclen) {
    alloclen *= 2;
    p = realloc(conn->quic.handshake.buf, alloclen);
    if(!p)
      return; /* BAAAAAD */
    hs->buf = p;
    hs->alloclen = alloclen;
  }
  memcpy(&hs->buf[hs->len], ptr, datalen);
  hs->len += datalen;
}

/** BIO functions ***/

static int bio_write(BIO *b, const char *buf, int len)
{
  (void)b;
  (void)buf;
  (void)len;
  assert(0);
  return -1;
}

static int bio_read(BIO *b, char *buf, int len)
{
  struct connectdata *conn;
  BIO_clear_retry_flags(b);

  conn = (struct connectdata *)BIO_get_data(b);

  len = read_server_handshake(conn, buf, len);
  if(len == 0) {
    BIO_set_retry_read(b);
    return -1;
  }

  return len;
}

static int bio_puts(BIO *b, const char *str)
{
  return bio_write(b, str, (int)strlen(str));
}

static int bio_gets(BIO *b, char *buf, int len)
{
  (void)b;
  (void)buf;
  (void)len;
  return -1;
}

static long bio_ctrl(BIO *b, int cmd, long num, void *ptr)
{
  (void)b;
  (void)cmd;
  (void)num;
  (void)ptr;
  switch(cmd) {
  case BIO_CTRL_FLUSH:
    return 1;
  }

  return 0;
}

static int bio_create(BIO *b)
{
  BIO_set_init(b, 1);
  return 1;
}

static int bio_destroy(BIO *b)
{
  if(!b)
    return 0;

  return 1;
}

static BIO_METHOD *create_bio_method(void)
{
  BIO_METHOD *meth = BIO_meth_new(BIO_TYPE_FD, "bio");
  BIO_meth_set_write(meth, bio_write);
  BIO_meth_set_read(meth, bio_read);
  BIO_meth_set_puts(meth, bio_puts);
  BIO_meth_set_gets(meth, bio_gets);
  BIO_meth_set_ctrl(meth, bio_ctrl);
  BIO_meth_set_create(meth, bio_create);
  BIO_meth_set_destroy(meth, bio_destroy);
  return meth;
}


static int quic_init_ssl(struct connectdata *conn)
{
  struct quicsocket *qs = &conn->quic;
  BIO *bio;
  const uint8_t *alpn = NULL;
  size_t alpnlen = 0;
  /* this will need some attention when HTTPS proxy over QUIC get fixed */
  const char * const hostname = conn->host.name;

  if(qs->ssl)
    SSL_free(qs->ssl);

  qs->ssl = SSL_new(qs->sslctx);
  bio = BIO_new(create_bio_method());
  /* supposedly this can fail too? */

  BIO_set_data(bio, conn);
  SSL_set_bio(qs->ssl, bio, bio);
  SSL_set_app_data(qs->ssl, conn);
  SSL_set_connect_state(qs->ssl);
  SSL_set_msg_callback(qs->ssl, ssl_msg_cb);
  SSL_set_msg_callback_arg(qs->ssl, conn);
  SSL_set_key_callback(qs->ssl, ssl_key_cb, conn);

  switch(qs->version) {
#ifdef NGTCP2_PROTO_VER
  case NGTCP2_PROTO_VER:
    alpn = (const uint8_t *)NGTCP2_ALPN_H3;
    alpnlen = sizeof(NGTCP2_ALPN_H3) - 1;
    break;
#endif
  }
  if(alpn)
    SSL_set_alpn_protos(qs->ssl, alpn, (int)alpnlen);

  /* set SNI */
  SSL_set_tlsext_host_name(qs->ssl, hostname);
  return 0;
}

static int quic_tls_handshake(struct connectdata *conn,
                              bool resumption,
                              bool initial)
{
  int rv;
  struct quicsocket *qs = &conn->quic;
  ERR_clear_error();

  /* Note that SSL_SESSION_get_max_early_data() and
     SSL_get_max_early_data() return completely different value. */
  if(initial && resumption &&
     SSL_SESSION_get_max_early_data(SSL_get_session(qs->ssl))) {
    size_t nwrite;
    /* OpenSSL returns error if SSL_write_early_data is called when resumption
       is not attempted.  Sending empty string is a trick to just early_data
       extension. */
    rv = SSL_write_early_data(qs->ssl, "", 0, &nwrite);
    if(rv == 0) {
      int err = SSL_get_error(qs->ssl, rv);
      switch(err) {
      case SSL_ERROR_SSL:
        fprintf(stderr, "TLS handshake error: %s\n",
                ERR_error_string(ERR_get_error(), NULL));
        return -1;
      default:
        fprintf(stderr, "TLS handshake error: %d\n", err);
        return -1;
      }
    }
  }

  rv = SSL_do_handshake(qs->ssl);
  if(rv <= 0) {
    int err = SSL_get_error(qs->ssl, rv);
    switch(err) {
    case SSL_ERROR_WANT_READ:
    case SSL_ERROR_WANT_WRITE:
      return 0;
    case SSL_ERROR_SSL:
        fprintf(stderr, "TLS handshake error: %s\n",
                ERR_error_string(ERR_get_error(), NULL));
      return -1;
    default:
      fprintf(stderr, "TLS handshake error: %d\n", err);
      return -1;
    }
  }

  /* SSL_get_early_data_status works after handshake completes. */
  if(resumption &&
     SSL_get_early_data_status(qs->ssl) != SSL_EARLY_DATA_ACCEPTED) {
    fprintf(stderr, "Early data was rejected by server\n");
    ngtcp2_conn_early_data_rejected(conn->quic.conn);
  }

  ngtcp2_conn_handshake_completed(conn->quic.conn);
  return 0;
}

static int cb_initial(ngtcp2_conn *quic, void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  (void)quic;
  if(quic_tls_handshake(conn, false, true) != 0)
    return NGTCP2_ERR_CALLBACK_FAILURE;
  return 0;
}

static int quic_read_tls(struct connectdata *conn)
{
  uint8_t buf[4096];
  size_t nread;

  ERR_clear_error();
  for(;;) {
    int err;
    int rv = SSL_read_ex(conn->quic.ssl, buf, sizeof(buf), &nread);
    if(rv == 1) {
      infof(conn->data,  "Read %zd bytes from TLS crypto stream",
            nread);
      continue;
    }
    err = SSL_get_error(conn->quic.ssl, 0);
    switch(err) {
    case SSL_ERROR_WANT_READ:
    case SSL_ERROR_WANT_WRITE:
      return 0;
    case SSL_ERROR_SSL:
    case SSL_ERROR_ZERO_RETURN:
      infof(conn->data, "TLS read error: %s\n",
            ERR_error_string(ERR_get_error(), NULL));
      return NGTCP2_ERR_CRYPTO;
    default:
      infof(conn->data, "TLS read error: %d\n", err);
      return NGTCP2_ERR_CRYPTO;
    }
  }
  /* NEVER-REACHED */
}

static int
cb_recv_crypto_data(ngtcp2_conn *tconn, ngtcp2_crypto_level crypto_level,
                    uint64_t offset,
                    const uint8_t *data, size_t datalen,
                    void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  (void)offset;
  (void)crypto_level;

  write_server_handshake(conn, data, datalen);

  if(!ngtcp2_conn_get_handshake_completed(tconn) &&
     quic_tls_handshake(conn, false, false)) {
    return NGTCP2_ERR_CRYPTO;
  }

  /* SSL_do_handshake() might not consume all data (e.g.,
     NewSessionTicket). */
  return quic_read_tls(conn);
}

static int init_ngh3_conn(struct connectdata *conn);

static int cb_handshake_completed(ngtcp2_conn *tconn, void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  (void)tconn;
  conn->quic.tx_crypto_level = NGTCP2_CRYPTO_LEVEL_APP;
  infof(conn->data, "QUIC handshake is completed\n");

  if(init_ngh3_conn(conn) != CURLE_OK) {
    return NGTCP2_ERR_CALLBACK_FAILURE;
  }

  return 0;
}

static ssize_t cb_in_encrypt(ngtcp2_conn *tconn,
                             uint8_t *dest, size_t destlen,
                             const uint8_t *plaintext,
                             size_t plaintextlen,
                             const uint8_t *key, size_t keylen,
                             const uint8_t *nonce, size_t noncelen,
                             const uint8_t *ad, size_t adlen,
                             void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  ssize_t nwrite = Curl_qc_encrypt(dest, destlen, plaintext, plaintextlen,
                                   &conn->quic.hs_crypto_ctx,
                                   key, keylen, nonce, noncelen, ad, adlen);
  if(nwrite < 0) {
    return NGTCP2_ERR_CALLBACK_FAILURE;
  }
  (void)tconn;

  return nwrite;
}

static ssize_t cb_in_decrypt(ngtcp2_conn *tconn,
                             uint8_t *dest, size_t destlen,
                             const uint8_t *ciphertext, size_t ciphertextlen,
                             const uint8_t *key, size_t keylen,
                             const uint8_t *nonce, size_t noncelen,
                             const uint8_t *ad, size_t adlen,
                             void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  (void)tconn;
  return Curl_qc_decrypt(dest, destlen, ciphertext, ciphertextlen,
                         &conn->quic.hs_crypto_ctx, key, keylen,
                         nonce, noncelen, ad, adlen);
}


static ssize_t cb_encrypt_data(ngtcp2_conn *tconn,
                               uint8_t *dest, size_t destlen,
                               const uint8_t *plaintext, size_t plaintextlen,
                               const uint8_t *key, size_t keylen,
                               const uint8_t *nonce, size_t noncelen,
                               const uint8_t *ad, size_t adlen,
                               void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  ssize_t rc;
  (void)tconn;
  rc = Curl_qc_encrypt(dest, destlen, plaintext, plaintextlen,
                       &conn->quic.crypto_ctx,
                       key, keylen, nonce, noncelen, ad, adlen);
  if(rc < 0)
    return NGTCP2_ERR_CALLBACK_FAILURE;
  return rc;
}

static ssize_t
cb_decrypt_data(ngtcp2_conn *tconn,
                uint8_t *dest, size_t destlen,
                const uint8_t *ciphertext, size_t ciphertextlen,
                const uint8_t *key, size_t keylen,
                const uint8_t *nonce, size_t noncelen,
                const uint8_t *ad, size_t adlen,
                void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  ssize_t rc;
  (void)tconn;
  rc = Curl_qc_decrypt(dest, destlen, ciphertext, ciphertextlen,
                       &conn->quic.crypto_ctx,
                       key, keylen, nonce, noncelen, ad, adlen);
  if(rc < 0)
    return NGTCP2_ERR_TLS_DECRYPT;
  return rc;
}

static int cb_recv_stream_data(ngtcp2_conn *tconn, int64_t stream_id,
                               int fin, uint64_t offset,
                               const uint8_t *buf, size_t buflen,
                               void *user_data, void *stream_user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  ssize_t nconsumed;
  (void)offset;
  (void)stream_user_data;
  /* TODO: handle the data */
  infof(conn->data, "Received %ld bytes at %p\n", buflen, buf);

  nconsumed =
      nghttp3_conn_read_stream(conn->quic.h3conn, stream_id, buf, buflen, fin);
  if(nconsumed < 0) {
    failf(conn->data, "nghttp3_conn_read_stream returned error: %s\n",
          nghttp3_strerror((int)nconsumed));
    return NGTCP2_ERR_CALLBACK_FAILURE;
  }

  ngtcp2_conn_extend_max_stream_offset(tconn, stream_id, buflen);
  ngtcp2_conn_extend_max_offset(tconn, buflen);
  return 0;
}

static int cb_acked_crypto_offset(ngtcp2_conn *tconn,
                                  ngtcp2_crypto_level crypto_level,
                                  uint64_t offset, size_t datalen,
                                  void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  (void)conn;
  (void)crypto_level;
  (void)tconn;
  (void)offset;
  (void)datalen;

  /* TODO: uhm... what should it do? */

  return 0;
}

static int
cb_acked_stream_data_offset(ngtcp2_conn *tconn, int64_t stream_id,
                            uint64_t offset, size_t datalen, void *user_data,
                            void *stream_user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  int rv;
  (void)conn;
  (void)stream_id;
  (void)tconn;
  (void)offset;
  (void)datalen;
  (void)stream_user_data;

  rv = nghttp3_conn_add_ack_offset(conn->quic.h3conn, stream_id, datalen);
  if(rv != 0) {
    failf(conn->data, "nghttp3_conn_add_ack_offset returned error: %s\n",
          nghttp3_strerror(rv));
    return NGTCP2_ERR_CALLBACK_FAILURE;
  }

  return 0;
}

static int cb_stream_close(ngtcp2_conn *tconn, int64_t stream_id,
                           uint64_t app_error_code,
                           void *user_data, void *stream_user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  int rv;
  (void)tconn;
  (void)stream_user_data;
  /* stream is closed... */

  rv = nghttp3_conn_close_stream(conn->quic.h3conn, stream_id, app_error_code);
  if(rv != 0) {
    failf(conn->data, "nghttp3_conn_close_stream returned error: %s\n",
          nghttp3_strerror(rv));
    return NGTCP2_ERR_CALLBACK_FAILURE;
  }

  return 0;
}

static int cb_stream_reset(ngtcp2_conn *tconn, int64_t stream_id,
                           uint64_t final_size, uint64_t app_error_code,
                           void *user_data, void *stream_user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  int rv;
  (void)tconn;
  (void)final_size;
  (void)app_error_code;
  (void)stream_user_data;

  rv = nghttp3_conn_reset_stream(conn->quic.h3conn, stream_id);
  if(rv != 0) {
    failf(conn->data, "nghttp3_conn_reset_stream returned error: %s\n",
          nghttp3_strerror(rv));
    return NGTCP2_ERR_CALLBACK_FAILURE;
  }

  return 0;
}

static int cb_recv_retry(ngtcp2_conn *tconn, const ngtcp2_pkt_hd *hd,
                         const ngtcp2_pkt_retry *retry, void *user_data)
{
  /* Re-generate handshake secrets here because connection ID might change. */
  struct connectdata *conn = (struct connectdata *)user_data;
  (void)tconn;
  (void)hd;
  (void)retry;

  quic_init_ssl(conn);
  setup_initial_crypto_context(conn);

  return 0;
}

static ssize_t cb_in_hp_mask(ngtcp2_conn *tconn, uint8_t *dest, size_t destlen,
                             const uint8_t *key, size_t keylen,
                             const uint8_t *sample, size_t samplelen,
                             void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  ssize_t nwrite;
  (void)tconn;

  nwrite = Curl_qc_hp_mask(dest, destlen, &conn->quic.hs_crypto_ctx,
                           key, keylen, sample, samplelen);
  if(nwrite < 0)
    return NGTCP2_ERR_CALLBACK_FAILURE;

  return nwrite;
}

static ssize_t cb_hp_mask(ngtcp2_conn *tconn, uint8_t *dest, size_t destlen,
                          const uint8_t *key, size_t keylen,
                          const uint8_t *sample, size_t samplelen,
                          void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  ssize_t nwrite;
  (void)tconn;

  nwrite = Curl_qc_hp_mask(dest, destlen, &conn->quic.crypto_ctx,
                           key, keylen, sample, samplelen);
  if(nwrite < 0)
    return NGTCP2_ERR_CALLBACK_FAILURE;

  return nwrite;
}

static int cb_extend_max_local_streams_bidi(ngtcp2_conn *tconn,
                                            uint64_t max_streams,
                                            void *user_data)
{
  /* struct connectdata *conn = (struct connectdata *)user_data; */
  (void)tconn;
  (void)max_streams;
  (void)user_data;

  return 0;
}

static int cb_extend_max_stream_data(ngtcp2_conn *tconn, int64_t stream_id,
                                     uint64_t max_data, void *user_data,
                                     void *stream_user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  int rv;
  (void)tconn;
  (void)max_data;
  (void)stream_user_data;

  rv = nghttp3_conn_unblock_stream(conn->quic.h3conn, stream_id);
  if(rv != 0) {
    failf(conn->data, "nghttp3_conn_unblock_stream returned error: %s\n",
          nghttp3_strerror(rv));
    return NGTCP2_ERR_CALLBACK_FAILURE;
  }

  return 0;
}

static int cb_get_new_connection_id(ngtcp2_conn *tconn, ngtcp2_cid *cid,
                                    uint8_t *token, size_t cidlen,
                                    void *user_data)
{
  struct connectdata *conn = (struct connectdata *)user_data;
  CURLcode result;
  (void)tconn;

  result = Curl_rand(conn->data, cid->data, cidlen);
  if(result)
    return NGTCP2_ERR_CALLBACK_FAILURE;
  cid->datalen = cidlen;

  result = Curl_rand(conn->data, token, NGTCP2_STATELESS_RESET_TOKENLEN);
  if(result)
    return NGTCP2_ERR_CALLBACK_FAILURE;

  return 0;
}

static void quic_callbacks(ngtcp2_conn_callbacks *c)
{
  memset(c, 0, sizeof(ngtcp2_conn_callbacks));
  c->client_initial = cb_initial;
  /* recv_client_initial = NULL */
  c->recv_crypto_data = cb_recv_crypto_data;
  c->handshake_completed = cb_handshake_completed;
  /* recv_version_negotiation = NULL */
  c->in_encrypt = cb_in_encrypt;
  c->in_decrypt = cb_in_decrypt;
  c->encrypt = cb_encrypt_data;
  c->decrypt = cb_decrypt_data;
  c->in_hp_mask = cb_in_hp_mask;
  c->hp_mask = cb_hp_mask;
  c->recv_stream_data = cb_recv_stream_data;
  c->acked_crypto_offset = cb_acked_crypto_offset;
  c->acked_stream_data_offset = cb_acked_stream_data_offset;
  /* stream_open = NULL */
  c->stream_close = cb_stream_close;
  c->stream_reset = cb_stream_reset;
  /* recv_stateless_reset = NULL */
  c->recv_retry = cb_recv_retry;
  c->extend_max_local_streams_bidi = cb_extend_max_local_streams_bidi;
  /* extend_max_local_streams_uni = NULL */
  c->extend_max_stream_data = cb_extend_max_stream_data;
  /* rand = NULL */
  c->get_new_connection_id = cb_get_new_connection_id;
  /* remove_connection_id = NULL */
}


CURLcode Curl_quic_connect(struct connectdata *conn,
                           curl_socket_t sockfd,
                           const struct sockaddr *addr,
                           socklen_t addrlen)
{
  int rc;
  int rv;
  struct quicsocket *qs = &conn->quic;
  CURLcode result;
  ngtcp2_path path; /* TODO: this must be initialized properly */
  (void)addr;
  (void)addrlen;
  infof(conn->data, "Connecting socket %d over QUIC\n", sockfd);

  qs->version = NGTCP2_PROTO_VER;
  qs->sslctx = quic_ssl_ctx(conn->data);
  if(!qs->sslctx)
    return CURLE_FAILED_INIT; /* TODO: better return code */

  if(quic_init_ssl(conn))
    return CURLE_FAILED_INIT; /* TODO: better return code */

  qs->dcid.datalen = NGTCP2_MAX_CIDLEN;
  result = Curl_rand(conn->data, qs->dcid.data, NGTCP2_MAX_CIDLEN);
  if(result)
    return result;

  qs->scid.datalen = NGTCP2_MAX_CIDLEN;
  result = Curl_rand(conn->data, qs->scid.data, NGTCP2_MAX_CIDLEN);
  if(result)
    return result;

  quic_settings(&qs->settings);
  quic_callbacks(&qs->callbacks);

  qs->tx_crypto_level = NGTCP2_CRYPTO_LEVEL_INITIAL;
  qs->rx_crypto_level = NGTCP2_CRYPTO_LEVEL_INITIAL;

  qs->local_addrlen = sizeof(qs->local_addr);
  rv = getsockname(sockfd, (struct sockaddr *)&qs->local_addr,
                   &qs->local_addrlen);
  if(rv == -1) {
    return CURLE_FAILED_INIT;
  }

  ngtcp2_addr_init(&path.local, (uint8_t *)&qs->local_addr, qs->local_addrlen,
                   NULL);
  ngtcp2_addr_init(&path.remote, (uint8_t*)addr, addrlen, NULL);

#ifdef NGTCP2_PROTO_VER
#define QUICVER NGTCP2_PROTO_VER
#else
#error "unsupported ngtcp2 version"
#endif
  rc = ngtcp2_conn_client_new(&qs->conn, &qs->dcid, &qs->scid, &path, QUICVER,
                              &qs->callbacks, &qs->settings, NULL, conn);
  if(rc)
    return CURLE_FAILED_INIT; /* TODO: create a QUIC error code */

  rc = setup_initial_crypto_context(conn);
  if(rc)
    return CURLE_FAILED_INIT; /* TODO: better return code */

  return CURLE_OK;
}

/*
 * Store ngtp2 version info in this buffer, Prefix with a space.  Return total
 * length written.
 */
int Curl_quic_ver(char *p, size_t len)
{
  return msnprintf(p, len, " ngtcp2/%s nghttp3/%s",
                   NGTCP2_VERSION, NGHTTP3_VERSION);
}

static int ng_getsock(struct connectdata *conn, curl_socket_t *socks)
{
  struct SingleRequest *k = &conn->data->req;
  int bitmap = GETSOCK_BLANK;

  socks[0] = conn->sock[FIRSTSOCKET];

  /* in a HTTP/2 connection we can basically always get a frame so we should
     always be ready for one */
  bitmap |= GETSOCK_READSOCK(FIRSTSOCKET);

  /* we're still uploading or the HTTP/2 layer wants to send data */
  if((k->keepon & (KEEP_SEND|KEEP_SEND_PAUSE)) == KEEP_SEND)
    bitmap |= GETSOCK_WRITESOCK(FIRSTSOCKET);

  return bitmap;
}

static int ng_perform_getsock(const struct connectdata *conn,
                              curl_socket_t *socks)
{
  return ng_getsock((struct connectdata *)conn, socks);
}

static CURLcode ng_disconnect(struct connectdata *conn,
                                  bool dead_connection)
{
  (void)conn;
  (void)dead_connection;
  return CURLE_OK;
}

static unsigned int ng_conncheck(struct connectdata *conn,
                                 unsigned int checks_to_perform)
{
  (void)conn;
  (void)checks_to_perform;
  return CONNRESULT_NONE;
}

static const struct Curl_handler Curl_handler_h3_quiche = {
  "HTTPS",                              /* scheme */
  ZERO_NULL,                            /* setup_connection */
  Curl_http,                            /* do_it */
  Curl_http_done,                       /* done */
  ZERO_NULL,                            /* do_more */
  ZERO_NULL,                            /* connect_it */
  ZERO_NULL,                            /* connecting */
  ZERO_NULL,                            /* doing */
  ng_getsock,                           /* proto_getsock */
  ng_getsock,                           /* doing_getsock */
  ZERO_NULL,                            /* domore_getsock */
  ng_perform_getsock,                   /* perform_getsock */
  ng_disconnect,                        /* disconnect */
  ZERO_NULL,                            /* readwrite */
  ng_conncheck,                         /* connection_check */
  PORT_HTTP,                            /* defport */
  CURLPROTO_HTTPS,                      /* protocol */
  PROTOPT_SSL | PROTOPT_STREAM          /* flags */
};

static int cb_h3_stream_close(nghttp3_conn *conn, int64_t stream_id,
                              uint64_t app_error_code, void *user_data,
                              void *stream_user_data)
{
  (void)conn;
  (void)stream_id;
  (void)app_error_code;
  (void)user_data;
  (void)stream_user_data;
  fprintf(stderr, "cb_h3_stream_close CALLED\n");
  return 0;
}

static int cb_h3_recv_data(nghttp3_conn *conn, int64_t stream_id,
                           const uint8_t *buf, size_t buflen,
                           void *user_data, void *stream_user_data)
{
  size_t ncopy;
  struct Curl_easy *data = stream_user_data;
  struct HTTP *stream = data->req.protop;
  (void)conn;
  (void)stream_id;
  (void)user_data;
  fprintf(stderr, "cb_h3_recv_data CALLED with %d bytes\n",
          buflen);

  /* TODO: this needs to be handled properly */
  DEBUGASSERT(buflen <= stream->len);

  ncopy = CURLMIN(stream->len, buflen);
  memcpy(stream->mem, buf, ncopy);
  stream->len -= ncopy;
  stream->memlen += ncopy;
  stream->mem += ncopy;

  return 0;
}

static int cb_h3_deferred_consume(nghttp3_conn *conn, int64_t stream_id,
                                  size_t consumed, void *user_data,
                                  void *stream_user_data)
{
  (void)conn;
  (void)stream_id;
  (void)consumed;
  (void)user_data;
  (void)stream_user_data;
  fprintf(stderr, "cb_h3_deferred_consume CALLED\n");
  return 0;
}

/* Decode HTTP status code.  Returns -1 if no valid status code was
   decoded. (duplicate from http2.c) */
static int decode_status_code(const uint8_t *value, size_t len)
{
  int i;
  int res;

  if(len != 3) {
    return -1;
  }

  res = 0;

  for(i = 0; i < 3; ++i) {
    char c = value[i];

    if(c < '0' || c > '9') {
      return -1;
    }

    res *= 10;
    res += c - '0';
  }

  return res;
}

static int cb_h3_end_headers(nghttp3_conn *conn, int64_t stream_id,
                             void *user_data, void *stream_user_data)
{
  struct Curl_easy *data = stream_user_data;
  struct HTTP *stream = data->req.protop;
  (void)conn;
  (void)stream_id;
  (void)user_data;

  if(stream->memlen >= 2) {
    memcpy(stream->mem, "\r\n", 2);
    stream->len -= 2;
    stream->memlen += 2;
    stream->mem += 2;
  }
  return 0;
}

static int cb_h3_recv_header(nghttp3_conn *conn, int64_t stream_id,
                             int32_t token, nghttp3_rcbuf *name,
                             nghttp3_rcbuf *value, uint8_t flags,
                             void *user_data, void *stream_user_data)
{
  nghttp3_vec h3name = nghttp3_rcbuf_get_buf(name);
  nghttp3_vec h3val = nghttp3_rcbuf_get_buf(value);
  struct Curl_easy *data = stream_user_data;
  struct HTTP *stream = data->req.protop;
  size_t ncopy;
  (void)conn;
  (void)stream_id;
  (void)token;
  (void)flags;
  (void)user_data;

  if(h3name.len == sizeof(":status") - 1 &&
     !memcmp(":status", h3name.base, h3name.len)) {
    int status = decode_status_code(h3val.base, h3val.len);
    DEBUGASSERT(status != -1);
    msnprintf(stream->mem, stream->len, "HTTP/3 %03d \r\n", status);
  }
  else {
    /* store as a HTTP1-style header */
    msnprintf(stream->mem, stream->len, "%.*s: %.*s\n",
              h3name.len, h3name.base, h3val.len, h3val.base);
  }

  ncopy = strlen(stream->mem);
  stream->len -= ncopy;
  stream->memlen += ncopy;
  stream->mem += ncopy;
  return 0;
}

static int cb_h3_send_stop_sending(nghttp3_conn *conn, int64_t stream_id,
                                   uint64_t app_error_code,
                                   void *user_data,
                                   void *stream_user_data)
{
  (void)conn;
  (void)stream_id;
  (void)app_error_code;
  (void)user_data;
  (void)stream_user_data;
  fprintf(stderr, "cb_h3_send_stop_sending CALLED\n");
  return 0;
}

static nghttp3_conn_callbacks ngh3_callbacks = {
  NULL, /* acked_stream_data */
  cb_h3_stream_close,
  cb_h3_recv_data,
  cb_h3_deferred_consume,
  NULL, /* begin_headers */
  cb_h3_recv_header,
  cb_h3_end_headers,
  NULL, /* begin_trailers */
  cb_h3_recv_header,
  NULL, /* end_trailers */
  NULL, /* http_begin_push_promise */
  NULL, /* http_recv_push_promise */
  NULL, /* http_end_push_promise */
  NULL, /* http_cancel_push */
  cb_h3_send_stop_sending,
  NULL, /* push_stream */
};

static int init_ngh3_conn(struct connectdata *conn)
{
  CURLcode result;
  struct quicsocket *qs = &conn->quic;
  int rc;
  int64_t ctrl_stream_id, qpack_enc_stream_id, qpack_dec_stream_id;

  if(ngtcp2_conn_get_max_local_streams_uni(qs->conn) < 3) {
    failf(conn->data, "too few available QUIC streams");
    return CURLE_FAILED_INIT;
  }

  nghttp3_conn_settings_default(&qs->h3settings);

  rc = nghttp3_conn_client_new(&qs->h3conn,
                               &ngh3_callbacks,
                               &qs->h3settings,
                               nghttp3_mem_default(),
                               conn->data);
  if(rc) {
    result = CURLE_OUT_OF_MEMORY;
    goto fail;
  }

  rc = ngtcp2_conn_open_uni_stream(qs->conn, &ctrl_stream_id, NULL);
  if(rc) {
    result = CURLE_FAILED_INIT;
    goto fail;
  }

  rc = nghttp3_conn_bind_control_stream(qs->h3conn, ctrl_stream_id);
  if(rc) {
    result = CURLE_FAILED_INIT;
    goto fail;
  }

  rc = ngtcp2_conn_open_uni_stream(qs->conn, &qpack_enc_stream_id, NULL);
  if(rc) {
    result = CURLE_FAILED_INIT;
    goto fail;
  }

  rc = ngtcp2_conn_open_uni_stream(qs->conn, &qpack_dec_stream_id, NULL);
  if(rc) {
    result = CURLE_FAILED_INIT;
    goto fail;
  }

  rc = nghttp3_conn_bind_qpack_streams(qs->h3conn, qpack_enc_stream_id,
                                       qpack_dec_stream_id);
  if(rc) {
    result = CURLE_FAILED_INIT;
    goto fail;
  }

  return CURLE_OK;
  fail:

  return result;
}

static Curl_recv ngh3_stream_recv;
static Curl_send ngh3_stream_send;

static ssize_t ngh3_stream_recv(struct connectdata *conn,
                                int sockindex,
                                char *buf,
                                size_t buffersize,
                                CURLcode *curlcode)
{
  curl_socket_t sockfd = conn->sock[sockindex];
  struct HTTP *stream = conn->data->req.protop;

  fprintf(stderr, "ngh3_stream_recv CALLED (easy %p)\n", conn->data);

  /* remember where to store incoming data for this stream and how big the
     buffer is */
  stream->mem = buf;
  stream->len = buffersize;
  stream->memlen = 0;

  if(process_ingress(conn, sockfd)) {
    infof(conn->data, "ngh3_stream_recv returns on ingress\n");
    *curlcode = CURLE_RECV_ERROR;
    return -1;
  }
  if(flush_egress(conn, sockfd)) {
    *curlcode = CURLE_SEND_ERROR;
    return -1;
  }

  if(stream->memlen) {
    /* data arrived */
    *curlcode = CURLE_OK;
    infof(conn->data, "ngh3_stream_recv returns %zd bytes\n",
          stream->memlen);
    return stream->memlen;
  }

  infof(conn->data, "ngh3_stream_recv returns 0 bytes and EAGAIN\n");
  *curlcode = CURLE_AGAIN;
  return -1;
}

/* Index where :authority header field will appear in request header
   field list. */
#define AUTHORITY_DST_IDX 3

static CURLcode http_request(struct connectdata *conn, const void *mem,
                             size_t len)
{
  struct HTTP *stream = conn->data->req.protop;
  size_t nheader;
  size_t i;
  size_t authority_idx;
  char *hdbuf = (char *)mem;
  char *end, *line_end;
  struct quicsocket *qs = &conn->quic;
  CURLcode result = CURLE_OK;
  struct Curl_easy *data = conn->data;
  nghttp3_nv *nva = NULL;
  int64_t stream3_id;
  int rc;

  rc = ngtcp2_conn_open_bidi_stream(qs->conn, &stream3_id, NULL);
  if(rc) {
    failf(conn->data, "can get bidi streams");
    result = CURLE_SEND_ERROR;
    goto fail;
  }

  stream->stream3_id = stream3_id;
  stream->h3req = TRUE; /* senf off! */

  /* Calculate number of headers contained in [mem, mem + len). Assumes a
     correctly generated HTTP header field block. */
  nheader = 0;
  for(i = 1; i < len; ++i) {
    if(hdbuf[i] == '\n' && hdbuf[i - 1] == '\r') {
      ++nheader;
      ++i;
    }
  }
  if(nheader < 2)
    goto fail;

  /* We counted additional 2 \r\n in the first and last line. We need 3
     new headers: :method, :path and :scheme. Therefore we need one
     more space. */
  nheader += 1;
  nva = malloc(sizeof(nghttp3_nv) * nheader);
  if(!nva) {
    result = CURLE_OUT_OF_MEMORY;
    goto fail;
  }

  /* Extract :method, :path from request line
     We do line endings with CRLF so checking for CR is enough */
  line_end = memchr(hdbuf, '\r', len);
  if(!line_end) {
    result = CURLE_BAD_FUNCTION_ARGUMENT; /* internal error */
    goto fail;
  }

  /* Method does not contain spaces */
  end = memchr(hdbuf, ' ', line_end - hdbuf);
  if(!end || end == hdbuf)
    goto fail;
  nva[0].name = (unsigned char *)":method";
  nva[0].namelen = strlen((char *)nva[0].name);
  nva[0].value = (unsigned char *)hdbuf;
  nva[0].valuelen = (size_t)(end - hdbuf);
  nva[0].flags = NGHTTP3_NV_FLAG_NONE;

  hdbuf = end + 1;

  /* Path may contain spaces so scan backwards */
  end = NULL;
  for(i = (size_t)(line_end - hdbuf); i; --i) {
    if(hdbuf[i - 1] == ' ') {
      end = &hdbuf[i - 1];
      break;
    }
  }
  if(!end || end == hdbuf)
    goto fail;
  nva[1].name = (unsigned char *)":path";
  nva[1].namelen = strlen((char *)nva[1].name);
  nva[1].value = (unsigned char *)hdbuf;
  nva[1].valuelen = (size_t)(end - hdbuf);
  nva[1].flags = NGHTTP3_NV_FLAG_NONE;

  nva[2].name = (unsigned char *)":scheme";
  nva[2].namelen = strlen((char *)nva[2].name);
  if(conn->handler->flags & PROTOPT_SSL)
    nva[2].value = (unsigned char *)"https";
  else
    nva[2].value = (unsigned char *)"http";
  nva[2].valuelen = strlen((char *)nva[2].value);
  nva[2].flags = NGHTTP3_NV_FLAG_NONE;


  authority_idx = 0;
  i = 3;
  while(i < nheader) {
    size_t hlen;

    hdbuf = line_end + 2;

    /* check for next CR, but only within the piece of data left in the given
       buffer */
    line_end = memchr(hdbuf, '\r', len - (hdbuf - (char *)mem));
    if(!line_end || (line_end == hdbuf))
      goto fail;

    /* header continuation lines are not supported */
    if(*hdbuf == ' ' || *hdbuf == '\t')
      goto fail;

    for(end = hdbuf; end < line_end && *end != ':'; ++end)
      ;
    if(end == hdbuf || end == line_end)
      goto fail;
    hlen = end - hdbuf;

    if(hlen == 4 && strncasecompare("host", hdbuf, 4)) {
      authority_idx = i;
      nva[i].name = (unsigned char *)":authority";
      nva[i].namelen = strlen((char *)nva[i].name);
    }
    else {
      nva[i].name = (unsigned char *)hdbuf;
      nva[i].namelen = (size_t)(end - hdbuf);
    }
    nva[i].flags = NGHTTP3_NV_FLAG_NONE;
    hdbuf = end + 1;
    while(*hdbuf == ' ' || *hdbuf == '\t')
      ++hdbuf;
    end = line_end;

#if 0 /* This should probably go in more or less like this */
    switch(inspect_header((const char *)nva[i].name, nva[i].namelen, hdbuf,
                          end - hdbuf)) {
    case HEADERINST_IGNORE:
      /* skip header fields prohibited by HTTP/2 specification. */
      --nheader;
      continue;
    case HEADERINST_TE_TRAILERS:
      nva[i].value = (uint8_t*)"trailers";
      nva[i].value_len = sizeof("trailers") - 1;
      break;
    default:
      nva[i].value = (unsigned char *)hdbuf;
      nva[i].value_len = (size_t)(end - hdbuf);
    }
#endif
    nva[i].value = (unsigned char *)hdbuf;
    nva[i].valuelen = (size_t)(end - hdbuf);
    nva[i].flags = NGHTTP3_NV_FLAG_NONE;

    ++i;
  }

  /* :authority must come before non-pseudo header fields */
  if(authority_idx != 0 && authority_idx != AUTHORITY_DST_IDX) {
    nghttp3_nv authority = nva[authority_idx];
    for(i = authority_idx; i > AUTHORITY_DST_IDX; --i) {
      nva[i] = nva[i - 1];
    }
    nva[i] = authority;
  }

  /* Warn stream may be rejected if cumulative length of headers is too
     large. */
#define MAX_ACC 60000  /* <64KB to account for some overhead */
  {
    size_t acc = 0;

    for(i = 0; i < nheader; ++i) {
      acc += nva[i].namelen + nva[i].valuelen;

      H3BUGF(infof(data, "h3 [%.*s: %.*s]\n",
                   nva[i].namelen, nva[i].name,
                   nva[i].valuelen, nva[i].value));
    }

    if(acc > MAX_ACC) {
      infof(data, "http_request: Warning: The cumulative length of all "
            "headers exceeds %zu bytes and that could cause the "
            "stream to be rejected.\n", MAX_ACC);
    }
  }

  stream->header_recvbuf = Curl_add_buffer_init();
  if(!stream->header_recvbuf) {
    result = CURLE_OUT_OF_MEMORY;
    goto fail;
  }

  switch(data->set.httpreq) {
  case HTTPREQ_POST:
  case HTTPREQ_POST_FORM:
  case HTTPREQ_POST_MIME:
  case HTTPREQ_PUT:
    if(data->state.infilesize != -1)
      stream->upload_left = data->state.infilesize;
    else
      /* data sending without specifying the data amount up front */
      stream->upload_left = -1; /* unknown, but not zero */

#if 0
    stream3_id = quiche_h3_send_request(qs->h3c, qs->conn, nva, nheader,
                                        stream->upload_left ? FALSE: TRUE);
    if((stream3_id >= 0) && data->set.postfields) {
      ssize_t sent = quiche_h3_send_body(qs->h3c, qs->conn, stream3_id,
                                         (uint8_t *)data->set.postfields,
                                         stream->upload_left, TRUE);
      if(sent <= 0) {
        failf(data, "quiche_h3_send_body failed!");
        result = CURLE_SEND_ERROR;
      }
      stream->upload_left = 0; /* nothing left to send */
    }
#endif
    break;
  default:
    rc = nghttp3_conn_submit_request(qs->h3conn, stream->stream3_id,
                                     nva, nheader,
                                     NULL, /* no body! */
                                     conn->data);
    if(rc) {
      result = CURLE_SEND_ERROR;
      goto fail;
    }
    break;
  }

  Curl_safefree(nva);

  infof(data, "Using HTTP/3 Stream ID: %x (easy handle %p)\n",
        stream3_id, (void *)data);

  return CURLE_OK;

fail:
  free(nva);
  return result;
}
static ssize_t ngh3_stream_send(struct connectdata *conn,
                                int sockindex,
                                const void *mem,
                                size_t len,
                                CURLcode *curlcode)
{
  ssize_t sent;
  struct quicsocket *qs = &conn->quic;
  curl_socket_t sockfd = conn->sock[sockindex];
  struct HTTP *stream = conn->data->req.protop;

  if(!stream->h3req) {
    CURLcode result = http_request(conn, mem, len);
    if(result) {
      *curlcode = CURLE_SEND_ERROR;
      return -1;
    }
    sent = len;
  }
  else {
    (void)qs;
    /* TODO */
  }

  if(flush_egress(conn, sockfd)) {
    *curlcode = CURLE_SEND_ERROR;
    return -1;
  }

  *curlcode = CURLE_OK;
  return sent;
}

static void ng_has_connected(struct connectdata *conn, int sockindex)
{
  conn->recv[sockindex] = ngh3_stream_recv;
  conn->send[sockindex] = ngh3_stream_send;
  conn->handler = &Curl_handler_h3_quiche;
  conn->bits.multiplex = TRUE; /* at least potentially multiplexed */
  conn->httpversion = 30;
  conn->bundle->multiuse = BUNDLE_MULTIPLEX;
}

CURLcode Curl_quic_is_connected(struct connectdata *conn, int sockindex,
                                bool *done)
{
  CURLcode result;
  struct quicsocket *qs = &conn->quic;
  curl_socket_t sockfd = conn->sock[sockindex];

  result = process_ingress(conn, sockfd);
  if(result)
    return result;

  result = flush_egress(conn, sockfd);
  if(result)
    return result;

  if(ngtcp2_conn_get_handshake_completed(qs->conn)) {
    *done = TRUE;
    ng_has_connected(conn, sockindex);
    DEBUGF(infof(conn->data, "ngtcp2 established connection!\n"));
  }

  return result;
}

static CURLcode process_ingress(struct connectdata *conn, int sockfd)
{
  ssize_t recvd;
  int rv;
  struct quicsocket *qs = &conn->quic;
  struct Curl_easy *data = conn->data;
  uint8_t *buf = (uint8_t *)data->state.buffer;
  size_t bufsize = data->set.buffer_size;
  struct sockaddr_storage remote_addr;
  socklen_t remote_addrlen;
  ngtcp2_path path;
  ngtcp2_tstamp ts = timestamp();

  for(;;) {
    remote_addrlen = sizeof(remote_addr);
    while((recvd = recvfrom(sockfd, buf, bufsize, MSG_DONTWAIT,
                            (struct sockaddr *)&remote_addr,
                            &remote_addrlen)) == -1 &&
          errno == EINTR)
      ;
    if(recvd == -1) {
      if(errno == EAGAIN || errno == EWOULDBLOCK)
        break;

      failf(conn->data, "ngtcp2: recvfrom() unexpectedly returned %d", recvd);
      return CURLE_RECV_ERROR;
    }

    ngtcp2_addr_init(&path.local, (uint8_t *)&qs->local_addr,
                     qs->local_addrlen, NULL);
    ngtcp2_addr_init(&path.remote, (uint8_t *)&remote_addr, remote_addrlen,
                     NULL);

    rv = ngtcp2_conn_read_pkt(qs->conn, &path, buf, recvd, ts);
    if(rv != 0) {
      /* TODO Send CONNECTION_CLOSE if possible */
      return CURLE_RECV_ERROR;
    }
  }

  return CURLE_OK;
}

static CURLcode flush_egress(struct connectdata *conn, int sockfd)
{
  int rv;
  ssize_t sent;
  ssize_t outlen;
  struct quicsocket *qs = &conn->quic;
  uint8_t out[NGTCP2_MAX_PKTLEN_IPV4];
  size_t pktlen;
  ngtcp2_path_storage ps;
  ngtcp2_tstamp ts = timestamp();
  struct sockaddr_storage remote_addr;
  ngtcp2_tstamp expiry;
  ngtcp2_duration timeout;
  int64_t stream_id;
  ssize_t veccnt;
  int fin;
  nghttp3_vec vec[16];
  ssize_t ndatalen;

  switch(qs->local_addr.ss_family) {
  case AF_INET:
    pktlen = NGTCP2_MAX_PKTLEN_IPV4;
    break;
  case AF_INET6:
    pktlen = NGTCP2_MAX_PKTLEN_IPV6;
    break;
  default:
    assert(0);
  }

  rv = ngtcp2_conn_handle_expiry(qs->conn, ts);
  if(rv != 0) {
    failf(conn->data, "ngtcp2_conn_handle_expiry returned error: %s\n",
          ngtcp2_strerror(rv));
    return CURLE_SEND_ERROR;
  }

  ngtcp2_path_storage_zero(&ps);

  for(;;) {
    outlen = -1;
    if(qs->h3conn && ngtcp2_conn_get_max_data_left(qs->conn)) {
      veccnt = nghttp3_conn_writev_stream(qs->h3conn, &stream_id, &fin, vec,
                                          sizeof(vec) / sizeof(vec[0]));
      if(veccnt < 0) {
        failf(conn->data, "nghttp3_conn_writev_stream returned error: %s\n",
              nghttp3_strerror((int)veccnt));
        return CURLE_SEND_ERROR;
      }
      else if(veccnt > 0) {
        outlen = ngtcp2_conn_writev_stream(
            qs->conn, &ps.path, out, pktlen, &ndatalen,
            NGTCP2_WRITE_STREAM_FLAG_MORE, stream_id, fin,
            (const ngtcp2_vec *)vec, veccnt, ts);
        if(outlen == 0) {
          break;
        }
        if(outlen < 0) {
          if(outlen == NGTCP2_ERR_STREAM_DATA_BLOCKED ||
             outlen == NGTCP2_ERR_STREAM_SHUT_WR) {
            rv = nghttp3_conn_block_stream(qs->h3conn, stream_id);
            if(rv != 0) {
              failf(conn->data,
                    "nghttp3_conn_block_stream returned error: %s\n",
                    nghttp3_strerror(rv));
              return CURLE_SEND_ERROR;
            }
            continue;
          }
          else if(outlen == NGTCP2_ERR_WRITE_STREAM_MORE) {
            assert(ndatalen > 0);
            rv = nghttp3_conn_add_write_offset(qs->h3conn, stream_id,
                                               ndatalen);
            if(rv != 0) {
              failf(conn->data,
                    "nghttp3_conn_add_write_offset returned error: %s\n",
                    nghttp3_strerror(rv));
              return CURLE_SEND_ERROR;
            }
            continue;
          }
          else {
            failf(conn->data, "ngtcp2_conn_writev_stream returned error: %s\n",
                  ngtcp2_strerror((int)outlen));
            return CURLE_SEND_ERROR;
          }
        }
      }
    }
    if(outlen < 0) {
      outlen = ngtcp2_conn_write_pkt(qs->conn, &ps.path, out, pktlen, ts);
      if(outlen < 0) {
        failf(conn->data, "ngtcp2_conn_write_pkt returned error: %s\n",
              ngtcp2_strerror((int)outlen));
        return CURLE_SEND_ERROR;
      }
      if(outlen == 0)
        break;
    }

    memcpy(&remote_addr, ps.path.remote.addr, ps.path.remote.addrlen);
    while((sent = sendto(sockfd, out, outlen, MSG_DONTWAIT,
                         (struct sockaddr *)&remote_addr,
                         (socklen_t)ps.path.remote.addrlen)) == -1 &&
          errno == EINTR)
      ;

    if(sent == -1) {
      if(errno == EAGAIN || errno == EWOULDBLOCK) {
        /* TODO Cache packet */
        break;
      }
      else {
        failf(conn->data, "sendto() returned %zd\n", sent);
        return CURLE_SEND_ERROR;
      }
    }
  }

  expiry = ngtcp2_conn_get_expiry(qs->conn);
  if(expiry != UINT64_MAX) {
    if(expiry <= ts) {
      timeout = NGTCP2_MILLISECONDS;
    }
    else {
      timeout = expiry - ts;
    }
    Curl_expire(conn->data, timeout / NGTCP2_MILLISECONDS, EXPIRE_QUIC);
  }

  return CURLE_OK;
}
#endif