summaryrefslogtreecommitdiffstats
path: root/src/dht.c
blob: 97c54ea2b4c794f6642af78d85dd7d4a211b324d (plain) (blame)
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
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
#include <time.h>
#include <sys/random.h>
#include <errno.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <limits.h>
#include <assert.h>
#include <sha1.h> // http://github.com/clibs/sha1 and in major distributions
#include <sha2.h>
#define ECB 1
#define AES128 1
#include <aes.c>
#include <bencoding.c>
#define STRX(x) #x
#define STR(x) STRX(x)
#include <lib.c>

time_t seconds (void) {
	struct timespec tp;
	clock_gettime(CLOCK_MONOTONIC, &tp);
	return tp.tv_sec;
}

int family (const unsigned char * addr) {
	return memcmp("\0\0\0\0\0\0\0\0\0\0\xFF\xFF", addr, 12) ? AF_INET6 : AF_INET;
}

#define K 8

/**
 * node representation
 */

struct node {
	unsigned char id[20];
	struct sockaddr_in6 addr;
	int unanswered; /**< number of packets I've sent since last_received */
	time_t last_received; /**< time when I received the last packet from it */
	time_t last_sent; /**< time when I sent the last query to it. not incremented if it has unanswered queries. */
	struct node * next;
#define SERVER_ERRORS_BAD 15
	unsigned server_errors; /**< number of server errors, set node grade to bad if more than SERVER_ERRORS_BAD. reset when replied() */
};

/**
 * creates a new node
 */

unsigned node_init_count = 0;

struct node * node_init (void) {
	struct node * n = calloc(1, sizeof *n);
	if (!n)
		return NULL;
	node_init_count++;
	n->last_received = seconds();
	n->addr.sin6_family = AF_INET6;
	return n;
}

/**
 * frees a node
 *
 * @param n	[in]	the node to be freed
 */

unsigned node_free_count = 0;

void node_free (struct node * n) {
	node_free_count++;
	free(n);
}

enum node_grade {
	good,
	bad,
	questionable
};

/**
 * @return a textual form of node_grade enum
 */

char * node_grade_str (enum node_grade g) {
	switch (g) {
		case good:
			return "good";
		case bad:
			return "bad";
		case questionable:
			return "questionable";
	}
	return "unknown node_grade";
}

/**
 * determines if node is considered good, bad or questionable
 *
 * @param n	[in]	node
 * @return enum node_grade
 */

#define QUESTIONABLE_AFTER (15*60)

enum node_grade node_grade (const struct node * n) {
	if (n->server_errors > SERVER_ERRORS_BAD)
		return bad;
	if (n->last_received + QUESTIONABLE_AFTER < seconds()) {
		if (n->last_sent + 60 < seconds() && n->unanswered > 1)
			return bad;
		return questionable;
	}
	return good;
}

/**
 * print node to stream, for debugging
 *
 * @param s	[out]	the stream to which to print to
 * @param n	[in]	the node to be printed
 */

void node_print (FILE * s, const struct node * n) {
	char buf[41];
	buf[40] = '\0';
	bin2hex(buf, n->id, 20);
	char remote[INET6_ADDRSTRLEN + 64];
	if (!inet_ntop(n->addr.sin6_family, n->addr.sin6_addr.s6_addr, remote, INET6_ADDRSTRLEN+7))
		snprintf(remote, sizeof remote,  "(inet_ntop: %s)", strerror(errno));
	fprintf(s, "%s %s/%d unans=%d %s", buf, remote, ntohs(n->addr.sin6_port), n->unanswered, node_grade_str(node_grade(n)));
}

/**
 * returns which 20 byte bytestring is closer with XOR metric to target 20 byte bytestring
 *
 * at most 20 bytes are read from each pointer
 *{
 * @param a	[in]	20 byte to consider
 * @param b	[in]	20 byte string to consider
 * @param t	[in]	target
 * @return 0 if a is closer or 1 if b is closer, -1 if both are the same
 */

int closer (const unsigned char * a, const unsigned char * b, const unsigned char * t) {
	for (int i = 0; i < 20; i++) {
		if ((a[i] ^ t[i]) < (b[i] ^ t[i]))
			return 0;
		if ((a[i] ^ t[i]) > (b[i] ^ t[i]))
			return 1;
	}
	return -1;
}

/**
 * bucket representation
 */

struct bucket {
	unsigned char id[20]; /**< bucket spans from id inclusive to next->id exclusive */
	struct node * nodes;
	struct bucket * next;
};

/**
 * creates a new bucket
 */

struct bucket * bucket_init (void) {
	struct bucket * b = calloc(1, sizeof *b);
	if (!b)
		return NULL;
	return b;
}

/**
 * frees a bucket
 *
 * @param b	[in]	the bucket to be freed
 */

void bucket_free (struct bucket * b) {
	struct node * node = b->nodes;
	while (node) {
		struct node * old = node;
		node = node->next;
		node_free(old);
	}
	free(b);
}

enum flags {
	nometasupport = 1 << 1, /**< peer does not support BEP-0009 metadata fetch extension */
	nometa = 1 << 2, /**< peer has no metadata downloaded */
	goodmeta = 1 << 3, /**< peer gave us good metadata that is currently stored in the torrent */
	badmeta = 1 << 4, /**< peer gave us bogus metadata that does not match it's hash */
	unreachable = 1 << 5, /**< pear unreachable - timed out */
	requested = 1 << 6, /**< because choking is unimplemented, packets are sent like with TFTP, a request is sent only when a reply is received */
	protocolerror = 1 << 7 /**< I don't understand you my g */
};

/**
 * peer of a torrent
 */

struct peer {
	enum flags flags;
	struct sockaddr_in6 addr; /**< peer ip address and port */
	struct peer * next;
};

/**
 * init a torrent peer
 */

struct peer * peer_init () {
	struct peer * p = calloc(1, sizeof *p);
	p->addr.sin6_family = AF_INET6;
	return p;
}

/**
 * free a torrent peer
 */

void peer_free (struct peer * p) {
	free(p);
}

/**
 * print a peer, for debugging purposes
 *
 * @param s	[out]	stream
 * @param p	[in]	peer
 */

void peer_print (FILE * s, const struct peer * p) {
	char remote[INET6_ADDRSTRLEN + 64];
	if (!inet_ntop(p->addr.sin6_family, p->addr.sin6_addr.s6_addr, remote, INET6_ADDRSTRLEN+7))
		snprintf(remote, sizeof remote,  "(inet_ntop: %s)", strerror(errno));
	fprintf(s, "%s/%d %s%s%s%s%s%s%s", remote, ntohs(p->addr.sin6_port), p->flags & nometasupport ? " nometasupport" : "", p->flags & nometa ? " nometa" : "", p->flags & goodmeta ? " goodmeta" : "", p->flags & badmeta ? " badmeta" : "", p->flags & unreachable ? " unreachable" : "", p->flags & requested ? " requested" : "", p->flags & protocolerror ? " protocolerror" : "");
}

/**
 * reason why a torrent is in our database. 0 just means it is stored as a result of an announce
 */

enum interested {
	announce = 1 << 0, /**< will announce myself periodically */
	peers = 1 << 1, /**< will get peers on every work() call with no packet */
	info = 1 << 2 /**< download metadata */
};

/**
 * state a tcp peer connection
 */

enum state {
	blank = 0,
	handshake_sent = 1,
	handshake_received = 1 << 1,
	extension_sent = 1 << 2,
	extension_received = 1 << 3,
	incoming = 1 << 4,
	outgoing = 1 << 5
};

#define DLTO 5 /**< timeout for torrent downloading - if this amount of seconds has passed and no new metadata piece was received, mark peer as unreach and disconnect */

/**
 * torrent we are either interested in or are storing metadata for
 */

struct torrent {
	unsigned char ut_metadata; /**< remote's byte for metadata transfer */
	unsigned char ut_pex; /**< remote's byte for pex */
	enum state state; /**< state of tcp connection */
	int socket; /**< tcp socket for bep-0009, enough to be stored in torrent since we only connect to one peer at a time */
#ifdef TORRENT_USERDATA
	TORRENT_USERDATA
#else
	void * userdata; /**< library user may use this to his will in dht->connection() and torrent->disconnection() */
#endif
	void (* disconnection)(struct torrent *); /**< user provided function that is called before torrent->socket is to be closed and must be removed from the pollfds list. that's a perfect time to store metadata, provided that ->dl->flags & goodmeta */
	struct peer * dl; /**< peer that's currently used for downloading metadata (only one at a time) */
	time_t time; /**< beginning of metadata download process or time of last received metadata piece */
	enum interested type; /**< is truthy only for manually added torrents */
	unsigned char hash[20]; /**< infohash */
	struct peer * peers;
	struct node * nodes; /**< closest K DHT nodes to this hash, used only for announce, peers and info torrents */
	struct torrent * next;
	struct torrent * prev; /**< prev is here so that we can easily pop the oldest torrent. dht->last_torrent is useful here */
	int progress; /**< number of pieces of metadata already downloaded */
	int size; /**< number of bytes of metadata for info torrents */
	unsigned char * metadata; /**< metadata being downloaded */
	void (* intentions)(struct torrent *); /**< user provided function that is called to update the user with my intentions - do I expect data to be read or written or both with this socket. the user should check if (t->state & incoming) and (t->state & outgoing) and set POLLIN and POLLOUT for example in his pollfds */
	unsigned char * packet; /**< packet being constructed from tcp for info torrents, 32727 bytes */
	int recvd; /**< length of received data for current packet */
	char * software; /**< can be read from disconnection() - software string client sent, may be NULL */
	time_t ttl; /**< if nonzero, torrent will get his ->type cleared after this seconds() timestamp. set to seconds()+512 for example */
	unsigned canary; /**< for debugging purposes. assert that it's zero. set in free. */
};

/**
 * initializes a torrent
 *
 * @return torrent object allocated on heap, memory ownership/responsibility is transfered to caller
 */

struct torrent * torrent_init (void) {
	struct torrent * t = calloc(1, sizeof *t);
	t->socket = -1;
	return t;
}

/**
 * kill peer connection and metadata download of torrent
 */

void disconnect (struct torrent * t) {
	if (t->disconnection && t->dl)
		t->disconnection(t);
	if (t->socket != -1)
		close(t->socket);
	t->socket = -1;
	t->state = 0;
	if (t->dl)
		t->dl->flags &= ~(requested);
	t->dl = NULL;
	t->size = 0;
	t->progress = 0;
	t->ut_metadata = 0;
	t->ut_pex = 0;
	free(t->packet);
	t->packet = NULL;
	t->recvd = 0;
	free(t->software);
	t->software = NULL;
}

/**
 * free a torrent object and it's nodes and peers
 */

void torrent_free (struct torrent * t) {
	if (!t)
		return;
	disconnect(t);
	struct node * n = t->nodes;
	while (n) {
		struct node * old = n;
		n = n->next;
		node_free(old);
	}
	struct peer * p = t->peers;
	while (p) {
		struct peer * old = p;
		p = p->next;
		peer_free(old);
	}
	free(t->software);
	free(t->metadata);
	t->canary = UINT_MAX;
	free(t);
}

/**
 * compares two torrent objects based on their hash
 */

int torrent_compare (const void * a, const void * b) {
	return memcmp(((const struct torrent *) a)->hash, ((const struct torrent *) b)->hash, 20);
}

/**
 * prints a torrent, for debugging purposes
 *
 * @param s	[out]	stream to which to write to
 * @param t	[in]	the torrent to print
 */

void torrent_print (FILE * s, const struct torrent * t) {
	char buf[41];
	buf[40] = '\0';
	bin2hex(buf, t->hash, 20);
	printf("magnet:?xt=urn:btih:%s%s%s%s%s%s%s%s ttl=%ld\n\t**** PEERS ****\n", buf, t->type & announce ? " announce" : "", t->type & peers ? " peers" : "", t->type & info ? " info" : "", t->state & handshake_sent ? " handshake_sent" : "", t->state & handshake_received ? " handshake_received" : "", t->state & extension_sent ? " extension_sent" : "", t->state & extension_received ? " extension_received" : "", t->ttl > 0 ? t->ttl-seconds() : -1);
	struct peer * p = t->peers;
	while (p) {
		fprintf(s, "\t");
		peer_print(s, p);
		if (t->dl == p)
			fprintf(s, "dl=%lds\n", seconds()-t->time);
		else
			fprintf(s, "\n");
		p = p->next;
	}
	printf("\t**** NODES ****\n");
	struct node * n = t->nodes;
	while (n) {
		fprintf(s, "\t");
		node_print(s, n);
		fprintf(s, "\n");
		n = n->next;
	}
}

/**
 * assert that torrent linked list is correct and contains no freed structures
 *
 * @param t	[in]	first element of torrent linked list
 */

void torrent_ll_assert (const struct torrent * t) {
	for (; t != NULL; t = t->next)
		assert(!t->canary);
}

