File: crypto.c

package info (click to toggle)
darkplaces 0~20180412~beta1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 18,200 kB
  • sloc: ansic: 176,886; makefile: 485; pascal: 455; perl: 372; objc: 245; sh: 102
file content (2646 lines) | stat: -rw-r--r-- 90,861 bytes parent folder | download | duplicates (2)
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
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
#include "quakedef.h"
#include "crypto.h"
#include "common.h"
#include "thread.h"

#include "hmac.h"
#include "libcurl.h"

cvar_t crypto_developer = {CVAR_SAVE, "crypto_developer", "0", "print extra info about crypto handshake"};
cvar_t crypto_aeslevel = {CVAR_SAVE, "crypto_aeslevel", "1", "whether to support AES encryption in authenticated connections (0 = no, 1 = supported, 2 = requested, 3 = required)"};

cvar_t crypto_servercpupercent = {CVAR_SAVE, "crypto_servercpupercent", "10", "allowed crypto CPU load in percent for server operation (0 = no limit, faster)"};
cvar_t crypto_servercpumaxtime = {CVAR_SAVE, "crypto_servercpumaxtime", "0.01", "maximum allowed crypto CPU time per frame (0 = no limit)"};
cvar_t crypto_servercpudebug = {CVAR_SAVE, "crypto_servercpudebug", "0", "print statistics about time usage by crypto"};
static double crypto_servercpu_accumulator = 0;
static double crypto_servercpu_lastrealtime = 0;

extern cvar_t net_sourceaddresscheck;

int crypto_keyfp_recommended_length;
static const char *crypto_idstring = NULL;
static char crypto_idstring_buf[512];


#define PROTOCOL_D0_BLIND_ID FOURCC_D0PK
#define PROTOCOL_VLEN (('v' << 0) | ('l' << 8) | ('e' << 16) | ('n' << 24))

// BEGIN stuff shared with crypto-keygen-standalone
#define FOURCC_D0PK (('d' << 0) | ('0' << 8) | ('p' << 16) | ('k' << 24))
#define FOURCC_D0SK (('d' << 0) | ('0' << 8) | ('s' << 16) | ('k' << 24))
#define FOURCC_D0PI (('d' << 0) | ('0' << 8) | ('p' << 16) | ('i' << 24))
#define FOURCC_D0SI (('d' << 0) | ('0' << 8) | ('s' << 16) | ('i' << 24))
#define FOURCC_D0IQ (('d' << 0) | ('0' << 8) | ('i' << 16) | ('q' << 24))
#define FOURCC_D0IR (('d' << 0) | ('0' << 8) | ('i' << 16) | ('r' << 24))
#define FOURCC_D0ER (('d' << 0) | ('0' << 8) | ('e' << 16) | ('r' << 24))
#define FOURCC_D0IC (('d' << 0) | ('0' << 8) | ('i' << 16) | ('c' << 24))

static unsigned long Crypto_LittleLong(const char *data)
{
	return
		((unsigned char) data[0]) |
		(((unsigned char) data[1]) << 8) |
		(((unsigned char) data[2]) << 16) |
		(((unsigned char) data[3]) << 24);
}

static void Crypto_UnLittleLong(char *data, unsigned long l)
{
	data[0] = l & 0xFF;
	data[1] = (l >> 8) & 0xFF;
	data[2] = (l >> 16) & 0xFF;
	data[3] = (l >> 24) & 0xFF;
}

static size_t Crypto_ParsePack(const char *buf, size_t len, unsigned long header, const char **lumps, size_t *lumpsize, size_t nlumps)
{
	size_t i;
	size_t pos;
	pos = 0;
	if(header)
	{
		if(len < 4)
			return 0;
		if(Crypto_LittleLong(buf) != header)
			return 0;
		pos += 4;
	}
	for(i = 0; i < nlumps; ++i)
	{
		if(pos + 4 > len)
			return 0;
		lumpsize[i] = Crypto_LittleLong(&buf[pos]);
		pos += 4;
		if(pos + lumpsize[i] > len)
			return 0;
		lumps[i] = &buf[pos];
		pos += lumpsize[i];
	}
	return pos;
}

static size_t Crypto_UnParsePack(char *buf, size_t len, unsigned long header, const char *const *lumps, const size_t *lumpsize, size_t nlumps)
{
	size_t i;
	size_t pos;
	pos = 0;
	if(header)
	{
		if(len < 4)
			return 0;
		Crypto_UnLittleLong(buf, header);
		pos += 4;
	}
	for(i = 0; i < nlumps; ++i)
	{
		if(pos + 4 + lumpsize[i] > len)
			return 0;
		Crypto_UnLittleLong(&buf[pos], (unsigned long)lumpsize[i]);
		pos += 4;
		memcpy(&buf[pos], lumps[i], lumpsize[i]);
		pos += lumpsize[i];
	}
	return pos;
}
// END stuff shared with xonotic-keygen

#define USE_AES

#ifdef LINK_TO_CRYPTO

#include <d0_blind_id/d0_blind_id.h>

#define d0_blind_id_dll 1
#define Crypto_OpenLibrary() true
#define Crypto_CloseLibrary()

#define qd0_blind_id_new d0_blind_id_new
#define qd0_blind_id_free d0_blind_id_free
//#define qd0_blind_id_clear d0_blind_id_clear
#define qd0_blind_id_copy d0_blind_id_copy
//#define qd0_blind_id_generate_private_key d0_blind_id_generate_private_key
//#define qd0_blind_id_generate_private_key_fastreject d0_blind_id_generate_private_key_fastreject
//#define qd0_blind_id_read_private_key d0_blind_id_read_private_key
#define qd0_blind_id_read_public_key d0_blind_id_read_public_key
//#define qd0_blind_id_write_private_key d0_blind_id_write_private_key
//#define qd0_blind_id_write_public_key d0_blind_id_write_public_key
#define qd0_blind_id_fingerprint64_public_key d0_blind_id_fingerprint64_public_key
//#define qd0_blind_id_generate_private_id_modulus d0_blind_id_generate_private_id_modulus
#define qd0_blind_id_read_private_id_modulus d0_blind_id_read_private_id_modulus
//#define qd0_blind_id_write_private_id_modulus d0_blind_id_write_private_id_modulus
#define qd0_blind_id_generate_private_id_start d0_blind_id_generate_private_id_start
#define qd0_blind_id_generate_private_id_request d0_blind_id_generate_private_id_request
//#define qd0_blind_id_answer_private_id_request d0_blind_id_answer_private_id_request
#define qd0_blind_id_finish_private_id_request d0_blind_id_finish_private_id_request
//#define qd0_blind_id_read_private_id_request_camouflage d0_blind_id_read_private_id_request_camouflage
//#define qd0_blind_id_write_private_id_request_camouflage d0_blind_id_write_private_id_request_camouflage
#define qd0_blind_id_read_private_id d0_blind_id_read_private_id
//#define qd0_blind_id_read_public_id d0_blind_id_read_public_id
#define qd0_blind_id_write_private_id d0_blind_id_write_private_id
//#define qd0_blind_id_write_public_id d0_blind_id_write_public_id
#define qd0_blind_id_authenticate_with_private_id_start d0_blind_id_authenticate_with_private_id_start
#define qd0_blind_id_authenticate_with_private_id_challenge d0_blind_id_authenticate_with_private_id_challenge
#define qd0_blind_id_authenticate_with_private_id_response d0_blind_id_authenticate_with_private_id_response
#define qd0_blind_id_authenticate_with_private_id_verify d0_blind_id_authenticate_with_private_id_verify
#define qd0_blind_id_fingerprint64_public_id d0_blind_id_fingerprint64_public_id
#define qd0_blind_id_sessionkey_public_id d0_blind_id_sessionkey_public_id
#define qd0_blind_id_INITIALIZE d0_blind_id_INITIALIZE
#define qd0_blind_id_SHUTDOWN d0_blind_id_SHUTDOWN
#define qd0_blind_id_util_sha256 d0_blind_id_util_sha256
#define qd0_blind_id_sign_with_private_id_sign d0_blind_id_sign_with_private_id_sign
#define qd0_blind_id_sign_with_private_id_sign_detached d0_blind_id_sign_with_private_id_sign_detached
#define qd0_blind_id_setmallocfuncs d0_blind_id_setmallocfuncs
#define qd0_blind_id_setmutexfuncs d0_blind_id_setmutexfuncs
#define qd0_blind_id_verify_public_id d0_blind_id_verify_public_id
#define qd0_blind_id_verify_private_id d0_blind_id_verify_private_id

#else

// d0_blind_id interface
#define D0_EXPORT
#ifdef __GNUC__
#define D0_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
#define D0_WARN_UNUSED_RESULT
#endif
#define D0_BOOL int

typedef void *(d0_malloc_t)(size_t len);
typedef void (d0_free_t)(void *p);
typedef void *(d0_createmutex_t)(void);
typedef void (d0_destroymutex_t)(void *);
typedef int (d0_lockmutex_t)(void *); // zero on success
typedef int (d0_unlockmutex_t)(void *); // zero on success

typedef struct d0_blind_id_s d0_blind_id_t;
typedef D0_BOOL (*d0_fastreject_function) (const d0_blind_id_t *ctx, void *pass);
static D0_EXPORT D0_WARN_UNUSED_RESULT d0_blind_id_t *(*qd0_blind_id_new) (void);
static D0_EXPORT void (*qd0_blind_id_free) (d0_blind_id_t *a);
//static D0_EXPORT void (*qd0_blind_id_clear) (d0_blind_id_t *ctx);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_copy) (d0_blind_id_t *ctx, const d0_blind_id_t *src);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_key) (d0_blind_id_t *ctx, int k);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_key_fastreject) (d0_blind_id_t *ctx, int k, d0_fastreject_function reject, void *pass);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_key) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_public_key) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_key) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_public_key) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_fingerprint64_public_key) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_id_modulus) (d0_blind_id_t *ctx);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_id_modulus) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_id_modulus) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_id_start) (d0_blind_id_t *ctx);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_generate_private_id_request) (d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_answer_private_id_request) (const d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_finish_private_id_request) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_id_request_camouflage) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_id_request_camouflage) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_private_id) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_read_public_id) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_private_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
//static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_write_public_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_start) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL send_modulus, const char *message, size_t msglen, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_challenge) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL recv_modulus, const char *inbuf, size_t inbuflen, char *outbuf, size_t *outbuflen, D0_BOOL *status);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_response) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_authenticate_with_private_id_verify) (d0_blind_id_t *ctx, const char *inbuf, size_t inbuflen, char *msg, size_t *msglen, D0_BOOL *status);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_fingerprint64_public_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_sessionkey_public_id) (const d0_blind_id_t *ctx, char *outbuf, size_t *outbuflen); // can only be done after successful key exchange, this performs a modpow; key length is limited by SHA_DIGESTSIZE for now; also ONLY valid after successful d0_blind_id_authenticate_with_private_id_verify/d0_blind_id_fingerprint64_public_id
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_INITIALIZE) (void);
static D0_EXPORT void (*qd0_blind_id_SHUTDOWN) (void);
static D0_EXPORT void (*qd0_blind_id_util_sha256) (char *out, const char *in, size_t n);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_sign_with_private_id_sign) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL send_modulus, const char *message, size_t msglen, char *outbuf, size_t *outbuflen);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_sign_with_private_id_sign_detached) (d0_blind_id_t *ctx, D0_BOOL is_first, D0_BOOL send_modulus, const char *message, size_t msglen, char *outbuf, size_t *outbuflen);
static D0_EXPORT void (*qd0_blind_id_setmallocfuncs)(d0_malloc_t *m, d0_free_t *f);
static D0_EXPORT void (*qd0_blind_id_setmutexfuncs)(d0_createmutex_t *c, d0_destroymutex_t *d, d0_lockmutex_t *l, d0_unlockmutex_t *u);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_verify_public_id)(const d0_blind_id_t *ctx, D0_BOOL *status);
static D0_EXPORT D0_WARN_UNUSED_RESULT D0_BOOL (*qd0_blind_id_verify_private_id)(const d0_blind_id_t *ctx);