/**
 * what to log to FILE * from L()
 */

enum verbosity {
	incoming_dht = 1,
	outgoing_dht = 1 << 1,
	std_fail = 1 << 2,
	disagreement = 1 << 3,
	expected = 1 << 4,
	user = 1 << 5,
	debug = 1 << 6,
};

/**
 * @return static string representation of a log message type
 */

char * verbosity2str (enum verbosity v) {
	switch (v) {
		case incoming_dht:
			return "incoming_dht";
		case outgoing_dht:
			return "outgoing_dht";
		case std_fail:
			return "std_fail";
		case disagreement:
			return "disagreement";
		case expected:
			return "expected";
		case user:
			return "user";
		case debug:
			return "debug";
		default:
			return "unknown";
	}
}

/**
 * handle for the library
 */

struct dht {
	unsigned char id[20]; /**< own id */
	int socket; /**< v4&v6 UDP socket that is bound on UDP and sends to nodes */
	unsigned char secret[16]; /**< for calculating opaque write token, random */
	FILE * log; /**< FILE to log to, defaults to stderr */
	struct bucket * buckets;
	struct bucket * buckets6; /**< IPv6 routing table */
	struct torrent * torrents; /**< linked list of torrents for which we want to know peers */
	void (* possible_torrent)(struct dht *, const unsigned char *, struct torrent *); /**< a user callback function that is called whenever we come across a torrent hash from a network. the library may signal that this torrent is in storage by including a pointer to it in the call, but this is not required. the torrent may be stored, but it wasn't reported to be stored since when we came across the hash we didn't need to look the torrent up. but if the torrent pointer is non NULL, it's definitely stored */
#ifdef DHT_USERDATA
	DHT_USERDATA
#else
	void * userdata; /**< unused, but left for the library user to set so he can refer back to his structures from callback code, such as dht->possible_torrent(d, h, t) */
#endif
	unsigned torrents_num; /**< number of torrents. this number can rise indefinitely, so it can, and should be capped by the caller, depending on available memory */
	unsigned peers_num; /**< number of peers. same notice regarding memory applies here as for torrents */
	unsigned torrents_max; /**< max number of torrents that we are allowed to store */
	unsigned peers_max; /**< max number of peers that we are allowed to store */
	struct torrent * last_torrent; /**< to quickly go to the end of the doubly linked list of torrents is helpful when reaching torrents_max and needing to pop oldest */
	unsigned peers_per_torrent_max; /**< max number of peers to store per torrent - applies to ->type and !->type torrents */
	unsigned time; /**< statistics: time of initialization, for amount of seconds since initialization, check seconds() */
	unsigned rxp; /**< statistics: total number of received packets */
	unsigned txp; /**< statistics: total number of sent packets */
	unsigned rxb; /**< statistics: total number of bytes in received UDP bodies */
	unsigned txb; /**< statistics: total number of bytes in transmitted UDP bodies */
	unsigned tcp_max; /**< max number of tcp connections to peers */
	void (* connection)(struct dht *, struct torrent *); /**< function for maintaining file descriptors for metadata downloading. this function is called with the torrent that just attempted to connect to a peer. it's the responsibility of the library user to then add the torrent->socket fd to a poll list of fds and to add a function in torrent->disconnection that will be called whenever the fd is closed so that the library user may remove the fd from the pollfds list. */
	unsigned tt; /**< tcp transmitted bytes */
	unsigned tr; /**< tcp received bytes */
	enum verbosity verbosity; /**< what to log */
#ifdef SAMPLE
	unsigned char sample[60000]; /**< for sample infohashes */
	int samples; /**< for sample infohashes, max 3000 */
#endif
	unsigned p; /**< number of sent pings */
#define PINGS_CAP 256 /**< capacity of circular buffer, one element is ~28 bytes, so this is 7168 B */
	struct sockaddr_in6 pings[PINGS_CAP]; /**< circular buffer of recent pings */
	unsigned periods; /**< number of times periodic() was called */
	unsigned rxqp;
	unsigned txqp;
	unsigned rxrp;
	unsigned txrp;
	unsigned removed_torrents;
};

/**
 * prints a dht, for debugging
 *
 * @param s	[out]	stream
 * @param d	[in]	dht
 */

void dht_print (FILE * s, const struct dht * d) {
	char buf[41];
	buf[40] = '\0';
	bin2hex(buf, d->id, 20);
	char secret[16*2+1];
	secret[16*2] = '\0';
	bin2hex(secret, d->secret, 16);
	fprintf(s, "id=%s socket=%d t=%u p=%u tmax=%u pmax=%u p/t-max=%u runsec=%ld rxp=%u txp=%u rxb=%u txb=%u secret=%s tt=%u tr=%u p=%u\n", buf, d->socket, d->torrents_num, d->peers_num, d->torrents_max, d->peers_max, d->peers_per_torrent_max, seconds()-d->time, d->rxp, d->txp, d->rxb, d->txb, secret, d->tt, d->tr, d->p);
	fprintf(s, "**** NODES ****\n");
	int nodes = 0;
	for (int i = 0; i <= 1; i++) {
		struct bucket * b = d->buckets;
		if (i)
			b = d->buckets6;
		int buckets = 0;
		while (b) {
			buckets++;
			bin2hex(buf, b->id, 20);
			fprintf(s, "\tBUCKET id=%s\n", buf);
			struct node * n = b->nodes;
			while (n) {
				nodes++;
				fprintf(s, "\t");
				node_print(s, n);
				fprintf(s, "\n");
				n = n->next;
			}
			b = b->next;
		}
		fprintf(s, "\t**** COUNT OF %s BUCKETS: %d\n", i ? "IPv6" : "IPv4", buckets);
	}
	fprintf(s, "**** COUNT OF NODES: %d\n", nodes);
	fprintf(s, "**** TORRENTS ****\n");
	struct torrent * t = d->torrents;
	unsigned torrents = 0;
	while (t) {
		torrents++;
		torrent_print(s, t);
		t = t->next;
	}
	fprintf(s, "**** COUNT OF TORRENTS: %u\n", torrents);
}

/**
 * a dummy function that does nothing that is set as the default for possible_torrent in struct dht
 *
 * @param d	[in]	the dht library handler
 * @param h	[in]	the infohash of the found torrent
 */

void possible_torrent (struct dht * d __attribute__((unused)), const unsigned char * h __attribute__((unused)), struct torrent * t __attribute__((unused))) {
	return;
}

/**
 * macro for printing logs
 *
 * @param o	[in]	FILE * to which to write to
 * @param f	[in]	printf style format string
 * @param ...	[in]	variable arguments to go with f
 */

#define L(Lv, Ld, Lf, ...) do {char Lt[512]; time_t Ln = time(NULL); strftime(Lt, 512, "%c", localtime(&Ln)); if (Ld->verbosity & Lv) fprintf(Ld->log, "[%s] %s@%s()%s:%d: " Lf "\n", Lt, verbosity2str(Lv), __func__, __FILE__, __LINE__ __VA_OPT__(,) __VA_ARGS__);} while (0)

/**
 * sends a bencoding object to the remote node. does not free the input bencoding. inserts a v key to the input bencoding.
 *
 * @param d	[in]	the dht library handle
 * @param b	[in]	the bencoding to send serialized, m. ownership NOT transfered
 * @param a	[in]	destination address
 */

void sendb (struct dht * d, struct bencoding * b, const struct sockaddr_in6 * a) {
	struct bencoding * y = bpath(b, "y");
	if (y && y->type & string && y->valuelen >= 1) {
		if (y->value[0] == 'r')
			d->txrp++;
		else
			d->txqp++;
	}
	char remote[INET6_ADDRSTRLEN + 64];
	if (!inet_ntop(a->sin6_family, &a->sin6_addr, remote, INET6_ADDRSTRLEN+7))
		snprintf(remote, sizeof remote,  "(inet_ntop: %s)", strerror(errno));
	sprintf(remote+strlen(remote), "/%d", ntohs(((struct sockaddr_in6 *) a)->sin6_port));
	struct bencoding * v = bstr(strdup("TK00"));
	v->key = bstr(strdup("v"));
	binsert(b, v);
	struct bencoding * ip = calloc(1, sizeof *ip);
	ip->type = string;
	ip->key = bstr(strdup("ip"));
	memcpy((ip->value = malloc(18)), a->sin6_addr.s6_addr + (family(a->sin6_addr.s6_addr) == AF_INET ? 12 : 0), (ip->valuelen = family(a->sin6_addr.s6_addr) == AF_INET ? 6 : 18));
	memcpy(ip->value + (family(a->sin6_addr.s6_addr) == AF_INET ? 4 : 16), &a->sin6_port, 2);
	binsert(b, ip);
	int len = b2json_length(b);
	char json[len+1];
	b2json(json, b);
	json[len] = '\0';
	L(outgoing_dht, d, "sending to %s: %s", remote, json);
	len = bencode_length(b);
	char text[len];
	bencode(text, b);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
	if (sendto(d->socket, text, len, MSG_DONTWAIT | MSG_NOSIGNAL, a, sizeof *a) == -1) {
		L(std_fail, d, "sendto(%s): %s", remote, strerror(errno));
	} else {
		d->txp++;
		d->txb += len;
	}
#pragma GCC diagnostic pop
}

#define GENERIC_T "a@4" "a.si" /**< generic token that we send if we have no statekeeping to do - developer's email address */

/**
 * sends a find_node query to a "raw node"
 * 
 * @param d	[in]	handle
 * @param a	[in]	address of the remote node
 * @param query	[in]	20 byte id we are querying
 */

void find_node (struct dht * d, const struct sockaddr_in6 * addr, const unsigned char * query) {
	struct bencoding * b = calloc(1, sizeof *b);
	b->type = dict;
	struct bencoding * t = bstr(strdup(GENERIC_T));
	t->key = bstr(strdup("t"));
	t->type = string;
	binsert(b, t);
	struct bencoding * y = bstr(strdup("q"));
	y->key = bstr(strdup("y"));
	y->type = string;
	binsert(b, y);
	struct bencoding * q = bstr(strdup("find_node"));
	q->key = bstr(strdup("q"));
	q->type = string;
	binsert(b, q);
	struct bencoding * a = calloc(1, sizeof *a);
	a->type = dict;
	a->key = bstr(strdup("a"));
	struct bencoding * id = calloc(1, sizeof *id);
	id->type = string;
	id->valuelen = 20;
	id->key = bstr(strdup("id"));
	memcpy((id->value = malloc(20)), d->id, 20);
	binsert(a, id);
	struct bencoding * want = calloc(1, sizeof *want); // BEP-0032
	want->key = bstr(strdup("want"));
	want->type = list;
	binsert(want, bstr(strdup("n4")));
	binsert(want, bstr(strdup("n6")));
	binsert(a, want);
	struct bencoding * target = calloc(1, sizeof *target);
	target->key = bstr(strdup("target"));
	target->type = string;
	memcpy((target->value = malloc(20)), query, (target->valuelen = 20));
	binsert(a, target);
	binsert(b, a);
	sendb(d, b, addr);
	free_bencoding(b);
}

/**
 * ping a raw node by sending a find_node
 *
 * instead of sending a ping query, we send a find_node query. this gets us useful information of peers around our ID instead of just a blank ping reply. infolgedessen we don't have to actively search for our neighbour nodes, since we'll get them through pings anyways
 *
 * does not ping if the same node was pinged in the last PINGS_CAP pings
 *
 * DEV THOUGHT: instead of sending a find_node for an ID close to ours, we could send a find_node for a random ID far from us. though those buckets will probably quickly be filled by torrent searches.
 *
 * @param d	[in]	library handle
 * @param a	[in]	address of node
 */

void ping_node (struct dht * d, const struct sockaddr_in6 * a) {
	for (int i = 0; i < PINGS_CAP; i++)
		if (!memcmp(a, &d->pings[i], sizeof *a)) {
			L(debug, d, "already pinged in last " STR(PINGS_CAP) " pings, ignoring request");
			return;
		}
	unsigned char target[20];
	memcpy(target, d->id, 20);
	if (target[19] & 1) // flip the last bit, so the other node doesn't just return
		target[19] &= 0xFE;	// our ID but K ids around it
	else
		target[19] |= 1;
	find_node(d, a, target);
}

/**
 * creates a handle. you can override log in the result struct.
 *
 * this function does not log, as log fd is not known yet
 *
 * socket must be close()d before being overriden, if the caller wants to use custom binding.
 *
 * binds UDP to all ifaces
 *
 * @param c	[in]	bencoding object containing the persistent config file, generated from a previous run with persistent(). memory ownership is NOT transfered, it's the caller's responsibility to free the object. can be NULL.
 */

struct dht * dht_init (const struct bencoding * c) {
	struct dht * d = calloc(1, sizeof *d);
	d->time = seconds();
	d->log = stderr;
	d->buckets = bucket_init();
	d->buckets6 = bucket_init();
	d->possible_torrent = possible_torrent;
	d->torrents_max = UINT_MAX; // this is hardcore - so many torrents makes LL traversal too slow
	d->peers_max = UINT_MAX; // there's no way there even are this many peers on the entire network at a time xDDDDDDDDDDD
	d->peers_per_torrent_max = UINT_MAX;
	d->verbosity = std_fail | disagreement | user;
	errno = 0;
	if (!d)
		return NULL;
	if (getrandom(d->id, 20, GRND_NONBLOCK) == -1)
		goto e;
	if (getrandom(d->secret, 16, GRND_NONBLOCK) == -1)
		goto e;
	d->socket = socket(AF_INET6, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
	if (d->socket == -1)
		goto e;
	struct sockaddr_in6 a = {
		.sin6_family = AF_INET6,
		.sin6_addr = in6addr_any
	};
	const struct bencoding * port = NULL;
	if (c && (port = bpath(c, "port")) && port->type & num)
		a.sin6_port = htons(port->intvalue);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
	if (bind(d->socket, &a, sizeof a) == -1)
		if (errno == EADDRINUSE) {
			a.sin6_port = 0;
			if (bind(d->socket, &a, sizeof a) == -1)
#pragma GCC diagnostic pop
				goto e;
		}
#define TOOMUCH (32727*1)
	unsigned pinged = 0;
	if (c) {
		const struct bencoding * id = bpath(c, "id");
		if (id && id->type & string && id->valuelen == 20)
			memcpy(d->id, id->value, 20);
		bforeach (bpath(c, "nodes"), str) {
			char remote[INET6_ADDRSTRLEN + 7];
			if (str->valuelen > INET6_ADDRSTRLEN+6)
				continue;
			strcpy(remote, str->value);
			char * port = strchr(remote, '/');
			if (!port)
				continue;
			port[0] = '\0';
			struct sockaddr_in6 addr = {
				.sin6_family = AF_INET6,
				.sin6_port = htons(atoi(++port))
			};
			if (inet_pton(AF_INET6, remote, addr.sin6_addr.s6_addr) == 1 && pinged++ < TOOMUCH/2)
				ping_node(d, &addr);
		}
	}
	return d;
	e:
	free(d);
	return NULL;
}

/**
 * frees a handle. does nothing if handle is NULL. does not fclose log. closes socket. please set socket to -1 before calling if you don't want to close it.
 */

void dht_free (struct dht * d) {
	if (d->socket != -1)
		if (close(d->socket) == -1)
			L(std_fail, d, "close(d->socket) == -1");
	struct bucket * bucket = d->buckets;
	while (bucket) {
		struct bucket * old = bucket;
		bucket = bucket->next;
		bucket_free(old);
	}
	struct bucket * bucket6 = d->buckets6;
	while (bucket6) {
		struct bucket * old = bucket6;
		bucket6 = bucket6->next;
		bucket_free(old);
	}
	struct torrent * torrent = d->torrents;
	while (torrent) {
		struct torrent * old = torrent;
		torrent = torrent->next;
		torrent_free(old);
	}
	free(d);
}

/**
 * generate a bencoding struct containing the persistent storage config
 *
 * this config contains:
 * 	- nodes from the routing table that can be used to bootstrap into the dht net
 * 	- this node's id
 *
 * please make sure that you do not start two nodes from the same config
 *
 * @param d	[in]	library handle
 * @return bencoding object, whose memory ownership is transfered to the caller, which must call bencoding_free() on it.
 */

struct bencoding * persistent (const struct dht * d) {
	struct bencoding * b = calloc(1, sizeof *b);
	b->type = dict;
	struct bencoding * id = calloc(1, sizeof *id);
	id->type = string;
	memcpy((id->value = malloc(20)), d->id, (id->valuelen = 20));
	id->key = bstr(strdup("id"));
	binsert(b, id);
	struct sockaddr_in6 bound;
	socklen_t size = sizeof bound;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
	if (getsockname(d->socket, &bound, &size) == -1)
		L(std_fail, d, "getsockname: %s", strerror(errno));
	else {
		struct bencoding * port = bnum(ntohs(bound.sin6_port));
		port->key = bstr(strdup("port"));
		binsert(b, port);
	}
#pragma GCC diagnostic pop
	struct bencoding * nodes = calloc(1, sizeof *nodes);
	nodes->type = list;
	nodes->key = bstr(strdup("nodes"));
	for (int i = 0; i <= 1; i++) {
		struct bucket * bucket = d->buckets;
		if (i)
			bucket = d->buckets6;
		while (bucket) {
			struct node * node = bucket->nodes;
			while (node) {
				char remote[INET6_ADDRSTRLEN + 7];
				if (inet_ntop(AF_INET6, &node->addr.sin6_addr, remote, INET6_ADDRSTRLEN+7)) {
					sprintf(remote+strlen(remote), "/%u", ntohs(node->addr.sin6_port));
					binsert(nodes, bstr(strdup(remote)));
				}
				node = node->next;
			}
			bucket = bucket->next;
		}
	}
	binsert(b, nodes);
	return b;
}

/**
 * generates a 16 byte token for allowing a node to store it's IP addres in our node. verify with valid()
 *
 * @param d	[in]	used to obtain the secret key
 * @param t	[out]	the destination to which to write the 16 bytes
 * @param a	[in]	16 bytes of the node's IP address, from which get_peers was received - addr.sin6_addr.s6_addr
 * @param l	[in]	the length of socket address struct a
 */

void token (const struct dht * d, unsigned char * t, const unsigned char * addr) {
	struct AES_ctx aes;
	memcpy(t, addr, 16);
	AES_init_ctx(&aes, d->secret);
	AES_ECB_encrypt(&aes, t);
}

/**
 * verifies a 16 byte token, if it was really generated with token(), to prevent unsolicited adding of IPs to storage with src ip addr spoofing.
 *
 * @param d	[in]	used to obtain the secret key
 * @param t	[in]	the address from which to obtain the 16 byte token
 * @param a	[in]	16 bytes of the node's IP address, from which announce was received - addr.sin6_addr.s6_addr
 * @param l	[in]	the length of socket address struct a
 * @return 1 if the token is valid for this node, 0 otherwise
 */

int valid (const struct dht * d, const unsigned char * t, const unsigned char * addr) {
	unsigned char try[16];
	memcpy(try, t, 16);
	token(d, try, addr);
	return !memcmp(try, t, 16);
}

/**
 * sends an error rpc packet to a node. make sure that this is always similar size to the received packet, otherwise we could get amplification attacks.
 *
 * @param d	[in]	the dht library handle, for logging and for socket fd
 * @param b	[in]	the incoming packet that caused the error, to get key t
 * @param a	[in]	address of the incoming packet to which an error is sent
 * @param num	[in]	error number, as specified by BEP-0005
 * @param text	[in]	error text. memory ownership is transfered and string is freed, so make sure it's allocated on heap and no longer used by the caller - for static strings use strdup()
 */

void send_error (struct dht * d, const struct bencoding * b, struct sockaddr_in6 * a, int errnum, char * text) {
	struct bencoding * e = calloc(1, sizeof *e);
	e->type = list;
	e->key = bstr(strdup("e"));
	binsert(e, bstr(text));
	binsert(e, bnum(errnum));
	struct bencoding * y = bstr(strdup("e"));
	y->key = bstr(strdup("y"));
	struct bencoding * response = calloc(1, sizeof *response);
	binsert(response, y);
	binsert(response, e);
	binsert(response, bpath(b, "t"));
	sendb(d, response, a);
	free_bencoding(response);
}

/**
 * decides if a node id belongs to a bucket or not. this does not actually check the bucket for it's contents, just the ranges.
 *
 * @param id	[in]	the node id
 * @param b	[in]	the bucket
 * @return 1 if belongs to a bucket, 0 otherwise
 */

int in_bucket (const unsigned char * id, const struct bucket * b) {
	return memcmp(id, b->id, 20) >= 0 && (!b->next || memcmp(id, b->next->id, 20) < 0);
}

/**
 * searches for a stored node based on id
 *
 * @param id	[in]	the node id
 * @param b		pointer to a variable containing a pointer to the first bucket in ll. after the call the value at this pointer is overwritten to the bucket that should contain this node. since it's overwritten, do NOT just pass &dht->buckets. do struct bucket * b = dht->buckets and pass &b instead.
 * @param n	[out]	the node directly before the searched for node. NULL is written if this node would be placed at the start of the bucket. NULL may be passed without consequences.
 * @return the pointer to the node or NULL if not found
 */ 

/* __attribute__((deprecated)) */ struct node * find (const unsigned char * id, struct bucket ** b, struct node ** n) {
	while (!in_bucket(id, *b))
		*b = (*b)->next;
	struct node * node = (*b)->nodes;
	struct node * prev;
	if (!n)
		n = &prev;
	*n = NULL;
	while (node && memcmp(node->id, id, 20) < 0) {
		*n = node;
		node = node->next;
	}
	if (node && !memcmp((node)->id, id, 20))
		return node;
	else
		return NULL;
}

/**
 * search for a node in a linked list of nodes.
 *
 * @param id	[in]	the node id
 * @param first	[in]	first node in LL
 * @return either location of pointer to the searched for node or the location where this node may be inserted.
 */

struct node ** search_node (const unsigned char * id, struct node ** first) {
	if (!(*first)->next)
		return first;
	if (memcmp((*first)->next->id, (*first)->id, 20) >= 0)
		return first;
	return search_node(id, &(*first)->next);
}

/**
 * search for a node in bucket list
 *
 * @param id	[in]	the node id
 * @param first	[io]	variable holding pointer to first bucket in LL, *WILL BE OVERWRITTEN* with bucket that should contain node
 * @param either location of pointer to the searched for node or the location where this node may be inserted.
 */

struct node ** search_bucket (const unsigned char * id, struct bucket ** first) {
	if (!in_bucket(id, *first))
		return search_bucket(id, &(*first)->next);
	return search_node(id, &(*first)->nodes);
}

/**
 * add two 20 byte numbers
 *
 * @param a	[io]	result and first operand
 * @param b	[in]	second operand
 */

void add (unsigned char * a, const unsigned char * b) {
	unsigned carry = 0;
	for (int i = 19; i >= 0; i--) {
		unsigned cursum = (unsigned) a[i] + (unsigned) b[i] + carry;
		carry = 0;
		if (cursum > 255) {
			carry = cursum / 256;
			a[i] = cursum % 256;
		} else
			a[i] = cursum;
	}
}

/**
 * subtract two 20 byte numbers
 *
 * @param a	[io]	result and first operand
 * @param b	[in]	second operand
 */

void subtract (unsigned char * a, const unsigned char * b) {
	int carry = 0;
	for (int i = 19; i >= 0; i--) {
		int cur = (int) a[i] - ((int) b[i] + carry);
		carry = 0;
		while (cur < 0) {
			cur += 256;
			carry++;
		}
		a[i] = cur;
	}
}

/**
 * divide a 20 byte number with 2
 *
 * @param a	[io]	result and operand
 */

void divide (unsigned char * a) {
	for (int i = 19; i >= 0; i--) {
		a[i] >>= 1;
		if (i && a[i-1] & 1)
			a[i] |= 1 << 7;
	}
}

/**
 * find the middle point of a bucket/or two 20 byte bytestrings
 *
 * arguments must not overlap
 *
 * @param r	[out]	midpoint. caller must provide 20 bytes here
 * @param a	[in]	lower boundary
 * @param b	[in]	upper boundary. if NULL, 0xffffffffffffffffffffffffffffffffffffffff is assumed
 */

void midpoint (unsigned char * r, const unsigned char * a, const unsigned char * b) {
	for (int i = 0; i < 20; i++)
		r[i] = 0xFF;
	if (b)
		memcpy(r, b, 20);
	subtract(r, a);
	divide(r);
	add(r, a);
}

/**
 * splits a bucket
 *
 * @param b	[in]	the bucket to split
 */

void split (struct bucket * b) {
	struct bucket * new = bucket_init();
	midpoint(new->id, b->id, b->next ? b->next->id : NULL);
	new->next = b->next;
	struct node ** n = &b->nodes;
	while (*n && !in_bucket((*n)->id, new))
		n = &(*n)->next;
	new->nodes = *n;
	*n = NULL;
	b->next = new;
}

/**
 * returns a count of nodes in a linked list
 *
 * @param n	[in]	first node in ll
 */

int node_count (const struct node * n) {
	int c = 0;
	while (n) {
		c++;
		n = n->next;
	}
	return c;
}

/**
 * returns the distance between two ids. if it cannot be represented with an unsigned int, UINT_MAX is returned.
 *
 * TODO: test util
 */

unsigned int distance (const unsigned char * a, const unsigned char * b) {
	unsigned char xor[20];
	memcpy(xor, a, 20);
	for (long unsigned int i = 0; i < 20; i++) {
		xor[i] ^= b[i];
		if (i < 20 - sizeof (unsigned int) && xor[i])
			return UINT_MAX;
	}
	unsigned r = 0;
	for (long unsigned int i = 0; i < sizeof (unsigned); i++)
		r |= xor[i] << (sizeof (unsigned) - 1 - i) * 8;
	return r;
}

/**
 * returns 1 if bucket is perfect, meaning it is fresh, has K nodes, and no node is bad. bucket that contains id is almost never perfect, as it can usually be split into smaller buckets, that's why param d is required to get own id
 *
 * if d is NULL, it's not checked whether we fall into the bucket and whether it could be split
 *
 * @param d	[in]	library handle to get own id
 * @param b	[in]	the bucket
 */

int bucket_grade (const struct dht * d, const struct bucket * b) {
	if (d) {
		if (!bucket_grade(NULL, b))
			return 0;
		if (in_bucket(d->id, b)) {
			struct node * n = b->nodes;
			while (n->next) {
				if (distance(n->id, n->next->id) > 1)	// we allow holes of 1, since we don't actually store our ID in the bucket
					return 0;			// it's really impossible that a non-malicious node would by chance get so close
				n = n->next;
			}
			return 1;
		}
		return 1;
	} else {
		if (node_count(b->nodes) < K)
			return 0;
		struct node * n = b->nodes;
		while (n) {
			if (node_grade(n) == bad)
				return 0;
			n = n->next;
		}
		return 1;
	}
}

/**
 * informs the library of a successfully received response packet from a node, knowing it's id and ip:port. do not call if the node queried us, if that's the case, use potential_node().
 *
 * if the node is new, it's added in a bucket.
 *
 * if the node is found in a bucket, it's last received time and unanswered are updated
 *
 * TODO: this could be refactored so that it reuses logic from potential_node, like done in replied_torrent_node() below
 *
 * @param d	[in]	handle
 * @param id	[in]	node id that was received
 * @param addr	[in]	address from which the id was received
 */

void replied (const struct dht * d, const unsigned char * id, const struct sockaddr_in6 * addr) {
	struct bucket * b = d->buckets;
	if (family(addr->sin6_addr.s6_addr) == AF_INET6)
		b = d->buckets6;
	struct node * n;
	struct node * found = find(id, &b, &n);
	if (found) {
		found->last_received = seconds();
		found->server_errors = found->unanswered = 0;
		return;
	}
	if (!memcmp(d->id, id, 15)) // WE COULDN'T'VE POSSIBLY REPLIED TO OURSELVES - or sybil attack
		return;
	if (bucket_grade(d, b))
		return;
	struct node * node = node_init();
	memcpy(&node->addr, addr, sizeof *addr);
	memcpy(node->id, id, 20);
	if (node_count(b->nodes) < K) {
		if (!n) {
			node->next = b->nodes;
			b->nodes = node;
		} else {
			node->next = n->next;
			n->next = node;
		}
		return;
	}
	node_free(node);
	if (in_bucket(d->id, b)) {
		struct bucket * bucket = d->buckets;
		if (family(addr->sin6_addr.s6_addr) == AF_INET6)
			bucket = d->buckets6;
		while (bucket) {
			struct node * n = bucket->nodes;
			while (n) {
				char remote[INET_ADDRSTRLEN + INET6_ADDRSTRLEN + 64];
				if (!inet_ntop(AF_INET6, addr->sin6_addr.s6_addr, remote, INET6_ADDRSTRLEN+7+INET_ADDRSTRLEN))
					snprintf(remote, sizeof remote,  "(inet_ntop: %s)", strerror(errno));
				switch(family(addr->sin6_addr.s6_addr)) {
					case AF_INET:
						if (!memcmp(addr->sin6_addr.s6_addr+12, n->addr.sin6_addr.s6_addr+12, 4)) {
							L(disagreement, d, "sybil: %s/%d is already present", remote, ntohs(addr->sin6_port));
							return;
						}
						break;
					case AF_INET6:
						if (!memcmp(addr->sin6_addr.s6_addr+1, n->addr.sin6_addr.s6_addr+1, 5)) {
							L(disagreement, d, "sybil: %s/%d is already present", remote, ntohs(addr->sin6_port));
						}
						break;
				}
				n = n->next;
			}
			bucket = bucket->next;
		}
		split(b);
		replied(d, id, addr); // find bucket again
	}
}

/**
 * when we are sure that a node exists on a specific ip:port and we know it's id, but we are unsure if the node is already in the routing table, we call this function, which makes a query to this node if it's a candidate for filling the routing table. this doesn't yet add it to the routing table, because we are unsure if it's a good node / can respond to queries. replied() is called if a node replied to our query.
 *
 * see NOTE02
 * 
 * @param d	[in]	library handle
 * @param a	[in]	pointer to sockaddr of the node
 * @param id	[in]	id of the node, 20 bytes is read from this address
 */

void potential_node (struct dht * d, const struct sockaddr_in6 * a, const unsigned char * id) {
	if (!a->sin6_port)
		return; // sorry, I can't send to port 0. this is a mistake or a malicious node
	if (!memcmp(d->id, id, 15)) // we are not a potential node of ourselves, if 15 bytes are same : sybil
		return;
	struct bucket * bucket = d->buckets;
	if (family(a->sin6_addr.s6_addr) == AF_INET6)
		bucket = d->buckets6;
	if (find(id, &bucket, NULL))
		return;
	if (!bucket_grade(d, bucket))
		ping_node(d, a);
}

#define MAXT 15 /**< see NOTE04 */

/**
 * find a torrent based on hash
 *
 * NOTE04: full length 20 byte binary hash can't be stored in "t" because some nodes' software discards t if it's longer than MAXT bytes
 * 	
 * that's why this function accepts shorter lengths to compare.
 *
 * @param d	[in]	the library handle
 * @param h	[in]	an l-byte infohash
 * @param l	[in]	number of bytes of infohash to compare - for truncated hashes. full hash is 20 bytes long.
 * @return pointer to torrent or NULL
 */

struct torrent * find_torrent (struct dht * d, const unsigned char * h, int l) {
	struct torrent * t = d->torrents;
	while (t) {
		if (!memcmp(t->hash, h, l))
			return t;
		t = t->next;
	}
	return NULL;
}

/**
 * deletes a torrent from storage. if you downloaded a torrent and set peers/announce flags, do not remove_torrent once you're done with it, but instead just clear peers/announce bits. this will remove the torrent when necessary.
 *
 * @param d	[in]	the library handle
 * @param t	[in]	the pointer to the torrent to be deleted. do not craft torrent yourself, it must be stored in dht and that specific instance must be passed
 */

void remove_torrent (struct dht * d, struct torrent * t) {
	if (!t)
		return;
	if (!t->next)
		d->last_torrent = t->prev;
	if (t->prev)
		t->prev->next = t->next;
	if (t->next)
		t->next->prev = t->prev;
	if (t == d->torrents)
		d->torrents = t->next;
	struct peer * p = t->peers;
	while (p) {
		d->peers_num--;
		p = p->next;
	}
	d->torrents_num--;
	torrent_free(t);
	torrent_ll_assert(d->torrents);
	d->removed_torrents++;
}

/**
 * what to do when there are too many torrents and their peers stored, used in add_peer and add_torrent
 *
 * removes last added torrents that aren't ->type and aren't ->dl until there's space
 *
 * @param d	[in]	libhandle
 */

void oom (struct dht * d) {
	struct torrent * drop = d->last_torrent;
	while (d->torrents_num >= d->torrents_max || d->peers_num >= d->peers_max) {
		if (!drop)
			break;
		while (drop && (drop->type || drop->dl))
			drop = drop->prev;
		struct torrent * old = drop;
		if (!drop)
			break;
		drop = drop->prev;
		remove_torrent(d, old);
	}
}

/**
 * adds a torrent to a list of torrents
 * 
 * if the torrent already exists in the database flags of this one will be anded with the flags of the old one, meaning this function can be used to set peers, announce and info flags. see @return for important details.
 *
 * @param d	[in]	dht library handler, for counting torrents in storage
 * @param t	[in]	torrent object, whose memory ownership is transfered to the library and must be heap allocated
 * @return the new pointer to the torrent. if the torrent is already in the storage, the passed torrent will be freed, so the return value must be checked if you intend to use the torrent weiter
 */

struct torrent * add_torrent (struct dht * d, struct torrent * t) {
	struct torrent * found = find_torrent(d, t->hash, 20);
	if (found) {
		found->type |= t->type;
		torrent_free(t);
		return found;
	}
	oom(d);
	if (d->torrents)
		d->torrents->prev = t;
	else
		d->last_torrent = t;
	t->prev = NULL;
	t->next = d->torrents;
	d->torrents = t;
	d->torrents_num++;
#ifdef SAMPLE
	if (d->samples < 3000)
		memcpy(d->sample+20*d->samples++, t->hash, 20);
	else
		memcpy(d->sample+20*(rand() % 3000), t->hash, 20);
#endif
	return t;
}

/**
 * adds a peer to a torrent, memory ownership is transfered, so make sure it's allocated on heap. if this peer already exists, the input peer is freed and the old peer is returned.
 *
 * @param d	[in]	library handle, for counting peers
 * @param t	[in]	torrent
 * @param p	[in]	peer to add
 * @param this peer in storage. could be different if old one was freed, so discard value that you passed in and replace it with this value. memory ownership is NOT transfered from storage to caller
 * @return input peer address if it was added. NULL if input peer is weird and not added. another peer that matches address and was already stored. peer is freed, unless it's address returned.
 */

struct peer * add_peer (struct dht * d, struct torrent * t, struct peer * p) {
	if (p->addr.sin6_port == htons(1)) { /* I saw some malicious (?) nodes sending port 1 */
		peer_free(p); /* no one in their right mind would use port 1 for torrents */
		return NULL; /* email me if you know which client does that */
	}
	struct peer ** peer = &t->peers;
	struct peer ** bad = NULL;
	struct peer ** nondl = NULL;
	unsigned l = 0;
	while (*peer) {
		l++;
		if (!memcmp((*peer)->addr.sin6_addr.s6_addr, p->addr.sin6_addr.s6_addr, 16)) { // ignore multiple peers on same port
			peer_free(p);
			return *peer;
		}
		if (*peer != t->dl)
			nondl = peer;
		else // dls are holy
			goto c;
		if ((*peer)->flags & badmeta)
			bad = peer;
		if ((*peer)->flags & nometasupport && !(bad && (*bad) && (*bad)->flags & badmeta))
			bad = peer;
		if ((*peer)->flags & unreachable && !(bad && (*bad) && (*bad)->flags & (badmeta | nometasupport)))
			bad = peer;
		if (l > d->peers_per_torrent_max && !bad) {
			l--;
			struct peer * next = (*peer)->next;
			peer_free(*peer);
			*peer = next;
			continue;
		}
		c:
		peer = &(*peer)->next;
	}
	if (bad && l > d->peers_per_torrent_max) {
		l--;
		struct peer * old = *bad;
		*bad = (*bad)->next;
		peer_free(old);
	}
	if (nondl && l > d->peers_per_torrent_max) {
		l--;
		struct peer * old = *nondl;
		*nondl = (*nondl)->next;
		peer_free(old);
	}
	p->next = t->peers;
	t->peers = p;
	d->peers_num++;
	oom(d);
	return p;
}

/**
 * sends a get_peers query to a raw node
 *
 * @param d	[in]	handle
 * @param a	[in]	address
 * @param q	[in]	20 byte hash we query for
 */

void get_peers (struct dht * d, const struct sockaddr_in6 * addr, const unsigned char * q) {
	struct bencoding * b = calloc(1, sizeof *b);
	b->type = dict;
	struct bencoding * t = calloc(1, sizeof *t);
	memcpy((t->value = malloc(MAXT)), q, (t->valuelen = MAXT));
	t->key = bstr(strdup("t"));
	t->type = string;
	binsert(b, t);
	struct bencoding * y = bstr(strdup("q"));
	y->key = bstr(strdup("y"));
	y->type = string;
	binsert(b, y);
	struct bencoding * q_elem = bstr(strdup("get_peers"));
	q_elem->key = bstr(strdup("q"));
	q_elem->type = string;
	binsert(b, q_elem);
	struct bencoding * a = calloc(1, sizeof *a);
	a->key = bstr(strdup("a"));
	a->type = dict;
	struct bencoding * id = calloc(1, sizeof *id);
	id->type = string;
	id->valuelen = 20;
	id->key = bstr(strdup("id"));
	memcpy((id->value = malloc(20)), d->id, 20);
	binsert(a, id);
	struct bencoding * want = calloc(1, sizeof *want); // BEP-0032
	want->key = bstr(strdup("want"));
	want->type = list;
	binsert(want, bstr(strdup("n4")));
	binsert(want, bstr(strdup("n6")));
	binsert(a, want);
	struct bencoding * info_hash = calloc(1, sizeof *info_hash);
	info_hash->key = bstr(strdup("info_hash"));
	info_hash->type = string;
	memcpy((info_hash->value = malloc(20)), q, (info_hash->valuelen = 20));
	binsert(a, info_hash);
	binsert(b, a);
	sendb(d, b, addr);
	free_bencoding(b);
}

/**
 * called from compact() on response to get_peers, this function sends a get_peers to a node if it would improve the node pool of a torrent
 *
 * @param d	[in]	library handle
 * @param t	[in]	torrent
 * @param a	[in]	address of node
 * @param i	[in]	20 byte id of node
 */

void potential_torrent_node (struct dht * d, struct torrent * t, const struct sockaddr_in6 * a, const unsigned char * i) {
	if (!t->nodes) {
		get_peers(d, a, t->hash);
		return;
	}
	struct node * n = t->nodes;
	struct node * badnode = NULL;
	struct node * farthest = t->nodes;
	unsigned l = 0;
	while (n) {
		l++;
		if (node_grade(n) == bad)
			badnode = n;
		if (!closer(n->id, farthest->id, t->hash))
			farthest = n;
		if (!memcmp(n->id, i, 20))
			return;
		n = n->next;
	}
	if (!closer(i, farthest->id, t->hash)) {
		get_peers(d, a, t->hash);
		return;
	}
	if (badnode) {
		get_peers(d, a, t->hash);
		return;
	}
	if (l < K) {
		get_peers(d, a, t->hash);
		return;
	}
}

/**
 * called on a response to get_peers, the node that responded is added to a list of good nodes of a torrent if it's a potential torrent node, if it's already in the list, it's stats are updated.
 *
 * note that torrent nodelists have no housekeeping like the routing table has with refresh(), so bad nodes are removed only when adding a new one.
 *
 * @param t	[in]	torrent
 * @param a	[in]	address of node
 * @param i	[in]	node id
 */

void replied_torrent_node (struct torrent * t, const struct sockaddr_in6 * a, const unsigned char * i) {
	struct node ** n = &t->nodes;
	struct node ** badnode = NULL;
	struct node ** farthest = &t->nodes;
	unsigned l = 0;
	while (*n) {
		l++;
		if (node_grade(*n) == bad)
			badnode = n;
		if (!closer((*n)->id, (*farthest)->id, t->hash))
			farthest = n;
		if (!memcmp((*n)->id, i, 20)) {
			(*n)->unanswered = 0;
			(*n)->last_received = seconds();
			return;
		}
		n = &(*n)->next;
	}
	struct node * new = node_init();
	memcpy(new->id, i, 20);
	memcpy(&new->addr, a, sizeof new->addr);
	if (l < K) {
		new->next = t->nodes;
		t->nodes = new;
		return;
	}
	if (badnode) {
		new->next = (*badnode)->next;
		node_free(*badnode);
		*badnode = new;
		return;
	}
	if (!closer(i, (*farthest)->id, t->hash)) {
		new->next = (*farthest)->next;
		node_free(*farthest);
		*farthest = new;
		return;
	}
	node_free(new);
}

/**
 * parses a compact node description in either ipv4 or ipv6 from nodes or nodes6 and invoke actions. call this for every string in nodes and nodes6 array in incoming response packets.
 *
 * if the newly found node is useful for filling the K closest nodes ll of the torrent, it will be added in the LL. it may also replace an existing node if the existing node is bad or furthest away from torrent hash and this one is closer. upon insertion, the node is queried for find_node.
 *
 * @param d	[in]	libh
 * @param value	[in]	compact node info buffer pointer
 * @param len	[in]	length of buffer, can be either 20+4+2 for ipv4 or 20+16+2 for ipv6
 * @param t
 */

void compact (struct dht * d, const char * value, int len, struct torrent * t) {
	if (len != 4+2+20 && len != 16+2+20) {
		L(disagreement, d, "received packet contained an invalid compact node");
		return;
	}
	struct sockaddr_in6 addr = {
		.sin6_family = AF_INET6
	};
	memcpy(addr.sin6_addr.s6_addr, "\0\0\0\0\0\0\0\0\0\0\xFF\xFF", 12);
	addr.sin6_port = *((uint16_t *) (value + len-2));
	memcpy(addr.sin6_addr.s6_addr+(len == 4+2+20 ? 12 : 0), value + 20, len == 4+2+20 ? 4 : 16);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
	if (t)
		potential_torrent_node(d, t, &addr, value);
	else
		potential_node(d, &addr, value); // NOTE02 at the beginning, a lot of packets will be sent, since every reply of potential_node will generate K replies. naively this would generate an exponentially increasing number of packets, in increasing powers of 8 (8**n). to prevent an absolute resource hog, this is only done when node would be useful and would contribute to the routing table
#pragma GCC diagnostic pop
}

/**
 * returns a dict containing nodes or nodes6 bencoding list (with a key) with compact nodes in the bucket. if exact node is found, only that one is in the list.
 *
 * @param d	[in]	library handle
 * @param id	[in]	target node id, 20 bytes is read from this location
 * @param f	[in]	address family, AF_INET or AF_INET6
 * @return bencoding object whose memory ownership and free responsibility is transfered to the caller
 */

struct bencoding * nodes (const struct dht * d, const unsigned char * id, sa_family_t f) {
	struct bencoding * nodes = calloc(1, sizeof *nodes);
	nodes->type = list;
	nodes->key = bstr(strdup(f == AF_INET ? "nodes" : "nodes6"));
	struct bucket * bucket = (f == AF_INET ? d->buckets : d->buckets6);
	struct node * found = find(id, &bucket, NULL);
#define ADDRLEN(f) (f == AF_INET ? 4 : 16)
	if (found) {
		struct bencoding * compact = calloc(1, sizeof *compact);
		compact->type = string;
		compact->value = malloc((compact->valuelen = 20+ADDRLEN(f)+2));
		memcpy(compact->value, found->id, 20);
		memcpy(compact->value+20, found->addr.sin6_addr.s6_addr+(16-ADDRLEN(f)), ADDRLEN(f));
		memcpy(compact->value+20+ADDRLEN(f), &found->addr.sin6_port, 2);
		binsert(nodes, compact);
	} else {
		struct node * node = bucket->nodes;
		while (node) {
			struct bencoding * compact = calloc(1, sizeof *compact);
			compact->type = string;
			compact->value = malloc((compact->valuelen = 20+ADDRLEN(f)+2));
			memcpy(compact->value, node->id, 20);
			memcpy(compact->value+20, node->addr.sin6_addr.s6_addr+(16-ADDRLEN(f)), ADDRLEN(f));
			memcpy(compact->value+20+ADDRLEN(f), &node->addr.sin6_port, 2);
			binsert(nodes, compact);
			node = node->next;
		}
	}
	return nodes;
}

/**
 * sends an announce_peer query to a raw node
 *
 * @param d	[in]	lh
 * @param a	[in]	node addr
 * @param t	[in]	bencoding object from r/token to be inserted into a/token when sending. memory ownership and responsibility is transfered and this object is freed after call to this function, so use something along the lines of bclone(bpath(b, "r/token")) as argument to call
 * @param h	[in]	torrent hash to announce from which 20 bytes are read
 */

void announce_peer (struct dht * d, const struct sockaddr_in6 * addr, struct bencoding * t, const unsigned char * h) {
	struct bencoding * b = calloc(1, sizeof *b);
	b->type = dict;
	struct bencoding * t_elem = bstr(strdup(GENERIC_T));
	t_elem->key = bstr(strdup("t"));
	binsert(b, t_elem);
	struct bencoding * y = bstr(strdup("q"));
	y->key = bstr(strdup("y"));
	y->type = string;
	binsert(b, y);
	struct bencoding * q = bstr(strdup("announce_peer"));
	q->key = bstr(strdup("q"));
	q->type = string;
	binsert(b, q);
	struct bencoding * a = calloc(1, sizeof *a);
	a->type = dict;
	struct bencoding * id = calloc(1, sizeof *id);
	id->type = string;
	id->valuelen = 20;
	id->key = bstr(strdup("id"));
	memcpy((id->value = malloc(20)), d->id, 20);
	binsert(a, id);
	struct bencoding * want = calloc(1, sizeof *want); // BEP-0032
	want->key = bstr(strdup("want"));
	want->type = list;
	binsert(want, bstr(strdup("n4")));
	binsert(want, bstr(strdup("n6")));
	binsert(a, want);
	struct bencoding * info_hash = calloc(1, sizeof *info_hash);
	info_hash->key = bstr(strdup("info_hash"));
	info_hash->type = string;
	info_hash->valuelen = 20;
	memcpy((info_hash->value = malloc(20)), h, 20);
	binsert(a, info_hash);
	struct bencoding * implied_port = bnum(1);
	implied_port->key = bstr(strdup("implied_port"));
	binsert(b, implied_port);
	binsert(b, t);
	struct sockaddr_in6 bound;
	socklen_t size = sizeof bound;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
	if (getsockname(d->socket, &bound, &size) == -1)
		L(std_fail, d, "getsockname: %s", strerror(errno));
	else {
		struct bencoding * port = bnum(ntohs(bound.sin6_port));
		b->key = bstr(strdup("port"));
		binsert(b, port);
	}
#pragma GCC diagnostic pop
	binsert(b, a);
	sendb(d, b, addr);
	free_bencoding(b);
}

/**
 * handles an incoming packet, be it: (polyglot packets are technically possible)
 * 	- bencoded packet from another DHT node
 * 	- DNS server response for bootstrapping queries
 * 	- uTP packet from a peer (TODO)
 *
 * @param d	[in]	library handle
 * @param pkt	[in]	incoming UDP packet content
 * @param len	[in]	length of the packet
 * @param addr	[in]	IP address and port of sender
 */

void handle (struct dht * d, char * pkt, int len, struct sockaddr_in6 addr) {
	struct bencoding * b = bdecode(pkt, len, replace);
	struct bencoding * v = bpath(b, "v");
	char * node_ver = "";
	char remote[INET_ADDRSTRLEN + INET6_ADDRSTRLEN + 64 + (v && v->type & string ? v->valuelen : 0)];
	if (!inet_ntop(addr.sin6_family, &addr.sin6_addr, remote, INET6_ADDRSTRLEN+7+INET_ADDRSTRLEN)) {
		snprintf(remote, sizeof remote,  "(inet_ntop: %s)", strerror(errno));
	}
	sprintf(remote+strlen(remote), "/%d", ntohs(addr.sin6_port));
	if (v && v->type & string) {
		node_ver = v->value;
		sprintf(remote+strlen(remote), "-%s", node_ver);
	}
	if (b) {
		int len = b2json_length(b);
		char out[len+1];
		char * end = b2json(out, b);
		*end = '\0';
		assert(out+len == end);
		L(incoming_dht, d, "handle(%s): %s", remote, out);
	}
	struct bencoding * y = bpath(b, "y");
	if (y && y->type & string && y->valuelen >= 1) {
		if (y->value[0] == 'r')
			d->rxrp++;
		else
			d->rxqp++;
	}
	char * msg_type = "";
	if (y && y->type & string)
		msg_type = y->value;
	switch (msg_type[0]) {
		case 'Q':
		case 'q':
			;
			struct bencoding * q = bpath(b, "q");
			char * qtype = "";
			if (q && q->type & string)
				qtype = q->value;
			struct bencoding * ro = bpath(b, "ro");
			struct bencoding * rid = bpath(b, "a/id");
			if (rid && rid->type & string && rid->valuelen == 20 && (!ro || !(ro->type & num) || ro->intvalue != 1 /* BEP-0043 */)) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
				potential_node(d, &addr, rid->value);
#pragma GCC diagnostic pop
			}
			else { // see NOTE01
				int len = b2json_length(b);
				char j[len+1];
				b2json(j, b);
				j[len] = '\0';
				L(disagreement, d, "%s did not send a valid id in %s", remote, j);
			}
			switch (qtype[0]) {
#ifdef SAMPLE
				case 'S': // sample_infohashes
				case 's': // oops, we don't do that. this would be a huge DDoS amplification possibility.
#error SAMPLE not implemented because it would be an amplification DDoS vector
					break;
#endif
				case 'P': // ping
				case 'p':
					;
					struct bencoding * id = calloc(1, sizeof *id);
					id->type = string;
					id->key = bstr(strdup("id"));
					memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20);
					struct bencoding * r = calloc(1, sizeof *r);
					r->type = dict;
					r->key = bstr(strdup("r"));
					binsert(r, id);
					struct bencoding * y = bstr(strdup("r"));
					y->key = bstr(strdup("y"));
					struct bencoding * response = calloc(1, sizeof *response);
					response->type = dict;
					binsert(response, y);
					binsert(response, r);
					binsert(response, bclone(bpath(b, "t")));
					sendb(d, response, &addr);
					free_bencoding(response);
					break;
				case 'F': // find_node
				case 'f':
					;
					struct bencoding * target = bpath(b, "a/target");
					if (!target || !(target->type & string) || target->valuelen != 20)
						break; // see NOTE01
					response = calloc(1, sizeof *response);
					response->type = dict;
					y = bstr(strdup("r"));
					y->key = bstr(strdup("y"));
					binsert(response, y);
					binsert(response, bclone(bpath(b, "t")));
					r = calloc(1, sizeof *r);
					r->key = bstr(strdup("r"));
					r->type = dict;
					id = calloc(1, sizeof *id);
					id->type = string;
					id->key = bstr(strdup("id"));
					memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20);
					binsert(r, id);
					binsert(response, r);
					if (family(addr.sin6_addr.s6_addr) == AF_INET || bval(bpath(b, "a/want"), bstrs("v4"))) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
						binsert(response, nodes(d, target->value, AF_INET));
#pragma GCC diagnostic pop
					}
					if (family(addr.sin6_addr.s6_addr) == AF_INET6 || bval(bpath(b, "a/want"), bstrs("v6"))) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
						binsert(response, nodes(d, target->value, AF_INET6));