#ifndef DISABLE_CRYPTO
static dllfunction_t d0_blind_id_funcs[] =
{
	{"d0_blind_id_new", (void **) &qd0_blind_id_new},
	{"d0_blind_id_free", (void **) &qd0_blind_id_free},
	//{"d0_blind_id_clear", (void **) &qd0_blind_id_clear},
	{"d0_blind_id_copy", (void **) &qd0_blind_id_copy},
	//{"d0_blind_id_generate_private_key", (void **) &qd0_blind_id_generate_private_key},
	//{"d0_blind_id_generate_private_key_fastreject", (void **) &qd0_blind_id_generate_private_key_fastreject},
	//{"d0_blind_id_read_private_key", (void **) &qd0_blind_id_read_private_key},
	{"d0_blind_id_read_public_key", (void **) &qd0_blind_id_read_public_key},
	//{"d0_blind_id_write_private_key", (void **) &qd0_blind_id_write_private_key},
	//{"d0_blind_id_write_public_key", (void **) &qd0_blind_id_write_public_key},
	{"d0_blind_id_fingerprint64_public_key", (void **) &qd0_blind_id_fingerprint64_public_key},
	//{"d0_blind_id_generate_private_id_modulus", (void **) &qd0_blind_id_generate_private_id_modulus},
	{"d0_blind_id_read_private_id_modulus", (void **) &qd0_blind_id_read_private_id_modulus},
	//{"d0_blind_id_write_private_id_modulus", (void **) &qd0_blind_id_write_private_id_modulus},
	{"d0_blind_id_generate_private_id_start", (void **) &qd0_blind_id_generate_private_id_start},
	{"d0_blind_id_generate_private_id_request", (void **) &qd0_blind_id_generate_private_id_request},
	//{"d0_blind_id_answer_private_id_request", (void **) &qd0_blind_id_answer_private_id_request},
	{"d0_blind_id_finish_private_id_request", (void **) &qd0_blind_id_finish_private_id_request},
	//{"d0_blind_id_read_private_id_request_camouflage", (void **) &qd0_blind_id_read_private_id_request_camouflage},
	//{"d0_blind_id_write_private_id_request_camouflage", (void **) &qd0_blind_id_write_private_id_request_camouflage},
	{"d0_blind_id_read_private_id", (void **) &qd0_blind_id_read_private_id},
	//{"d0_blind_id_read_public_id", (void **) &qd0_blind_id_read_public_id},
	{"d0_blind_id_write_private_id", (void **) &qd0_blind_id_write_private_id},
	//{"d0_blind_id_write_public_id", (void **) &qd0_blind_id_write_public_id},
	{"d0_blind_id_authenticate_with_private_id_start", (void **) &qd0_blind_id_authenticate_with_private_id_start},
	{"d0_blind_id_authenticate_with_private_id_challenge", (void **) &qd0_blind_id_authenticate_with_private_id_challenge},
	{"d0_blind_id_authenticate_with_private_id_response", (void **) &qd0_blind_id_authenticate_with_private_id_response},
	{"d0_blind_id_authenticate_with_private_id_verify", (void **) &qd0_blind_id_authenticate_with_private_id_verify},
	{"d0_blind_id_fingerprint64_public_id", (void **) &qd0_blind_id_fingerprint64_public_id},
	{"d0_blind_id_sessionkey_public_id", (void **) &qd0_blind_id_sessionkey_public_id},
	{"d0_blind_id_INITIALIZE", (void **) &qd0_blind_id_INITIALIZE},
	{"d0_blind_id_SHUTDOWN", (void **) &qd0_blind_id_SHUTDOWN},
	{"d0_blind_id_util_sha256", (void **) &qd0_blind_id_util_sha256},
	{"d0_blind_id_sign_with_private_id_sign", (void **) &qd0_blind_id_sign_with_private_id_sign},
	{"d0_blind_id_sign_with_private_id_sign_detached", (void **) &qd0_blind_id_sign_with_private_id_sign_detached},
	{"d0_blind_id_setmallocfuncs", (void **) &qd0_blind_id_setmallocfuncs},
	{"d0_blind_id_setmutexfuncs", (void **) &qd0_blind_id_setmutexfuncs},
	{"d0_blind_id_verify_public_id", (void **) &qd0_blind_id_verify_public_id},
	{"d0_blind_id_verify_private_id", (void **) &qd0_blind_id_verify_private_id},
	{NULL, NULL}
};
#endif
// end of d0_blind_id interface

static dllhandle_t d0_blind_id_dll = NULL;
static qboolean Crypto_OpenLibrary (void)
{
#ifdef DISABLE_CRYPTO
	return false;
#else
	const char* dllnames [] =
	{
#if defined(WIN32)
		"libd0_blind_id-0.dll",
#elif defined(MACOSX)
		"libd0_blind_id.0.dylib",
#else
		"libd0_blind_id.so.0",
		"libd0_blind_id.so", // FreeBSD
#endif
		NULL
	};

	// Already loaded?
	if (d0_blind_id_dll)
		return true;

	// Load the DLL
	return Sys_LoadLibrary (dllnames, &d0_blind_id_dll, d0_blind_id_funcs);
#endif
}

static void Crypto_CloseLibrary (void)
{
#ifndef DISABLE_CRYPTO
	Sys_UnloadLibrary (&d0_blind_id_dll);
#endif
}

#endif

#ifdef LINK_TO_CRYPTO_RIJNDAEL

#include <d0_blind_id/d0_rijndael.h>

#define d0_rijndael_dll 1
#define Crypto_Rijndael_OpenLibrary() true
#define Crypto_Rijndael_CloseLibrary()

#define qd0_rijndael_setup_encrypt d0_rijndael_setup_encrypt
#define qd0_rijndael_setup_decrypt d0_rijndael_setup_decrypt
#define qd0_rijndael_encrypt d0_rijndael_encrypt
#define qd0_rijndael_decrypt d0_rijndael_decrypt

#else

// no need to do the #define dance here, as the upper part declares out macros either way

D0_EXPORT int (*qd0_rijndael_setup_encrypt) (unsigned long *rk, const unsigned char *key,
  int keybits);
D0_EXPORT int (*qd0_rijndael_setup_decrypt) (unsigned long *rk, const unsigned char *key,
  int keybits);
D0_EXPORT void (*qd0_rijndael_encrypt) (const unsigned long *rk, int nrounds,
  const unsigned char plaintext[16], unsigned char ciphertext[16]);
D0_EXPORT void (*qd0_rijndael_decrypt) (const unsigned long *rk, int nrounds,
  const unsigned char ciphertext[16], unsigned char plaintext[16]);
#define D0_RIJNDAEL_KEYLENGTH(keybits) ((keybits)/8)
#define D0_RIJNDAEL_RKLENGTH(keybits)  ((keybits)/8+28)
#define D0_RIJNDAEL_NROUNDS(keybits)   ((keybits)/32+6)

#ifndef DISABLE_CRYPTO_RIJNDAEL
static dllfunction_t d0_rijndael_funcs[] =
{
	{"d0_rijndael_setup_decrypt", (void **) &qd0_rijndael_setup_decrypt},
	{"d0_rijndael_setup_encrypt", (void **) &qd0_rijndael_setup_encrypt},
	{"d0_rijndael_decrypt", (void **) &qd0_rijndael_decrypt},
	{"d0_rijndael_encrypt", (void **) &qd0_rijndael_encrypt},
	{NULL, NULL}
};
#endif
// end of d0_blind_id interface

static dllhandle_t d0_rijndael_dll = NULL;
static qboolean Crypto_Rijndael_OpenLibrary (void)
{
#ifdef DISABLE_CRYPTO_RIJNDAEL
	return false;
#else
	const char* dllnames [] =
	{
#if defined(WIN32)
		"libd0_rijndael-0.dll",
#elif defined(MACOSX)
		"libd0_rijndael.0.dylib",
#else
		"libd0_rijndael.so.0",
		"libd0_rijndael.so", // FreeBSD
#endif
		NULL
	};

	// Already loaded?
	if (d0_rijndael_dll)
		return true;

	// Load the DLL
	return Sys_LoadLibrary (dllnames, &d0_rijndael_dll, d0_rijndael_funcs);
#endif
}

static void Crypto_Rijndael_CloseLibrary (void)
{
#ifndef DISABLE_CRYPTO_RIJNDAEL
	Sys_UnloadLibrary (&d0_rijndael_dll);
#endif
}

#endif

// various helpers
void sha256(unsigned char *out, const unsigned char *in, int n)
{
	qd0_blind_id_util_sha256((char *) out, (const char *) in, n);
}

static size_t Crypto_LoadFile(const char *path, char *buf, size_t nmax, qboolean inuserdir)
{
	char vabuf[1024];
	qfile_t *f = NULL;
	fs_offset_t n;
	if(inuserdir)
		f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%s%s", *fs_userdir ? fs_userdir : fs_basedir, path), "rb", false);
	else
		f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%s%s", fs_basedir, path), "rb", false);
	if(!f)
		return 0;
	n = FS_Read(f, buf, nmax);
	if(n < 0)
		n = 0;
	FS_Close(f);
	return (size_t) n;
}

static qboolean PutWithNul(char **data, size_t *len, const char *str)
{
	// invariant: data points to insertion point
	size_t l = strlen(str);
	if(l >= *len)
		return false;
	memcpy(*data, str, l+1);
	*data += l+1;
	*len -= l+1;
	return true;
}

static const char *GetUntilNul(const char **data, size_t *len)
{
	// invariant: data points to next character to take
	const char *data_save = *data;
	size_t n;
	const char *p;

	if(!*data)
		return NULL;

	if(!*len)
	{
		*data = NULL;
		return NULL;
	}

	p = (const char *) memchr(*data, 0, *len);
	if(!p) // no terminating NUL
	{
		*data = NULL;
		*len = 0;
		return NULL;
	}
	n = (p - *data) + 1;
	*len -= n;
	*data += n;
	if(*len == 0)
		*data = NULL;
	return (const char *) data_save;
}

// d0pk reading
static d0_blind_id_t *Crypto_ReadPublicKey(char *buf, size_t len)
{
	d0_blind_id_t *pk = NULL;
	const char *p[2];
	size_t l[2];
	if(Crypto_ParsePack(buf, len, FOURCC_D0PK, p, l, 2))
	{
		pk = qd0_blind_id_new();
		if(pk)
			if(qd0_blind_id_read_public_key(pk, p[0], l[0]))
				if(qd0_blind_id_read_private_id_modulus(pk, p[1], l[1]))
					return pk;
	}
	if(pk)
		qd0_blind_id_free(pk);
	return NULL;
}

// d0si reading
static qboolean Crypto_AddPrivateKey(d0_blind_id_t *pk, char *buf, size_t len)
{
	const char *p[1];
	size_t l[1];
	if(Crypto_ParsePack(buf, len, FOURCC_D0SI, p, l, 1))
	{
		if(qd0_blind_id_read_private_id(pk, p[0], l[0]))
			return true;
	}
	return false;
}

#define MAX_PUBKEYS 16
static d0_blind_id_t *pubkeys[MAX_PUBKEYS];
static char pubkeys_fp64[MAX_PUBKEYS][FP64_SIZE+1];
static qboolean pubkeys_havepriv[MAX_PUBKEYS];
static qboolean pubkeys_havesig[MAX_PUBKEYS];
static char pubkeys_priv_fp64[MAX_PUBKEYS][FP64_SIZE+1];
static char challenge_append[1400];
static size_t challenge_append_length;

static int keygen_i = -1;
static char keygen_buf[8192];

#define MAX_CRYPTOCONNECTS 16
#define CRYPTOCONNECT_NONE 0
#define CRYPTOCONNECT_PRECONNECT 1
#define CRYPTOCONNECT_CONNECT 2
#define CRYPTOCONNECT_RECONNECT 3
#define CRYPTOCONNECT_DUPLICATE 4
typedef struct server_cryptoconnect_s
{
	double lasttime;
	lhnetaddress_t address;
	crypto_t crypto;
	int next_step;
}
server_cryptoconnect_t;
static server_cryptoconnect_t cryptoconnects[MAX_CRYPTOCONNECTS];

static int cdata_id = 0;
typedef struct
{
	d0_blind_id_t *id;
	int s, c;
	int next_step;
	char challenge[2048];
	char wantserver_idfp[FP64_SIZE+1];
	qboolean wantserver_aes;
	qboolean wantserver_issigned;
	int cdata_id;
}
crypto_data_t;

// crypto specific helpers
#define CDATA ((crypto_data_t *) crypto->data)
#define MAKE_CDATA if(!crypto->data) crypto->data = Z_Malloc(sizeof(crypto_data_t))
#define CLEAR_CDATA if(crypto->data) { if(CDATA->id) qd0_blind_id_free(CDATA->id); Z_Free(crypto->data); } crypto->data = NULL

static crypto_t *Crypto_ServerFindInstance(lhnetaddress_t *peeraddress, qboolean allow_create)
{
	crypto_t *crypto; 
	int i, best;

	if(!d0_blind_id_dll)
		return NULL; // no support

	for(i = 0; i < MAX_CRYPTOCONNECTS; ++i)
		if(LHNETADDRESS_Compare(peeraddress, &cryptoconnects[i].address))
			break;
	if(i < MAX_CRYPTOCONNECTS && (allow_create || cryptoconnects[i].crypto.data))
	{
		crypto = &cryptoconnects[i].crypto;
		cryptoconnects[i].lasttime = realtime;
		return crypto;
	}
	if(!allow_create)
		return NULL;
	best = 0;
	for(i = 1; i < MAX_CRYPTOCONNECTS; ++i)
		if(cryptoconnects[i].lasttime < cryptoconnects[best].lasttime)
			best = i;
	crypto = &cryptoconnects[best].crypto;
	cryptoconnects[best].lasttime = realtime;
	memcpy(&cryptoconnects[best].address, peeraddress, sizeof(cryptoconnects[best].address));
	CLEAR_CDATA;
	return crypto;
}