#pragma GCC diagnostic pop
					}
					sendb(d, response, &addr);
					free_bencoding(response);
					break;
				case 'G': // get_peers
				case 'g':
					;
					struct bencoding * hash = bpath(b, "a/info_hash");
					if (!hash || !(hash->type & string) || hash->valuelen != 20)
						break; // see NOTE01
					response = calloc(1, sizeof *response);
					response->type = dict;
					y = bstr(strdup("r"));
					y->key = bstr(strdup("y"));
					binsert(response, y);
					binsert(response, bclone(bpath(b, "t")));
					r = calloc(1, sizeof *r);
					r->key = bstr(strdup("r"));
					r->type = dict;
					id = calloc(1, sizeof *id);
					id->type = string;
					id->key = bstr(strdup("id"));
					memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20);
					binsert(r, id);
					binsert(response, r);
					if (family(addr.sin6_addr.s6_addr) == AF_INET || bval(bpath(b, "a/want"), bstrs("v4"))) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
						binsert(response, nodes(d, hash->value, AF_INET));
#pragma GCC diagnostic pop
					}
					if (family(addr.sin6_addr.s6_addr) == AF_INET6 || bval(bpath(b, "a/want"), bstrs("v6"))) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
						binsert(response, nodes(d, hash->value, AF_INET6));