qboolean Crypto_FinishInstance(crypto_t *out, crypto_t *crypto)
{
	// no check needed here (returned pointers are only used in prefilled fields)
	if(!crypto || !crypto->authenticated)
	{
		Con_Printf("Passed an invalid crypto connect instance\n");
		memset(out, 0, sizeof(*out));
		return false;
	}
	CLEAR_CDATA;
	memcpy(out, crypto, sizeof(*out));
	memset(crypto, 0, sizeof(*crypto));
	return true;
}

crypto_t *Crypto_ServerGetInstance(lhnetaddress_t *peeraddress)
{
	// no check needed here (returned pointers are only used in prefilled fields)
	return Crypto_ServerFindInstance(peeraddress, false);
}

typedef struct crypto_storedhostkey_s
{
	struct crypto_storedhostkey_s *next;
	lhnetaddress_t addr;
	int keyid;
	char idfp[FP64_SIZE+1];
	int aeslevel;
	qboolean issigned;
}
crypto_storedhostkey_t;
static crypto_storedhostkey_t *crypto_storedhostkey_hashtable[CRYPTO_HOSTKEY_HASHSIZE];

static void Crypto_InitHostKeys(void)
{
	int i;
	for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
		crypto_storedhostkey_hashtable[i] = NULL;
}

static void Crypto_ClearHostKeys(void)
{
	int i;
	crypto_storedhostkey_t *hk, *hkn;
	for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
	{
		for(hk = crypto_storedhostkey_hashtable[i]; hk; hk = hkn)
		{
			hkn = hk->next;
			Z_Free(hk);
		}
		crypto_storedhostkey_hashtable[i] = NULL;
	}
}

static qboolean Crypto_ClearHostKey(lhnetaddress_t *peeraddress)
{
	char buf[128];
	int hashindex;
	crypto_storedhostkey_t **hkp;
	qboolean found = false;

	LHNETADDRESS_ToString(peeraddress, buf, sizeof(buf), 1);
	hashindex = CRC_Block((const unsigned char *) buf, strlen(buf)) % CRYPTO_HOSTKEY_HASHSIZE;
	for(hkp = &crypto_storedhostkey_hashtable[hashindex]; *hkp && LHNETADDRESS_Compare(&((*hkp)->addr), peeraddress); hkp = &((*hkp)->next));

	if(*hkp)
	{
		crypto_storedhostkey_t *hk = *hkp;
		*hkp = hk->next;
		Z_Free(hk);
		found = true;
	}

	return found;
}

static void Crypto_StoreHostKey(lhnetaddress_t *peeraddress, const char *keystring, qboolean complain)
{
	char buf[128];
	int hashindex;
	crypto_storedhostkey_t *hk;
	int keyid;
	char idfp[FP64_SIZE+1];
	int aeslevel;
	qboolean issigned;

	if(!d0_blind_id_dll)
		return;
	
	// syntax of keystring:
	// aeslevel id@key id@key ...

	if(!*keystring)
		return;
	aeslevel = bound(0, *keystring - '0', 3);
	while(*keystring && *keystring != ' ')
		++keystring;

	keyid = -1;
	issigned = false;
	while(*keystring && keyid < 0)
	{
		// id@key
		const char *idstart, *idend, *keystart, *keyend;
		qboolean thisissigned = true;
		++keystring; // skip the space
		idstart = keystring;
		while(*keystring && *keystring != ' ' && *keystring != '@')
			++keystring;
		idend = keystring;
		if(!*keystring)
			break;
		++keystring;
		keystart = keystring;
		while(*keystring && *keystring != ' ')
			++keystring;
		keyend = keystring;

		if (keystart[0] == '~')
		{
			thisissigned = false;
			++keystart;
		}

		if(idend - idstart == FP64_SIZE && keyend - keystart == FP64_SIZE)
		{
			int thiskeyid;
			for(thiskeyid = MAX_PUBKEYS - 1; thiskeyid >= 0; --thiskeyid)
				if(pubkeys[thiskeyid])
					if(!memcmp(pubkeys_fp64[thiskeyid], keystart, FP64_SIZE))
					{
						memcpy(idfp, idstart, FP64_SIZE);
						idfp[FP64_SIZE] = 0;
						keyid = thiskeyid;
						issigned = thisissigned;
						break;
					}
			// If this failed, keyid will be -1.
		}
	}

	if(keyid < 0)
		return;

	LHNETADDRESS_ToString(peeraddress, buf, sizeof(buf), 1);
	hashindex = CRC_Block((const unsigned char *) buf, strlen(buf)) % CRYPTO_HOSTKEY_HASHSIZE;
	for(hk = crypto_storedhostkey_hashtable[hashindex]; hk && LHNETADDRESS_Compare(&hk->addr, peeraddress); hk = hk->next);

	if(hk)
	{
		if(complain)
		{
			if(hk->keyid != keyid || memcmp(hk->idfp, idfp, FP64_SIZE+1))
				Con_Printf("Server %s tried to change the host key to a value not in the host cache. Connecting to it will fail. To accept the new host key, do crypto_hostkey_clear %s\n", buf, buf);
			if(hk->aeslevel > aeslevel)
				Con_Printf("Server %s tried to reduce encryption status, not accepted. Connecting to it will fail. To accept, do crypto_hostkey_clear %s\n", buf, buf);
			if(hk->issigned > issigned)
				Con_Printf("Server %s tried to reduce signature status, not accepted. Connecting to it will fail. To accept, do crypto_hostkey_clear %s\n", buf, buf);
		}
		hk->aeslevel = max(aeslevel, hk->aeslevel);
		hk->issigned = issigned;
		return;
	}

	// great, we did NOT have it yet
	hk = (crypto_storedhostkey_t *) Z_Malloc(sizeof(*hk));
	memcpy(&hk->addr, peeraddress, sizeof(hk->addr));
	hk->keyid = keyid;
	memcpy(hk->idfp, idfp, FP64_SIZE+1);
	hk->next = crypto_storedhostkey_hashtable[hashindex];
	hk->aeslevel = aeslevel;
	hk->issigned = issigned;
	crypto_storedhostkey_hashtable[hashindex] = hk;
}

qboolean Crypto_RetrieveHostKey(lhnetaddress_t *peeraddress, int *keyid, char *keyfp, size_t keyfplen, char *idfp, size_t idfplen, int *aeslevel, qboolean *issigned)
{
	char buf[128];
	int hashindex;
	crypto_storedhostkey_t *hk;

	if(!d0_blind_id_dll)
		return false;

	LHNETADDRESS_ToString(peeraddress, buf, sizeof(buf), 1);
	hashindex = CRC_Block((const unsigned char *) buf, strlen(buf)) % CRYPTO_HOSTKEY_HASHSIZE;
	for(hk = crypto_storedhostkey_hashtable[hashindex]; hk && LHNETADDRESS_Compare(&hk->addr, peeraddress); hk = hk->next);

	if(!hk)
		return false;

	if(keyid)
		*keyid = hk->keyid;
	if(keyfp)
		strlcpy(keyfp, pubkeys_fp64[hk->keyid], keyfplen);
	if(idfp)
		strlcpy(idfp, hk->idfp, idfplen);
	if(aeslevel)
		*aeslevel = hk->aeslevel;
	if(issigned)
		*issigned = hk->issigned;

	return true;
}
int Crypto_RetrieveLocalKey(int keyid, char *keyfp, size_t keyfplen, char *idfp, size_t idfplen, qboolean *issigned) // return value: -1 if more to come, +1 if valid, 0 if end of list
{
	if(keyid < 0 || keyid >= MAX_PUBKEYS)
		return 0;
	if(keyfp)
		*keyfp = 0;
	if(idfp)
		*idfp = 0;
	if(!pubkeys[keyid])
		return -1;
	if(keyfp)
		strlcpy(keyfp, pubkeys_fp64[keyid], keyfplen);
	if(idfp)
		if(pubkeys_havepriv[keyid])
			strlcpy(idfp, pubkeys_priv_fp64[keyid], idfplen);
	if(issigned)
		*issigned = pubkeys_havesig[keyid];
	return 1;
}
// end

// init/shutdown code
static void Crypto_BuildChallengeAppend(void)
{
	char *p, *lengthptr, *startptr;
	size_t n;
	int i;
	p = challenge_append;
	n = sizeof(challenge_append);
	Crypto_UnLittleLong(p, PROTOCOL_VLEN);
	p += 4;
	n -= 4;
	lengthptr = p;
	Crypto_UnLittleLong(p, 0);
	p += 4;
	n -= 4;
	Crypto_UnLittleLong(p, PROTOCOL_D0_BLIND_ID);
	p += 4;
	n -= 4;
	startptr = p;
	for(i = 0; i < MAX_PUBKEYS; ++i)
		if(pubkeys_havepriv[i])
			PutWithNul(&p, &n, pubkeys_fp64[i]);
	PutWithNul(&p, &n, "");
	for(i = 0; i < MAX_PUBKEYS; ++i)
		if(!pubkeys_havepriv[i] && pubkeys[i])
			PutWithNul(&p, &n, pubkeys_fp64[i]);
	Crypto_UnLittleLong(lengthptr, p - startptr);
	challenge_append_length = p - challenge_append;
}

static qboolean Crypto_SavePubKeyTextFile(int i)
{
	qfile_t *f;
	char vabuf[1024];

	if(!pubkeys_havepriv[i])
		return false;
	f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%skey_%d-public-fp%s.txt", *fs_userdir ? fs_userdir : fs_basedir, i, sessionid.string), "w", false);
	if(!f)
		return false;

	// we ignore errors for this file, as it's not necessary to have
	FS_Printf(f, "ID-Fingerprint: %s\n", pubkeys_priv_fp64[i]);
	FS_Printf(f, "ID-Is-Signed: %s\n", pubkeys_havesig[i] ? "yes" : "no");
	FS_Printf(f, "ID-Is-For-Key: %s\n", pubkeys_fp64[i]);
	FS_Printf(f, "\n");
	FS_Printf(f, "This is a PUBLIC ID file for DarkPlaces.\n");
	FS_Printf(f, "You are free to share this file or its contents.\n");
	FS_Printf(f, "\n");
	FS_Printf(f, "This file will be automatically generated again if deleted.\n");
	FS_Printf(f, "\n");
	FS_Printf(f, "However, NEVER share the accompanying SECRET ID file called\n");
	FS_Printf(f, "key_%d.d0si%s, as doing so would compromise security!\n", i, sessionid.string);
	FS_Close(f);

	return true;
}

static void Crypto_BuildIdString(void)
{
	int i;
	char vabuf[1024];

	crypto_idstring = NULL;
	dpsnprintf(crypto_idstring_buf, sizeof(crypto_idstring_buf), "%d", d0_rijndael_dll ? crypto_aeslevel.integer : 0);
	for (i = 0; i < MAX_PUBKEYS; ++i)
		if (pubkeys[i])
			strlcat(crypto_idstring_buf, va(vabuf, sizeof(vabuf), " %s@%s%s", pubkeys_priv_fp64[i], pubkeys_havesig[i] ? "" : "~", pubkeys_fp64[i]), sizeof(crypto_idstring_buf));
	crypto_idstring = crypto_idstring_buf;
}