#pragma GCC diagnostic pop
					}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
					struct torrent * torrent = find_torrent(d, hash->value, 20);
					d->possible_torrent(d, hash->value, torrent);
#pragma GCC diagnostic pop
					unsigned i = 8;
					if (torrent) {
						struct peer * peer = torrent->peers;
						struct bencoding * values = calloc(1, sizeof *values);
						values->type = list;
						while (i-- && peer) { // TODO implement peer preference: prefer sending peers that responded to us
							if (family(peer->addr.sin6_addr.s6_addr) != family(addr.sin6_addr.s6_addr)) // possible
								goto c;
							if (peer->flags & (unreachable || protocolerror))
								goto c;
							struct bencoding * value = calloc(1, sizeof *value);
							memcpy((value->value = malloc((value->valuelen = ADDRLEN(family(peer->addr.sin6_addr.s6_addr))+2))), peer->addr.sin6_addr.s6_addr, ADDRLEN(family(peer->addr.sin6_addr.s6_addr)));
							memcpy(value->value+ADDRLEN(family(peer->addr.sin6_addr.s6_addr)), &peer->addr.sin6_port, 2);
							binsert(values, value);
							c:
							peer = peer->next;
						}
						binsert(r, values);
					}
					struct bencoding * tok = calloc(1, sizeof *tok);
					tok->type = string;
					tok->key = bstr(strdup("token"));
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
					token(d, (tok->value = malloc((tok->valuelen = 16))), addr.sin6_addr.s6_addr);
#pragma GCC diagnostic pop
					binsert(r, tok);
					sendb(d, response, &addr);
					free_bencoding(response);
					break;
				case 'A': // announce
				case 'a':
					tok = bpath(b, "a/token");
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
					if (!tok || !(tok->type & string) || tok->valuelen != 16 || !valid(d, tok->value, addr.sin6_addr.s6_addr)) {
						L(disagreement, d, "invalid announce token from %s", remote);
						break; // see NOTE01
					}
#pragma GCC diagnostic pop
					hash = bpath(b, "a/info_hash");
					if (!hash || !(hash->type & string) || hash->valuelen != 20)
						break; // see NOTE01
					response = calloc(1, sizeof *response);
					response->type = dict;
					binsert(response, bclone(bpath(b, "t")));
					r = calloc(1, sizeof *r);
					r->type = dict;
					r->key = bstr(strdup("r"));
					id = calloc(1, sizeof *id);
					id->key = bstr(strdup("id"));
					id->type = string;
					memcpy((id->value = malloc((id->valuelen = 20))), d->id, 20);
					binsert(r, id);
					binsert(response, r);
					y = bstr(strdup("r"));
					y->key = bstr(strdup("y"));
					binsert(response, y);
					sendb(d, response, &addr);
					free_bencoding(response);
					torrent = torrent_init(); // gucci, because add_torrent returns existing and frees if already stored
					memcpy(torrent->hash, hash->value, 20);
					torrent = add_torrent(d, torrent);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
					d->possible_torrent(d, hash->value, torrent);
#pragma GCC diagnostic pop
					struct peer * peer = peer_init(); // same as with torrent
					memcpy(&peer->addr, &addr, sizeof addr);
					if (bpath(b, "a/port") && (!bpath(b, "a/implied_port") || !bpath(b, "a/implied_port")->intvalue))
						peer->addr.sin6_port = htons(bpath(b, "a/port")->intvalue);
					add_peer(d, torrent, peer);
					break;
				default: // see NOTE01
					;
					int len = b2json_length(b);
					char json[len+1];
					b2json(json, b);
					json[len] = '\0';
					L(disagreement, d, "%s sent an unknown query type: %s", remote, json);
					break;
			}
			break;
		case 'R': // we only ever query and expect responses to get_peers and find_node, so it's egal
		case 'r': 
			;
			rid = bpath(b, "r/id");
			if (rid && rid->type & string && rid->valuelen == 20) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
				replied(d, rid->value, &addr); // since here I'm only really interested about nodes and values or
#pragma GCC diagnostic pop
			}
			struct bencoding * t = bpath(b, "t");
			struct torrent * torrent = NULL;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
			if (t && t->type & string && t->valuelen == MAXT) {
				if ((torrent = find_torrent(d, t->value, MAXT)) && torrent->type) {
#pragma GCC diagnostic pop
						if (rid && rid->type & string && rid->valuelen == 20) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
							replied_torrent_node(torrent, &addr, rid->value);
#pragma GCC diagnostic pop
						}
						bforeach (bpath(b, "r/values"), p) {
							if (!(p->type & string) || (p->valuelen != 6 && p->valuelen != 18))
								break;
							struct peer * peer = peer_init();
							memcpy(peer->addr.sin6_addr.s6_addr, "\0\0\0\0\0\0\0\0\0\0\xFF\xFF", 12);
							peer->addr.sin6_port = *((uint16_t *) (p->value + p->valuelen-2));
							memcpy(peer->addr.sin6_addr.s6_addr+(p->valuelen == 6 ? 12 : 0), p->value, p->valuelen == 6 ? 4 : 16);
							add_peer(d, torrent, peer);
						}
						if (torrent->type & announce)
							announce_peer(d, &addr, bclone(bpath(b, "r/token")), torrent->hash);
				}
			}
			struct bencoding * nodes = bpath(b, "r/nodes");
			struct bencoding * nodes6 = bpath(b, "r/nodes6");
			if (nodes && nodes->type & string && !(nodes->valuelen % 26))
				for (unsigned i = 0; i < MIN(nodes->valuelen, K*26); i += 26)
					compact(d, nodes->value+i, 26, torrent);
			if (nodes6 && nodes6->type & string && !(nodes6->valuelen % 38))
				for (unsigned i = 0; i < MIN(nodes6->valuelen, K*38); i += 38)
					compact(d, nodes6->value+i, 38, torrent);
			break;
		case 'E':
		case 'e':
			;
			struct bencoding * e = bpath(b, "e");
			char * errtype = "Unspecified Error";
			if (e && e->child)
				switch (e->child->intvalue) {
					case 201:
						errtype = "Generic Error";
						break;
					case 202:
						errtype = "Server Error";
						break;
					case 203:
						errtype = "Protocol Error, such as a malformed packet, invalid arguments, or bad token";
						break;
					case 204:
						errtype = "Method Unknown";
						break;
					default:
						errtype = "Unknown Error";
						break;
				}
			char * msg = NULL;
			if (e && e->child && e->child->next && e->child->next->type & string)
				msg = e->child->next->value;
			L(disagreement, d, "%s sent %s%s%s", remote, errtype, msg ? ": " : "", msg ? msg : "");
			break;
		case '\0': // y is not present, this may just be a DNS response,
			break; // do not log
		default: // NOTE01 sending an error is unfortunately bad in this case, since clever hackers can force two servers speaking entirely different UDP based protcols into sending error messages to each other, telling one another that they don't understand each other's messages.
			; // we don't report, since it may be DNS packet
			int len = b2json_length(b);
			char json[len+1];
			b2json(json, b);
			json[len] = '\0';
			L(disagreement, d, "%s sent an unknown type: %s", remote, json);
			// send_error(d, b, &addr, addrlen, 203, "unknown type");
			break;
	}
	free_bencoding(b);
	ns_msg handle; // parsing incoming DNS packet as utils/dns.c
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
	if (ns_initparse(pkt, len, &handle) != -1) { // queries are sent by periodic
#pragma GCC diagnostic pop
		for (int i = 0; i < ns_msg_count(handle, ns_s_an); i++) {
			struct __ns_rr rr;
			if (ns_parserr(&handle, ns_s_an, i, &rr) == -1) {
				L(std_fail, d, "ns_parserr(%s) == -1", remote);
				break;
			}
			if (rr.type != ns_t_srv && rr.type != ns_t_a && rr.type != ns_t_aaaa) {
				L(disagreement, d, "%s unknown RR type %d", remote, rr.type);
				continue;
			}
			char address[INET_ADDRSTRLEN+INET6_ADDRSTRLEN+7];
			switch (rr.rdlength) {
				case 4:
					if (!inet_ntop(AF_INET, rr.rdata, address, INET6_ADDRSTRLEN+INET_ADDRSTRLEN+7)) {
						L(std_fail, d, "%s !inet_ntop(AF_INET)", remote);
						break; // this can't fail!?
					}
					sprintf(address+strlen(address), "/%u", ntohs(*((uint16_t *) pkt)));
					L(expected, d, "%s: A %s", remote, address);
					struct sockaddr_in6 a = {
						.sin6_family = AF_INET6,
						.sin6_port = *((uint16_t *) pkt)
					};
					memcpy(a.sin6_addr.s6_addr, "\0\0\0\0\0\0\0\0\0\0\xFF\xFF", 12);
					memcpy(a.sin6_addr.s6_addr+12, rr.rdata, 4);
					ping_node(d, &a);
					break;
				case 16:
					if (!inet_ntop(AF_INET6, rr.rdata, address, INET6_ADDRSTRLEN+INET_ADDRSTRLEN+7))
						L(std_fail, d, "%s !inet_ntop(AF_INET6)", remote);
					sprintf(address+strlen(address), "/%u", ntohs(*((uint16_t *) pkt)));
					L(expected, d, "%s: AAAA %s", remote, address);
					struct sockaddr_in6 aaaa = {
						.sin6_family = AF_INET6,
						.sin6_port = *((uint16_t *) pkt)
					};
					memcpy(aaaa.sin6_addr.s6_addr, rr.rdata, 16);
					ping_node(d, &aaaa);
					break;
				default: // SRV
					if (rr.rdlength < 3*2+3) // . indicates
						break; // disabled service - useless
					char target[NS_MAXDNAME];
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
					if (ns_name_uncompress(pkt, pkt+len, rr.rdata+3*2, target, NS_MAXDNAME) == -1) {
#pragma GCC diagnostic pop
						break;
						L(std_fail, d, "ns_name_uncompress(%s) == -1", remote);
					}
					for (int j = 0; j <= 1; j++) {
						struct __res_state state;
						if (res_ninit(&state) == -1) {
							L(std_fail, d, "res_ninit(%s, %s) == -1", remote, target);
							continue;
						}
						unsigned char packet[65536];
						int size = res_nmkquery(&state, QUERY, target, ns_c_in, j ? ns_t_a : ns_t_aaaa, NULL, 0, NULL, packet, 65536);
						if (size == -1) {
							L(std_fail, d, "res_nmkquery(%s) == -1", target);
							goto d;
						}
						memcpy(packet, rr.rdata+4, 2);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
						if (sendto(d->socket, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, &addr, sizeof addr) == -1)
							L(std_fail, d, "sendto(%s, %s)", remote, target);
						d->txp++;
						d->txb += size;
#pragma GCC diagnostic pop
d:
						res_nclose(&state);
					}
					break;
					
			}
		}
	} // do not log, it may have been a bencoded reply
}