void Crypto_LoadKeys(void)
{
	char buf[8192];
	size_t len, len2;
	int i;
	char vabuf[1024];

	if(!d0_blind_id_dll) // don't if we can't
		return;

	if(crypto_idstring) // already loaded? then not
		return;

	Host_LockSession(); // we use the session ID here

	// load keys
	// note: we are just a CLIENT
	// so we load:
	//   PUBLIC KEYS to accept (including modulus)
	//   PRIVATE KEY of user

	for(i = 0; i < MAX_PUBKEYS; ++i)
	{
		memset(pubkeys_fp64[i], 0, sizeof(pubkeys_fp64[i]));
		memset(pubkeys_priv_fp64[i], 0, sizeof(pubkeys_fp64[i]));
		pubkeys_havepriv[i] = false;
		pubkeys_havesig[i] = false;
		len = Crypto_LoadFile(va(vabuf, sizeof(vabuf), "key_%d.d0pk", i), buf, sizeof(buf), false);
		if((pubkeys[i] = Crypto_ReadPublicKey(buf, len)))
		{
			len2 = FP64_SIZE;
			if(qd0_blind_id_fingerprint64_public_key(pubkeys[i], pubkeys_fp64[i], &len2)) // keeps final NUL
			{
				Con_Printf("Loaded public key key_%d.d0pk (fingerprint: %s)\n", i, pubkeys_fp64[i]);
				len = Crypto_LoadFile(va(vabuf, sizeof(vabuf), "key_%d.d0si%s", i, sessionid.string), buf, sizeof(buf), true);
				if(len)
				{
					if(Crypto_AddPrivateKey(pubkeys[i], buf, len))
					{
						len2 = FP64_SIZE;
						if(qd0_blind_id_fingerprint64_public_id(pubkeys[i], pubkeys_priv_fp64[i], &len2)) // keeps final NUL
						{
							D0_BOOL status = 0;

							Con_Printf("Loaded private ID key_%d.d0si%s for key_%d.d0pk (public key fingerprint: %s)\n", i, sessionid.string, i, pubkeys_priv_fp64[i]);

							// verify the key we just loaded (just in case)
							if(qd0_blind_id_verify_private_id(pubkeys[i]) && qd0_blind_id_verify_public_id(pubkeys[i], &status))
							{
								pubkeys_havepriv[i] = true;
								pubkeys_havesig[i] = status;

								// verify the key we just got (just in case)
								if(!status)
									Con_Printf("NOTE: this ID has not yet been signed!\n");

								Crypto_SavePubKeyTextFile(i);
							}
							else
							{
								Con_Printf("d0_blind_id_verify_private_id failed, this is not a valid key!\n");
								qd0_blind_id_free(pubkeys[i]);
								pubkeys[i] = NULL;
							}
						}
						else
						{
							Con_Printf("d0_blind_id_fingerprint64_public_id failed\n");
							qd0_blind_id_free(pubkeys[i]);
							pubkeys[i] = NULL;
						}
					}
				}
			}
			else
			{
				// can't really happen
				qd0_blind_id_free(pubkeys[i]);
				pubkeys[i] = NULL;
			}
		}
	}

	keygen_i = -1;
	Crypto_BuildIdString();
	Crypto_BuildChallengeAppend();

	// find a good prefix length for all the keys we know (yes, algorithm is not perfect yet, may yield too long prefix length)
	crypto_keyfp_recommended_length = 0;
	memset(buf+256, 0, MAX_PUBKEYS + MAX_PUBKEYS);
	while(crypto_keyfp_recommended_length < FP64_SIZE)
	{
		memset(buf, 0, 256);
		for(i = 0; i < MAX_PUBKEYS; ++i)
			if(pubkeys[i])
			{
				if(!buf[256 + i])
					++buf[(unsigned char) pubkeys_fp64[i][crypto_keyfp_recommended_length]];
				if(pubkeys_havepriv[i])
					if(!buf[256 + MAX_PUBKEYS + i])
						++buf[(unsigned char) pubkeys_priv_fp64[i][crypto_keyfp_recommended_length]];
			}
		for(i = 0; i < MAX_PUBKEYS; ++i)
			if(pubkeys[i])
			{
				if(!buf[256 + i])
					if(buf[(unsigned char) pubkeys_fp64[i][crypto_keyfp_recommended_length]] < 2)
						buf[256 + i] = 1;
				if(pubkeys_havepriv[i])
					if(!buf[256 + MAX_PUBKEYS + i])
						if(buf[(unsigned char) pubkeys_priv_fp64[i][crypto_keyfp_recommended_length]] < 2)
							buf[256 + MAX_PUBKEYS + i] = 1;
			}
		++crypto_keyfp_recommended_length;
		for(i = 0; i < MAX_PUBKEYS; ++i)
			if(pubkeys[i])
			{
				if(!buf[256 + i])
					break;
				if(pubkeys_havepriv[i])
					if(!buf[256 + MAX_PUBKEYS + i])
						break;
			}
		if(i >= MAX_PUBKEYS)
			break;
	}
	if(crypto_keyfp_recommended_length < 7)
		crypto_keyfp_recommended_length = 7;
}

static void Crypto_UnloadKeys(void)
{
	int i;

	keygen_i = -1;
	for(i = 0; i < MAX_PUBKEYS; ++i)
	{
		if(pubkeys[i])
			qd0_blind_id_free(pubkeys[i]);
		pubkeys[i] = NULL;
		pubkeys_havepriv[i] = false;
		pubkeys_havesig[i] = false;
		memset(pubkeys_fp64[i], 0, sizeof(pubkeys_fp64[i]));
		memset(pubkeys_priv_fp64[i], 0, sizeof(pubkeys_fp64[i]));
		challenge_append_length = 0;
	}
	crypto_idstring = NULL;
}

static mempool_t *cryptomempool;

#ifdef __cplusplus
extern "C"
{
#endif
static void *Crypto_d0_malloc(size_t len)
{
	return Mem_Alloc(cryptomempool, len);
}

static void Crypto_d0_free(void *p)
{
	Mem_Free(p);
}

static void *Crypto_d0_createmutex(void)
{
	return Thread_CreateMutex();
}

static void Crypto_d0_destroymutex(void *m)
{
	Thread_DestroyMutex(m);
}

static int Crypto_d0_lockmutex(void *m)
{
	return Thread_LockMutex(m);
}

static int Crypto_d0_unlockmutex(void *m)
{
	return Thread_UnlockMutex(m);
}
#ifdef __cplusplus
}
#endif

void Crypto_Shutdown(void)
{
	crypto_t *crypto;
	int i;

	Crypto_Rijndael_CloseLibrary();

	if(d0_blind_id_dll)
	{
		// free memory
		for(i = 0; i < MAX_CRYPTOCONNECTS; ++i)
		{
			crypto = &cryptoconnects[i].crypto;
			CLEAR_CDATA;
		}
		memset(cryptoconnects, 0, sizeof(cryptoconnects));
		crypto = &cls.crypto;
		CLEAR_CDATA;

		Crypto_UnloadKeys();

		qd0_blind_id_SHUTDOWN();

		Crypto_CloseLibrary();
	}

	Mem_FreePool(&cryptomempool);
}

void Crypto_Init(void)
{
	cryptomempool = Mem_AllocPool("crypto", 0, NULL);

	if(!Crypto_OpenLibrary())
		return;

	qd0_blind_id_setmallocfuncs(Crypto_d0_malloc, Crypto_d0_free);
	if (Thread_HasThreads())
		qd0_blind_id_setmutexfuncs(Crypto_d0_createmutex, Crypto_d0_destroymutex, Crypto_d0_lockmutex, Crypto_d0_unlockmutex);

	if(!qd0_blind_id_INITIALIZE())
	{
		Crypto_Rijndael_CloseLibrary();
		Crypto_CloseLibrary();
		Con_Printf("libd0_blind_id initialization FAILED, cryptography support has been disabled\n");
		return;
	}

	(void) Crypto_Rijndael_OpenLibrary(); // if this fails, it's uncritical

	Crypto_InitHostKeys();
}
// end

qboolean Crypto_Available(void)
{
	if(!d0_blind_id_dll)
		return false;
	return true;
}