/**
 * delete all but first bucket in ll, used in refresh on both lls (v4 and v6) in case of sybil
 *
 * @param b	[in]	first bucket in ll
 */

void delete_buckets (struct bucket * b) {
	struct node * n = b->nodes;
	while (n) {
		struct node * old = n;
		n = n->next;
		node_free(old);
	}
	b->nodes = NULL;
	memset(b->id, '\0', 20);
	struct bucket * del = b->next;
	b->next = NULL;
	while (del) {
		struct bucket * old = del;
		del = del->next;
		bucket_free(old);
	}
}

#define PERIODIC 10

/**
 * do periodic housekeeping on the routing table LL, making sure no nodes are bad. removes bad nodes. detects sybil. see NOTE03
 *
 * @param d	[in]	library handle
 * @param fam	[in]	AF_INET for buckets and AF_INET6 for buckets6
 * @return number of good nodes
 */

int refresh (struct dht * d, int fam) {
	int nrgood = 0;
	int buckets = 0;
	struct bucket * b = d->buckets;
	if (fam == AF_INET6)
		b = d->buckets6;
	while (b) {
		buckets++;
		struct node ** n = &b->nodes;
		while (*n) {
			switch (node_grade(*n)) {
				case bad:
					;
					struct node * old = *n;
					*n = (*n)->next;
					node_free(old);
					continue;
				case questionable:
					// if (!(rand() % ())) // I disabled it again because it was too spammy
					//	ping_node(d, &(*n)->addr); // NOTE03 about not pinging questionable nodes: this ensures a constant regeneration of the routing table. this is just an idea, if the client frequently gets in a situation without any nodes in the routing table, remove the comment before ping_node call.
					break; // update on why I uncommented: to mitigate sybil attack, it's baje important to prefer old nodes
				case good:
					nrgood++;
					break;
			}
			n = &(*n)->next;
		}
		b = b->next;
	}
	if (buckets > 64) { // sybil attack - node is broken - clear whole routing table, keeping one bucket
		dht_print(d->log, d);
		L(disagreement, d, "@@@@@@ SYBIL ATTACK - CLEARING ROUTING TABLE @@@@@@");
		delete_buckets(d->buckets);
		delete_buckets(d->buckets6);
		if (getrandom(d->id, 20, GRND_NONBLOCK) == -1) // changing our ID. note that this might make
			L(std_fail, d, "getrandom: %s", strerror(errno)); // existing nodes hate us, though we'll probably have no existing nodes
		return 0;
	}
	return nrgood;
}

/**
 * does periodic work for the library
 *
 * namely, it sends UDP packets:
 * 	- searching deeper DHT storage nodes for torrents with peers and announce
 * 	- get_peers on torrents with peers or announce. when a response is received for a torrent with announce, an announce will be sent as well
 *
 * for bootstrapping, an **IPv4** nameserver is required in /etc/resolv.conf. res_*() functions only provide IPv4 nameservers. example script with this algorithm is available in utils/dns.c
 *
 * this can be a lot of packets, so please keep number of torrents with peers and announce low
 *
 * call this:
 * 	- every PERIODIC seconds, even if it was called for incoming packets in this time period
 * 		+ stale buckets are refreshed
 *		+ peers are refetched for joined torrents and announcements are sent
 *		+ calling it more often is discouraged, since every periodic call sends out UDP packets for PEX and DHT searches/announces of torrents
 *
 * @param d	[in]	the dht library handle
 */

void periodic (struct dht * d) {
	d->periods++;
	int dns = 0;
	if (!refresh(d, AF_INET))
		dns++;
	if (!refresh(d, AF_INET6))
		dns++;
	if (dns) {
		char packet[512];
		memset(packet, '\0', 512);
		struct __res_state state;
		if (res_ninit(&state) == -1) {
			L(std_fail, d, "res_ninit(&state) == -1");
			goto t;
		}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
		int size = res_nmkquery(&state, QUERY, "_dht._udp.travnik.sijanec.eu", ns_c_in, ns_t_srv, NULL, 0, NULL, packet, 512) != -1; // for some reason always returns 1
#pragma GCC diagnostic pop
		if (size == -1) {
			L(std_fail, d, "res_nmkquery(SRV) == -1");
			goto d;
		}
		for (int i = 0; i < state.nscount; i++)
			if (state.nsaddr_list[i].sin_family == AF_INET) { // leider only ipv4 NSs
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
				if (sendto(d->socket, packet, 512, MSG_DONTWAIT | MSG_NOSIGNAL, &state.nsaddr_list[i], sizeof state.nsaddr_list[i]) == -1)
					L(std_fail, d, "sendto: %s", strerror(errno));
#pragma GCC diagnostic pop
				d->txp++;
				d->txb += size;
			}
#ifdef HARDCODED_DNS // because ipv6 dns is not supported
		struct sockaddr_in6 hc = {
			.sin6_family = AF_INET6,
			.sin6_port = htons(53)
		};
		int ret = inet_pton(AF_INET6, STR(HARDCODED_DNS), hc.sin6_addr.s6_addr);
		switch (ret) {
			case 0:
				L(disagreement, d, "hardcoded dns server " STR(HARDCODED_DNS) " is invalid");
				break;
			case 1:
				L(expected, d, "querying hardcoded dns server " STR(HARDCODED_DNS));
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
				if (sendto(d->socket, packet, 512, MSG_DONTWAIT | MSG_NOSIGNAL, &hc, sizeof hc) == -1)
					L(std_fail, d, "sendto hardcoded dns: %s", strerror(errno));
#pragma GCC diagnostic pop
				break;
			case -1:
				L(std_fail, d, "inet_pton(" STR(HARDCODED_DNS) "): %s", strerror(errno));
				break;
		}
#endif
		d:
		res_nclose(&state); // receiving and resolving SRV->{A,AAAA} in handle()
	}
	t:
	torrent_ll_assert(d->torrents);
	struct torrent * t = d->torrents;
	while (t) {
		if (t->ttl && seconds() > t->ttl) {
			disconnect(t);
			t->ttl = 0;
			t->type = 0;
		}
		if (t->type & (peers | announce)) {
			struct node * n = t->nodes;
			int sent = 0;
			int c = node_count(n);
			if (c)
				c = rand() % c;
			while (n && c--)
				n = n->next;
			while (n && sent < 3) { // we pick some consecutive at random and ping them.
				sent++;	// increase to more than this if desired ... idk this is shit
				if (!n->unanswered)
					n->last_sent = seconds();
				n->unanswered++;
				get_peers(d, &n->addr, t->hash);
				n = n->next;
				if (!n && !t->nodes->unanswered) // if unanswered, we already sent it
					n = t->nodes;
			}
			if (sent < 2) {
#define RTGP(buckets)		{struct bucket * b = d->buckets; \
				find(t->hash, &b, NULL); \
				struct node * n = b->nodes; \
				int c = node_count(n); \
				if (c) \
					c = rand() % c; \
				while (n && c--) \
					n = n->next; \
				if (n) { \
					sent++; \
					if (!n->unanswered) \
						n->last_sent = seconds(); \
					n->unanswered++; \
					get_peers(d, &n->addr, t->hash); \
				}}
				RTGP(buckets);
				RTGP(buckets6);
			}
			while (sent < 1) {
				struct bucket * b = d->buckets;
				while (sent < 1 && b) {
					n = b->nodes;
					int c = node_count(n);
					if (c)
						c = rand() % c;
					while (n && c--)
						n = n->next;
					while (sent < 1 && n) {
						sent++;
						if (!n->unanswered)
							n->last_sent = seconds();
						n->unanswered++;
						get_peers(d, &n->addr, t->hash);
					}
					b = b->next;
				}
			}
		}
		if (t->type & info) {
			if (t->dl) {
				if (seconds() - t->time > DLTO) {
					t->dl->flags |= unreachable;
					disconnect(t);
				} else
					goto a;
			}
			struct peer * p = t->peers;
			int c = 0;
			while (p) {
				if (!(p->flags & (badmeta | nometasupport | unreachable | protocolerror)))
					c++;
				p = p->next;
			}
			if (!c)
				goto a;
			int s = rand() % c; // OB1 untested
			p = t->peers;
			while (p) {
				if (!(p->flags & (badmeta | nometasupport | unreachable | protocolerror)) && !s--) {
					t->dl = p;
					t->state = 0;
					t->socket = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
					if (t->socket == -1) {
						t->dl = NULL;
						L(std_fail, d, "socket: %s", strerror(errno));
						break;
					}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
					if (connect(t->socket, &p->addr, sizeof p->addr) == -1) {
#pragma GCC diagnostic pop
						if (errno != EINPROGRESS) {
							L(std_fail, d, "connect: %s", strerror(errno));
							disconnect(t);
						}
					}
					t->time = seconds();
					t->size = 0;
					t->progress = 0;
					t->state &= ~(incoming | outgoing);
					t->state |= outgoing;
					if (t->packet)
						free(t->packet);
					t->packet = malloc(32727);
					t->recvd = 0;
					t->dl->flags &= ~(requested);
					d->connection(d, t);
					t->intentions(t);
					break;
				}
				p = p->next;
			}
		}
		a:
		t = t->next;
	}
	L(debug, d, "txqp=%u rxrp=%u rxqp=%u txrp=%u", d->txqp, d->rxrp, d->rxqp, d->txrp);
	if (d->txqp > TOOMUCH || d->rxrp > TOOMUCH || d->rxqp > TOOMUCH || d->txrp > TOOMUCH) {
		dht_print(stdout, d);
		raise(SIGABRT);
	}
	d->txqp = d->txrp = d->rxqp = d->rxrp = 0;
}

/**
 * handle tcp activity
 */

void tcp_work (struct dht * d) {
	char packet[65536];
	L(debug, d, "called");
	struct torrent * t = d->torrents;
	while (t) {
		if (!t->dl)
			goto c;
		if (!(t->state & ~(incoming | outgoing))) { // initial state isn't really blank - outgoing
			unsigned char handshake[1+19+8+20*2] = "aBitTorrent protocol";
			handshake[0] = 19;
			handshake[1+19+5] = 0x10;
			memcpy(handshake+1+19+8, t->hash, 20);
			memcpy(handshake+1+19+8+20, d->id, 20);
			if (send(t->socket, handshake, 1+19+8+20*2, MSG_DONTWAIT | MSG_NOSIGNAL) != -1) {
				d->tt += 1+19+8+20*2;
				t->state |= handshake_sent;
				t->state &= ~(incoming | outgoing);
				t->state |= incoming;
				t->intentions(t);
			} else
				if (errno != EAGAIN) {
					L(std_fail, d, "send(): %s", strerror(errno));
					t->dl->flags |= unreachable;
					disconnect(t);
					goto c;
				}
		}
		if (t->state & handshake_received && !(t->state & extension_sent)) {
			char e[1024] = "\0\0\0\0\0\0d1:md11:ut_metadatai1eee";
			e[3] = 2+strlen(e+6);
			e[4] = 20;
			if (send(t->socket, e, e[3]+4, MSG_DONTWAIT | MSG_NOSIGNAL) != -1) {
				d->tt += e[3]+4;
				t->state |= extension_sent;
				t->state &= ~(incoming | outgoing);
				t->state |= incoming;
				t->intentions(t);
			} else
				if (errno != EAGAIN) {
					L(std_fail, d, "send(): %s", strerror(errno));
					disconnect(t);
					goto c;
				}
		}
		if (t->ut_metadata && !(t->dl->flags & requested)) {
			char r[1024] = "\0\0\0";
			r[4] = 20;
			r[5] = t->ut_metadata;
			r[3] = 2+sprintf(r+6, "d8:msg_typei0e5:piecei%uee", t->progress);
			if (send(t->socket, r, r[3]+4, MSG_DONTWAIT | MSG_NOSIGNAL) != -1) {
				d->tt += r[3]+4;
				t->dl->flags |= requested;
				t->state &= ~(incoming | outgoing);
				t->state |= incoming;
				t->intentions(t);
			} else
				if (errno != EAGAIN) {
					L(std_fail, d, "send(): %s", strerror(errno));
					disconnect(t);
					goto c;
				}
		}
		if (!(t->state & ~(handshake_sent | incoming | outgoing))) {
			int ret = recv(t->socket, packet, 1+19+8+20*2, MSG_DONTWAIT);
			L(expected, d, "handshake recv returned value %d, t->recvd == %d", ret, t->recvd);
			if (ret == 0) {
				L(disagreement, d, "received 0 bytes instead of handshake. EOF");
				t->dl->flags |= protocolerror;
				disconnect(t);
				goto c;
			}
			if (ret < 0) {
				if (errno != EAGAIN) {
					L(std_fail, d, "recv(TCP, MSG_PEEK): %s (%d)", strerror(errno), errno);
					t->dl->flags |= unreachable;
					disconnect(t);
				}
				goto c;
			}
			if (ret < 1+19+8+20*2) { // c'mon, this could've arrived in one packet HACK UGLY!
				L(disagreement, d, "expected handshake, received only %d bytes", ret);
				t->dl->flags |= protocolerror; // cause it sent a nonsensical packet
				disconnect(t);
				goto c;
			}
			d->tr += 1+19+8+20*2;
			t->state &= ~(incoming | outgoing);
			t->state |= outgoing;
			t->intentions(t);
			t->state |= handshake_received;
			if (memcmp(packet+1+19+8, t->hash, 20)) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
				possible_torrent(d, packet+1+19+8, NULL);
#pragma GCC diagnostic pop
				disconnect(t);
				goto c;
			}
			if (!(packet[1+19+5] & 0x10)) {
				L(disagreement, d, "peer did not set extension bit for dynamic extension");
				t->dl->flags |= nometasupport;
				disconnect(t);
				goto c;
			}
		}
		if (t->recvd < 4) {
			int ret = recv(t->socket, t->packet+t->recvd, 4-t->recvd, MSG_DONTWAIT);
			if (ret < 0) {
				if (errno != EAGAIN) {
					L(std_fail, d, "recv(TCP, MSG_PEEK): %s (%d)", strerror(errno), errno);
					disconnect(t);
				}
				goto c;
			} else if (!ret){
				L(disagreement, d, "peer EOF");
				t->dl->flags |= protocolerror;
				disconnect(t);
				goto c;
			} else {
				d->tr += ret;
				t->recvd += ret;
			}
			if (t->recvd == 4) {
				uint32_t l = ntohl(*((uint32_t *) t->packet));
				L(debug, d, "found length of a packet to be %u", l);
			}
		}
		if (t->recvd >= 4) {
			char buf[41];
			buf[40] = '\0';
			bin2hex(buf, t->packet, MIN(20, t->recvd));
			if (t->packet[0]) {
				L(disagreement, d, "peer wants to send too big of a packet %.*s", MIN(20, t->recvd)*2, buf);
				t->dl->flags |= protocolerror; // too big pkt, sorry
				disconnect(t);
				goto c;
			}
			uint32_t l = ntohl(*((uint32_t *) t->packet));
			int ret = recv(t->socket, t->packet+t->recvd, MIN(l-t->recvd+4, 32727-t->recvd), MSG_DONTWAIT);
			L(debug, d, "reading packet content: read %d bytes", ret);
			if (ret < 0) {
				if (errno != EAGAIN) {
					L(std_fail, d, "recv(TCP): %s (%d)", strerror(errno), errno);
					disconnect(t);
				}
				goto c;
			} else if (!ret) {
				L(disagreement, d, "peer EOF");
				t->dl->flags |= protocolerror;
				disconnect(t);
				goto c;
			} else {
				d->tr += ret;
				t->recvd += ret;
			}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
			if (l > (t->recvd-4)) // we don't have a full packet
				goto c;
#pragma GCC diagnostic pop
			L(expected, d, "full packet: type %u subtype %u recvd=%d", t->packet[4], t->packet[5], t->recvd);
			if (t->packet[4] != 20) // if it's not extension, the only supported type
				goto end_packet;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
			struct bencoding * e = bdecode(t->packet+6, 32727-6, replace);
#pragma GCC diagnostic pop
			struct bencoding * v = bpath(e, "v");
			if (v && v->type & string) {
				L(expected, d, "peer's software is %s", v->value);
				free(t->software);
				t->software = strdup(v->value);
			}
			switch (t->packet[5]) {
				case 0:
					;
					struct bencoding * ut_metadata = bpath(e, "m/ut_metadata");
					struct bencoding * ut_pex = bpath(e, "m/ut_pex");
					struct bencoding * metadata_size = bpath(e, "metadata_size");
					if (ut_pex && ut_pex->type & num)
						t->ut_pex = ut_pex->intvalue;
					if (ut_metadata && ut_metadata->type & num)
						t->ut_metadata = ut_metadata->intvalue;
					else
						goto nometa;
					if (metadata_size && metadata_size->type & num && metadata_size->intvalue > 0 && metadata_size->intvalue < 100000000) {
						t->size = metadata_size->intvalue;
						t->metadata = realloc(t->metadata, metadata_size->intvalue);
					} else {
						nometa:
						L(disagreement, d, "peer does not support ut_metadata in dynamic extension");
						t->dl->flags = nometasupport;
						if (t->ut_pex) {
							// ask for pex
						}
						disconnect(t);
						break;
					}
					t->state |= extension_received;
					t->state &= ~(incoming | outgoing);
					t->state |= outgoing;
					t->intentions(t);
					break;
				case 1:
					;
					struct bencoding * msg_type = bpath(e, "msg_type");
					struct bencoding * piece = bpath(e, "piece");
					if (msg_type && msg_type->type & num && piece && piece->type & num) {
						switch (msg_type->intvalue) {
							case 0: // request, we just reject it
								;
								char r[1024] = "\0\0\0";
								r[4] = t->ut_metadata;
								r[3] = 2+sprintf(r+6, "d8:msg_typei2e5:piecei%ldee", piece->intvalue);
								if (send(t->socket, r, r[3]+4, MSG_DONTWAIT | MSG_NOSIGNAL) == -1) {
									if (errno != EAGAIN) {
										L(std_fail, d, "send(): %s", strerror(errno));
										disconnect(t);
										break;
									}
								} else
									d->tt += r[3]+4;
								t->state &= ~(incoming | outgoing);
								t->state |= outgoing;
								t->intentions(t);
								break;
							case 1: // data
								if (piece->intvalue != t->progress)
									break;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-sign"
								unsigned char * ee = strstr(t->packet+6, "ee");
#pragma GCC diagnostic pop
								if (!ee) {
									disconnect(t);
									L(disagreement, d, "malformed packet");
									break;
								}
								int piecelen = t->recvd-((ee+2)-t->packet);
								L(debug, d, "received a %d byte piece", piecelen);
								if (t->size < t->progress*16384+piecelen) {
									L(disagreement, d, "sent more packets than space available. UNREACHABLE!!!");
									disconnect(t);
									break;
								}
								if (!t->metadata) {
									disconnect(t);
									L(disagreement, d, "i have nowhere to store!");
									break;
								}
								t->packet[32726] = '\0';
								memcpy(t->metadata+t->progress++*16384, ee+2, piecelen);
								t->time = seconds();
								if (t->progress*16384 >= t->size) {
									SHA1_CTX sha;
									uint8_t results[SHA1_DIGEST_LENGTH];
									SHA1Init(&sha);
									SHA1Update(&sha, t->metadata, t->size);
									SHA1Final(results, &sha);
									SHA2_CTX ctx;
									uint8_t results2[SHA256_DIGEST_LENGTH];
									SHA256Init(&ctx);
									SHA256Update(&ctx, t->metadata, t->size);
									SHA256Final(results2, &ctx);
									if (memcmp(results, t->hash, 20) && memcmp(results2, t->hash, 20)) {
										t->dl->flags |= badmeta;
										t->dl->flags &= ~goodmeta;
										L(disagreement, d, "received invalid metadata!");
										disconnect(t);
										break;
									}
									t->dl->flags &= ~badmeta;
									t->dl->flags |= goodmeta;
									L(expected, d, "received good metadata!");
									disconnect(t);
									break;
								}
								t->dl->flags &= ~requested;
								t->state &= ~(incoming | outgoing);
								t->state |= outgoing;
								t->intentions(t);
								break;
							case 2: // reject
								t->dl->flags |= nometa;
								disconnect(t);
								break;
						}
					}
					break;
			}
			free_bencoding(e);
			end_packet:
			L(debug, d, "cleared packet recvd to 0");
			t->recvd = 0;
		}
		/*
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-compare"
		if (t->state) {
#pragma GCC diagnostic pop
			recv(t->socket, packet, 4+l, MSG_DONTWAIT);
			d->tr += 4+l;
			if (packet[4] == 20) {
				t->state &= ~(incoming | outgoing);
				t->state |= outgoing;
				t->intentions(t);
				switch (packet[5]) {
					case 0:
						;
						struct bencoding * ut_metadata = bpath(e, "m/ut_metadata");
						struct bencoding * ut_pex = bpath(e, "m/ut_pex");
						struct bencoding * metadata_size = bpath(e, "metadata_size");
						if (ut_pex && ut_pex->type & num)
							t->ut_pex = ut_pex->intvalue;
						if (ut_metadata && ut_metadata->type & num)
							t->ut_metadata = ut_pex->intvalue;
						else
							goto nometa;
						if (metadata_size && metadata_size->type & num && metadata_size->intvalue > 0 && metadata_size->intvalue < 100000000) {
							t->size = metadata_size->intvalue;
							t->metadata = realloc(t->metadata, metadata_size->intvalue);
						} else {
							nometa:
							t->dl->flags = nometasupport;
							if (t->ut_pex) {
								// ask for pex
							}
							disconnect(t);
							break;
						}
						break;
					case 1:
						;
						struct bencoding * msg_type = bpath(e, "msg_type");
						struct bencoding * piece = bpath(e, "piece");
						if (msg_type && msg_type->type & num && piece && piece->type & num) {
							switch (msg_type->intvalue) {
								case 0: // request, we just reject it
									;
									char r[1024] = "\0\0\0";
									r[4] = t->ut_metadata;
									r[3] = 2+sprintf(r+6, "d8:msg_typei2e5:piecei%ldee", piece->intvalue);
									if (send(t->socket, r, r[3]+4, MSG_DONTWAIT | MSG_NOSIGNAL) == -1) {
										if (errno != EAGAIN) {
											L(std_fail, d, "send(): %s", strerror(errno));
											disconnect(t);
											break;
										}
									} else
										d->tt += r[3]+4;
									break;
								case 1: // data
									if (piece->intvalue != t->progress)
										break;
									if (t->size < (t->progress+1)*16384) {
										disconnect(t);
										L(disagreement, d, "sent more packets than space available. UNREACHABLE!!!");
										break;
									}
									if (!t->metadata) {
										disconnect(t);
										L(disagreement, d, "i have nowhere to store!");
										break;
									}
									packet[65535] = '\0';
									char * ee = strstr(packet+6, "ee");
									if (!ee) {
										disconnect(t);
										L(disagreement, d, "malformed packet");
										break;
									}
									memcpy(t->metadata+t->progress++*16384, ee+2, 16384);
									t->time = seconds();
									if (t->progress*16384 >= t->size) {
										SHA1_CTX sha; // TODO SHA256 for torrent v2
										uint8_t results[SHA1_DIGEST_LENGTH];
										SHA1Init(&sha);
										SHA1Update(&sha, t->metadata, t->size);
										SHA1Final(results, &sha);
										if (memcmp(results, t->hash, 20)) {
											t->dl->flags |= badmeta;
											t->dl->flags &= ~goodmeta;
											L(disagreement, d, "received invalid metadata!");
											disconnect(t);
											break;
										}
										L(expected, d, "received good metadata!");
										disconnect(t);
										break;
									}
									t->dl->flags &= ~requested;
									break;
								case 2: // reject
									t->dl->flags |= nometa;
									disconnect(t);
									break;
							}
						}
						break;
				}
			}
		} */
		c:
		t = t->next;
	}
}

/**
 * does work; syncs with the network, handles incoming queries.
 *
 * call this:
 * 	- whenever socket can be read from (via poll/epoll/select/...)
 * @param d	[in]	dht library handle
 */

void work (struct dht * d) {
	char packet[65536];
	struct sockaddr_in6 addr;
	socklen_t addrlen = sizeof addr;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincompatible-pointer-types"
	int ret = recvfrom(d->socket, packet, 65536, MSG_DONTWAIT | MSG_TRUNC, &addr, &addrlen);
#pragma GCC diagnostic pop
	if (addrlen != sizeof addr)
		L(disagreement, d, "addrlen changed, not parsing packet");
	else if (ret > 65536)
		L(disagreement, d, "recvfrom()d larger packet than 65536, not parsing packet");
	else if (ret < 0) {
		if (errno != EAGAIN)
			L(std_fail, d, "recvfrom(): %s (%d)", strerror(errno), errno);
		else
			tcp_work(d);
	} else {
		d->rxp++;
		d->rxb += ret;
		handle(d, packet, ret, addr);
	}
}