// keygen code
static void Crypto_KeyGen_Finished(int code, size_t length_received, unsigned char *buffer, void *cbdata)
{
	const char *p[1];
	size_t l[1];
	static char buf[8192];
	static char buf2[8192];
	size_t buf2size;
	qfile_t *f = NULL;
	D0_BOOL status;
	char vabuf[1024];

	SV_LockThreadMutex();

	if(!d0_blind_id_dll)
	{
		Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}

	if(keygen_i < 0)
	{
		Con_Printf("Unexpected response from keygen server:\n");
		Com_HexDumpToConsole(buffer, (int)length_received);
		SV_UnlockThreadMutex();
		return;
	}
	if(keygen_i >= MAX_PUBKEYS || !pubkeys[keygen_i])
	{
		Con_Printf("overflow of keygen_i\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	if(!Crypto_ParsePack((const char *) buffer, length_received, FOURCC_D0IR, p, l, 1))
	{
		if(length_received >= 5 && Crypto_LittleLong((const char *) buffer) == FOURCC_D0ER)
		{
			Con_Printf("Error response from keygen server: %.*s\n", (int)(length_received - 5), buffer + 5);
		}
		else
		{
			Con_Printf("Invalid response from keygen server:\n");
			Com_HexDumpToConsole(buffer, (int)length_received);
		}
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	if(!qd0_blind_id_finish_private_id_request(pubkeys[keygen_i], p[0], l[0]))
	{
		Con_Printf("d0_blind_id_finish_private_id_request failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}

	// verify the key we just got (just in case)
	if(!qd0_blind_id_verify_public_id(pubkeys[keygen_i], &status) || !status)
	{
		Con_Printf("d0_blind_id_verify_public_id failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}

	// we have a valid key now!
	// make the rest of crypto.c know that
	Con_Printf("Received signature for private ID key_%d.d0pk (public key fingerprint: %s)\n", keygen_i, pubkeys_priv_fp64[keygen_i]);
	pubkeys_havesig[keygen_i] = true;

	// write the key to disk
	p[0] = buf;
	l[0] = sizeof(buf);
	if(!qd0_blind_id_write_private_id(pubkeys[keygen_i], buf, &l[0]))
	{
		Con_Printf("d0_blind_id_write_private_id failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	if(!(buf2size = Crypto_UnParsePack(buf2, sizeof(buf2), FOURCC_D0SI, p, l, 1)))
	{
		Con_Printf("Crypto_UnParsePack failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}

	FS_CreatePath(va(vabuf, sizeof(vabuf), "%skey_%d.d0si%s", *fs_userdir ? fs_userdir : fs_basedir, keygen_i, sessionid.string));
	f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%skey_%d.d0si%s", *fs_userdir ? fs_userdir : fs_basedir, keygen_i, sessionid.string), "wb", false);
	if(!f)
	{
		Con_Printf("Cannot open key_%d.d0si%s\n", keygen_i, sessionid.string);
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	FS_Write(f, buf2, buf2size);
	FS_Close(f);

	Crypto_SavePubKeyTextFile(keygen_i);

	Con_Printf("Saved to key_%d.d0si%s\n", keygen_i, sessionid.string);

	Crypto_BuildIdString();

	keygen_i = -1;
	SV_UnlockThreadMutex();
}

static void Crypto_KeyGen_f(void)
{
	int i;
	const char *p[1];
	size_t l[1];
	static char buf[8192];
	static char buf2[8192];
	size_t buf2size;
	size_t buf2l, buf2pos;
	char vabuf[1024];
	size_t len2;
	qfile_t *f = NULL;

	if(!d0_blind_id_dll)
	{
		Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
		return;
	}
	if(Cmd_Argc() != 3)
	{
		Con_Printf("usage:\n%s id url\n", Cmd_Argv(0));
		return;
	}
	SV_LockThreadMutex();
	Crypto_LoadKeys();
	i = atoi(Cmd_Argv(1));
	if(!pubkeys[i])
	{
		Con_Printf("there is no public key %d\n", i);
		SV_UnlockThreadMutex();
		return;
	}
	if(keygen_i >= 0)
	{
		Con_Printf("there is already a keygen run on the way\n");
		SV_UnlockThreadMutex();
		return;
	}
	keygen_i = i;

	// how to START the keygenning...
	if(pubkeys_havepriv[keygen_i])
	{
		if(pubkeys_havesig[keygen_i])
		{
			Con_Printf("there is already a signed private key for %d\n", i);
			keygen_i = -1;
			SV_UnlockThreadMutex();
			return;
		}
		// if we get here, we only need a signature, no new keygen run needed
		Con_Printf("Only need a signature for an existing key...\n");
	}
	else
	{
		// we also need a new ID itself
		if(!qd0_blind_id_generate_private_id_start(pubkeys[keygen_i]))
		{
			Con_Printf("d0_blind_id_start failed\n");
			keygen_i = -1;
			SV_UnlockThreadMutex();
			return;
		}
		// verify the key we just got (just in case)
		if(!qd0_blind_id_verify_private_id(pubkeys[keygen_i]))
		{
			Con_Printf("d0_blind_id_verify_private_id failed\n");
			keygen_i = -1;
			SV_UnlockThreadMutex();
			return;
		}
		// we have a valid key now!
		// make the rest of crypto.c know that
		len2 = FP64_SIZE;
		if(qd0_blind_id_fingerprint64_public_id(pubkeys[keygen_i], pubkeys_priv_fp64[keygen_i], &len2)) // keeps final NUL
		{
			Con_Printf("Generated private ID key_%d.d0pk (public key fingerprint: %s)\n", keygen_i, pubkeys_priv_fp64[keygen_i]);
			pubkeys_havepriv[keygen_i] = true;
			strlcat(crypto_idstring_buf, va(vabuf, sizeof(vabuf), " %s@%s", pubkeys_priv_fp64[keygen_i], pubkeys_fp64[keygen_i]), sizeof(crypto_idstring_buf));
			crypto_idstring = crypto_idstring_buf;
			Crypto_BuildChallengeAppend();
		}
		// write the key to disk
		p[0] = buf;
		l[0] = sizeof(buf);
		if(!qd0_blind_id_write_private_id(pubkeys[keygen_i], buf, &l[0]))
		{
			Con_Printf("d0_blind_id_write_private_id failed\n");
			keygen_i = -1;
			SV_UnlockThreadMutex();
			return;
		}
		if(!(buf2size = Crypto_UnParsePack(buf2, sizeof(buf2), FOURCC_D0SI, p, l, 1)))
		{
			Con_Printf("Crypto_UnParsePack failed\n");
			keygen_i = -1;
			SV_UnlockThreadMutex();
			return;
		}

		FS_CreatePath(va(vabuf, sizeof(vabuf), "%skey_%d.d0si%s", *fs_userdir ? fs_userdir : fs_basedir, keygen_i, sessionid.string));
		f = FS_SysOpen(va(vabuf, sizeof(vabuf), "%skey_%d.d0si%s", *fs_userdir ? fs_userdir : fs_basedir, keygen_i, sessionid.string), "wb", false);
		if(!f)
		{
			Con_Printf("Cannot open key_%d.d0si%s\n", keygen_i, sessionid.string);
			keygen_i = -1;
			SV_UnlockThreadMutex();
			return;
		}
		FS_Write(f, buf2, buf2size);
		FS_Close(f);

		Crypto_SavePubKeyTextFile(keygen_i);

		Con_Printf("Saved unsigned key to key_%d.d0si%s\n", keygen_i, sessionid.string);
	}
	p[0] = buf;
	l[0] = sizeof(buf);
	if(!qd0_blind_id_generate_private_id_request(pubkeys[keygen_i], buf, &l[0]))
	{
		Con_Printf("d0_blind_id_generate_private_id_request failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	buf2pos = strlen(Cmd_Argv(2));
	memcpy(buf2, Cmd_Argv(2), buf2pos);
	if(!(buf2l = Crypto_UnParsePack(buf2 + buf2pos, sizeof(buf2) - buf2pos - 1, FOURCC_D0IQ, p, l, 1)))
	{
		Con_Printf("Crypto_UnParsePack failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	if(!(buf2l = base64_encode((unsigned char *) (buf2 + buf2pos), buf2l, sizeof(buf2) - buf2pos - 1)))
	{
		Con_Printf("base64_encode failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	buf2l += buf2pos;
	buf2[buf2l] = 0;
	if(!Curl_Begin_ToMemory(buf2, 0, (unsigned char *) keygen_buf, sizeof(keygen_buf), Crypto_KeyGen_Finished, NULL))
	{
		Con_Printf("curl failed\n");
		keygen_i = -1;
		SV_UnlockThreadMutex();
		return;
	}
	Con_Printf("Signature generation in progress...\n");
	SV_UnlockThreadMutex();
}
// end

// console commands
static void Crypto_Reload_f(void)
{
	Crypto_ClearHostKeys();
	Crypto_UnloadKeys();
	Crypto_LoadKeys();
}

static void Crypto_Keys_f(void)
{
	int i;
	if(!d0_blind_id_dll)
	{
		Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
		return;
	}
	for(i = 0; i < MAX_PUBKEYS; ++i)
	{
		if(pubkeys[i])
		{
			Con_Printf("%2d: public key key_%d.d0pk (fingerprint: %s)\n", i, i, pubkeys_fp64[i]);
			if(pubkeys_havepriv[i])
			{
				Con_Printf("    private ID key_%d.d0si%s (public key fingerprint: %s)\n", i, sessionid.string, pubkeys_priv_fp64[i]);
				if(!pubkeys_havesig[i])
					Con_Printf("    NOTE: this ID has not yet been signed!\n");
			}
		}
	}
}

static void Crypto_HostKeys_f(void)
{
	int i;
	crypto_storedhostkey_t *hk;
	char buf[128];

	if(!d0_blind_id_dll)
	{
		Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
		return;
	}
	for(i = 0; i < CRYPTO_HOSTKEY_HASHSIZE; ++i)
	{
		for(hk = crypto_storedhostkey_hashtable[i]; hk; hk = hk->next)
		{
			LHNETADDRESS_ToString(&hk->addr, buf, sizeof(buf), 1);
			Con_Printf("%d %s@%.*s %s\n",
					hk->aeslevel,
					hk->idfp,
					crypto_keyfp_recommended_length, pubkeys_fp64[hk->keyid],
					buf);
		}
	}
}

static void Crypto_HostKey_Clear_f(void)
{
	lhnetaddress_t addr;
	int i;

	if(!d0_blind_id_dll)
	{
		Con_Print("libd0_blind_id DLL not found, this command is inactive.\n");
		return;
	}

	for(i = 1; i < Cmd_Argc(); ++i)
	{
		LHNETADDRESS_FromString(&addr, Cmd_Argv(i), 26000);
		if(Crypto_ClearHostKey(&addr))
		{
			Con_Printf("cleared host key for %s\n", Cmd_Argv(i));
		}
	}
}

void Crypto_Init_Commands(void)
{
	if(d0_blind_id_dll)
	{
		Cmd_AddCommand("crypto_reload", Crypto_Reload_f, "reloads cryptographic keys");
		Cmd_AddCommand("crypto_keygen", Crypto_KeyGen_f, "generates and saves a cryptographic key");
		Cmd_AddCommand("crypto_keys", Crypto_Keys_f, "lists the loaded keys");
		Cmd_AddCommand("crypto_hostkeys", Crypto_HostKeys_f, "lists the cached host keys");
		Cmd_AddCommand("crypto_hostkey_clear", Crypto_HostKey_Clear_f, "clears a cached host key");
		Cvar_RegisterVariable(&crypto_developer);
		if(d0_rijndael_dll)
			Cvar_RegisterVariable(&crypto_aeslevel);
		else
			crypto_aeslevel.integer = 0; // make sure
		Cvar_RegisterVariable(&crypto_servercpupercent);
		Cvar_RegisterVariable(&crypto_servercpumaxtime);
		Cvar_RegisterVariable(&crypto_servercpudebug);
	}
}
// end

// AES encryption
static void aescpy(unsigned char *key, const unsigned char *iv, unsigned char *dst, const unsigned char *src, size_t len)
{
	const unsigned char *xorpos = iv;
	unsigned char xorbuf[16];
	unsigned long rk[D0_RIJNDAEL_RKLENGTH(DHKEY_SIZE * 8)];
	size_t i;
	qd0_rijndael_setup_encrypt(rk, key, DHKEY_SIZE * 8);
	while(len > 16)
	{
		for(i = 0; i < 16; ++i)
			xorbuf[i] = src[i] ^ xorpos[i];
		qd0_rijndael_encrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), xorbuf, dst);
		xorpos = dst;
		len -= 16;
		src += 16;
		dst += 16;
	}
	if(len > 0)
	{
		for(i = 0; i < len; ++i)
			xorbuf[i] = src[i] ^ xorpos[i];
		for(; i < 16; ++i)
			xorbuf[i] = xorpos[i];
		qd0_rijndael_encrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), xorbuf, dst);
	}
}
static void seacpy(unsigned char *key, const unsigned char *iv, unsigned char *dst, const unsigned char *src, size_t len)
{
	const unsigned char *xorpos = iv;
	unsigned char xorbuf[16];
	unsigned long rk[D0_RIJNDAEL_RKLENGTH(DHKEY_SIZE * 8)];
	size_t i;
	qd0_rijndael_setup_decrypt(rk, key, DHKEY_SIZE * 8);
	while(len > 16)
	{
		qd0_rijndael_decrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), src, xorbuf);
		for(i = 0; i < 16; ++i)
			dst[i] = xorbuf[i] ^ xorpos[i];
		xorpos = src;
		len -= 16;
		src += 16;
		dst += 16;
	}
	if(len > 0)
	{
		qd0_rijndael_decrypt(rk, D0_RIJNDAEL_NROUNDS(DHKEY_SIZE * 8), src, xorbuf);
		for(i = 0; i < len; ++i)
			dst[i] = xorbuf[i] ^ xorpos[i];
	}
}

// NOTE: we MUST avoid the following begins of the packet:
//   1. 0xFF, 0xFF, 0xFF, 0xFF
//   2. 0x80, 0x00, length/256, length%256
// this luckily does NOT affect AES mode, where the first byte always is in the range from 0x00 to 0x0F
const void *Crypto_EncryptPacket(crypto_t *crypto, const void *data_src, size_t len_src, void *data_dst, size_t *len_dst, size_t len)
{
	unsigned char h[32];
	int i;
	if(crypto->authenticated)
	{
		if(crypto->use_aes)
		{
			// AES packet = 1 byte length overhead, 15 bytes from HMAC-SHA-256, data, 0..15 bytes padding
			// 15 bytes HMAC-SHA-256 (112bit) suffice as the attacker can't do more than forge a random-looking packet
			// HMAC is needed to not leak information about packet content
			if(developer_networking.integer)
			{
				Con_Print("To be encrypted:\n");
				Com_HexDumpToConsole((const unsigned char *) data_src, (int)len_src);
			}
			if(len_src + 32 > len || !HMAC_SHA256_32BYTES(h, (const unsigned char *) data_src, (int)len_src, crypto->dhkey, DHKEY_SIZE))
			{
				Con_Printf("Crypto_EncryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
				return NULL;
			}
			*len_dst = ((len_src + 15) / 16) * 16 + 16; // add 16 for HMAC, then round to 16-size for AES
			((unsigned char *) data_dst)[0] = (unsigned char)(*len_dst - len_src);
			memcpy(((unsigned char *) data_dst)+1, h, 15);
			aescpy(crypto->dhkey, (const unsigned char *) data_dst, ((unsigned char *) data_dst) + 16, (const unsigned char *) data_src, len_src);
			//                    IV                                dst                                src                               len
		}
		else
		{
			// HMAC packet = 16 bytes HMAC-SHA-256 (truncated to 128 bits), data
			if(len_src + 16 > len || !HMAC_SHA256_32BYTES(h, (const unsigned char *) data_src, (int)len_src, crypto->dhkey, DHKEY_SIZE))
			{
				Con_Printf("Crypto_EncryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
				return NULL;
			}
			*len_dst = len_src + 16;
			memcpy(data_dst, h, 16);
			memcpy(((unsigned char *) data_dst) + 16, (unsigned char *) data_src, len_src);

			// handle the "avoid" conditions:
			i = BuffBigLong((unsigned char *) data_dst);
			if(
				(i == (int)0xFFFFFFFF) // avoid QW control packet
				||
				(i == (int)0x80000000 + (int)*len_dst) // avoid NQ control packet
			)
				*(unsigned char *)data_dst ^= 0x80; // this will ALWAYS fix it
		}
		return data_dst;
	}
	else
	{
		*len_dst = len_src;
		return data_src;
	}
}

const void *Crypto_DecryptPacket(crypto_t *crypto, const void *data_src, size_t len_src, void *data_dst, size_t *len_dst, size_t len)
{
	unsigned char h[32];
	int i;

	// silently handle non-crypto packets
	i = BuffBigLong((unsigned char *) data_src);
	if(
		(i == (int)0xFFFFFFFF) // avoid QW control packet
		||
		(i == (int)0x80000000 + (int)len_src) // avoid NQ control packet
	)
		return NULL;

	if(crypto->authenticated)
	{
		if(crypto->use_aes)
		{
			if(len_src < 16 || ((len_src - 16) % 16))
			{
				Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
				return NULL;
			}
			*len_dst = len_src - ((unsigned char *) data_src)[0];
			if(len < *len_dst || *len_dst > len_src - 16)
			{
				Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d->%d bytes out)\n", (int) len_src, (int) *len_dst, (int) len);
				return NULL;
			}
			seacpy(crypto->dhkey, (unsigned char *) data_src, (unsigned char *) data_dst, ((const unsigned char *) data_src) + 16, *len_dst);
			//                    IV                          dst                         src                                      len
			if(!HMAC_SHA256_32BYTES(h, (const unsigned char *) data_dst, (int)*len_dst, crypto->dhkey, DHKEY_SIZE))
			{
				Con_Printf("HMAC fail\n");
				return NULL;
			}
			if(memcmp(((const unsigned char *) data_src)+1, h, 15)) // ignore first byte, used for length
			{
				Con_Printf("HMAC mismatch\n");
				return NULL;
			}
			if(developer_networking.integer)
			{
				Con_Print("Decrypted:\n");
				Com_HexDumpToConsole((const unsigned char *) data_dst, (int)*len_dst);
			}
			return data_dst; // no need to copy
		}
		else
		{
			if(len_src < 16)
			{
				Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d bytes out)\n", (int) len_src, (int) len);
				return NULL;
			}
			*len_dst = len_src - 16;
			if(len < *len_dst)
			{
				Con_Printf("Crypto_DecryptPacket failed (not enough space: %d bytes in, %d->%d bytes out)\n", (int) len_src, (int) *len_dst, (int) len);
				return NULL;
			}
			//memcpy(data_dst, data_src + 16, *len_dst);
			if(!HMAC_SHA256_32BYTES(h, ((const unsigned char *) data_src) + 16, (int)*len_dst, crypto->dhkey, DHKEY_SIZE))
			{
				Con_Printf("HMAC fail\n");
				Com_HexDumpToConsole((const unsigned char *) data_src, (int)len_src);
				return NULL;
			}

			if(memcmp((const unsigned char *) data_src, h, 16)) // ignore first byte, used for length
			{
				// undo the "avoid conditions"
				if(
						(i == (int)0x7FFFFFFF) // avoided QW control packet
						||
						(i == (int)0x00000000 + (int)len_src) // avoided NQ control packet
				  )
				{
					// do the avoidance on the hash too
					h[0] ^= 0x80;
					if(memcmp((const unsigned char *) data_src, h, 16)) // ignore first byte, used for length
					{
						Con_Printf("HMAC mismatch\n");
						Com_HexDumpToConsole((const unsigned char *) data_src, (int)len_src);
						return NULL;
					}
				}
				else
				{
					Con_Printf("HMAC mismatch\n");
					Com_HexDumpToConsole((const unsigned char *) data_src, (int)len_src);
					return NULL;
				}
			}
			return ((const unsigned char *) data_src) + 16; // no need to copy, so data_dst is not used
		}
	}
	else
	{
		*len_dst = len_src;
		return data_src;
	}
}
// end

const char *Crypto_GetInfoResponseDataString(void)
{
	crypto_idstring_buf[0] = '0' + crypto_aeslevel.integer;
	return crypto_idstring;
}

// network protocol
qboolean Crypto_ServerAppendToChallenge(const char *data_in, size_t len_in, char *data_out, size_t *len_out, size_t maxlen_out)
{
	// cheap op, all is precomputed
	if(!d0_blind_id_dll)
		return false; // no support
	// append challenge
	if(maxlen_out <= *len_out + challenge_append_length)
		return false;
	memcpy(data_out + *len_out, challenge_append, challenge_append_length);
	*len_out += challenge_append_length;
	return false;
}

static int Crypto_ServerError(char *data_out, size_t *len_out, const char *msg, const char *msg_client)
{
	if(!msg_client)
		msg_client = msg;
	Con_DPrintf("rejecting client: %s\n", msg);
	if(*msg_client)
		dpsnprintf(data_out, *len_out, "reject %s", msg_client);
	*len_out = strlen(data_out);
	return CRYPTO_DISCARD;
}

static int Crypto_SoftServerError(char *data_out, size_t *len_out, const char *msg)
{
	*len_out = 0;
	Con_DPrintf("%s\n", msg);
	return CRYPTO_DISCARD;
}

static int Crypto_ServerParsePacket_Internal(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
{
	// if "connect": reject if in the middle of crypto handshake
	crypto_t *crypto = NULL;
	char *data_out_p = data_out;
	const char *string = data_in;
	int aeslevel;
	D0_BOOL aes;
	D0_BOOL status;
	char infostringvalue[MAX_INPUTLINE];
	char vabuf[1024];

	if(!d0_blind_id_dll)
		return CRYPTO_NOMATCH; // no support

	if (len_in > 8 && !memcmp(string, "connect\\", 8) && d0_rijndael_dll && crypto_aeslevel.integer >= 3)
	{
		const char *s;
		int i;
		// sorry, we have to verify the challenge here to not reflect network spam

		if (!(s = InfoString_GetValue(string + 4, "challenge", infostringvalue, sizeof(infostringvalue))))
			return CRYPTO_NOMATCH; // will be later accepted if encryption was set up
		// validate the challenge
		for (i = 0;i < MAX_CHALLENGES;i++)
			if(challenges[i].time > 0)
				if (!LHNETADDRESS_Compare(peeraddress, &challenges[i].address) && !strcmp(challenges[i].string, s))
					break;
		// if the challenge is not recognized, drop the packet
		if (i == MAX_CHALLENGES) // challenge mismatch is silent
			return Crypto_SoftServerError(data_out, len_out, "missing challenge in connect");

		crypto = Crypto_ServerFindInstance(peeraddress, false);
		if(!crypto || !crypto->authenticated)
			return Crypto_ServerError(data_out, len_out, "This server requires authentication and encryption to be supported by your client", NULL);
	}
	else if(len_in > 5 && !memcmp(string, "d0pk\\", 5) && ((LHNETADDRESS_GetAddressType(peeraddress) == LHNETADDRESSTYPE_LOOP) || sv_public.integer > -3))
	{
		const char *cnt, *s, *p;
		int id;
		int clientid = -1, serverid = -1;
		cnt = InfoString_GetValue(string + 4, "id", infostringvalue, sizeof(infostringvalue));
		id = (cnt ? atoi(cnt) : -1);
		cnt = InfoString_GetValue(string + 4, "cnt", infostringvalue, sizeof(infostringvalue));
		if(!cnt)
			return Crypto_SoftServerError(data_out, len_out, "missing cnt in d0pk");
		GetUntilNul(&data_in, &len_in);
		if(!data_in)
			return Crypto_SoftServerError(data_out, len_out, "missing appended data in d0pk");
		if(!strcmp(cnt, "0"))
		{
			int i;
			if (!(s = InfoString_GetValue(string + 4, "challenge", infostringvalue, sizeof(infostringvalue))))
				return Crypto_SoftServerError(data_out, len_out, "missing challenge in d0pk\\0");
			// validate the challenge
			for (i = 0;i < MAX_CHALLENGES;i++)
				if(challenges[i].time > 0)
					if (!LHNETADDRESS_Compare(peeraddress, &challenges[i].address) && !strcmp(challenges[i].string, s))
						break;
			// if the challenge is not recognized, drop the packet
			if (i == MAX_CHALLENGES)
				return Crypto_SoftServerError(data_out, len_out, "invalid challenge in d0pk\\0");

			if (!(s = InfoString_GetValue(string + 4, "aeslevel", infostringvalue, sizeof(infostringvalue))))
				aeslevel = 0; // not supported
			else
				aeslevel = bound(0, atoi(s), 3);
			switch(bound(0, d0_rijndael_dll ? crypto_aeslevel.integer : 0, 3))
			{
				default: // dummy, never happens, but to make gcc happy...
				case 0:
					if(aeslevel >= 3)
						return Crypto_ServerError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)", NULL);
					aes = false;
					break;
				case 1:
					aes = (aeslevel >= 2);
					break;
				case 2:
					aes = (aeslevel >= 1);
					break;
				case 3:
					if(aeslevel <= 0)
						return Crypto_ServerError(data_out, len_out, "This server requires encryption to be supported (crypto_aeslevel >= 1, and d0_rijndael library must be present)", NULL);
					aes = true;
					break;
			}

			p = GetUntilNul(&data_in, &len_in);
			if(p && *p)
			{
				// Find the highest numbered matching key for p.
				for(i = 0; i < MAX_PUBKEYS; ++i)
				{
					if(pubkeys[i])
						if(!strcmp(p, pubkeys_fp64[i]))
							if(pubkeys_havepriv[i])
								serverid = i;
				}
				if(serverid < 0)
					return Crypto_ServerError(data_out, len_out, "Invalid server key", NULL);
			}
			p = GetUntilNul(&data_in, &len_in);
			if(p && *p)
			{
				// Find the highest numbered matching key for p.
				for(i = 0; i < MAX_PUBKEYS; ++i)
				{
					if(pubkeys[i])
						if(!strcmp(p, pubkeys_fp64[i]))
							clientid = i;
				}
				if(clientid < 0)
					return Crypto_ServerError(data_out, len_out, "Invalid client key", NULL);
			}

			crypto = Crypto_ServerFindInstance(peeraddress, true);
			if(!crypto)
				return Crypto_ServerError(data_out, len_out, "Could not create a crypto connect instance", NULL);
			MAKE_CDATA;
			CDATA->cdata_id = id;
			CDATA->s = serverid;
			CDATA->c = clientid;
			memset(crypto->dhkey, 0, sizeof(crypto->dhkey));
			CDATA->challenge[0] = 0;
			crypto->client_keyfp[0] = 0;
			crypto->client_idfp[0] = 0;
			crypto->server_keyfp[0] = 0;
			crypto->server_idfp[0] = 0;
			crypto->use_aes = aes != 0;

			if(CDATA->s >= 0)
			{
				// I am the server, and my key is ok... so let's set server_keyfp and server_idfp
				strlcpy(crypto->server_keyfp, pubkeys_fp64[CDATA->s], sizeof(crypto->server_keyfp));
				strlcpy(crypto->server_idfp, pubkeys_priv_fp64[CDATA->s], sizeof(crypto->server_idfp));
				crypto->server_issigned = pubkeys_havesig[CDATA->s];

				if(!CDATA->id)
					CDATA->id = qd0_blind_id_new();
				if(!CDATA->id)
				{
					CLEAR_CDATA;
					return Crypto_ServerError(data_out, len_out, "d0_blind_id_new failed", "Internal error");
				}
				if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->s]))
				{
					CLEAR_CDATA;
					return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
				}
				PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\1\\id\\%d\\aes\\%d", CDATA->cdata_id, crypto->use_aes));
				if(!qd0_blind_id_authenticate_with_private_id_start(CDATA->id, true, false, "XONOTIC", 8, data_out_p, len_out)) // len_out receives used size by this op
				{
					CLEAR_CDATA;
					return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed", "Internal error");
				}
				CDATA->next_step = 2;
				data_out_p += *len_out;
				*len_out = data_out_p - data_out;
				return CRYPTO_DISCARD;
			}
			else if(CDATA->c >= 0)
			{
				if(!CDATA->id)
					CDATA->id = qd0_blind_id_new();
				if(!CDATA->id)
				{
					CLEAR_CDATA;
					return Crypto_ServerError(data_out, len_out, "d0_blind_id_new failed", "Internal error");
				}
				if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
				{
					CLEAR_CDATA;
					return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
				}
				PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\5\\id\\%d\\aes\\%d", CDATA->cdata_id, crypto->use_aes));
				if(!qd0_blind_id_authenticate_with_private_id_challenge(CDATA->id, true, false, data_in, len_in, data_out_p, len_out, &status))
				{
					CLEAR_CDATA;
					return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed", "Internal error");
				}
				CDATA->next_step = 6;
				data_out_p += *len_out;
				*len_out = data_out_p - data_out;
				return CRYPTO_DISCARD;
			}
			else
			{
				CLEAR_CDATA;
				return Crypto_ServerError(data_out, len_out, "Missing client and server key", NULL);
			}
		}
		else if(!strcmp(cnt, "2"))
		{
			size_t fpbuflen;
			crypto = Crypto_ServerFindInstance(peeraddress, false);
			if(!crypto)
				return CRYPTO_NOMATCH; // pre-challenge, rather be silent
			if(id >= 0)
				if(CDATA->cdata_id != id)
					return Crypto_SoftServerError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
			if(CDATA->next_step != 2)
				return Crypto_SoftServerError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));

			PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\3\\id\\%d", CDATA->cdata_id));
			if(!qd0_blind_id_authenticate_with_private_id_response(CDATA->id, data_in, len_in, data_out_p, len_out))
			{
				CLEAR_CDATA;
				return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_response failed", "Internal error");
			}
			fpbuflen = DHKEY_SIZE;
			if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) crypto->dhkey, &fpbuflen))
			{
				CLEAR_CDATA;
				return Crypto_ServerError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed", "Internal error");
			}
			if(CDATA->c >= 0)
			{
				if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
				{
					CLEAR_CDATA;
					return Crypto_ServerError(data_out, len_out, "d0_blind_id_copy failed", "Internal error");
				}
				CDATA->next_step = 4;
			}
			else
			{
				// session key is FINISHED (no server part is to be expected)! By this, all keys are set up
				crypto->authenticated = true;
				CDATA->next_step = 0;
			}
			data_out_p += *len_out;
			*len_out = data_out_p - data_out;
			return CRYPTO_DISCARD;
		}
		else if(!strcmp(cnt, "4"))
		{
			crypto = Crypto_ServerFindInstance(peeraddress, false);
			if(!crypto)
				return CRYPTO_NOMATCH; // pre-challenge, rather be silent
			if(id >= 0)
				if(CDATA->cdata_id != id)
					return Crypto_SoftServerError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
			if(CDATA->next_step != 4)
				return Crypto_SoftServerError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));
			PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\5\\id\\%d", CDATA->cdata_id));
			if(!qd0_blind_id_authenticate_with_private_id_challenge(CDATA->id, true, false, data_in, len_in, data_out_p, len_out, &status))
			{
				CLEAR_CDATA;
				return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed", "Internal error");
			}
			CDATA->next_step = 6;
			data_out_p += *len_out;
			*len_out = data_out_p - data_out;
			return CRYPTO_DISCARD;
		}
		else if(!strcmp(cnt, "6"))
		{
			static char msgbuf[32];
			size_t msgbuflen = sizeof(msgbuf);
			size_t fpbuflen;
			int i;
			unsigned char dhkey[DHKEY_SIZE];
			crypto = Crypto_ServerFindInstance(peeraddress, false);
			if(!crypto)
				return CRYPTO_NOMATCH; // pre-challenge, rather be silent
			if(id >= 0)
				if(CDATA->cdata_id != id)
					return Crypto_SoftServerError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
			if(CDATA->next_step != 6)
				return Crypto_SoftServerError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));

			if(!qd0_blind_id_authenticate_with_private_id_verify(CDATA->id, data_in, len_in, msgbuf, &msgbuflen, &status))
			{
				CLEAR_CDATA;
				return Crypto_ServerError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_verify failed (authentication error)", "Authentication error");
			}
			strlcpy(crypto->client_keyfp, pubkeys_fp64[CDATA->c], sizeof(crypto->client_keyfp));
			crypto->client_issigned = status;

			memset(crypto->client_idfp, 0, sizeof(crypto->client_idfp));
			fpbuflen = FP64_SIZE;
			if(!qd0_blind_id_fingerprint64_public_id(CDATA->id, crypto->client_idfp, &fpbuflen))
			{
				CLEAR_CDATA;
				return Crypto_ServerError(data_out, len_out, "d0_blind_id_fingerprint64_public_id failed", "Internal error");
			}
			fpbuflen = DHKEY_SIZE;
			if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) dhkey, &fpbuflen))
			{
				CLEAR_CDATA;
				return Crypto_ServerError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed", "Internal error");
			}
			// XOR the two DH keys together to make one
			for(i = 0; i < DHKEY_SIZE; ++i)
				crypto->dhkey[i] ^= dhkey[i];

			// session key is FINISHED (no server part is to be expected)! By this, all keys are set up
			crypto->authenticated = true;
			CDATA->next_step = 0;
			// send a challenge-less challenge
			PutWithNul(&data_out_p, len_out, "challenge ");
			*len_out = data_out_p - data_out;
			--*len_out; // remove NUL terminator
			return CRYPTO_MATCH;
		}
		return CRYPTO_NOMATCH; // pre-challenge, rather be silent
	}
	return CRYPTO_NOMATCH;
}

int Crypto_ServerParsePacket(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
{
	int ret;
	double t = 0;
	static double complain_time = 0;
	const char *cnt;
	qboolean do_time = false;
	qboolean do_reject = false;
	char infostringvalue[MAX_INPUTLINE];
	if(crypto_servercpupercent.value > 0 || crypto_servercpumaxtime.value > 0)
		if(len_in > 5 && !memcmp(data_in, "d0pk\\", 5))
		{
			do_time = true;
			cnt = InfoString_GetValue(data_in + 4, "cnt", infostringvalue, sizeof(infostringvalue));
			if(cnt)
				if(!strcmp(cnt, "0"))
					do_reject = true;
		}
	if(do_time)
	{
		// check if we may perform crypto...
		if(crypto_servercpupercent.value > 0)
		{
			crypto_servercpu_accumulator += (realtime - crypto_servercpu_lastrealtime) * crypto_servercpupercent.value * 0.01;
			if(crypto_servercpumaxtime.value)
				if(crypto_servercpu_accumulator > crypto_servercpumaxtime.value)
					crypto_servercpu_accumulator = crypto_servercpumaxtime.value;
		}
		else
		{
			if(crypto_servercpumaxtime.value > 0)
				if(realtime != crypto_servercpu_lastrealtime)
					crypto_servercpu_accumulator = crypto_servercpumaxtime.value;
		}
		crypto_servercpu_lastrealtime = realtime;
		if(do_reject && crypto_servercpu_accumulator < 0)
		{
			if(realtime > complain_time + 5)
				Con_Printf("crypto: cannot perform requested crypto operations; denial service attack or crypto_servercpupercent/crypto_servercpumaxtime are too low\n");
			*len_out = 0;
			return CRYPTO_DISCARD;
		}
		t = Sys_DirtyTime();
	}
	ret = Crypto_ServerParsePacket_Internal(data_in, len_in, data_out, len_out, peeraddress);
	if(do_time)
	{
		t = Sys_DirtyTime() - t;if (t < 0.0) t = 0.0; // dirtytime can step backwards
		if(crypto_servercpudebug.integer)
			Con_Printf("crypto: accumulator was %.1f ms, used %.1f ms for crypto, ", crypto_servercpu_accumulator * 1000, t * 1000);
		crypto_servercpu_accumulator -= t;
		if(crypto_servercpudebug.integer)
			Con_Printf("is %.1f ms\n", crypto_servercpu_accumulator * 1000);
	}
	return ret;
}

static int Crypto_ClientError(char *data_out, size_t *len_out, const char *msg)
{
	dpsnprintf(data_out, *len_out, "reject %s", msg);
	*len_out = strlen(data_out);
	return CRYPTO_REPLACE;
}

static int Crypto_SoftClientError(char *data_out, size_t *len_out, const char *msg)
{
	*len_out = 0;
	Con_DPrintf("%s\n", msg);
	return CRYPTO_DISCARD;
}

int Crypto_ClientParsePacket(const char *data_in, size_t len_in, char *data_out, size_t *len_out, lhnetaddress_t *peeraddress)
{
	crypto_t *crypto = &cls.crypto;
	const char *string = data_in;
	const char *s;
	D0_BOOL aes;
	char *data_out_p = data_out;
	D0_BOOL status;
	char infostringvalue[MAX_INPUTLINE];
	char vabuf[1024];

	if(!d0_blind_id_dll)
		return CRYPTO_NOMATCH; // no support

	// if "challenge": verify challenge, and discard message, send next crypto protocol message instead
	// otherwise, just handle actual protocol messages

	if (len_in == 6 && !memcmp(string, "accept", 6) && cls.connect_trying && d0_rijndael_dll)
	{
		int wantserverid = -1;
		Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, NULL, 0, NULL, NULL);
		if(!crypto || !crypto->authenticated) // we ALSO get here if we are using an encrypted connection, so let's rule this out
		{
			if(wantserverid >= 0)
				return Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though a host key is present");
			if(crypto_aeslevel.integer >= 3)
				return Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)");
		}
		return CRYPTO_NOMATCH;
	}
	else if (len_in >= 1 && string[0] == 'j' && cls.connect_trying && d0_rijndael_dll)
	{
		int wantserverid = -1;
		Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, NULL, 0, NULL, NULL);
		//if(!crypto || !crypto->authenticated)
		{
			if(wantserverid >= 0)
				return Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though a host key is present");
			if(crypto_aeslevel.integer >= 3)
				return Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)");
		}
		return CRYPTO_NOMATCH;
	}
	else if (len_in >= 5 && BuffLittleLong((unsigned char *) string) == ((int)NETFLAG_CTL | (int)len_in))
	{
		int wantserverid = -1;

		// these three are harmless
		if((unsigned char) string[4] == CCREP_SERVER_INFO)
			return CRYPTO_NOMATCH;
		if((unsigned char) string[4] == CCREP_PLAYER_INFO)
			return CRYPTO_NOMATCH;
		if((unsigned char) string[4] == CCREP_RULE_INFO)
			return CRYPTO_NOMATCH;

		Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, NULL, 0, NULL, NULL);
		//if(!crypto || !crypto->authenticated)
		{
			if(wantserverid >= 0)
				return Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though a host key is present");
			if(crypto_aeslevel.integer >= 3)
				return Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)");
		}
		return CRYPTO_NOMATCH;
	}
	else if (len_in >= 13 && !memcmp(string, "infoResponse\x0A", 13))
	{
		s = InfoString_GetValue(string + 13, "d0_blind_id", infostringvalue, sizeof(infostringvalue));
		if(s)
			Crypto_StoreHostKey(peeraddress, s, true);
		return CRYPTO_NOMATCH;
	}
	else if (len_in >= 15 && !memcmp(string, "statusResponse\x0A", 15))
	{
		char save = 0;
		const char *p;
		p = strchr(string + 15, '\n');
		if(p)
		{
			save = *p;
			* (char *) p = 0; // cut off the string there
		}
		s = InfoString_GetValue(string + 15, "d0_blind_id", infostringvalue, sizeof(infostringvalue));
		if(s)
			Crypto_StoreHostKey(peeraddress, s, true);
		if(p)
		{
			* (char *) p = save;
			// invoking those nasal demons again (do not run this on the DS9k)
		}
		return CRYPTO_NOMATCH;
	}
	else if(len_in > 10 && !memcmp(string, "challenge ", 10) && cls.connect_trying)
	{
		const char *vlen_blind_id_ptr = NULL;
		size_t len_blind_id_ptr = 0;
		unsigned long k, v;
		const char *challenge = data_in + 10;
		const char *p;
		int i;
		int clientid = -1, serverid = -1, wantserverid = -1;
		qboolean server_can_auth = true;
		char wantserver_idfp[FP64_SIZE+1];
		int wantserver_aeslevel = 0;
		qboolean wantserver_issigned = false;

		// Must check the source IP here, if we want to prevent other servers' replies from falsely advancing the crypto state, preventing successful connect to the real server.
		if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address))
			return Crypto_SoftClientError(data_out, len_out, "challenge message from wrong server");

		// if we have a stored host key for the server, assume serverid to already be selected!
		// (the loop will refuse to overwrite this one then)
		wantserver_idfp[0] = 0;
		Crypto_RetrieveHostKey(&cls.connect_address, &wantserverid, NULL, 0, wantserver_idfp, sizeof(wantserver_idfp), &wantserver_aeslevel, &wantserver_issigned);
		// requirement: wantserver_idfp is a full ID if wantserverid set

		// if we leave, we have to consider the connection
		// unauthenticated; NOTE: this may be faked by a clever
		// attacker to force an unauthenticated connection; so we have
		// a safeguard check in place when encryption is required too
		// in place, or when authentication is required by the server
		crypto->authenticated = false;

		GetUntilNul(&data_in, &len_in);
		if(!data_in)
			return (wantserverid >= 0) ? Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though a host key is present") :
				(d0_rijndael_dll && crypto_aeslevel.integer >= 3) ? Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)") :
				CRYPTO_NOMATCH;

		// FTEQW extension protocol
		while(len_in >= 8)
		{
			k = Crypto_LittleLong(data_in);
			v = Crypto_LittleLong(data_in + 4);
			data_in += 8;
			len_in -= 8;
			switch(k)
			{
				case PROTOCOL_VLEN:
					if(len_in >= 4 + v)
					{
						k = Crypto_LittleLong(data_in);
						data_in += 4;
						len_in -= 4;
						switch(k)
						{
							case PROTOCOL_D0_BLIND_ID:
								vlen_blind_id_ptr = data_in;
								len_blind_id_ptr = v;
								break;
						}
						data_in += v;
						len_in -= v;
					}
					break;
				default:
					break;
			}
		}

		if(!vlen_blind_id_ptr)
			return (wantserverid >= 0) ? Crypto_ClientError(data_out, len_out, "Server tried an unauthenticated connection even though authentication is required") :
				(d0_rijndael_dll && crypto_aeslevel.integer >= 3) ? Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)") :
				CRYPTO_NOMATCH;

		data_in = vlen_blind_id_ptr;
		len_in = len_blind_id_ptr;

		// parse fingerprints
		//   once we found a fingerprint we can auth to (ANY), select it as clientfp
		//   once we found a fingerprint in the first list that we know, select it as serverfp

		for(;;)
		{
			p = GetUntilNul(&data_in, &len_in);
			if(!p)
				break;
			if(!*p)
			{
				if(!server_can_auth)
					break; // other protocol message may follow
				server_can_auth = false;
				if(clientid >= 0)
					break;
				continue;
			}
			// Find the highest numbered matching key for p.
			for(i = 0; i < MAX_PUBKEYS; ++i)
			{
				if(pubkeys[i])
				if(!strcmp(p, pubkeys_fp64[i]))
				{
					if(pubkeys_havepriv[i])
						clientid = i;
					if(server_can_auth)
						if(wantserverid < 0 || i == wantserverid)
							serverid = i;
				}
			}
			// Not breaking, as higher keys in the list always have priority.
		}

		// if stored host key is not found:
		if(wantserverid >= 0 && serverid < 0)
			return Crypto_ClientError(data_out, len_out, "Server CA does not match stored host key, refusing to connect");

		if(serverid >= 0 || clientid >= 0)
		{
			MAKE_CDATA;
			CDATA->cdata_id = ++cdata_id;
			CDATA->s = serverid;
			CDATA->c = clientid;
			memset(crypto->dhkey, 0, sizeof(crypto->dhkey));
			strlcpy(CDATA->challenge, challenge, sizeof(CDATA->challenge));
			crypto->client_keyfp[0] = 0;
			crypto->client_idfp[0] = 0;
			crypto->server_keyfp[0] = 0;
			crypto->server_idfp[0] = 0;
			memcpy(CDATA->wantserver_idfp, wantserver_idfp, sizeof(crypto->server_idfp));
			CDATA->wantserver_issigned = wantserver_issigned;

			if(CDATA->wantserver_idfp[0]) // if we know a host key, honor its encryption setting
			switch(bound(0, d0_rijndael_dll ? crypto_aeslevel.integer : 0, 3))
			{
				default: // dummy, never happens, but to make gcc happy...
				case 0:
					if(wantserver_aeslevel >= 3)
						return Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)");
					CDATA->wantserver_aes = false;
					break;
				case 1:
					CDATA->wantserver_aes = (wantserver_aeslevel >= 2);
					break;
				case 2:
					CDATA->wantserver_aes = (wantserver_aeslevel >= 1);
					break;
				case 3:
					if(wantserver_aeslevel <= 0)
						return Crypto_ClientError(data_out, len_out, "This server requires encryption to be supported (crypto_aeslevel >= 1, and d0_rijndael library must be present)");
					CDATA->wantserver_aes = true;
					break;
			}

			// build outgoing message
			// append regular stuff
			PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\0\\id\\%d\\aeslevel\\%d\\challenge\\%s", CDATA->cdata_id, d0_rijndael_dll ? crypto_aeslevel.integer : 0, challenge));
			PutWithNul(&data_out_p, len_out, serverid >= 0 ? pubkeys_fp64[serverid] : "");
			PutWithNul(&data_out_p, len_out, clientid >= 0 ? pubkeys_fp64[clientid] : "");

			if(clientid >= 0)
			{
				// I am the client, and my key is ok... so let's set client_keyfp and client_idfp
				strlcpy(crypto->client_keyfp, pubkeys_fp64[CDATA->c], sizeof(crypto->client_keyfp));
				strlcpy(crypto->client_idfp, pubkeys_priv_fp64[CDATA->c], sizeof(crypto->client_idfp));
				crypto->client_issigned = pubkeys_havesig[CDATA->c];
			}

			if(serverid >= 0)
			{
				if(!CDATA->id)
					CDATA->id = qd0_blind_id_new();
				if(!CDATA->id)
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "d0_blind_id_new failed");
				}
				if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->s]))
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
				}
				CDATA->next_step = 1;
				*len_out = data_out_p - data_out;
			}
			else // if(clientid >= 0) // guaranteed by condition one level outside
			{
				// skip over server auth, perform client auth only
				if(!CDATA->id)
					CDATA->id = qd0_blind_id_new();
				if(!CDATA->id)
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "d0_blind_id_new failed");
				}
				if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
				}
				if(!qd0_blind_id_authenticate_with_private_id_start(CDATA->id, true, false, "XONOTIC", 8, data_out_p, len_out)) // len_out receives used size by this op
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed");
				}
				CDATA->next_step = 5;
				data_out_p += *len_out;
				*len_out = data_out_p - data_out;
			}
			return CRYPTO_DISCARD;
		}
		else
		{
			if(wantserver_idfp[0]) // if we know a host key, honor its encryption setting
			if(wantserver_aeslevel >= 3)
				return Crypto_ClientError(data_out, len_out, "Server insists on encryption, but neither can authenticate to the other");
			return (d0_rijndael_dll && crypto_aeslevel.integer >= 3) ? Crypto_ClientError(data_out, len_out, "This server requires encryption to be not required (crypto_aeslevel <= 2)") :
				CRYPTO_NOMATCH;
		}
	}
	else if(len_in > 5 && !memcmp(string, "d0pk\\", 5) && cls.connect_trying)
	{
		const char *cnt;
		int id;

		// Must check the source IP here, if we want to prevent other servers' replies from falsely advancing the crypto state, preventing successful connect to the real server.
		if (net_sourceaddresscheck.integer && LHNETADDRESS_Compare(peeraddress, &cls.connect_address))
			return Crypto_SoftClientError(data_out, len_out, "d0pk\\ message from wrong server");

		cnt = InfoString_GetValue(string + 4, "id", infostringvalue, sizeof(infostringvalue));
		id = (cnt ? atoi(cnt) : -1);
		cnt = InfoString_GetValue(string + 4, "cnt", infostringvalue, sizeof(infostringvalue));
		if(!cnt)
			return Crypto_ClientError(data_out, len_out, "d0pk\\ message without cnt");
		GetUntilNul(&data_in, &len_in);
		if(!data_in)
			return Crypto_ClientError(data_out, len_out, "d0pk\\ message without attachment");

		if(!strcmp(cnt, "1"))
		{
			if(id >= 0)
				if(CDATA->cdata_id != id)
					return Crypto_SoftClientError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
			if(CDATA->next_step != 1)
				return Crypto_SoftClientError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));

			cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"

			if((s = InfoString_GetValue(string + 4, "aes", infostringvalue, sizeof(infostringvalue))))
				aes = atoi(s);
			else
				aes = false;
			// we CANNOT toggle the AES status any more!
			// as the server already decided
			if(CDATA->wantserver_idfp[0]) // if we know a host key, honor its encryption setting
			if(!aes && CDATA->wantserver_aes)
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "Stored host key requires encryption, but server did not enable encryption");
			}
			if(aes && (!d0_rijndael_dll || crypto_aeslevel.integer <= 0))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "Server insists on encryption too hard");
			}
			if(!aes && (d0_rijndael_dll && crypto_aeslevel.integer >= 3))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "Server insists on plaintext too hard");
			}
			crypto->use_aes = aes != 0;

			PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\2\\id\\%d", CDATA->cdata_id));
			if(!qd0_blind_id_authenticate_with_private_id_challenge(CDATA->id, true, false, data_in, len_in, data_out_p, len_out, &status))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_challenge failed");
			}
			CDATA->next_step = 3;
			data_out_p += *len_out;
			*len_out = data_out_p - data_out;
			return CRYPTO_DISCARD;
		}
		else if(!strcmp(cnt, "3"))
		{
			static char msgbuf[32];
			size_t msgbuflen = sizeof(msgbuf);
			size_t fpbuflen;

			if(id >= 0)
				if(CDATA->cdata_id != id)
					return Crypto_SoftClientError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
			if(CDATA->next_step != 3)
				return Crypto_SoftClientError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));

			cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"

			if(!qd0_blind_id_authenticate_with_private_id_verify(CDATA->id, data_in, len_in, msgbuf, &msgbuflen, &status))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_verify failed (server authentication error)");
			}

			strlcpy(crypto->server_keyfp, pubkeys_fp64[CDATA->s], sizeof(crypto->server_keyfp));
			if (!status && CDATA->wantserver_issigned)
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "Stored host key requires a valid signature, but server did not provide any");
			}
			crypto->server_issigned = status;

			memset(crypto->server_idfp, 0, sizeof(crypto->server_idfp));
			fpbuflen = FP64_SIZE;
			if(!qd0_blind_id_fingerprint64_public_id(CDATA->id, crypto->server_idfp, &fpbuflen))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "d0_blind_id_fingerprint64_public_id failed");
			}
			if(CDATA->wantserver_idfp[0])
			if(memcmp(CDATA->wantserver_idfp, crypto->server_idfp, sizeof(crypto->server_idfp)))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "Server ID does not match stored host key, refusing to connect");
			}
			fpbuflen = DHKEY_SIZE;
			if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) crypto->dhkey, &fpbuflen))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed");
			}

			// cache the server key
			Crypto_StoreHostKey(&cls.connect_address, va(vabuf, sizeof(vabuf), "%d %s@%s%s", crypto->use_aes ? 1 : 0, crypto->server_idfp, crypto->server_issigned ? "" : "~", pubkeys_fp64[CDATA->s]), false);

			if(CDATA->c >= 0)
			{
				// client will auth next
				PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\4\\id\\%d", CDATA->cdata_id));
				if(!qd0_blind_id_copy(CDATA->id, pubkeys[CDATA->c]))
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "d0_blind_id_copy failed");
				}
				if(!qd0_blind_id_authenticate_with_private_id_start(CDATA->id, true, false, "XONOTIC", 8, data_out_p, len_out)) // len_out receives used size by this op
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_start failed");
				}
				CDATA->next_step = 5;
				data_out_p += *len_out;
				*len_out = data_out_p - data_out;
				return CRYPTO_DISCARD;
			}
			else
			{
				// session key is FINISHED (no server part is to be expected)! By this, all keys are set up
				crypto->authenticated = true;
				CDATA->next_step = 0;
				// assume we got the empty challenge to finish the protocol
				PutWithNul(&data_out_p, len_out, "challenge ");
				*len_out = data_out_p - data_out;
				--*len_out; // remove NUL terminator
				return CRYPTO_REPLACE;
			}
		}
		else if(!strcmp(cnt, "5"))
		{
			size_t fpbuflen;
			unsigned char dhkey[DHKEY_SIZE];
			int i;

			if(id >= 0)
				if(CDATA->cdata_id != id)
					return Crypto_SoftClientError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\id\\%d when expecting %d", id, CDATA->cdata_id));
			if(CDATA->next_step != 5)
				return Crypto_SoftClientError(data_out, len_out, va(vabuf, sizeof(vabuf), "Got d0pk\\cnt\\%s when expecting %d", cnt, CDATA->next_step));

			cls.connect_nextsendtime = max(cls.connect_nextsendtime, realtime + 1); // prevent "hammering"

			if(CDATA->s < 0) // only if server didn't auth
			{
				if((s = InfoString_GetValue(string + 4, "aes", infostringvalue, sizeof(infostringvalue))))
					aes = atoi(s);
				else
					aes = false;
				if(CDATA->wantserver_idfp[0]) // if we know a host key, honor its encryption setting
				if(!aes && CDATA->wantserver_aes)
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "Stored host key requires encryption, but server did not enable encryption");
				}
				if(aes && (!d0_rijndael_dll || crypto_aeslevel.integer <= 0))
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "Server insists on encryption too hard");
				}
				if(!aes && (d0_rijndael_dll && crypto_aeslevel.integer >= 3))
				{
					CLEAR_CDATA;
					return Crypto_ClientError(data_out, len_out, "Server insists on plaintext too hard");
				}
				crypto->use_aes = aes != 0;
			}

			PutWithNul(&data_out_p, len_out, va(vabuf, sizeof(vabuf), "d0pk\\cnt\\6\\id\\%d", CDATA->cdata_id));
			if(!qd0_blind_id_authenticate_with_private_id_response(CDATA->id, data_in, len_in, data_out_p, len_out))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "d0_blind_id_authenticate_with_private_id_response failed");
			}
			fpbuflen = DHKEY_SIZE;
			if(!qd0_blind_id_sessionkey_public_id(CDATA->id, (char *) dhkey, &fpbuflen))
			{
				CLEAR_CDATA;
				return Crypto_ClientError(data_out, len_out, "d0_blind_id_sessionkey_public_id failed");
			}
			// XOR the two DH keys together to make one
			for(i = 0; i < DHKEY_SIZE; ++i)
				crypto->dhkey[i] ^= dhkey[i];
			// session key is FINISHED! By this, all keys are set up
			crypto->authenticated = true;
			CDATA->next_step = 0;
			data_out_p += *len_out;
			*len_out = data_out_p - data_out;
			return CRYPTO_DISCARD;
		}
		return Crypto_SoftClientError(data_out, len_out, "Got unknown d0_blind_id message from server");
	}

	return CRYPTO_NOMATCH;
}

size_t Crypto_SignData(const void *data, size_t datasize, int keyid, void *signed_data, size_t signed_size)
{
	if(keyid < 0 || keyid >= MAX_PUBKEYS)
		return 0;
	if(!pubkeys_havepriv[keyid])
		return 0;
	if(qd0_blind_id_sign_with_private_id_sign(pubkeys[keyid], true, false, (const char *)data, datasize, (char *)signed_data, &signed_size))
		return signed_size;
	return 0;
}

size_t Crypto_SignDataDetached(const void *data, size_t datasize, int keyid, void *signed_data, size_t signed_size)
{
	if(keyid < 0 || keyid >= MAX_PUBKEYS)
		return 0;
	if(!pubkeys_havepriv[keyid])
		return 0;
	if(qd0_blind_id_sign_with_private_id_sign_detached(pubkeys[keyid], true, false, (const char *)data, datasize, (char *)signed_data, &signed_size))
		return signed_size;
	return 0;
}