mirror of
https://github.com/savoirfairelinux/opendht.git
synced 2026-11-08 12:28:42 +00:00
Compare commits
1173
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccb0b4340e | ||
|
|
fa78704062 | ||
|
|
625625a186 | ||
|
|
f0d039b4a0 | ||
|
|
d464214d73 | ||
|
|
b69c66feed | ||
|
|
3d9ee6a51a | ||
|
|
f71697c81b | ||
|
|
b071022283 | ||
|
|
487bc2fce2 | ||
|
|
758f280651 | ||
|
|
20464e6f16 | ||
|
|
d211de73e0 | ||
|
|
bde661a2d4 | ||
|
|
49ef8ee84d | ||
|
|
390528a1af | ||
|
|
97c9d58a5c | ||
|
|
e5903d5c94 | ||
|
|
65bbbead34 | ||
|
|
ffaf1e2ca3 | ||
|
|
af7d5c2770 | ||
|
|
c14858a82a | ||
|
|
1010a4c90f | ||
|
|
ea6bacf0a1 | ||
|
|
36f67747d7 | ||
|
|
b093dc0907 | ||
|
|
a06695734d | ||
|
|
35aa47029e | ||
|
|
4af12a4c2c | ||
|
|
3f77b6b820 | ||
|
|
858867dc56 | ||
|
|
fcb0632a41 | ||
|
|
3ba61e7e4e | ||
|
|
4ef2c21ce0 | ||
|
|
d98c66b2c0 | ||
|
|
dc09983b6b | ||
|
|
da00246fe8 | ||
|
|
e092e4d89f | ||
|
|
ed8131a3c6 | ||
|
|
f29c77cadf | ||
|
|
d90988cb6a | ||
|
|
3cf24c89d4 | ||
|
|
5e7bcd1189 | ||
|
|
8ac6baee22 | ||
|
|
f9bb4bcb40 | ||
|
|
35f486e035 | ||
|
|
0d5e4c761a | ||
|
|
efc372dc3f | ||
|
|
ddfbca3106 | ||
|
|
353c3d4e11 | ||
|
|
51324683e8 | ||
|
|
4633483e06 | ||
|
|
6aee7ceb5c | ||
|
|
32709230c6 | ||
|
|
7b526410dd | ||
|
|
fbff1eced4 | ||
|
|
d23cb42b27 | ||
|
|
e78e54b8c5 | ||
|
|
40560eec4e | ||
|
|
853bb1eeed | ||
|
|
22d87a0f0e | ||
|
|
dfb66c5a23 | ||
|
|
56fcc5b918 | ||
|
|
26b30d4162 | ||
|
|
791a667fe2 | ||
|
|
b693e3028b | ||
|
|
3e975d530a | ||
|
|
a32acbfa08 | ||
|
|
43147b8791 | ||
|
|
c1762af7e9 | ||
|
|
68b5996ba9 | ||
|
|
7bc287fe2f | ||
|
|
523dda8b3d | ||
|
|
1c32dd0efb | ||
|
|
1c914d8977 | ||
|
|
3c87991e92 | ||
|
|
52287bf608 | ||
|
|
061ce2deb4 | ||
|
|
64b536fb53 | ||
|
|
67c76f17de | ||
|
|
25fde756e8 | ||
|
|
f6b3eda280 | ||
|
|
9aee407a42 | ||
|
|
722ef44c7d | ||
|
|
6ed2720bd7 | ||
|
|
9005f73141 | ||
|
|
9785c0a127 | ||
|
|
5662cc36d1 | ||
|
|
e116cfe548 | ||
|
|
1c5e8378b8 | ||
|
|
c630e80345 | ||
|
|
17f83edce4 | ||
|
|
afab251376 | ||
|
|
86d452fbb6 | ||
|
|
08ff775232 | ||
|
|
738e0e22bf | ||
|
|
8ec5b47c86 | ||
|
|
e1c31568f9 | ||
|
|
45bad769b4 | ||
|
|
09780fd923 | ||
|
|
747e70d1ae | ||
|
|
05abfa89bf | ||
|
|
b714714128 | ||
|
|
2e8b36477d | ||
|
|
14543ae477 | ||
|
|
044135732f | ||
|
|
21b7f0d757 | ||
|
|
a5bfd3d933 | ||
|
|
af38323728 | ||
|
|
62e0ded803 | ||
|
|
a09cfefe5e | ||
|
|
13f340694e | ||
|
|
3723c4acf1 | ||
|
|
f19bca0df1 | ||
|
|
fbc7f90897 | ||
|
|
3a3c421ef9 | ||
|
|
9ec7a58ee3 | ||
|
|
ce73eb052e | ||
|
|
d716fae4bc | ||
|
|
a040bfeebb | ||
|
|
3223742d70 | ||
|
|
d2d56fcc20 | ||
|
|
af814f027f | ||
|
|
2016a9e2fa | ||
|
|
1db8abb7fc | ||
|
|
3f7b1bc3f5 | ||
|
|
019c25633e | ||
|
|
8193f43593 | ||
|
|
39564f14c1 | ||
|
|
83778d84fe | ||
|
|
b61ee620e4 | ||
|
|
0d120eb5d4 | ||
|
|
9b9056c0c8 | ||
|
|
bf8e3ea251 | ||
|
|
34eb86a119 | ||
|
|
75c789ceb2 | ||
|
|
da438d1bd2 | ||
|
|
44e67e1389 | ||
|
|
7f9126b3b0 | ||
|
|
574674d3a2 | ||
|
|
c60703bfc3 | ||
|
|
a0220827cd | ||
|
|
fb90211157 | ||
|
|
9501465293 | ||
|
|
95bd26c3be | ||
|
|
87463c2d6c | ||
|
|
baf413dd0d | ||
|
|
6bf01f3b6d | ||
|
|
852403fbeb | ||
|
|
5f6d5c769e | ||
|
|
42e4419b75 | ||
|
|
4e94d123b2 | ||
|
|
7f3f1b4ec4 | ||
|
|
6d462c0dbf | ||
|
|
0285acc766 | ||
|
|
0626e82f4a | ||
|
|
aa01f68cb5 | ||
|
|
af3fd618bf | ||
|
|
b96bdfbf04 | ||
|
|
60ca85f782 | ||
|
|
e4966aa457 | ||
|
|
aa9d23870b | ||
|
|
ac68db84eb | ||
|
|
bbbd9122af | ||
|
|
cf58d66282 | ||
|
|
2ddf1e5ec5 | ||
|
|
e48bfd578a | ||
|
|
1c3fc22c31 | ||
|
|
b6cf2fd246 | ||
|
|
91c3f62c0c | ||
|
|
2703cf129d | ||
|
|
51c2aadd4e | ||
|
|
8b20e912d6 | ||
|
|
b66ff83fe2 | ||
|
|
552813e1b9 | ||
|
|
601a8fbf80 | ||
|
|
26488d18a6 | ||
|
|
53c509c54f | ||
|
|
def6a28d96 | ||
|
|
dbd5953b17 | ||
|
|
2893823a77 | ||
|
|
3ec03ccc0b | ||
|
|
20fa751da0 | ||
|
|
0d572f0dab | ||
|
|
d9c401e1e2 | ||
|
|
dbdbe65a5d | ||
|
|
6f5bec3af6 | ||
|
|
d07a9e6583 | ||
|
|
fd43a329e7 | ||
|
|
93b2e8d5b9 | ||
|
|
d66713d97e | ||
|
|
7af9868c47 | ||
|
|
05a524b038 | ||
|
|
57ed00579e | ||
|
|
9ffccb3956 | ||
|
|
d99324ebd4 | ||
|
|
933f6cbca1 | ||
|
|
d5d7d6483f | ||
|
|
cc09a39ade | ||
|
|
621b44c8e8 | ||
|
|
e1c088f2e4 | ||
|
|
a6e0e441ac | ||
|
|
dcc2ba3492 | ||
|
|
ccf00d6b09 | ||
|
|
d8250574fc | ||
|
|
0d698c76e8 | ||
|
|
e4e3b4e73b | ||
|
|
b26d622f5d | ||
|
|
78694751bd | ||
|
|
f9b90c5c1c | ||
|
|
56b848bf47 | ||
|
|
dd875230c3 | ||
|
|
de1d428e63 | ||
|
|
55e3a6514f | ||
|
|
f4bbef210c | ||
|
|
2c1470cef6 | ||
|
|
adb6aa57e6 | ||
|
|
acd0abdb70 | ||
|
|
b9c8f5e0fd | ||
|
|
18fedf431f | ||
|
|
fc6edb4d20 | ||
|
|
d1093c77a3 | ||
|
|
b543f1e3cb | ||
|
|
be210e27da | ||
|
|
f7243fca37 | ||
|
|
1f6efd5736 | ||
|
|
54fbad3a7e | ||
|
|
1315489a7b | ||
|
|
c189fa0e82 | ||
|
|
3eae03289e | ||
|
|
e5e5a45b91 | ||
|
|
7a71beb892 | ||
|
|
74a894229f | ||
|
|
c81c1f70c8 | ||
|
|
3a383ac873 | ||
|
|
3149fe60c4 | ||
|
|
d5956e0778 | ||
|
|
8baf53d078 | ||
|
|
82ab21dc3f | ||
|
|
d676aef027 | ||
|
|
a2d9fdf334 | ||
|
|
0cec4135c0 | ||
|
|
6f76686a3e | ||
|
|
c211b3c376 | ||
|
|
0179b6ecc7 | ||
|
|
44e1ad839e | ||
|
|
dddd97daff | ||
|
|
632bec459e | ||
|
|
910ca10a5f | ||
|
|
0826822a4d | ||
|
|
8aa6b009c3 | ||
|
|
2caa21d65f | ||
|
|
cf64fa454c | ||
|
|
ef9ef12195 | ||
|
|
74a1918a4d | ||
|
|
56a60fb557 | ||
|
|
f98df1d615 | ||
|
|
8f779f2efb | ||
|
|
699073acd8 | ||
|
|
02d49b9f6a | ||
|
|
85b0bc52c8 | ||
|
|
af02c3a117 | ||
|
|
74b99453ce | ||
|
|
cba3d0e18f | ||
|
|
f9332985f5 | ||
|
|
513d0eb803 | ||
|
|
139852a531 | ||
|
|
3a73ad3aca | ||
|
|
9031cf06c4 | ||
|
|
7b1369931e | ||
|
|
64364602d7 | ||
|
|
2dbec3df97 | ||
|
|
507e2de3c4 | ||
|
|
c37abed715 | ||
|
|
0eb1c33ba5 | ||
|
|
45918186a2 | ||
|
|
29cb909228 | ||
|
|
9f6a03bf3d | ||
|
|
732da0e478 | ||
|
|
9a60329f66 | ||
|
|
0bb393ec36 | ||
|
|
947610003b | ||
|
|
dcbe158554 | ||
|
|
38e9a7fd61 | ||
|
|
7cf3e8b738 | ||
|
|
e924ef5620 | ||
|
|
d96115b445 | ||
|
|
bb96d2d80e | ||
|
|
8b96652b32 | ||
|
|
d1235660d5 | ||
|
|
23c6b5547b | ||
|
|
61c4a3880f | ||
|
|
44f2aaa876 | ||
|
|
a363d573e3 | ||
|
|
3ff9338980 | ||
|
|
ea3c0f0d93 | ||
|
|
f0cf074576 | ||
|
|
760586ed4a | ||
|
|
b951f4f40a | ||
|
|
63cc650a72 | ||
|
|
c020d2e1ef | ||
|
|
aae1bb2ae5 | ||
|
|
593e59e093 | ||
|
|
86d5065aca | ||
|
|
308d8ff82b | ||
|
|
34b9ddd023 | ||
|
|
88cb14ad95 | ||
|
|
e453a47242 | ||
|
|
199090b959 | ||
|
|
d250e6a349 | ||
|
|
99da0be2b7 | ||
|
|
22d219c695 | ||
|
|
ccd4865df5 | ||
|
|
5afc452f32 | ||
|
|
a06596d365 | ||
|
|
aa260c7b40 | ||
|
|
7183847e44 | ||
|
|
884cb09220 | ||
|
|
04edaafa57 | ||
|
|
6be58884aa | ||
|
|
d50d3d4f32 | ||
|
|
8acafe844d | ||
|
|
688b713c09 | ||
|
|
017df59dde | ||
|
|
964800a506 | ||
|
|
4f423d066f | ||
|
|
ae49b96c2d | ||
|
|
3701b21425 | ||
|
|
55af602026 | ||
|
|
eda121297b | ||
|
|
603e777c9e | ||
|
|
bef4e61fc6 | ||
|
|
42971d9587 | ||
|
|
4a43326de1 | ||
|
|
8fcb19627d | ||
|
|
b6ea2ed8e2 | ||
|
|
ac520bd587 | ||
|
|
4bd796cddd | ||
|
|
ad372bf232 | ||
|
|
299b4510f5 | ||
|
|
ae44ac98fb | ||
|
|
c37ff1b167 | ||
|
|
f94f072ad6 | ||
|
|
c51beca374 | ||
|
|
4b9a6489c3 | ||
|
|
34722cab7a | ||
|
|
9e1dc3f793 | ||
|
|
0eacd7fe6c | ||
|
|
37f4469961 | ||
|
|
e9c4a31949 | ||
|
|
1b5d9569ec | ||
|
|
e70f76f7f9 | ||
|
|
0f25da371e | ||
|
|
f33f66c038 | ||
|
|
1d08ff1489 | ||
|
|
b892be092a | ||
|
|
9a902fa80c | ||
|
|
984d720fac | ||
|
|
931d79b701 | ||
|
|
58a5791063 | ||
|
|
33b2bf12fa | ||
|
|
08e9f0b763 | ||
|
|
12cb93f9cf | ||
|
|
71d14bb0fe | ||
|
|
635a73141a | ||
|
|
de4327c056 | ||
|
|
348d6be920 | ||
|
|
dbdf2ba94d | ||
|
|
ef7505baaa | ||
|
|
9ad6b3a608 | ||
|
|
a32d76d312 | ||
|
|
8ebecfa25a | ||
|
|
ae3c2ae0d3 | ||
|
|
808ef0c51e | ||
|
|
6cf6892767 | ||
|
|
9ebe6e8bb6 | ||
|
|
a5455c19a6 | ||
|
|
166566dbf4 | ||
|
|
9b1534e6fe | ||
|
|
0263104373 | ||
|
|
0fc7e451e6 | ||
|
|
85cbee0f1a | ||
|
|
724b5e592e | ||
|
|
28001840fa | ||
|
|
047c10cf85 | ||
|
|
152f9a2f54 | ||
|
|
62243fb4f6 | ||
|
|
01eab83a7b | ||
|
|
2c71662af7 | ||
|
|
64032eb6d2 | ||
|
|
d91f3bdbbd | ||
|
|
1abaddba3e | ||
|
|
65b537f6e9 | ||
|
|
f44646ff82 | ||
|
|
73dc55155e | ||
|
|
aa000ee586 | ||
|
|
ec4c3e343c | ||
|
|
4b24f1da38 | ||
|
|
c47048121b | ||
|
|
638ffdc669 | ||
|
|
40ffafa756 | ||
|
|
e6836f076f | ||
|
|
03c1158d7e | ||
|
|
0018e577d9 | ||
|
|
eb7d94ee79 | ||
|
|
ea6ca025fc | ||
|
|
1105a68f93 | ||
|
|
76ae1cd6f2 | ||
|
|
c59c0ef64d | ||
|
|
1011d82b35 | ||
|
|
29f87169f8 | ||
|
|
435ee9cbbc | ||
|
|
6f111bcc0c | ||
|
|
f9cba71d51 | ||
|
|
4fd4745647 | ||
|
|
7165a02aaf | ||
|
|
fb34682e78 | ||
|
|
db8ca78943 | ||
|
|
da9360143d | ||
|
|
f55884b7d3 | ||
|
|
d978b471a3 | ||
|
|
4a6a7e3827 | ||
|
|
d3e6788dc0 | ||
|
|
e355e1fd5c | ||
|
|
5890971e1d | ||
|
|
512d81e0c0 | ||
|
|
c433fbe460 | ||
|
|
7f5d39ad36 | ||
|
|
8c6dd935a9 | ||
|
|
79d51e10ab | ||
|
|
b582ced6da | ||
|
|
c7079c7200 | ||
|
|
c60c6b8af2 | ||
|
|
9f7e4aaa96 | ||
|
|
0bfd3cd9fc | ||
|
|
442e5501d8 | ||
|
|
0203bd8318 | ||
|
|
cd07d68bef | ||
|
|
88f3870f20 | ||
|
|
d9d2c44e0f | ||
|
|
f427f36d9c | ||
|
|
a1c881d914 | ||
|
|
fbc489863f | ||
|
|
504a3638d9 | ||
|
|
a85abccd62 | ||
|
|
afce0fb0b4 | ||
|
|
99f0334229 | ||
|
|
55ac11bf5c | ||
|
|
e028c1be8c | ||
|
|
3e8d9835d4 | ||
|
|
18df23bd50 | ||
|
|
6b8c3ea581 | ||
|
|
7645f284e4 | ||
|
|
2cec478dfc | ||
|
|
54f07e449c | ||
|
|
09308321f8 | ||
|
|
e4b333b672 | ||
|
|
69f382449d | ||
|
|
47d2f41930 | ||
|
|
d6b124eec0 | ||
|
|
0330ee6683 | ||
|
|
1b854b8a09 | ||
|
|
4f6c561540 | ||
|
|
79ffe663f6 | ||
|
|
a14a97e3a2 | ||
|
|
bddc34d47b | ||
|
|
de6ea1d632 | ||
|
|
1d2fd80fad | ||
|
|
f7df3413e1 | ||
|
|
4cb67002e3 | ||
|
|
197a9a6bcd | ||
|
|
8641de139d | ||
|
|
adcb61bbf9 | ||
|
|
70709c9a68 | ||
|
|
bf930de9e4 | ||
|
|
bb4e716fc7 | ||
|
|
54fd6cf64f | ||
|
|
d905a02b32 | ||
|
|
d12f9271b8 | ||
|
|
3639d651a2 | ||
|
|
07824391a2 | ||
|
|
c855f495d0 | ||
|
|
cc5c148fc1 | ||
|
|
949751f632 | ||
|
|
6dfc4e4ba1 | ||
|
|
db8d62e17b | ||
|
|
7226775987 | ||
|
|
9c264e1cad | ||
|
|
deee57b6dd | ||
|
|
95f0b27eae | ||
|
|
b6f98a8488 | ||
|
|
73acc27a11 | ||
|
|
d46e302b3f | ||
|
|
6f57e03b48 | ||
|
|
a5e39768e4 | ||
|
|
6f6fdba8dd | ||
|
|
e5ef0a8900 | ||
|
|
b6f21933ab | ||
|
|
e4b8b0259d | ||
|
|
8134d6201a | ||
|
|
db4cd7dcc1 | ||
|
|
9d6107c01c | ||
|
|
de46d55b13 | ||
|
|
75afd9d9dc | ||
|
|
99c56d13bb | ||
|
|
95fa29d2ec | ||
|
|
f3d9d8414d | ||
|
|
0c9d715d6d | ||
|
|
cfff247e06 | ||
|
|
04edc70fee | ||
|
|
fdc4bdee68 | ||
|
|
69bf7afe31 | ||
|
|
7b3ee44175 | ||
|
|
122c30cce8 | ||
|
|
957e05319f | ||
|
|
58f83ab3c6 | ||
|
|
6151ee8c0b | ||
|
|
c08b6a7f5d | ||
|
|
0139e7a2d4 | ||
|
|
416de4b4f8 | ||
|
|
b45f32e8f8 | ||
|
|
cda5b0afa2 | ||
|
|
f66a57b033 | ||
|
|
72a688cd14 | ||
|
|
e882efe89e | ||
|
|
7b49ed873c | ||
|
|
3fec6e7636 | ||
|
|
67ac7a4d86 | ||
|
|
615534fa0f | ||
|
|
4250336951 | ||
|
|
932cacbda3 | ||
|
|
3b254663ca | ||
|
|
18f74693e9 | ||
|
|
e0cc973aa4 | ||
|
|
c866d46798 | ||
|
|
c762e4e43f | ||
|
|
3eed83c22d | ||
|
|
234f47a018 | ||
|
|
615463e103 | ||
|
|
d50585188d | ||
|
|
dd247d15ba | ||
|
|
4a34045c0f | ||
|
|
edfdb39970 | ||
|
|
89551496c7 | ||
|
|
becb878f5f | ||
|
|
a94f99dcd2 | ||
|
|
8de9584b72 | ||
|
|
303a3c2c5a | ||
|
|
e6dcc3226d | ||
|
|
ab71e5a59e | ||
|
|
bf9561c4af | ||
|
|
c139fc9791 | ||
|
|
31ddf3cc27 | ||
|
|
1bbdc3e673 | ||
|
|
60ecb95cf6 | ||
|
|
075ea59244 | ||
|
|
2f98f1f987 | ||
|
|
2b22fe9055 | ||
|
|
e144460869 | ||
|
|
6b54c42fdb | ||
|
|
57587b6cd8 | ||
|
|
0fd642f92d | ||
|
|
91310c83a7 | ||
|
|
daf2f8edaf | ||
|
|
a957cdba86 | ||
|
|
5a9a8dc67a | ||
|
|
5fe0dad574 | ||
|
|
a051b391a8 | ||
|
|
ec27ff6c49 | ||
|
|
0e1042124e | ||
|
|
f7e7101abc | ||
|
|
26957ee632 | ||
|
|
04fa07edfe | ||
|
|
6cf763dfa4 | ||
|
|
c41e42e58c | ||
|
|
1b238083d3 | ||
|
|
0784270c2e | ||
|
|
e675bb62fd | ||
|
|
43ac0e14e0 | ||
|
|
f4d494cb3d | ||
|
|
b3dfbf13d8 | ||
|
|
93538e89c6 | ||
|
|
947e845dcd | ||
|
|
6b49de7e4b | ||
|
|
f6191fa2a5 | ||
|
|
b167887d51 | ||
|
|
77769898ea | ||
|
|
42189e3cf7 | ||
|
|
73f8000e49 | ||
|
|
298e334482 | ||
|
|
bb982b8cf9 | ||
|
|
80145c37bb | ||
|
|
bc8503a21e | ||
|
|
2947dbfe5f | ||
|
|
bf9ddfc72f | ||
|
|
c848a7e70b | ||
|
|
e7c5b0e36f | ||
|
|
41282c99f9 | ||
|
|
e25f6f131a | ||
|
|
e69f0fd01e | ||
|
|
30c9534bc5 | ||
|
|
6d56fb7510 | ||
|
|
e46d03b440 | ||
|
|
8255596171 | ||
|
|
baae3ba701 | ||
|
|
6c43be2a03 | ||
|
|
ee4c8a19d6 | ||
|
|
e8cf9dd25f | ||
|
|
df21c4524c | ||
|
|
ccec6c2f67 | ||
|
|
5ab450491c | ||
|
|
3b0cce8c25 | ||
|
|
d6b6f30275 | ||
|
|
c9f18c8349 | ||
|
|
df3186ad95 | ||
|
|
58956549b8 | ||
|
|
74ed041791 | ||
|
|
312f883387 | ||
|
|
fad4093183 | ||
|
|
5c005e097e | ||
|
|
69f23e49c4 | ||
|
|
f53976dc2f | ||
|
|
1d80a77e55 | ||
|
|
fb8734c448 | ||
|
|
090fe75b7f | ||
|
|
173ca3d923 | ||
|
|
f5c875a19d | ||
|
|
6780013f50 | ||
|
|
2f21a6e35a | ||
|
|
9e9e364048 | ||
|
|
2c3296542b | ||
|
|
72988cca28 | ||
|
|
a105513750 | ||
|
|
bece03eab8 | ||
|
|
0fdb6979dd | ||
|
|
a77c1d9538 | ||
|
|
4a7e1aba15 | ||
|
|
a4263b9b54 | ||
|
|
e26ed26e05 | ||
|
|
526b11f973 | ||
|
|
627af36085 | ||
|
|
a22c84d013 | ||
|
|
3707f6294e | ||
|
|
94cb17ef63 | ||
|
|
9bb08fa194 | ||
|
|
425cd58ea6 | ||
|
|
43eb062ac5 | ||
|
|
29d878fad7 | ||
|
|
a3a95a8f59 | ||
|
|
550721e233 | ||
|
|
fa11d60672 | ||
|
|
6f8c681b26 | ||
|
|
718e445370 | ||
|
|
5e469cba0f | ||
|
|
a05479e2dc | ||
|
|
7f6e47c7aa | ||
|
|
2e7c1a7272 | ||
|
|
0f69153900 | ||
|
|
e1885a17d9 | ||
|
|
87a9df28c6 | ||
|
|
bf7cb5a848 | ||
|
|
d24ffb8a1d | ||
|
|
962aed25fe | ||
|
|
a1582220d6 | ||
|
|
a3bd1416d4 | ||
|
|
f49dabaadc | ||
|
|
2e38ec093d | ||
|
|
7995c2283d | ||
|
|
7bb457d851 | ||
|
|
80d0648d6d | ||
|
|
44508cd040 | ||
|
|
e5cc48c068 | ||
|
|
520a15118c | ||
|
|
81931a211f | ||
|
|
9a895d71d9 | ||
|
|
9d2b3e0b35 | ||
|
|
14dbd3341c | ||
|
|
f032c7a52b | ||
|
|
cee24974d6 | ||
|
|
d3e2fd1099 | ||
|
|
dd9d74e227 | ||
|
|
e1744ef950 | ||
|
|
3f64c32b7a | ||
|
|
6b0e154bd5 | ||
|
|
11bca9e307 | ||
|
|
fb630e29b9 | ||
|
|
3a0b09816b | ||
|
|
8ab6b5b06e | ||
|
|
28ea18671f | ||
|
|
01e9c341df | ||
|
|
94006f2fe1 | ||
|
|
9ca1c45ae7 | ||
|
|
b9a6b1001c | ||
|
|
cc7c48a07e | ||
|
|
798adefcde | ||
|
|
72afb61079 | ||
|
|
e6fc8b7586 | ||
|
|
09da6db5e7 | ||
|
|
e870c3b486 | ||
|
|
dcf31b2c5f | ||
|
|
f2eb234fd9 | ||
|
|
c3f120f8f1 | ||
|
|
305f437f74 | ||
|
|
c27f0f8fdc | ||
|
|
701e8c89fb | ||
|
|
aa212c4b2d | ||
|
|
48254a6759 | ||
|
|
37ccc2f3a2 | ||
|
|
2819047649 | ||
|
|
8d8b082ae2 | ||
|
|
5377a48074 | ||
|
|
ca8998e62b | ||
|
|
62359d9011 | ||
|
|
3022c4b378 | ||
|
|
03e4be3974 | ||
|
|
91b241599d | ||
|
|
fcf2e7f94e | ||
|
|
f1ff618dc8 | ||
|
|
5dcb342308 | ||
|
|
2d9d0761c9 | ||
|
|
4df297df6c | ||
|
|
70e8f7efb5 | ||
|
|
de8b441dae | ||
|
|
5c4997d07e | ||
|
|
9b33ff8a15 | ||
|
|
5c21401728 | ||
|
|
acae4bc4ff | ||
|
|
68dc6a64be | ||
|
|
54a8fef0ee | ||
|
|
a722726196 | ||
|
|
b9bd954dfd | ||
|
|
49b1daec38 | ||
|
|
aeb0b163cf | ||
|
|
1eba919dbd | ||
|
|
c4e75ae66c | ||
|
|
d9afd2631b | ||
|
|
405220795b | ||
|
|
3e407e65fa | ||
|
|
a2dff6a123 | ||
|
|
8d030f75f6 | ||
|
|
13af7a6002 | ||
|
|
2bc46e9657 | ||
|
|
b3b050ca26 | ||
|
|
38b0b2248f | ||
|
|
5cfb1c6c9c | ||
|
|
7aad21b7ed | ||
|
|
3cd5338890 | ||
|
|
2fc81ad2dd | ||
|
|
63a49896bf | ||
|
|
80755e5f15 | ||
|
|
ba25b8aeba | ||
|
|
279589fa78 | ||
|
|
c3669cfd36 | ||
|
|
45f04a7b6f | ||
|
|
33f9570ecb | ||
|
|
1c1c99974a | ||
|
|
c2d8b19380 | ||
|
|
9bd957da48 | ||
|
|
352e36500c | ||
|
|
7397bd615f | ||
|
|
6a264d6f73 | ||
|
|
b0fa19d6f8 | ||
|
|
b2860e1731 | ||
|
|
ad65ce872b | ||
|
|
0cdc828953 | ||
|
|
65e13fff4e | ||
|
|
748247d660 | ||
|
|
456f266be3 | ||
|
|
2c26030108 | ||
|
|
efc26245ae | ||
|
|
b9e00c7a0f | ||
|
|
5bf19c875c | ||
|
|
5c18c980aa | ||
|
|
b8d6fdc8eb | ||
|
|
27bfd547c5 | ||
|
|
5237f0a3b3 | ||
|
|
23af860532 | ||
|
|
4c98f7c8f4 | ||
|
|
2a4b357420 | ||
|
|
a26ac441ba | ||
|
|
80cfed38a1 | ||
|
|
83ae498008 | ||
|
|
7c184e1c8c | ||
|
|
4aa417802f | ||
|
|
cdba5b33cc | ||
|
|
81bd05fe84 | ||
|
|
cf135d18b4 | ||
|
|
c7ba7f6703 | ||
|
|
c73c8c77f2 | ||
|
|
c3bb16e92f | ||
|
|
3f27cd7069 | ||
|
|
b222efe638 | ||
|
|
3c62026b5c | ||
|
|
7cf43f53ac | ||
|
|
df189e3e12 | ||
|
|
7e0e7d5483 | ||
|
|
1aeb596b04 | ||
|
|
950194f68e | ||
|
|
5dc3d3cfd7 | ||
|
|
5397f80b87 | ||
|
|
88d0af9e3d | ||
|
|
792b851d77 | ||
|
|
9da832c1d1 | ||
|
|
44f6d21c83 | ||
|
|
38454eaf6e | ||
|
|
3be70cd90d | ||
|
|
76a2bd234a | ||
|
|
972d4d28a1 | ||
|
|
72e0a4fb6b | ||
|
|
3e2fd5e8fa | ||
|
|
8b3f7f2480 | ||
|
|
57c855e1cb | ||
|
|
56e7cd94a5 | ||
|
|
074e05cc32 | ||
|
|
251f66dfce | ||
|
|
227a7aa0d9 | ||
|
|
e12e344a79 | ||
|
|
d4fc4fd658 | ||
|
|
08d67cc8d8 | ||
|
|
208afd22f2 | ||
|
|
9eea01202a | ||
|
|
304a9992fe | ||
|
|
ae62216bf4 | ||
|
|
cd92eeaae5 | ||
|
|
9dad7c69fd | ||
|
|
5cc5b98aeb | ||
|
|
c03ce419ca | ||
|
|
ceef3f048c | ||
|
|
8dd926182c | ||
|
|
c8b528b3f4 | ||
|
|
a65148cd08 | ||
|
|
5a2a20a32f | ||
|
|
318d02c55a | ||
|
|
a69da52f89 | ||
|
|
ac0ea6ac57 | ||
|
|
88d65a55a7 | ||
|
|
dffe7d91ee | ||
|
|
da638b3ae6 | ||
|
|
379568ae0d | ||
|
|
24adfbf2c4 | ||
|
|
89179cad4f | ||
|
|
f2cee8e9ce | ||
|
|
386943de39 | ||
|
|
60b810af7e | ||
|
|
aa2c0c2da9 | ||
|
|
62debfa58a | ||
|
|
9741dba974 | ||
|
|
93ac28ead2 | ||
|
|
a0a3cd3028 | ||
|
|
611ecbd06a | ||
|
|
70c465b006 | ||
|
|
59c8d9b9be | ||
|
|
7f70fcd316 | ||
|
|
17e9ad5093 | ||
|
|
42435bdd4f | ||
|
|
c125a2af1f | ||
|
|
c0a1356049 | ||
|
|
5e6679139b | ||
|
|
c118f85886 | ||
|
|
b40d604ef7 | ||
|
|
f630b013ee | ||
|
|
36167c3e45 | ||
|
|
4eaa53a4a6 | ||
|
|
4859e9c4e7 | ||
|
|
c82c393102 | ||
|
|
5dc162a4ec | ||
|
|
5a4c599139 | ||
|
|
07ca10a451 | ||
|
|
0e556b88be | ||
|
|
0b242e62c5 | ||
|
|
acde8fa6ec | ||
|
|
c8b5611386 | ||
|
|
f7e4533282 | ||
|
|
5abbef547b | ||
|
|
3c27b2c777 | ||
|
|
903eba6a31 | ||
|
|
a37e42af37 | ||
|
|
cc6cce6157 | ||
|
|
2dc9f25ff4 | ||
|
|
7ca39b4a20 | ||
|
|
fcffcee383 | ||
|
|
e371bddd48 | ||
|
|
26d23cf94f | ||
|
|
b608349e94 | ||
|
|
f9b46168d0 | ||
|
|
88d15be4ea | ||
|
|
0c4942439b | ||
|
|
b03df3f7a6 | ||
|
|
6a6816ada7 | ||
|
|
372c87ac12 | ||
|
|
728c99999f | ||
|
|
2017473156 | ||
|
|
08d6367fdc | ||
|
|
23d07dae38 | ||
|
|
29c83d9c97 | ||
|
|
abbc77744e | ||
|
|
7a61fa371f | ||
|
|
ce7f592b1c | ||
|
|
111bfea6f3 | ||
|
|
e35a11a495 | ||
|
|
0592b9ff51 | ||
|
|
297e182576 | ||
|
|
b285e6fd2b | ||
|
|
8ed72e204b | ||
|
|
4592663fd2 | ||
|
|
4c1c6cf8e9 | ||
|
|
09046ec698 | ||
|
|
24e7b00e4e | ||
|
|
95fdadf16b | ||
|
|
a271ab1680 | ||
|
|
ac9d7942ce | ||
|
|
5ca7b8d6dc | ||
|
|
805cdbed1d | ||
|
|
29efd42de3 | ||
|
|
ae2a1d83cf | ||
|
|
bad8bdfe13 | ||
|
|
13194b66d3 | ||
|
|
601758f5fd | ||
|
|
3191498855 | ||
|
|
4882826f58 | ||
|
|
61f43c6b05 | ||
|
|
8b91c24414 | ||
|
|
dbebaae1f3 | ||
|
|
7cc743ff5e | ||
|
|
3b02cee495 | ||
|
|
2e520bea4f | ||
|
|
f9f57b50b1 | ||
|
|
fb9e6eee48 | ||
|
|
b53af75a7f | ||
|
|
2ed40aeefe | ||
|
|
bb61b8468b | ||
|
|
55688a25aa | ||
|
|
21fd58a39c | ||
|
|
ae56d4e9be | ||
|
|
982896a718 | ||
|
|
2ae092e266 | ||
|
|
27ce8b00ed | ||
|
|
3a8adb4e17 | ||
|
|
899d18968e | ||
|
|
285105c8d1 | ||
|
|
9e0ad9d926 | ||
|
|
0fdded0606 | ||
|
|
9947172abb | ||
|
|
b034a823a9 | ||
|
|
7baee925f6 | ||
|
|
ed6c5381d8 | ||
|
|
d58e4c8a89 | ||
|
|
2f2ed9bca7 | ||
|
|
3e888d8e2d | ||
|
|
f461eaa191 | ||
|
|
411d8dbe62 | ||
|
|
825cf98bf4 | ||
|
|
aff1ed4575 | ||
|
|
6b1e7513b3 | ||
|
|
8c94dc8f89 | ||
|
|
a7f459eab9 | ||
|
|
7383e3ea29 | ||
|
|
a416d472fb | ||
|
|
8fb707824e | ||
|
|
e646636bde | ||
|
|
fafd2f0233 | ||
|
|
9f031303a2 | ||
|
|
9a2e69ea9c | ||
|
|
54eff3b0aa | ||
|
|
817a5baef2 | ||
|
|
79dfc0403a | ||
|
|
675d892fc1 | ||
|
|
2654970499 | ||
|
|
b3c5c2fcfa | ||
|
|
6919df592f | ||
|
|
6cfede0868 | ||
|
|
e176e4baa6 | ||
|
|
4041b69800 | ||
|
|
da6579132c | ||
|
|
24628ff13d | ||
|
|
d2f29b72c3 | ||
|
|
546a960951 | ||
|
|
27978f3b9f | ||
|
|
a831afdc1e | ||
|
|
13bb50b863 | ||
|
|
d16d30c483 | ||
|
|
4480436cb3 | ||
|
|
d4114830be | ||
|
|
9fbac2707d | ||
|
|
7cdd6948bf | ||
|
|
d9c5ff9624 | ||
|
|
47691b8242 | ||
|
|
adf57ce2f0 | ||
|
|
aea84977fd | ||
|
|
2f1aef272a | ||
|
|
76089d09a4 | ||
|
|
f88f99959b | ||
|
|
dc6aca83c6 | ||
|
|
b0e18e9ca4 | ||
|
|
8516e35e5f | ||
|
|
41eabc7261 | ||
|
|
424fe61a49 | ||
|
|
02e03771d4 | ||
|
|
e35f8c29ee | ||
|
|
64e3bcf0dc | ||
|
|
a9f3883bfa | ||
|
|
3c3b3dc303 | ||
|
|
970e71d215 | ||
|
|
b6552ec300 | ||
|
|
58bc772256 | ||
|
|
31af08feaa | ||
|
|
9e60a681f3 | ||
|
|
51525d144b | ||
|
|
965fbb43c7 | ||
|
|
133d77d985 | ||
|
|
9451861f51 | ||
|
|
4b489fb7d7 | ||
|
|
7fcaf19ca3 | ||
|
|
c51d59a3a3 | ||
|
|
bcc02837d3 | ||
|
|
611017e187 | ||
|
|
7f7bff6a28 | ||
|
|
b9d7957bf6 | ||
|
|
fa31cec73e | ||
|
|
550a8cf362 | ||
|
|
50996eaf7e | ||
|
|
813c3b43d2 | ||
|
|
4ce9292b28 | ||
|
|
655aa074bf | ||
|
|
2e9c119dca | ||
|
|
7bf2d2a7a9 | ||
|
|
d9a97e2cec | ||
|
|
6395399c2d | ||
|
|
e6971c196b | ||
|
|
b1009a54e3 | ||
|
|
33d73d5d55 | ||
|
|
f42d94da59 | ||
|
|
2418b355d7 | ||
|
|
2cb57251a1 | ||
|
|
446da4b792 | ||
|
|
aa958b0f1d | ||
|
|
58be07a8b0 | ||
|
|
6c61ac53c4 | ||
|
|
6e73a78a8b | ||
|
|
f2623bd51d | ||
|
|
d6a99d0edd | ||
|
|
b9ccc968b2 | ||
|
|
7e33c4fc76 | ||
|
|
39bb520339 | ||
|
|
18e53b9ec8 | ||
|
|
0b5379380a | ||
|
|
b800012c57 | ||
|
|
ebeff20215 | ||
|
|
16ff16bd39 | ||
|
|
0d28a7bdab | ||
|
|
69a1bdfc45 | ||
|
|
af7d88b057 | ||
|
|
abe2e018b6 | ||
|
|
2e79ee4f11 | ||
|
|
8b022d0022 | ||
|
|
5399dbdfbc | ||
|
|
0e3bca1dde | ||
|
|
a992aa1f05 | ||
|
|
1a267418dd | ||
|
|
0f8d891476 | ||
|
|
b9c79a1de5 | ||
|
|
2c7edb695f | ||
|
|
c3ad33687e | ||
|
|
9c5e5cd7b7 | ||
|
|
9048e4a31c | ||
|
|
ba1b3c26c5 | ||
|
|
c6b4e317df | ||
|
|
44267a72de | ||
|
|
8c1c5d09c7 | ||
|
|
acadeb220a | ||
|
|
ff7c80d416 | ||
|
|
577f2a0645 | ||
|
|
48e718ffd8 | ||
|
|
07d25a4140 | ||
|
|
2f7fabf1c7 | ||
|
|
60274655dd | ||
|
|
eace3d91b2 | ||
|
|
86cc41f446 | ||
|
|
3ac5b9466a | ||
|
|
c95c3de136 | ||
|
|
a865d6854c | ||
|
|
52b735b1b9 | ||
|
|
f862305f78 | ||
|
|
ce7ffbf2cd | ||
|
|
687f643059 | ||
|
|
f6e3fc99e6 | ||
|
|
293662a710 | ||
|
|
437252bfcc | ||
|
|
ead21d24a0 | ||
|
|
53de63e829 | ||
|
|
633a03d76a | ||
|
|
3e5fbb0b5c | ||
|
|
6d13e301f9 | ||
|
|
4d356b6dca | ||
|
|
44a251de56 | ||
|
|
1c536a4c51 | ||
|
|
502a649f42 | ||
|
|
12a52c78ac | ||
|
|
df2a775927 | ||
|
|
2c86ccbe15 | ||
|
|
b9321a338b | ||
|
|
dc9a211fb0 | ||
|
|
d49b394eae | ||
|
|
f82c68a871 | ||
|
|
3f4235da69 | ||
|
|
e259cb0847 | ||
|
|
08f9b424de | ||
|
|
d33c3515f8 | ||
|
|
0a70b0f80f | ||
|
|
949cbb9fc7 | ||
|
|
37cfbffdca | ||
|
|
efad2ada89 | ||
|
|
d825f4e5ae | ||
|
|
baa2a5d21c | ||
|
|
b3f9683018 | ||
|
|
6d1819acb9 | ||
|
|
d6ee44b640 | ||
|
|
383c53d71f | ||
|
|
833c647524 | ||
|
|
7f6f50411c | ||
|
|
1c7089c055 | ||
|
|
4641780fe6 | ||
|
|
c67df2ead3 | ||
|
|
5f743344e5 | ||
|
|
56442acc84 | ||
|
|
41c9104b8a | ||
|
|
126f0ca966 | ||
|
|
adeca7fa1f | ||
|
|
5527b6553d | ||
|
|
5a6b9db60c | ||
|
|
8f1c075897 | ||
|
|
fca11e621c | ||
|
|
38a7234ae3 | ||
|
|
115a0c683f | ||
|
|
61b7bed0f8 | ||
|
|
dcd8ec7394 | ||
|
|
51880afcce | ||
|
|
db3a4e52b2 | ||
|
|
af8e66b813 | ||
|
|
9646eb9374 | ||
|
|
0df2fbe5de | ||
|
|
c39eceeddf | ||
|
|
11396c315e | ||
|
|
955af06e29 | ||
|
|
e207e59226 | ||
|
|
0302cee8d5 | ||
|
|
8f4031c8cb | ||
|
|
f72d1ffa64 | ||
|
|
90c65fb0be | ||
|
|
c8eb704a92 | ||
|
|
4c5e26922c | ||
|
|
724c3e431c | ||
|
|
a9ddf49ecc | ||
|
|
de3dba7ce4 | ||
|
|
cd9eda6511 | ||
|
|
ed972fd365 | ||
|
|
75834fb08f | ||
|
|
9991c976ff | ||
|
|
92b08bbbc9 | ||
|
|
4f9b50dd60 | ||
|
|
d6d73efa37 | ||
|
|
19a4729bf2 | ||
|
|
405b8739ab | ||
|
|
7ed11a02ae | ||
|
|
3442e0acd9 | ||
|
|
59f86861d2 | ||
|
|
091d01a799 | ||
|
|
1ed45cdcf9 | ||
|
|
c40ba83cb3 | ||
|
|
7dc5aa9dfd | ||
|
|
808eb688b3 | ||
|
|
12b75a612c | ||
|
|
ac79dc5761 |
No files matched your search
@@ -0,0 +1,99 @@
|
||||
Language: Cpp
|
||||
AccessModifierOffset: -4
|
||||
AlignAfterOpenBracket: Align
|
||||
AlignArrayOfStructures: Left
|
||||
AlignConsecutiveAssignments: false
|
||||
AlignConsecutiveDeclarations: false
|
||||
AlignConsecutiveMacros: true
|
||||
AlignEscapedNewlines: DontAlign
|
||||
AlignOperands: true
|
||||
AlignTrailingComments: true
|
||||
AllowAllParametersOfDeclarationOnNextLine: true
|
||||
AllowShortBlocksOnASingleLine: false
|
||||
AllowShortCaseLabelsOnASingleLine: false
|
||||
AllowShortFunctionsOnASingleLine: Inline
|
||||
AllowShortIfStatementsOnASingleLine: false
|
||||
AllowShortLambdasOnASingleLine: Inline
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
AlwaysBreakAfterReturnType: TopLevelDefinitions
|
||||
AlwaysBreakBeforeMultilineStrings: false
|
||||
AlwaysBreakTemplateDeclarations: Yes
|
||||
BinPackArguments: false
|
||||
BinPackParameters: false
|
||||
BraceWrapping:
|
||||
AfterClass: true
|
||||
AfterControlStatement: false
|
||||
AfterEnum: false
|
||||
AfterFunction: true
|
||||
AfterNamespace: false
|
||||
AfterObjCDeclaration: false
|
||||
AfterStruct: true
|
||||
AfterUnion: false
|
||||
BeforeCatch: false
|
||||
BeforeElse: false
|
||||
IndentBraces: false
|
||||
SplitEmptyFunction: false
|
||||
SplitEmptyRecord: false
|
||||
SplitEmptyNamespace: false
|
||||
BreakBeforeBinaryOperators: All
|
||||
BreakBeforeBraces: Custom
|
||||
BreakBeforeInheritanceComma: false
|
||||
BreakBeforeTernaryOperators: true
|
||||
BreakConstructorInitializersBeforeComma: false
|
||||
BreakConstructorInitializers: BeforeComma
|
||||
BreakAfterJavaFieldAnnotations: false
|
||||
BreakStringLiterals: true
|
||||
ColumnLimit: 120
|
||||
CommentPragmas: '^ IWYU pragma:'
|
||||
CompactNamespaces: false
|
||||
ConstructorInitializerAllOnOneLineOrOnePerLine: false
|
||||
ConstructorInitializerIndentWidth: 4
|
||||
ContinuationIndentWidth: 4
|
||||
Cpp11BracedListStyle: true
|
||||
DerivePointerAlignment: false
|
||||
DisableFormat: false
|
||||
ExperimentalAutoDetectBinPacking: false
|
||||
FixNamespaceComments: true
|
||||
ForEachMacros:
|
||||
- forever # avoids { wrapped to next line
|
||||
- foreach
|
||||
IncludeIsMainRegex: '(Test)?$'
|
||||
IndentCaseLabels: false
|
||||
IndentWidth: 4
|
||||
IndentWrappedFunctionNames: false
|
||||
JavaScriptQuotes: Leave
|
||||
JavaScriptWrapImports: true
|
||||
KeepEmptyLinesAtTheStartOfBlocks: false
|
||||
MacroBlockBegin: ""
|
||||
MacroBlockEnd: ""
|
||||
MaxEmptyLinesToKeep: 1
|
||||
NamespaceIndentation: None
|
||||
ObjCBlockIndentWidth: 4
|
||||
ObjCSpaceAfterProperty: false
|
||||
ObjCSpaceBeforeProtocolList: true
|
||||
PenaltyBreakAssignment: 150
|
||||
PenaltyBreakBeforeFirstCallParameter: 300
|
||||
PenaltyBreakComment: 500
|
||||
PenaltyBreakFirstLessLess: 400
|
||||
PenaltyBreakString: 600
|
||||
PenaltyExcessCharacter: 50
|
||||
PenaltyReturnTypeOnItsOwnLine: 300
|
||||
PointerAlignment: Left
|
||||
ReflowComments: true
|
||||
SortIncludes: false
|
||||
SortUsingDeclarations: false
|
||||
SpaceAfterCStyleCast: true
|
||||
SpaceAfterTemplateKeyword: false
|
||||
SpaceBeforeAssignmentOperators: true
|
||||
SpaceBeforeCpp11BracedList: true
|
||||
SpaceBeforeParens: ControlStatements
|
||||
SpaceInEmptyParentheses: false
|
||||
SpacesBeforeTrailingComments: 1
|
||||
SpacesInAngles: false
|
||||
SpacesInContainerLiterals: false
|
||||
SpacesInCStyleCastParentheses: false
|
||||
SpacesInParentheses: false
|
||||
SpacesInSquareBrackets: false
|
||||
Standard: c++17
|
||||
TabWidth: 4
|
||||
UseTab: Never
|
||||
@@ -4,9 +4,12 @@
|
||||
"dockerfile": "../docker/DockerfileDepsLlvm",
|
||||
},
|
||||
"runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined"],
|
||||
"settings": {},
|
||||
"extensions": [
|
||||
"ms-vscode.cpptools"
|
||||
],
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"ms-vscode.cpptools"
|
||||
]
|
||||
}
|
||||
},
|
||||
"forwardPorts": [4222],
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
.git
|
||||
.vscode
|
||||
.DS_Store
|
||||
build
|
||||
build-*
|
||||
build_*
|
||||
install
|
||||
vcpkg_installed
|
||||
rust/target
|
||||
**/__pycache__
|
||||
python/dist
|
||||
python/*.egg-info
|
||||
@@ -0,0 +1 @@
|
||||
custom: ['https://jami.net/donate/']
|
||||
@@ -0,0 +1,22 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "docker"
|
||||
directory: "/docker"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "vcpkg"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "devcontainers"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
- package-ecosystem: "cargo"
|
||||
directory: "/rust"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
+175
-52
@@ -1,66 +1,189 @@
|
||||
name: C/C++ CI
|
||||
|
||||
env:
|
||||
LLHTTP_VERSION: "v9.2.1"
|
||||
RESTINIO_VERSION: "0.7.10"
|
||||
EXPECTED_LITE_URL: "https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp"
|
||||
UBUNTU_FULL_DEPS: "libncurses5-dev libreadline-dev nettle-dev libasio-dev libgnutls28-dev libuv1-dev python3-pip python3-dev python3-setuptools libcppunit-dev libjsoncpp-dev libfmt-dev libmsgpack-dev libargon2-dev"
|
||||
UBUNTU_MESON_DEPS: "ninja-build libncurses5-dev libreadline-dev nettle-dev libasio-dev libgnutls28-dev libuv1-dev python3-dev python3-setuptools python3-pip libcppunit-dev libjsoncpp-dev libfmt-dev libmsgpack-dev libargon2-dev"
|
||||
UBUNTU_MINIMAL_DEPS: "libncurses5-dev libreadline-dev nettle-dev libfmt-dev libgnutls28-dev libcppunit-dev libmsgpack-dev libargon2-dev"
|
||||
DEBIAN13_DEPS: "git libtool pkg-config wget cmake libncurses5-dev libreadline-dev nettle-dev libasio-dev libgnutls28-dev libuv1-dev python3-pip python3-dev python3-setuptools libcppunit-dev libjsoncpp-dev libfmt-dev libmsgpack-cxx-dev libargon2-dev"
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
build-ubuntu:
|
||||
name: Ubuntu/GCC build
|
||||
build-ubuntu-meson:
|
||||
name: Ubuntu/GCC Meson build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: deps
|
||||
run: |
|
||||
sudo apt install libncurses5-dev libreadline-dev nettle-dev \
|
||||
libgnutls28-dev libuv1-dev cython3 python3-dev python3-setuptools libcppunit-dev libjsoncpp-dev \
|
||||
autotools-dev autoconf libfmt-dev libhttp-parser-dev libmsgpack-dev libargon2-0-dev
|
||||
- name: autogen
|
||||
run: ./autogen.sh
|
||||
- name: asio
|
||||
run: |
|
||||
wget https://github.com/aberaud/asio/archive/b2b7a1c166390459e1c169c8ae9ef3234b361e3f.tar.gz \
|
||||
&& tar -xvf b2b7a1c166390459e1c169c8ae9ef3234b361e3f.tar.gz && cd asio-b2b7a1c166390459e1c169c8ae9ef3234b361e3f/asio \
|
||||
&& ./autogen.sh && ./configure --prefix=/usr --without-boost --disable-examples --disable-tests \
|
||||
&& sudo make install \
|
||||
&& cd ../../ && rm -rf asio*
|
||||
- name: configure
|
||||
run: ./configure
|
||||
- name: make
|
||||
run: make
|
||||
- name: make check
|
||||
run: make check
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
echo "Installing Ubuntu meson dependencies:"
|
||||
sudo apt update
|
||||
sudo apt install -y $UBUNTU_MESON_DEPS
|
||||
|
||||
- name: Install Python dependencies
|
||||
run: sudo pip3 install meson Cython
|
||||
|
||||
- name: Configure with Meson
|
||||
run: meson setup build .
|
||||
|
||||
- name: Build with Ninja
|
||||
run: cd build && ninja
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Test Rust bindings
|
||||
env:
|
||||
LIBRARY_PATH: ${{ github.workspace }}/build
|
||||
LD_LIBRARY_PATH: ${{ github.workspace }}/build
|
||||
RUSTFLAGS: -L native=${{ github.workspace }}/build
|
||||
run: |
|
||||
cargo test --manifest-path rust/Cargo.toml --all-targets
|
||||
cargo test --manifest-path rust/Cargo.toml --all-features --all-targets
|
||||
cargo test --manifest-path rust/Cargo.toml --all-features --doc
|
||||
|
||||
build-ubuntu-minimal:
|
||||
name: Ubuntu/GCC minimal build
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
cxx_standard: [17, 20, 23]
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Install Minimal Dependencies
|
||||
run: |
|
||||
echo "Installing Ubuntu minimal dependencies:"
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y $UBUNTU_MINIMAL_DEPS
|
||||
|
||||
- name: Configure project with CMake
|
||||
run: |
|
||||
mkdir build && cd build
|
||||
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DCMAKE_CXX_STANDARD=${{ matrix.cxx_standard }} \
|
||||
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
|
||||
-DOPENDHT_C=Off -DBUILD_TESTING=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=Off -DOPENDHT_PYTHON=Off \
|
||||
-DOPENDHT_TOOLS=On -DOPENDHT_PROXY_SERVER=Off -DOPENDHT_PROXY_CLIENT=Off
|
||||
|
||||
- name: Build
|
||||
run: cd build && make
|
||||
|
||||
- name: Run Unit tests
|
||||
run: ctest --output-on-failure --test-dir build
|
||||
|
||||
build-debian13:
|
||||
name: Debian 13/GCC build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
container:
|
||||
image: debian:13
|
||||
volumes:
|
||||
- .:/workspace
|
||||
options: --workdir /workspace
|
||||
env:
|
||||
DEBIAN_FRONTEND: noninteractive
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Install Dependencies
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y $DEBIAN13_DEPS
|
||||
|
||||
- name: Build llhttp dependency
|
||||
run: |
|
||||
mkdir llhttp
|
||||
wget "https://github.com/nodejs/llhttp/archive/refs/tags/release/${LLHTTP_VERSION}.tar.gz" -O llhttp.tar.gz
|
||||
tar -xzf llhttp.tar.gz -C llhttp --strip-components=1
|
||||
cd llhttp && cmake -DCMAKE_INSTALL_PREFIX=/usr . && make -j2 && make install
|
||||
cd ../ && rm -rf llhttp*
|
||||
|
||||
- name: Install expected-lite header
|
||||
run: |
|
||||
mkdir -p /usr/local/include/nonstd
|
||||
wget "${EXPECTED_LITE_URL}" -O /usr/local/include/nonstd/expected.hpp
|
||||
|
||||
- name: Build restinio dependency
|
||||
run: |
|
||||
mkdir restinio && cd restinio
|
||||
wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2"
|
||||
tar -xjf restinio-${RESTINIO_VERSION}.tar.bz2
|
||||
cd restinio-${RESTINIO_VERSION}/dev
|
||||
cmake -DCMAKE_INSTALL_PREFIX=/usr/local \
|
||||
-DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off \
|
||||
-DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system .
|
||||
make install
|
||||
cd ../../ && rm -rf restinio*
|
||||
|
||||
- name: Configure project with CMake
|
||||
run: |
|
||||
mkdir build && cd build
|
||||
cmake .. -DCMAKE_BUILD_TYPE=Debug \
|
||||
-DOPENDHT_C=On -DBUILD_TESTING=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On -DOPENDHT_PYTHON=Off \
|
||||
-DOPENDHT_TOOLS=On -DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On
|
||||
|
||||
- name: Build
|
||||
run: cd build && make
|
||||
|
||||
build-macos:
|
||||
name: macOS/Clang build
|
||||
runs-on: macos-11
|
||||
runs-on: macos-15
|
||||
strategy:
|
||||
matrix:
|
||||
cxx_standard: [17, 20, 23]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: deps
|
||||
run: |
|
||||
brew install msgpack-cxx asio gnutls nettle readline fmt jsoncpp argon2 openssl http-parser cppunit
|
||||
|
||||
- name: restinio
|
||||
run: |
|
||||
mkdir restinio && cd restinio
|
||||
wget https://github.com/aberaud/restinio/archive/e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz
|
||||
ls -l && tar -xzf e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz
|
||||
cd restinio-e0a261dd8488246a3cb8bbb3ea781ea5139c3c94/dev
|
||||
cmake -DCMAKE_INSTALL_PREFIX=/usr/local -DRESTINIO_TEST=OFF -DRESTINIO_SAMPLE=OFF \
|
||||
-DRESTINIO_INSTALL_SAMPLES=OFF -DRESTINIO_BENCH=OFF -DRESTINIO_INSTALL_BENCHES=OFF \
|
||||
-DRESTINIO_FIND_DEPS=ON -DRESTINIO_ALLOW_SOBJECTIZER=Off -DRESTINIO_USE_BOOST_ASIO=none .
|
||||
make -j8 && sudo make install
|
||||
cd ../../.. && rm -rf restinio
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: cmake
|
||||
run: |
|
||||
mkdir build && cd build
|
||||
export PATH="/opt/homebrew/opt/openssl@3/bin:$PATH"
|
||||
export LDFLAGS="-L/usr/local/opt/openssl@3/lib"
|
||||
export CPPFLAGS="-I/usr/local/opt/openssl@3/include"
|
||||
export PKG_CONFIG_PATH="/usr/local/opt/openssl@3/lib/pkgconfig"
|
||||
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local -DCMAKE_BUILD_TYPE=Debug \
|
||||
-DOPENDHT_C=On -DOPENDHT_TESTS=On -DOPENDHT_PEER_DISCOVERY=On -DOPENDHT_PYTHON=Off \
|
||||
-DOPENDHT_TOOLS=On -DOPENDHT_PROXY_SERVER=On -DOPENDHT_PROXY_CLIENT=On
|
||||
- name: Install Homebrew Dependencies
|
||||
run: brew install msgpack-cxx asio gnutls nettle readline fmt jsoncpp argon2 openssl cppunit
|
||||
|
||||
- name: make
|
||||
run: cd build && make
|
||||
- name: Install expected-lite header
|
||||
run: |
|
||||
sudo mkdir -p /usr/local/include/nonstd
|
||||
sudo wget "${EXPECTED_LITE_URL}" -O /usr/local/include/nonstd/expected.hpp
|
||||
|
||||
- name: Build restinio dependency
|
||||
run: |
|
||||
mkdir restinio && cd restinio
|
||||
wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2"
|
||||
tar -xjf restinio-${RESTINIO_VERSION}.tar.bz2
|
||||
cd restinio-${RESTINIO_VERSION}/dev
|
||||
cmake -DCMAKE_INSTALL_PREFIX=/usr/local \
|
||||
-DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off \
|
||||
-DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system .
|
||||
make -j2 && sudo make install
|
||||
cd ../../ && rm -rf restinio*
|
||||
|
||||
- name: Configure project with CMake
|
||||
run: |
|
||||
mkdir build && cd build
|
||||
# Set Homebrew OpenSSL paths
|
||||
export PATH="/opt/homebrew/opt/openssl@3/bin:$PATH"
|
||||
export LDFLAGS="-L/usr/local/opt/openssl@3/lib"
|
||||
export CPPFLAGS="-I/usr/local/opt/openssl@3/include"
|
||||
export PKG_CONFIG_PATH="/usr/local/opt/openssl@3/lib/pkgconfig"
|
||||
cmake .. -DCMAKE_INSTALL_PREFIX=/usr/local \
|
||||
-DOPENDHT_DOWNLOAD_DEPS=ON \
|
||||
-DCMAKE_BUILD_TYPE=Debug \
|
||||
-DCMAKE_CXX_STANDARD=${{ matrix.cxx_standard }} \
|
||||
-DCMAKE_CXX_STANDARD_REQUIRED=ON \
|
||||
-DOPENDHT_C=On -DBUILD_TESTING=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On -DOPENDHT_PYTHON=Off \
|
||||
-DOPENDHT_TOOLS=On -DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On -DOPENDHT_PUSH_NOTIFICATIONS=On
|
||||
|
||||
- name: Build
|
||||
run: cd build && make
|
||||
@@ -1,35 +1,44 @@
|
||||
name: Clang Static Analysis
|
||||
on:
|
||||
push
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
clang-analyzer:
|
||||
name: Clang Static Analysis
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v7
|
||||
- name: deps
|
||||
run: |
|
||||
sudo apt update && \
|
||||
sudo apt install libncurses5-dev libreadline-dev nettle-dev \
|
||||
libgnutls28-dev libuv1-dev cython3 python3-dev python3-setuptools libcppunit-dev libjsoncpp-dev \
|
||||
autotools-dev autoconf libfmt-dev libhttp-parser-dev libmsgpack-dev libargon2-0-dev libasio-dev \
|
||||
libgnutls28-dev libuv1-dev python3-dev python3-setuptools libcppunit-dev libjsoncpp-dev \
|
||||
libfmt-dev libmsgpack-dev libargon2-dev libasio-dev \
|
||||
llvm llvm-dev clang clang-tools && \
|
||||
sudo apt remove gcc g++
|
||||
|
||||
- name: restinio
|
||||
- name: expected-lite
|
||||
run: |
|
||||
mkdir restinio && cd restinio \
|
||||
&& wget https://github.com/aberaud/restinio/archive/e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz \
|
||||
&& ls -l && tar -xzf e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz \
|
||||
&& cd restinio-e0a261dd8488246a3cb8bbb3ea781ea5139c3c94/dev \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=OFF -DRESTINIO_SAMPLE=OFF \
|
||||
-DRESTINIO_INSTALL_SAMPLES=OFF -DRESTINIO_BENCH=OFF -DRESTINIO_INSTALL_BENCHES=OFF \
|
||||
-DRESTINIO_FIND_DEPS=ON -DRESTINIO_ALLOW_SOBJECTIZER=Off -DRESTINIO_USE_BOOST_ASIO=none . \
|
||||
&& make -j8 && sudo make install \
|
||||
&& cd ../../.. && rm -rf restinio
|
||||
sudo mkdir /usr/include/nonstd
|
||||
sudo wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp \
|
||||
-O /usr/include/nonstd/expected.hpp
|
||||
|
||||
- name: restinio
|
||||
env:
|
||||
RESTINIO_VERSION: "0.7.10"
|
||||
run: |
|
||||
mkdir restinio && cd restinio
|
||||
wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2"
|
||||
ls -l && tar -xjf "restinio-${RESTINIO_VERSION}.tar.bz2"
|
||||
cd "restinio-${RESTINIO_VERSION}/dev"
|
||||
cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system .
|
||||
make -j2 && sudo make install
|
||||
cd ../../ && rm -rf restinio*
|
||||
|
||||
- name: cmake
|
||||
run: |
|
||||
mkdir build && cd build && \
|
||||
cmake .. -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Debug -DOPENDHT_C=On -DOPENDHT_PEER_DISCOVERY=On -DOPENDHT_PYTHON=Off -DOPENDHT_TOOLS=On -DOPENDHT_PROXY_SERVER=On -DOPENDHT_PROXY_CLIENT=On
|
||||
cmake .. -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Debug -DOPENDHT_C=On -DOPENDHT_DOWNLOAD_DEPS=ON -DOPENDHT_PEER_DISCOVERY=On -DOPENDHT_PYTHON=Off -DOPENDHT_TOOLS=On -DOPENDHT_PROXY_SERVER=On -DOPENDHT_PROXY_CLIENT=On -DOPENDHT_PUSH_NOTIFICATIONS=On
|
||||
- name: scan-build
|
||||
run: cd build && scan-build --status-bugs make
|
||||
@@ -0,0 +1,41 @@
|
||||
name: "CodeQL Advanced"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze (${{ matrix.language }})
|
||||
runs-on: 'ubuntu-latest'
|
||||
permissions:
|
||||
security-events: write
|
||||
packages: read
|
||||
actions: read
|
||||
contents: read
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- language: c-cpp
|
||||
build-mode: autobuild
|
||||
- language: actions
|
||||
build-mode: none
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
build-mode: ${{ matrix.build-mode }}
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4
|
||||
with:
|
||||
category: "/language:${{matrix.language}}"
|
||||
@@ -0,0 +1,206 @@
|
||||
name: Node.js Package
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
paths:
|
||||
- 'nodejs/**'
|
||||
- '.github/workflows/nodejs-package.yml'
|
||||
- 'src/**'
|
||||
- 'include/**'
|
||||
- 'cmake/**'
|
||||
- 'CMakeLists.txt'
|
||||
- 'vcpkg*.json'
|
||||
- 'ports/**'
|
||||
- 'LICENSE'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'nodejs/**'
|
||||
- '.github/workflows/nodejs-package.yml'
|
||||
- 'src/**'
|
||||
- 'include/**'
|
||||
- 'cmake/**'
|
||||
- 'CMakeLists.txt'
|
||||
- 'vcpkg*.json'
|
||||
- 'ports/**'
|
||||
- 'LICENSE'
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build ${{ matrix.target }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
container:
|
||||
image: ${{ matrix.container }}
|
||||
credentials:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
timeout-minutes: 45
|
||||
defaults:
|
||||
run:
|
||||
working-directory: nodejs
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-26.04
|
||||
target: linux-x64
|
||||
container: ghcr.io/${{ github.repository }}/opendht-deps-noble:latest
|
||||
- os: macos-15
|
||||
target: darwin-arm64
|
||||
- os: macos-15-intel
|
||||
target: darwin-x64
|
||||
- os: windows-2022
|
||||
target: win32-x64
|
||||
env:
|
||||
VCPKG_DISABLE_METRICS: '1'
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows-release
|
||||
VCPKG_INSTALLED_DIR: ${{ github.workspace }}/vcpkg_installed
|
||||
VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}/vcpkg-binary-cache,readwrite
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
cache-dependency-path: nodejs/package-lock.json
|
||||
- name: Install macOS dependencies
|
||||
if: runner.os == 'macOS'
|
||||
run: brew install cmake ninja pkg-config dylibbundler gnutls nettle argon2 msgpack-cxx fmt jsoncpp simdutf asio llhttp openssl
|
||||
- name: Install restinio
|
||||
if: runner.os == 'macOS'
|
||||
env:
|
||||
RESTINIO_VERSION: '0.7.10'
|
||||
run: |
|
||||
include="$RUNNER_TEMP/opendht-proxy/include"
|
||||
mkdir -p "$include/nonstd"
|
||||
curl -fsSL --retry 3 https://raw.githubusercontent.com/martinmoene/expected-lite/v0.10.0/include/nonstd/expected.hpp -o "$include/nonstd/expected.hpp"
|
||||
curl -fsSL --retry 3 "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" -o "$RUNNER_TEMP/restinio.tar.bz2"
|
||||
tar -xjf "$RUNNER_TEMP/restinio.tar.bz2" -C "$RUNNER_TEMP"
|
||||
cp -R "$RUNNER_TEMP/restinio-${RESTINIO_VERSION}/dev/restinio" "$include/"
|
||||
echo "CMAKE_PREFIX_PATH=$RUNNER_TEMP/opendht-proxy" >> "$GITHUB_ENV"
|
||||
- name: Set up MSVC
|
||||
if: runner.os == 'Windows'
|
||||
uses: ilammy/msvc-dev-cmd@v1
|
||||
with:
|
||||
arch: x64
|
||||
- name: Set up vcpkg
|
||||
if: runner.os == 'Windows'
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
- name: Cache Windows native dependencies
|
||||
if: runner.os == 'Windows'
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: node-vcpkg-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
node-vcpkg-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
- run: npm ci --no-audit --no-fund
|
||||
- name: Build Unix addon
|
||||
if: runner.os != 'Windows'
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$RUNNER_OS" == 'macOS' ]]; then
|
||||
export MACOSX_DEPLOYMENT_TARGET=15.0
|
||||
openssl_prefix=$(brew --prefix openssl)
|
||||
export PKG_CONFIG_PATH="$openssl_prefix/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
|
||||
fi
|
||||
npm run build -- --CDOPENDHT_DOWNLOAD_DEPS=OFF
|
||||
- name: Build Windows addon
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: |
|
||||
npm run build -- `
|
||||
"--CDCMAKE_TOOLCHAIN_FILE=$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" `
|
||||
"--CDVCPKG_MANIFEST_DIR=$env:GITHUB_WORKSPACE" `
|
||||
"--CDVCPKG_INSTALLED_DIR=$env:VCPKG_INSTALLED_DIR" `
|
||||
"--CDVCPKG_TARGET_TRIPLET=$env:VCPKG_DEFAULT_TRIPLET" `
|
||||
--CDVCPKG_MANIFEST_NO_DEFAULT_FEATURES=ON `
|
||||
--CDVCPKG_MANIFEST_FEATURES=proxy `
|
||||
--CDCMAKE_MSVC_RUNTIME_LIBRARY=MultiThreadedDLL `
|
||||
--CDOPENDHT_DOWNLOAD_DEPS=OFF
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
"$env:VCPKG_INSTALLED_DIR/$env:VCPKG_DEFAULT_TRIPLET/bin" >> $env:GITHUB_PATH
|
||||
"OPENDHT_LIBRARY_PATH=$env:VCPKG_INSTALLED_DIR/$env:VCPKG_DEFAULT_TRIPLET/bin" >> $env:GITHUB_ENV
|
||||
- run: npm test
|
||||
- run: npm run typecheck
|
||||
- run: npm run bundle
|
||||
- name: Include static simdutf licenses
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
mkdir -p prebuilds/linux-x64/licenses/simdutf
|
||||
cp /usr/share/doc/simdutf/LICENSE-* prebuilds/linux-x64/licenses/simdutf/
|
||||
- run: npm run test:package
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-node-prebuild-${{ matrix.target }}
|
||||
path: nodejs/prebuilds/
|
||||
if-no-files-found: error
|
||||
|
||||
package:
|
||||
name: Assemble npm archive
|
||||
needs: build
|
||||
runs-on: ubuntu-26.04
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '22'
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: opendht-node-prebuild-*
|
||||
path: nodejs/prebuilds
|
||||
merge-multiple: true
|
||||
- name: Set release version
|
||||
if: github.event_name == 'push' && github.ref_type == 'tag'
|
||||
working-directory: nodejs
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
release_version=$(npm version "${RELEASE_TAG#v}" --no-git-tag-version --ignore-scripts --allow-same-version)
|
||||
if [[ "$release_version" != "$RELEASE_TAG" ]]; then
|
||||
printf '::error::Release tag %s is not an exact npm semantic version (normalized to %s).\n' "$RELEASE_TAG" "$release_version" >&2
|
||||
exit 1
|
||||
fi
|
||||
- name: Pack all platforms
|
||||
working-directory: nodejs
|
||||
run: |
|
||||
npm ci --ignore-scripts
|
||||
mkdir -p dist
|
||||
npm pack --pack-destination dist
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-node-npm
|
||||
path: nodejs/dist/*.tgz
|
||||
if-no-files-found: error
|
||||
|
||||
smoke:
|
||||
name: Install on ${{ matrix.os }} / Node ${{ matrix.node }}
|
||||
needs: package
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 10
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-24.04, ubuntu-26.04, macos-15, macos-15-intel, windows-2022]
|
||||
node: ['22', '24', '26']
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: opendht-node-npm
|
||||
path: nodejs/dist
|
||||
- name: Test installed archive without a native build toolchain
|
||||
working-directory: nodejs
|
||||
run: npm run test:package -- dist
|
||||
@@ -0,0 +1,84 @@
|
||||
name: Python Package
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
pull_request:
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build_wheels:
|
||||
name: Build wheels on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, ubuntu-24.04-arm, macos-15]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
# Run locally with: pipx run cibuildwheel --platform linux python
|
||||
- name: Build wheels
|
||||
uses: pypa/cibuildwheel@v4.3.4
|
||||
with:
|
||||
package-dir: python
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-wheels-${{ matrix.os }}
|
||||
path: ./wheelhouse/*.whl
|
||||
|
||||
build_wheels_windows:
|
||||
name: Build wheels on Windows
|
||||
runs-on: windows-latest
|
||||
env:
|
||||
VCPKG_DISABLE_METRICS: "1"
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows-release
|
||||
VCPKG_INSTALLED_DIR: ${{ github.workspace }}\vcpkg_installed
|
||||
VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}/vcpkg-binary-cache,readwrite
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set up vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
|
||||
- name: Cache vcpkg binary packages
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: ${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-
|
||||
|
||||
- name: Build wheels
|
||||
run: |
|
||||
pip install cython delvewheel build
|
||||
cmake -S . -B build `
|
||||
-DCMAKE_BUILD_TYPE=Release `
|
||||
-DVCPKG_TARGET_TRIPLET=${{ env.VCPKG_DEFAULT_TRIPLET }} `
|
||||
"-DCMAKE_TOOLCHAIN_FILE=$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" `
|
||||
-DVCPKG_INSTALLED_DIR=${{ env.VCPKG_INSTALLED_DIR }} `
|
||||
-DBUILD_TESTING=OFF `
|
||||
-DOPENDHT_C=OFF `
|
||||
-DOPENDHT_TOOLS=OFF `
|
||||
-DOPENDHT_PYTHON=ON `
|
||||
-DOPENDHT_DOCUMENTATION=OFF `
|
||||
-DOPENDHT_PROXY_CLIENT=ON `
|
||||
-DOPENDHT_PROXY_SERVER=ON
|
||||
cd build
|
||||
pipx run cibuildwheel python
|
||||
shell: pwsh
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-wheels-win_amd64
|
||||
path: ./build/wheelhouse/*.whl
|
||||
@@ -0,0 +1,685 @@
|
||||
name: Release actions
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME_DEPS: ${{ github.repository }}/opendht-deps
|
||||
IMAGE_NAME_DEPS_NOBLE: ${{ github.repository }}/opendht-deps-noble
|
||||
IMAGE_NAME: ${{ github.repository }}/opendht
|
||||
IMAGE_NAME_NOBLE: ${{ github.repository }}/opendht-noble
|
||||
IMAGE_NAME_DEPS_LLVM: ${{ github.repository }}/opendht-deps-llvm
|
||||
IMAGE_NAME_LLVM: ${{ github.repository }}/opendht-llvm
|
||||
IMAGE_NAME_DHTNODE: ${{ github.repository }}/dhtnode
|
||||
IMAGE_NAME_ALPINE: ${{ github.repository }}/opendht-alpine
|
||||
IMAGE_NAME_ALPINE_DEPS: ${{ github.repository }}/opendht-deps-alpine
|
||||
|
||||
jobs:
|
||||
nodejs-package:
|
||||
name: Build and verify Node.js package
|
||||
uses: ./.github/workflows/nodejs-package.yml
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
|
||||
python-wheels:
|
||||
name: Build Python wheels
|
||||
uses: ./.github/workflows/python-wheels.yml
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
build-and-push-deps-image:
|
||||
name: Dependency Docker image
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME_DEPS }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileDeps
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-deps-image-noble:
|
||||
name: Dependency Docker image (Ubuntu 24.04)
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME_DEPS_NOBLE }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileDepsNoble
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-image:
|
||||
name: OpenDHT Docker image
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push-deps-image
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-image-noble:
|
||||
name: OpenDHT Docker image (Ubuntu 24.04)
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push-deps-image-noble
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME_NOBLE }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileNoble
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-deps-image-llvm:
|
||||
name: Dependency Docker image (LLVM)
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME_DEPS_LLVM }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileDepsLlvm
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-image-llvm:
|
||||
name: OpenDHT Docker image (LLVM)
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push-deps-image-llvm
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME_LLVM }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileLlvm
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-image-dhtnode:
|
||||
name: dhtnode Docker image
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push-image
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME_DHTNODE }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileDhtnode
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-image-alpine-deps:
|
||||
name: Alpine Deps Docker image
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME_ALPINE_DEPS }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileDepsAlpine
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-and-push-image-alpine:
|
||||
name: Alpine Docker image
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-and-push-image-alpine-deps
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME_ALPINE }}
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: docker/DockerfileAlpine
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-windows-msi:
|
||||
name: Build Windows MSI Installer
|
||||
runs-on: windows-latest
|
||||
env:
|
||||
VCPKG_DISABLE_METRICS: "1"
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows
|
||||
VCPKG_INSTALLED_DIR: ${{ github.workspace }}\vcpkg_installed
|
||||
VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}/vcpkg-binary-cache,readwrite
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Set up vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
|
||||
- name: Set up MSVC developer environment
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: Install WIX using .net tools
|
||||
run: |
|
||||
dotnet tool install --global wix --version 6.0.1
|
||||
wix extension add --global WixToolset.UI.wixext/6.0.1
|
||||
shell: pwsh
|
||||
|
||||
- name: Cache vcpkg binary packages
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: ${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-
|
||||
|
||||
- name: Configure CMake for MSI
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir build -ErrorAction SilentlyContinue
|
||||
cmake -B build `
|
||||
-S . `
|
||||
"-DCMAKE_TOOLCHAIN_FILE=$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" `
|
||||
-DVCPKG_TARGET_TRIPLET=x64-windows `
|
||||
-DVCPKG_INSTALLED_DIR=${{ env.VCPKG_INSTALLED_DIR }} `
|
||||
-DVCPKG_MANIFEST_FEATURES=test `
|
||||
-DCMAKE_BUILD_TYPE=Release `
|
||||
-DOPENDHT_C=On `
|
||||
-DOPENDHT_TOOLS=On `
|
||||
-DOPENDHT_PYTHON=Off `
|
||||
-DOPENDHT_DOCUMENTATION=OFF `
|
||||
-DOPENDHT_PEER_DISCOVERY=On `
|
||||
-DOPENDHT_PROXY_SERVER=On `
|
||||
-DOPENDHT_PROXY_CLIENT=On `
|
||||
-DOPENDHT_HTTP=On `
|
||||
-DBUILD_TESTING=Off `
|
||||
-DOPENDHT_CPACK=On `
|
||||
-A x64
|
||||
|
||||
- name: Build with MSVC
|
||||
shell: pwsh
|
||||
run: |
|
||||
cmake --build build --config Release --parallel $([System.Environment]::ProcessorCount)
|
||||
# Copy vcpkg installed libraries to the build directory
|
||||
Copy-Item -Path "${{ env.VCPKG_INSTALLED_DIR }}\x64-windows\lib\*.lib" -Destination "build" -Force
|
||||
Copy-Item -Path "${{ env.VCPKG_INSTALLED_DIR }}\x64-windows\bin\*.dll" -Destination "build" -Force
|
||||
|
||||
- name: Package MSI with CPack
|
||||
shell: pwsh
|
||||
id: cpack_msi
|
||||
run: |
|
||||
cd build
|
||||
cpack -C Release -G WIX
|
||||
$msiFile = Get-ChildItem -Path . -Recurse -Filter *.msi | Select-Object -First 1
|
||||
if ($msiFile) {
|
||||
$msiOutputPath = "opendht-installer.msi" # Standardized artifact name
|
||||
Copy-Item $msiFile.FullName -Destination $msiOutputPath
|
||||
echo "msi_path=$msiOutputPath" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
||||
Write-Host "MSI created at build/$msiOutputPath"
|
||||
} else {
|
||||
Write-Error "MSI file not found after cpack execution!"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Upload MSI Artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-windows-msi
|
||||
path: build/${{ steps.cpack_msi.outputs.msi_path }} # Path to the MSI in the build directory
|
||||
retention-days: 7
|
||||
|
||||
build-windows-dhtnode:
|
||||
name: Build Windows dhtnode
|
||||
runs-on: windows-latest
|
||||
env:
|
||||
VCPKG_DISABLE_METRICS: "1"
|
||||
VCPKG_DEFAULT_TRIPLET: x64-windows-static-release
|
||||
VCPKG_INSTALLED_DIR: ${{ github.workspace }}\vcpkg_installed
|
||||
VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}/vcpkg-binary-cache,readwrite
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Set up vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
|
||||
- name: Set up MSVC developer environment
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: Cache vcpkg binary packages
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: ${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-
|
||||
|
||||
- name: Configure CMake for Static Build
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir build_static -ErrorAction SilentlyContinue
|
||||
cmake -B build_static `
|
||||
-S . `
|
||||
"-DCMAKE_TOOLCHAIN_FILE=$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" `
|
||||
-DVCPKG_TARGET_TRIPLET=x64-windows-static-release `
|
||||
-DVCPKG_INSTALLED_DIR=${{ env.VCPKG_INSTALLED_DIR }} `
|
||||
-DVCPKG_MANIFEST_FEATURES=test `
|
||||
-DCMAKE_BUILD_TYPE=Release `
|
||||
-DBUILD_SHARED_LIBS=OFF `
|
||||
-DOPENDHT_PROXY_CLIENT=ON `
|
||||
-DOPENDHT_PROXY_SERVER=ON `
|
||||
-DOPENDHT_C=ON `
|
||||
-DOPENDHT_TOOLS=ON `
|
||||
-DOPENDHT_DOCUMENTATION=OFF `
|
||||
-DOPENDHT_PYTHON=OFF `
|
||||
-DOPENDHT_PEER_DISCOVERY=ON `
|
||||
-DOPENDHT_HTTP=ON `
|
||||
-A x64
|
||||
|
||||
- name: Build Static dhtnode
|
||||
shell: pwsh
|
||||
run: |
|
||||
cmake --build build_static --config Release --parallel $([System.Environment]::ProcessorCount)
|
||||
|
||||
- name: Upload Static dhtnode Artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-windows-dhtnode
|
||||
path: |
|
||||
build_static/**/*dhtnode.exe
|
||||
retention-days: 7
|
||||
|
||||
create-github-release:
|
||||
name: Create GitHub Release
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-windows-msi, build-windows-dhtnode, nodejs-package]
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Download Windows MSI artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: opendht-windows-msi
|
||||
path: downloaded_artifacts/windows_msi
|
||||
|
||||
- name: Download Static dhtnode artifact
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: opendht-windows-dhtnode
|
||||
path: downloaded_artifacts/static_dhtnode
|
||||
|
||||
- name: Download npm archive
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: opendht-node-npm
|
||||
path: downloaded_artifacts/nodejs
|
||||
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
draft: true
|
||||
files: |
|
||||
downloaded_artifacts/windows_msi/*.msi
|
||||
downloaded_artifacts/static_dhtnode/**/*dhtnode.exe
|
||||
downloaded_artifacts/nodejs/*.tgz
|
||||
|
||||
publish-npm:
|
||||
name: Publish opendht to npm
|
||||
needs: create-github-release
|
||||
runs-on: ubuntu-26.04
|
||||
environment:
|
||||
name: npm
|
||||
url: https://www.npmjs.com/package/opendht
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '24'
|
||||
registry-url: https://registry.npmjs.org/
|
||||
package-manager-cache: false
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: opendht-node-npm
|
||||
path: nodejs/dist
|
||||
- name: Publish verified archive
|
||||
working-directory: nodejs
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
dist_tag=latest
|
||||
if [[ "${RELEASE_TAG#v}" == *-* ]]; then
|
||||
dist_tag=next
|
||||
fi
|
||||
npm publish ./dist/*.tgz --access public --provenance --tag "$dist_tag"
|
||||
|
||||
publish-pypi:
|
||||
name: Publish opendht to PyPI
|
||||
needs: [create-github-release, python-wheels]
|
||||
runs-on: ubuntu-latest
|
||||
environment:
|
||||
name: pypi
|
||||
url: https://pypi.org/p/opendht
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: opendht-wheels-*
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
- name: Publish wheels
|
||||
uses: pypa/gh-action-pypi-publish@release/v1
|
||||
|
||||
publish-crate:
|
||||
name: Publish opendht to crates.io
|
||||
needs: create-github-release
|
||||
runs-on: ubuntu-latest
|
||||
environment:
|
||||
name: crates-io
|
||||
url: https://crates.io/crates/opendht
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: cargo-edit
|
||||
- name: Set crate version from release tag
|
||||
working-directory: rust
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
run: cargo set-version "${RELEASE_TAG#v}"
|
||||
- name: Authenticate with crates.io
|
||||
id: auth
|
||||
uses: rust-lang/crates-io-auth-action@v1
|
||||
- name: Publish crate
|
||||
working-directory: rust
|
||||
env:
|
||||
CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
|
||||
run: cargo publish --allow-dirty
|
||||
@@ -0,0 +1,369 @@
|
||||
name: Windows Build
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, master ]
|
||||
pull_request:
|
||||
branches: [ main, master ]
|
||||
|
||||
env:
|
||||
VCPKG_DISABLE_METRICS: "1"
|
||||
VCPKG_INSTALLED_DIR: ${{ github.workspace }}\vcpkg_installed
|
||||
VCPKG_BINARY_SOURCES: clear;files,${{ github.workspace }}/vcpkg-binary-cache,readwrite
|
||||
|
||||
jobs:
|
||||
prepare-dependencies:
|
||||
name: Prepare Windows Dependencies
|
||||
runs-on: windows-latest
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: ${{ matrix.arch }}-windows
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [x64]
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up MSVC
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: Cache vcpkg binary packages
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: ${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-
|
||||
|
||||
- name: Set up vcpkg and install dependencies
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
runVcpkgInstall: true
|
||||
runVcpkgFormatString: >-
|
||||
[`install`, `--clean-after-build`, `--x-feature=test`,
|
||||
`--triplet`, `$[env.VCPKG_DEFAULT_TRIPLET]`,
|
||||
`--x-install-root`, `$[env.VCPKG_INSTALLED_DIR]`]
|
||||
|
||||
prepare-static-dependencies:
|
||||
name: Prepare Windows Static Dependencies
|
||||
runs-on: windows-latest
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: ${{ matrix.arch }}-windows-static-release
|
||||
strategy:
|
||||
matrix:
|
||||
arch: [x64]
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up MSVC
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: Cache vcpkg binary packages
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: ${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-
|
||||
|
||||
- name: Set up vcpkg and install dependencies
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
runVcpkgInstall: true
|
||||
runVcpkgFormatString: >-
|
||||
[`install`, `--clean-after-build`, `--x-feature=test`,
|
||||
`--triplet`, `$[env.VCPKG_DEFAULT_TRIPLET]`,
|
||||
`--x-install-root`, `$[env.VCPKG_INSTALLED_DIR]`]
|
||||
|
||||
build-windows:
|
||||
name: Windows MSVC Build
|
||||
runs-on: windows-latest
|
||||
needs: prepare-dependencies
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: ${{ matrix.arch }}-windows
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
build_type: [Debug, Release]
|
||||
arch: [x64]
|
||||
cxx_standard: [17, 20, 23]
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
|
||||
- name: Set up MSVC
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: Restore vcpkg binary packages
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: ${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-
|
||||
|
||||
- name: Configure CMake
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir build -ErrorAction SilentlyContinue
|
||||
cmake -B build `
|
||||
-S . `
|
||||
"-DCMAKE_TOOLCHAIN_FILE=$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" `
|
||||
-DVCPKG_TARGET_TRIPLET=${{ matrix.arch }}-windows `
|
||||
-DVCPKG_INSTALLED_DIR=${{ env.VCPKG_INSTALLED_DIR }} `
|
||||
-DVCPKG_MANIFEST_FEATURES=test `
|
||||
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }} `
|
||||
-DCMAKE_CXX_STANDARD=${{ matrix.cxx_standard }} `
|
||||
-DCMAKE_CXX_STANDARD_REQUIRED=ON `
|
||||
-DBUILD_TESTING=ON `
|
||||
-DOPENDHT_PROXY_CLIENT=ON `
|
||||
-DOPENDHT_PROXY_SERVER=ON `
|
||||
-DOPENDHT_C=ON `
|
||||
-DOPENDHT_TOOLS=ON `
|
||||
-DOPENDHT_PYTHON=OFF `
|
||||
-DOPENDHT_DOCUMENTATION=OFF `
|
||||
-DOPENDHT_PEER_DISCOVERY=ON `
|
||||
-DOPENDHT_HTTP=ON `
|
||||
-A ${{ matrix.arch }}
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cmake --build build --config ${{ matrix.build_type }} --parallel 4
|
||||
# Copy vcpkg installed libraries to the build directory
|
||||
Copy-Item -Path "${{ env.VCPKG_INSTALLED_DIR }}\${{ matrix.arch }}-windows\lib\*.lib" -Destination "build" -Force
|
||||
Copy-Item -Path "${{ env.VCPKG_INSTALLED_DIR }}\${{ matrix.arch }}-windows\bin\*.dll" -Destination "build" -Force
|
||||
|
||||
- name: Test
|
||||
if: matrix.build_type == 'Release'
|
||||
run: |
|
||||
cd build
|
||||
ctest --build-config ${{ matrix.build_type }} --output-on-failure --parallel 4
|
||||
|
||||
- name: Upload build artifacts
|
||||
if: matrix.build_type == 'Release'
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-windows-${{ matrix.arch }}-cxx${{ matrix.cxx_standard }}-${{ matrix.build_type }}
|
||||
path: |
|
||||
build/**/*.exe
|
||||
build/**/*.dll
|
||||
build/**/*.lib
|
||||
retention-days: 7
|
||||
|
||||
build-windows-static:
|
||||
name: Windows Static MSVC Build
|
||||
runs-on: windows-latest
|
||||
needs: prepare-static-dependencies
|
||||
env:
|
||||
VCPKG_DEFAULT_TRIPLET: ${{ matrix.arch }}-windows-static-release
|
||||
strategy:
|
||||
matrix:
|
||||
build_type: [Release]
|
||||
arch: [x64]
|
||||
cxx_standard: [17, 20, 23]
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up vcpkg
|
||||
uses: lukka/run-vcpkg@v11
|
||||
with:
|
||||
vcpkgJsonGlob: vcpkg.json
|
||||
vcpkgConfigurationJsonGlob: vcpkg-configuration.json
|
||||
|
||||
- name: Set up MSVC
|
||||
uses: microsoft/setup-msbuild@v3
|
||||
|
||||
- name: Restore vcpkg binary packages
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ${{ github.workspace }}/vcpkg-binary-cache
|
||||
key: ${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-${{ hashFiles('vcpkg.json', 'vcpkg-configuration.json', 'ports/**') }}-
|
||||
${{ runner.os }}-vcpkg-binary-${{ env.VCPKG_DEFAULT_TRIPLET }}-
|
||||
|
||||
- name: Configure CMake for Static Build
|
||||
shell: pwsh
|
||||
run: |
|
||||
mkdir build -ErrorAction SilentlyContinue
|
||||
cmake -B build `
|
||||
-S . `
|
||||
"-DCMAKE_TOOLCHAIN_FILE=$env:VCPKG_ROOT/scripts/buildsystems/vcpkg.cmake" `
|
||||
-DVCPKG_TARGET_TRIPLET=${{ matrix.arch }}-windows-static-release `
|
||||
-DVCPKG_INSTALLED_DIR=${{ env.VCPKG_INSTALLED_DIR }} `
|
||||
-DVCPKG_MANIFEST_FEATURES=test `
|
||||
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }} `
|
||||
-DCMAKE_CXX_STANDARD=${{ matrix.cxx_standard }} `
|
||||
-DCMAKE_CXX_STANDARD_REQUIRED=ON `
|
||||
-DBUILD_SHARED_LIBS=OFF `
|
||||
-DBUILD_TESTING=ON `
|
||||
-DOPENDHT_PROXY_CLIENT=ON `
|
||||
-DOPENDHT_PROXY_SERVER=ON `
|
||||
-DOPENDHT_C=ON `
|
||||
-DOPENDHT_TOOLS=ON `
|
||||
-DOPENDHT_PYTHON=OFF `
|
||||
-DOPENDHT_DOCUMENTATION=OFF `
|
||||
-DOPENDHT_PEER_DISCOVERY=ON `
|
||||
-DOPENDHT_HTTP=ON `
|
||||
-A ${{ matrix.arch }}
|
||||
|
||||
- name: Build Static
|
||||
shell: pwsh
|
||||
run: |
|
||||
cmake --build build --config ${{ matrix.build_type }} --parallel 4
|
||||
|
||||
- name: Test Static Build
|
||||
shell: pwsh
|
||||
run: |
|
||||
cd build
|
||||
ctest --build-config ${{ matrix.build_type }} --output-on-failure --parallel 4
|
||||
|
||||
- name: Upload static build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-windows-static-${{ matrix.arch }}-cxx${{ matrix.cxx_standard }}-${{ matrix.build_type }}
|
||||
path: |
|
||||
build/**/*.exe
|
||||
build/**/*.lib
|
||||
retention-days: 7
|
||||
|
||||
build-windows-mingw:
|
||||
name: Windows MinGW Build
|
||||
runs-on: windows-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
build_type: [Release]
|
||||
#build_type: [Debug, Release]
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Setup MinGW
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: MINGW64
|
||||
update: true
|
||||
install: >-
|
||||
mingw-w64-x86_64-gcc
|
||||
mingw-w64-x86_64-cmake
|
||||
mingw-w64-x86_64-make
|
||||
mingw-w64-x86_64-ninja
|
||||
mingw-w64-x86_64-pkg-config
|
||||
mingw-w64-x86_64-cppunit
|
||||
mingw-w64-x86_64-readline
|
||||
mingw-w64-x86_64-ncurses
|
||||
mingw-w64-x86_64-gnutls
|
||||
mingw-w64-x86_64-nettle
|
||||
mingw-w64-x86_64-jsoncpp
|
||||
mingw-w64-x86_64-fmt
|
||||
mingw-w64-x86_64-asio
|
||||
mingw-w64-x86_64-argon2
|
||||
mingw-w64-x86_64-openssl
|
||||
mingw-w64-clang-x86_64-msgpack-cxx
|
||||
|
||||
- name: Prepare dependencies from source (expected-lite, llhttp, restinio)
|
||||
shell: msys2 {0}
|
||||
env:
|
||||
LLHTTP_VERSION: "v9.2.1"
|
||||
RESTINIO_VERSION: "0.7.10"
|
||||
EXPECTED_LITE_URL: "https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp"
|
||||
run: |
|
||||
MSYS2_SYSROOT=$(cygpath -u "$MSYSTEM_PREFIX")
|
||||
|
||||
# Install expected-lite header
|
||||
mkdir -p ${MSYS2_SYSROOT}/include/nonstd
|
||||
curl -L "${EXPECTED_LITE_URL}" -o ${MSYS2_SYSROOT}/include/nonstd/expected.hpp
|
||||
|
||||
# Build and install llhttp
|
||||
mkdir llhttp
|
||||
curl -L "https://github.com/nodejs/llhttp/archive/refs/tags/release/${LLHTTP_VERSION}.tar.gz" -o llhttp.tar.gz
|
||||
tar -xzf llhttp.tar.gz -C llhttp --strip-components=1
|
||||
cd llhttp
|
||||
cmake -G "MinGW Makefiles" \
|
||||
-DCMAKE_INSTALL_PREFIX=${MSYS2_SYSROOT} \
|
||||
-DCMAKE_BUILD_TYPE=Release .
|
||||
cmake --build . --parallel 2
|
||||
cmake --install .
|
||||
cd ..
|
||||
rm -rf llhttp*
|
||||
|
||||
# Build and install restinio
|
||||
mkdir restinio && cd restinio
|
||||
curl -L "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" -o restinio.tar.bz2
|
||||
tar -xjf restinio.tar.bz2
|
||||
cd restinio-${RESTINIO_VERSION}/dev
|
||||
cmake -G "MinGW Makefiles" \
|
||||
-DCMAKE_INSTALL_PREFIX=${MSYS2_SYSROOT} \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off \
|
||||
-DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system .
|
||||
cmake --install .
|
||||
cd ../../..
|
||||
rm -rf restinio*
|
||||
|
||||
# Copy msgpack-cxx headers
|
||||
mkdir -p ${MSYS2_SYSROOT}/include/msgpack
|
||||
cp -r /clang64/include/msgpack/* ${MSYS2_SYSROOT}/include/msgpack/
|
||||
cp /clang64/include/msgpack.hpp ${MSYS2_SYSROOT}/include/msgpack.hpp
|
||||
|
||||
- name: Build with MinGW
|
||||
shell: msys2 {0}
|
||||
run: |
|
||||
mkdir build_mingw
|
||||
cd build_mingw
|
||||
cmake .. \
|
||||
-G "MinGW Makefiles" \
|
||||
-DHAVE_MSGPACKCXX=ON \
|
||||
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }} \
|
||||
-DBUILD_TESTING=ON \
|
||||
-DOPENDHT_PROXY_CLIENT=ON \
|
||||
-DOPENDHT_PROXY_SERVER=ON \
|
||||
-DOPENDHT_C=ON \
|
||||
-DOPENDHT_TOOLS=ON \
|
||||
-DOPENDHT_PYTHON=OFF \
|
||||
-DOPENDHT_DOCUMENTATION=OFF \
|
||||
-DOPENDHT_PEER_DISCOVERY=ON \
|
||||
-DOPENDHT_HTTP=ON
|
||||
cmake --build . --parallel 4
|
||||
|
||||
#- name: Test MinGW Build
|
||||
# shell: msys2 {0}
|
||||
# run: |
|
||||
# cd build_mingw
|
||||
# ctest --output-on-failure --parallel 4
|
||||
|
||||
- name: Upload MinGW artifacts
|
||||
if: matrix.build_type == 'Release'
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: opendht-windows-mingw-${{ matrix.build_type }}
|
||||
path: |
|
||||
build_mingw/**/*.exe
|
||||
build_mingw/**/*.dll
|
||||
build_mingw/**/*.a
|
||||
retention-days: 7
|
||||
+17
-25
@@ -23,39 +23,23 @@
|
||||
**/dhtchat
|
||||
**/dhtscanner
|
||||
|
||||
# Autotools
|
||||
/ac
|
||||
Makefile
|
||||
Makefile.in
|
||||
/aclocal.m4
|
||||
/autom4te.cache/
|
||||
/config.*
|
||||
/configure
|
||||
/depcomp
|
||||
/install-sh
|
||||
/libtool
|
||||
/ltmain.sh
|
||||
/m4/
|
||||
/missing
|
||||
/stamp-h?
|
||||
.deps/
|
||||
.dirstamp
|
||||
.libs/
|
||||
*.l[ao]
|
||||
*~
|
||||
# CMake
|
||||
CMakeCache.txt
|
||||
CMakeFiles/
|
||||
cmake_install.cmake
|
||||
*ConfigVersion.cmake
|
||||
*.pc
|
||||
|
||||
# KDevelop
|
||||
.kdev4/
|
||||
*.kdev4
|
||||
|
||||
# VSCode
|
||||
.vscode/*
|
||||
|
||||
# Visual Studio
|
||||
.vs/
|
||||
CMakeSettings.json
|
||||
|
||||
# Eclipse CDT
|
||||
.cproject
|
||||
.project
|
||||
.autotools
|
||||
language.settings.xml
|
||||
|
||||
# Python
|
||||
@@ -63,6 +47,9 @@ language.settings.xml
|
||||
*.stamp
|
||||
python/opendht.cpp
|
||||
python/setup.py
|
||||
python/dist/
|
||||
wheelhouse/
|
||||
*.egg-info/
|
||||
|
||||
# Doxygen
|
||||
doc/Doxyfile
|
||||
@@ -76,4 +63,9 @@ doc/Doxyfile
|
||||
|
||||
# build dir
|
||||
build
|
||||
build_dev
|
||||
.DS_Store
|
||||
build-*/
|
||||
install/
|
||||
vcpkg_installed/
|
||||
|
||||
Vendored
+4
-4
@@ -41,14 +41,14 @@
|
||||
}
|
||||
],
|
||||
"preLaunchTask": "build",
|
||||
"linux": {
|
||||
"linux": {
|
||||
"MIMode": "gdb",
|
||||
"externalConsole": false,
|
||||
},
|
||||
"osx": {
|
||||
},
|
||||
"osx": {
|
||||
"MIMode": "lldb",
|
||||
"externalConsole": true,
|
||||
},
|
||||
},
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"C_Cpp.default.compileCommands": "${workspaceFolder}/build/compile_commands.json",
|
||||
"C_Cpp.default.cppStandard": "c++17",
|
||||
"C_Cpp.default.cStandard": "c11",
|
||||
"C_Cpp.autoAddFileAssociations": false,
|
||||
"cmake.configureOnOpen": false,
|
||||
"cmake.configureOnEdit": false,
|
||||
"editor.formatOnSave": true,
|
||||
"files.eol": "\n",
|
||||
}
|
||||
Vendored
+3
-1
@@ -20,10 +20,12 @@
|
||||
"command": "cmake",
|
||||
"args": [
|
||||
"${workspaceRoot}",
|
||||
"-DCMAKE_EXPORT_COMPILE_COMMANDS=On",
|
||||
"-DCMAKE_BUILD_TYPE=Debug",
|
||||
"-DBUILD_TESTING=On",
|
||||
"-DOPENDHT_SANITIZE=On",
|
||||
"-DOPENDHT_PROXY_CLIENT=On",
|
||||
"-DOPENDHT_PROXY_SERVER=On",
|
||||
"-DOPENDHT_TESTS=On",
|
||||
"-DOPENDHT_C=On"
|
||||
],
|
||||
"dependsOn": "builddir"
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# OpenDHT – Agent Instructions
|
||||
|
||||
## Build
|
||||
|
||||
### Primary: CMake (C++17)
|
||||
```sh
|
||||
mkdir build && cd build
|
||||
cmake .. -DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON -GNinja
|
||||
ninja
|
||||
```
|
||||
|
||||
### Common CMake options
|
||||
| Option | Default | Purpose |
|
||||
|--------|---------|---------|
|
||||
| `OPENDHT_TOOLS` | ON | CLI tools (dhtnode, dhtchat, …) |
|
||||
| `OPENDHT_C` | OFF | C language bindings |
|
||||
| `OPENDHT_PYTHON` | OFF | Python 3 Cython bindings |
|
||||
| `OPENDHT_PROXY_SERVER` | OFF | REST API proxy server (requires RESTinio + llhttp) |
|
||||
| `OPENDHT_PROXY_CLIENT` | OFF | REST API proxy client |
|
||||
| `OPENDHT_PEER_DISCOVERY` | OFF | Multicast local peer discovery |
|
||||
| `OPENDHT_PUSH_NOTIFICATIONS` | OFF | Push notification support |
|
||||
| `OPENDHT_SANITIZE` | OFF | AddressSanitizer + stack protector |
|
||||
|
||||
### Alternative: Meson (C++20)
|
||||
```sh
|
||||
meson setup build . && cd build && ninja
|
||||
```
|
||||
|
||||
### Run tests
|
||||
```sh
|
||||
# Full suite
|
||||
ctest --output-on-failure --test-dir build
|
||||
|
||||
# Single test executable
|
||||
./build/test_testName
|
||||
```
|
||||
|
||||
## dhtnode
|
||||
|
||||
The `dhtnode` CLI tool is a simple DHT node implementation using `DhtRunner`.
|
||||
|
||||
---
|
||||
|
||||
## Commit
|
||||
|
||||
After implementing a feature or fixing a bug, commit your changes in clean, atomic commits with descriptive messages with format:
|
||||
`topic: short description`
|
||||
|
||||
If any test are added or modified, commit them separately before the fix (if any).
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
OpenDHT is a Kademlia-based DHT library. The implementation is layered:
|
||||
|
||||
```
|
||||
DhtRunner (public API — thread-safe, manages lifecycle & I/O threads)
|
||||
└── SecureDht (GnuTLS crypto: signing, encryption, identity)
|
||||
└── Dht (core DHT logic: routing, storage, find/get/put operations)
|
||||
└── NetworkEngine (raw UDP sockets, message parsing, IPv4/IPv6)
|
||||
```
|
||||
|
||||
- **`DhtRunner`** (`include/opendht/dhtrunner.h`, `src/dhtrunner.cpp`) — entry point for all users of the library. Wraps everything in a thread-pool and exposes async callbacks as well as blocking calls.
|
||||
- **`Dht`** (`include/opendht/dht.h`, `src/dht.cpp`) — Kademlia protocol: routing table, k-buckets, value replication, expiry.
|
||||
- **`SecureDht`** (`include/opendht/securedht.h`, `src/securedht.cpp`) — transparent encryption/signing layer on top of `Dht`. Identity is a GnuTLS certificate.
|
||||
- **`NetworkEngine`** (`include/opendht/network_engine.h`, `src/network_engine.cpp`) — UDP socket layer, serializes/deserializes msgpack messages.
|
||||
- **`RoutingTable`** (`include/opendht/routing_table.h`, `src/routing_table.cpp`) — Kademlia routing table with bucket splitting.
|
||||
- **`Value`** (`include/opendht/value.h`) — the storable unit: binary blob, optional signature, optional encryption; typed via `ValueType`.
|
||||
- **`InfoHash`** (`include/opendht/infohash.h`) — 20-byte SHA-1 identifier; alias `Hash<HASH_LEN>`.
|
||||
|
||||
Optional components (`DhtProxyServer`, `DhtProxyClient`, `PeerDiscovery`) are compiled in only when the corresponding CMake options are enabled.
|
||||
|
||||
---
|
||||
@@ -0,0 +1,155 @@
|
||||
# Build the library
|
||||
|
||||
The build is currently tested on GNU/Linux, macOS, and Windows.
|
||||
|
||||
## Unix-like systems (Linux, macOS, MSYS2/MinGW, etc.)
|
||||
|
||||
## Install dependencies
|
||||
|
||||
### Debian 13
|
||||
|
||||
```sh
|
||||
# Install dependencies
|
||||
sudo apt install pkg-config libncurses5-dev libreadline-dev nettle-dev libgnutls28-dev libargon2-dev libmsgpack-dev libssl-dev libfmt-dev libjsoncpp-dev libhttp-parser-dev libasio-dev libmsgpack-cxx-dev
|
||||
|
||||
# Install Python binding dependencies
|
||||
sudo apt-get install cython3 python3-dev python3-setuptools python3-build
|
||||
```
|
||||
|
||||
Optionally, install RESTinio to enable the OpenDHT proxy client and server:
|
||||
```sh
|
||||
mkdir /usr/include/nonstd
|
||||
wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp -O /usr/include/nonstd/expected.hpp
|
||||
|
||||
wget https://github.com/Stiffstream/restinio/releases/download/v.0.7.9/restinio-0.7.9.tar.bz2
|
||||
tar -xjf restinio-0.7.9.tar.bz2
|
||||
cd restinio-0.7.9/dev
|
||||
cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off -DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system -DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system .
|
||||
make && make install
|
||||
```
|
||||
|
||||
To run openDHT on a different computer from the build computer, the following runtime dependencies are required:
|
||||
```sh
|
||||
sudo apt install libargon2-1 libjsoncpp26
|
||||
```
|
||||
|
||||
### Ubuntu 24.04 and Debian 12
|
||||
|
||||
```sh
|
||||
# Install dependencies
|
||||
sudo apt install pkg-config libncurses5-dev libreadline-dev nettle-dev libgnutls28-dev libargon2-0-dev libmsgpack-dev libssl-dev libfmt-dev libjsoncpp-dev libhttp-parser-dev libasio-dev
|
||||
|
||||
# Install Python binding dependencies
|
||||
sudo apt-get install cython3 python3-dev python3-setuptools python3-build
|
||||
```
|
||||
|
||||
Optionally, install RESTinio to enable the OpenDHT proxy client and server:
|
||||
```sh
|
||||
mkdir /usr/include/nonstd
|
||||
wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp -O /usr/include/nonstd/expected.hpp
|
||||
|
||||
wget https://github.com/Stiffstream/restinio/releases/download/v.0.7.9/restinio-0.7.9.tar.bz2
|
||||
tar -xjf restinio-0.7.9.tar.bz2
|
||||
cd restinio-0.7.9/dev
|
||||
cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off -DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system -DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system .
|
||||
make && make install
|
||||
```
|
||||
|
||||
### Fedora
|
||||
|
||||
```sh
|
||||
# Install GnuTLS, Readline and msgpack-c
|
||||
sudo dnf install readline-devel gnutls-devel msgpack-devel asio-devel libargon2-devel fmt-devel
|
||||
# Install python binding dependencies
|
||||
sudo dnf install python3-Cython python3-devel redhat-rpm-config
|
||||
```
|
||||
|
||||
### macOS
|
||||
|
||||
```sh
|
||||
brew install gnutls msgpack-cxx argon2 asio readline jsoncpp fmt llhttp
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
Using CMake:
|
||||
|
||||
```sh
|
||||
# Clone the repository
|
||||
git clone https://github.com/savoirfairelinux/opendht.git
|
||||
|
||||
# Build and install
|
||||
cd opendht
|
||||
mkdir build && cd build
|
||||
cmake ..
|
||||
make -j$(nproc)
|
||||
sudo make install
|
||||
```
|
||||
|
||||
#### Example Configurations
|
||||
|
||||
Minimal build (libraries only):
|
||||
```sh
|
||||
cmake -DOPENDHT_TOOLS=OFF ..
|
||||
```
|
||||
|
||||
Full-featured build with proxy support, Python, and C bindings:
|
||||
```sh
|
||||
cmake -DOPENDHT_PYTHON=ON \
|
||||
-DOPENDHT_C=ON \
|
||||
-DOPENDHT_PROXY_SERVER=ON \
|
||||
-DOPENDHT_PROXY_SERVER_IDENTITY=ON \
|
||||
-DOPENDHT_PROXY_CLIENT=ON \
|
||||
-DOPENDHT_PUSH_NOTIFICATIONS=ON ..
|
||||
```
|
||||
|
||||
#### Common CMake options
|
||||
| Option | Default | Purpose |
|
||||
|--------|---------|---------|
|
||||
| `OPENDHT_TOOLS` | ON | CLI tools (dhtnode, dhtchat, …) |
|
||||
| `OPENDHT_C` | OFF | C language bindings |
|
||||
| `OPENDHT_PYTHON` | OFF | Python 3 Cython bindings |
|
||||
| `OPENDHT_PROXY_SERVER` | OFF | REST API proxy server (requires RESTinio + llhttp) |
|
||||
| `OPENDHT_PROXY_CLIENT` | OFF | REST API proxy client |
|
||||
| `OPENDHT_PEER_DISCOVERY` | OFF | Multicast local peer discovery |
|
||||
| `OPENDHT_PUSH_NOTIFICATIONS` | OFF | Push notification support |
|
||||
| `OPENDHT_SANITIZE` | OFF | AddressSanitizer + stack protector |
|
||||
|
||||
## Node.js Bindings
|
||||
|
||||
Node-API bindings wrap the C++ API directly with `node-addon-api`, including
|
||||
RSA/EC keys, certificates, identities, and signed/encrypted DHT operations.
|
||||
With the native dependencies above, Node.js 22.9+, and CMake installed, run
|
||||
`npm ci`, `npm run build`, `npm test`, and `npm run typecheck` from `nodejs/`.
|
||||
This creates a separate native build without changing the existing build tree.
|
||||
See [the Node.js binding guide](nodejs/README.md) for the API and current limits.
|
||||
`npm run package` creates a platform prebuild with bundled native dependencies;
|
||||
`npm run test:package` verifies installation outside the source tree. The Node.js
|
||||
package CI builds Linux x64, macOS ARM64/x64, and Windows x64 prebuilds and checks
|
||||
the assembled npm archive on Node 22, 24, and 26 before release attachment.
|
||||
|
||||
## C and Rust Bindings
|
||||
|
||||
Enable `OPENDHT_C=ON` to build the C ABI.
|
||||
See [the Rust build guide](rust/BUILD.md) for build instructions.
|
||||
|
||||
## Windows/MSVC
|
||||
|
||||
Building on Windows with MSVC is supported with VCPKG and CMake.
|
||||
|
||||
### Build with VCPKG in manifest mode
|
||||
|
||||
1. Install [VCPKG](https://github.com/microsoft/vcpkg) 2026.10.16 and required dependencies:
|
||||
```ps1
|
||||
git clone https://github.com/microsoft/vcpkg.git
|
||||
cd vcpkg
|
||||
git checkout 9eec002df1cd109f8f104cd966a763daf9751489
|
||||
.\bootstrap-vcpkg.bat
|
||||
```
|
||||
|
||||
2. Use CMake preset for vcpkg:
|
||||
```ps1
|
||||
cd opendht
|
||||
cmake --preset=vcpkg_manifest .
|
||||
cmake --build .
|
||||
```
|
||||
+717
-247
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,250 @@
|
||||
{
|
||||
"version": 2,
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "default",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"hidden": true
|
||||
},
|
||||
{
|
||||
"name": "unix-make",
|
||||
"description": "Unix Makefiles",
|
||||
"generator": "Unix Makefiles",
|
||||
"inherits": "default",
|
||||
"cacheVariables": {
|
||||
"CMAKE_EXPORT_COMPILE_COMMANDS": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "unix-make-full",
|
||||
"description": "Unix Makefiles (Full build)",
|
||||
"inherits": "unix-make",
|
||||
"cacheVariables": {
|
||||
"OPENDHT_C": true,
|
||||
"OPENDHT_PROXY_CLIENT": true,
|
||||
"OPENDHT_PROXY_SERVER": true,
|
||||
"OPENDHT_PUSH_NOTIFICATIONS": true,
|
||||
"OPENDHT_PYTHON": true,
|
||||
"OPENDHT_INDEX": true,
|
||||
"BUILD_TESTING": true,
|
||||
"OPENDHT_EXAMPLES": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "unix-make-release",
|
||||
"description": "Unix Makefiles (Release build)",
|
||||
"inherits": "unix-make-full",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"BUILD_SHARED_LIBS": true,
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_SANITIZE": false,
|
||||
"OPENDHT_EXAMPLES": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "ninja",
|
||||
"generator": "Ninja",
|
||||
"inherits": "default",
|
||||
"cacheVariables": {
|
||||
"CMAKE_EXPORT_COMPILE_COMMANDS": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "ninja-release",
|
||||
"inherits": "ninja",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"BUILD_SHARED_LIBS": true,
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_SANITIZE": false,
|
||||
"OPENDHT_CPACK": true,
|
||||
"OPENDHT_C": true,
|
||||
"OPENDHT_PROXY_CLIENT": true,
|
||||
"OPENDHT_PROXY_SERVER": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "msvc",
|
||||
"generator": "Visual Studio 17 2022",
|
||||
"inherits": "default",
|
||||
"cacheVariables": {
|
||||
"BUILD_TESTING": true,
|
||||
"VCPKG_MANIFEST_FEATURES": "test",
|
||||
"OPENDHT_PROXY_CLIENT": false,
|
||||
"OPENDHT_PROXY_SERVER": false,
|
||||
"OPENDHT_C": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_manifest",
|
||||
"inherits": "msvc",
|
||||
"cacheVariables": {
|
||||
"CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake",
|
||||
"BUILD_SHARED_LIBS": true,
|
||||
"CMAKE_BUILD_TYPE": "Debug",
|
||||
"VCPKG_MANIFEST_MODE": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_manifest_static",
|
||||
"inherits": "vcpkg_manifest",
|
||||
"cacheVariables": {
|
||||
"BUILD_SHARED_LIBS": false,
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-static"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_local",
|
||||
"inherits": "msvc",
|
||||
"cacheVariables": {
|
||||
"CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake",
|
||||
"BUILD_SHARED_LIBS": true,
|
||||
"CMAKE_BUILD_TYPE": "Debug",
|
||||
"BUILD_TESTING": true,
|
||||
"VCPKG_MANIFEST_MODE": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release",
|
||||
"inherits": "vcpkg_manifest",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-release",
|
||||
"VCPKG_OVERLAY_TRIPLETS": "x64-windows-release;x64-windows-rel;x64-windows",
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_CPACK": true,
|
||||
"OPENDHT_C": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release_full",
|
||||
"inherits": "vcpkg_release",
|
||||
"cacheVariables": {
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_PROXY_CLIENT": true,
|
||||
"OPENDHT_PROXY_SERVER": true,
|
||||
"OPENDHT_C": true,
|
||||
"OPENDHT_PYTHON": true,
|
||||
"OPENDHT_CPACK": true,
|
||||
"OPENDHT_DOCUMENTATION": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release_static",
|
||||
"inherits": "vcpkg_manifest_static",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-static-release",
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_CPACK": true,
|
||||
"OPENDHT_C": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release_static_full",
|
||||
"inherits": "vcpkg_manifest_static",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-static-release",
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_PROXY_CLIENT": true,
|
||||
"OPENDHT_PROXY_SERVER": true,
|
||||
"OPENDHT_C": true,
|
||||
"OPENDHT_CPACK": true,
|
||||
"OPENDHT_DOCUMENTATION": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release_local",
|
||||
"inherits": "vcpkg_local",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-release",
|
||||
"VCPKG_OVERLAY_TRIPLETS": "x64-windows-release;x64-windows-rel;x64-windows",
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_CPACK": true,
|
||||
"OPENDHT_C": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release_local_full",
|
||||
"inherits": "vcpkg_local",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-release",
|
||||
"VCPKG_OVERLAY_TRIPLETS": "x64-windows-release;x64-windows-rel;x64-windows",
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_PROXY_CLIENT": true,
|
||||
"OPENDHT_PROXY_SERVER": true,
|
||||
"OPENDHT_CPACK": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release_static_local",
|
||||
"inherits": "vcpkg_local",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"BUILD_SHARED_LIBS": false,
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-static-release",
|
||||
"VCPKG_OVERLAY_TRIPLETS": "x64-windows-static-release;x64-windows-static-rel;x64-windows-static",
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_CPACK": true,
|
||||
"OPENDHT_C": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "vcpkg_release_static_local_full",
|
||||
"inherits": "vcpkg_local",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"BUILD_SHARED_LIBS": false,
|
||||
"VCPKG_TARGET_TRIPLET": "x64-windows-static-release",
|
||||
"VCPKG_OVERLAY_TRIPLETS": "x64-windows-static-release;x64-windows-static-rel;x64-windows-static",
|
||||
"BUILD_TESTING": false,
|
||||
"OPENDHT_PROXY_CLIENT": true,
|
||||
"OPENDHT_PROXY_SERVER": true,
|
||||
"OPENDHT_CPACK": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"buildPresets": [
|
||||
{
|
||||
"name": "default",
|
||||
"configurePreset": "default",
|
||||
"hidden": true
|
||||
},
|
||||
{
|
||||
"name": "unix-make",
|
||||
"inherits": "default",
|
||||
"configurePreset": "unix-make"
|
||||
},
|
||||
{
|
||||
"name": "ninja",
|
||||
"inherits": "default",
|
||||
"configurePreset": "ninja"
|
||||
},
|
||||
{
|
||||
"name": "msvc",
|
||||
"inherits": "default",
|
||||
"configurePreset": "msvc"
|
||||
},
|
||||
{
|
||||
"name": "vcpkg-dev",
|
||||
"inherits": "default",
|
||||
"configurePreset": "vcpkg_manifest"
|
||||
},
|
||||
{
|
||||
"name": "vcpkg-release-static",
|
||||
"inherits": "default",
|
||||
"configurePreset": "vcpkg_release_static_full",
|
||||
"configuration": "Release"
|
||||
},
|
||||
{
|
||||
"name": "vcpkg-release",
|
||||
"inherits": "default",
|
||||
"configurePreset": "vcpkg_release_full",
|
||||
"configuration": "Release"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,674 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,7 @@
|
||||
Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
-31
@@ -1,31 +0,0 @@
|
||||
AM_CXXFLAGS = -pthread
|
||||
|
||||
SUBDIRS =
|
||||
|
||||
SUBDIRS += src
|
||||
|
||||
if ENABLE_TOOLS
|
||||
SUBDIRS += tools
|
||||
endif
|
||||
|
||||
if USE_CYTHON
|
||||
SUBDIRS += python
|
||||
endif
|
||||
|
||||
if ENABLE_TESTS
|
||||
SUBDIRS += tests
|
||||
endif
|
||||
|
||||
SUBDIRS += doc
|
||||
|
||||
ACLOCAL_AMFLAGS = -I m4
|
||||
|
||||
DOC_FILES = \
|
||||
README.md \
|
||||
COPYING
|
||||
|
||||
EXTRA_DIST = \
|
||||
$(DOC_FILES)
|
||||
|
||||
pkgconfigdir = $(libdir)/pkgconfig
|
||||
pkgconfig_DATA = opendht.pc
|
||||
@@ -4,6 +4,11 @@
|
||||
<a id="user-content-opendht-" class="anchor" href="/savoirfairelinux/opendht/blob/master/README.md#opendht-" aria-hidden="true"></a>OpenDHT
|
||||
</h1>
|
||||
|
||||
[](https://pypi.org/project/opendht/)
|
||||
[](https://crates.io/crates/opendht)
|
||||
[](https://www.npmjs.com/package/opendht)
|
||||
[](https://github.com/savoirfairelinux/opendht/pkgs/container/opendht%2Fopendht)
|
||||
|
||||
A lightweight C++17 Distributed Hash Table implementation.
|
||||
|
||||
OpenDHT provides an easy to use distributed in-memory data store.
|
||||
@@ -15,20 +20,20 @@ Values are distributed over the network, with redundancy.
|
||||
* Public key cryptography layer providing optional data signature and encryption (using GnuTLS)
|
||||
* IPv4 and IPv6 support
|
||||
* Clean and powerful **C++17** map API
|
||||
* Bindings for **C, Rust & Python 3**
|
||||
* Bindings for **C, Rust, Node.js & Python 3**
|
||||
* REST API with optional HTTP client+server with push notification support
|
||||
|
||||
## Documentation
|
||||
See the wiki: <https://github.com/savoirfairelinux/opendht/wiki>
|
||||
|
||||
#### How to run a node
|
||||
|
||||
You can help contribute to the public network by running a stable node with a public IP address.
|
||||
https://github.com/savoirfairelinux/opendht/wiki/Running-a-node-with-dhtnode
|
||||
|
||||
#### How-to build and install
|
||||
|
||||
Build instructions: <https://github.com/savoirfairelinux/opendht/wiki/Build-the-library>
|
||||
|
||||
#### How-to build a simple client app
|
||||
```bash
|
||||
g++ main.cpp -std=c++17 -lopendht
|
||||
```
|
||||
Build instructions: see [BUILD.md](BUILD.md)
|
||||
|
||||
## Examples
|
||||
### C++ example
|
||||
@@ -73,14 +78,22 @@ int main()
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
### Python 3 example
|
||||
|
||||
Install on Linux, macOS and Windows with:
|
||||
```sh
|
||||
pip install opendht
|
||||
```
|
||||
|
||||
Using the simple, blocking API:
|
||||
```python
|
||||
import opendht as dht
|
||||
|
||||
node = dht.DhtRunner()
|
||||
node.run()
|
||||
|
||||
# Join the network through any running node,
|
||||
# Join the DHT network through any running node,
|
||||
# here using a known bootstrap node.
|
||||
node.bootstrap("bootstrap.jami.net", "4222")
|
||||
|
||||
@@ -88,35 +101,68 @@ node.bootstrap("bootstrap.jami.net", "4222")
|
||||
node.put(dht.InfoHash.get("unique_key"), dht.Value(b'some binary data'))
|
||||
|
||||
results = node.get(dht.InfoHash.get("unique_key"))
|
||||
for r in results:
|
||||
print(r)
|
||||
for value in results:
|
||||
print(value)
|
||||
```
|
||||
|
||||
Or using asyncio:
|
||||
```python
|
||||
import asyncio
|
||||
import opendht.aio as dht
|
||||
|
||||
async def dht_async_demo(key_str: str):
|
||||
# Start a new node using an async context manager.
|
||||
# It is also possible to call run()/await shutdown() manually.
|
||||
async with dht.DhtRunner(
|
||||
bootstrap=(("bootstrap.jami.net", "4222"),)
|
||||
) as node:
|
||||
# compute key hash
|
||||
key = dht.InfoHash.get(key_str)
|
||||
|
||||
# put data, waiting for completion
|
||||
await node.put(key, dht.Value(b'tata data'))
|
||||
|
||||
# get all values at key
|
||||
results = await node.getAll(key)
|
||||
for value in results:
|
||||
print(value)
|
||||
|
||||
# same operation, but stream values as they come from the network
|
||||
with node.get(key) as results:
|
||||
async for value in results:
|
||||
print(value)
|
||||
|
||||
# listen for change of values at key
|
||||
with node.listen(key) as values:
|
||||
async for value, expired in values:
|
||||
print(value)
|
||||
if value.data == b'tata data':
|
||||
break
|
||||
|
||||
asyncio.run(dht_async_demo("unique_key"))
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
Core dependencies:
|
||||
- msgpack-c 1.2+, used for data serialization.
|
||||
- GnuTLS 3.3+, used for cryptographic operations.
|
||||
- Nettle 2.4+, a GnuTLS dependency for crypto.
|
||||
- (optional) restinio used for the REST API.
|
||||
- (optional) jsoncpp 1.7.4-3+, used for the REST API.
|
||||
- Build tested with GCC 7+ (GNU/Linux, Windows with MinGW), Clang/LLVM (GNU/Linux, Android, macOS, iOS).
|
||||
- Build tested with Microsoft Visual Studio 2017, 2019, 2022
|
||||
- {fmt} 9.0+, for log formatting.
|
||||
|
||||
## Contact
|
||||
Optional dependencies for the REST API (DHT proxy client/server):
|
||||
- (optional) restinio
|
||||
- (optional) llhttp
|
||||
- (optional) jsoncpp 1.7.4-3+
|
||||
- (optional) simdutf
|
||||
|
||||
IRC: join us on Libera.chat at [`#opendht`](https://web.libera.chat/#opendht).
|
||||
Build environment:
|
||||
- Build tested with GCC 9+ (GNU/Linux, Windows with MinGW), Clang/LLVM (GNU/Linux, Android, macOS, iOS).
|
||||
- Build tested with Microsoft Visual Studio 2019, 2022
|
||||
|
||||
## License
|
||||
Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
|
||||
OpenDHT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
|
||||
|
||||
See COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html for the full GPLv3 license.
|
||||
OpenDHT is released under the MIT License. See [LICENSE](LICENSE) for details.
|
||||
|
||||
## Acknowledgements
|
||||
This project was originally based on https://github.com/jech/dht by Juliusz Chroboczek.
|
||||
It is independent from another project called OpenDHT (Sean Rhea. Ph.D. Thesis, 2005), now extinct.
|
||||
|
||||
## Donations
|
||||
We gratefully accept Bitcoin donations to support OpenDHT development at: `bitcoin:3EykSd1An888efq4Bq3KaV3hJ3JQ4FPnwm`.
|
||||
@@ -1 +0,0 @@
|
||||
autoreconf --install --verbose -Wall
|
||||
+882
-221
File diff suppressed because it is too large.
Load diff
+169
-35
@@ -1,41 +1,37 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include "def.h"
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <opendht/def.h>
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
typedef uint16_t sa_family_t;
|
||||
typedef uint16_t in_port_t;
|
||||
#else
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#endif
|
||||
|
||||
// Non-owning data view
|
||||
struct OPENDHT_C_PUBLIC dht_data_view {
|
||||
struct OPENDHT_C_PUBLIC dht_data_view
|
||||
{
|
||||
const uint8_t* data;
|
||||
size_t size;
|
||||
};
|
||||
typedef struct dht_data_view dht_data_view;
|
||||
|
||||
OPENDHT_C_PUBLIC const char* dht_version(void);
|
||||
|
||||
// dht::Blob
|
||||
struct OPENDHT_C_PUBLIC dht_blob;
|
||||
typedef struct dht_blob dht_blob;
|
||||
@@ -43,19 +39,35 @@ OPENDHT_C_PUBLIC dht_data_view dht_blob_get_data(const dht_blob* data);
|
||||
OPENDHT_C_PUBLIC void dht_blob_delete(dht_blob* data);
|
||||
|
||||
// dht::InfoHash
|
||||
struct OPENDHT_C_PUBLIC dht_infohash { uint8_t d[HASH_LEN]; };
|
||||
#ifdef __cplusplus
|
||||
#define OPENDHT_C_ALIGN_UINT32 alignas(uint32_t)
|
||||
#elif defined(_MSC_VER)
|
||||
#define OPENDHT_C_ALIGN_UINT32 __declspec(align(4))
|
||||
#else
|
||||
#define OPENDHT_C_ALIGN_UINT32 _Alignas(uint32_t)
|
||||
#endif
|
||||
|
||||
struct OPENDHT_C_PUBLIC dht_infohash
|
||||
{
|
||||
OPENDHT_C_ALIGN_UINT32 uint8_t d[HASH_LEN];
|
||||
};
|
||||
typedef struct dht_infohash dht_infohash;
|
||||
OPENDHT_C_PUBLIC void dht_infohash_zero(dht_infohash* h);
|
||||
OPENDHT_C_PUBLIC void dht_infohash_random(dht_infohash* h);
|
||||
OPENDHT_C_PUBLIC void dht_infohash_from_hex(dht_infohash* h, const char* dat);
|
||||
OPENDHT_C_PUBLIC void dht_infohash_from_hex_null(dht_infohash* h, const char* dat);
|
||||
OPENDHT_C_PUBLIC void dht_infohash_get(dht_infohash* h, const uint8_t* dat, size_t dat_size);
|
||||
OPENDHT_C_PUBLIC void dht_infohash_get_from_string(dht_infohash* h, const char* str);
|
||||
OPENDHT_C_PUBLIC const char* dht_infohash_print(const dht_infohash* h);
|
||||
OPENDHT_C_PUBLIC bool dht_infohash_is_zero(const dht_infohash* h);
|
||||
|
||||
// dht::PkId
|
||||
struct OPENDHT_C_PUBLIC dht_pkid { uint8_t d[32]; };
|
||||
struct OPENDHT_C_PUBLIC dht_pkid
|
||||
{
|
||||
OPENDHT_C_ALIGN_UINT32 uint8_t d[32];
|
||||
};
|
||||
typedef struct dht_pkid dht_pkid;
|
||||
#undef OPENDHT_C_ALIGN_UINT32
|
||||
OPENDHT_C_PUBLIC const char* dht_pkid_print(const dht_pkid* h);
|
||||
|
||||
// dht::crypto::PublicKey
|
||||
@@ -64,17 +76,23 @@ typedef struct dht_publickey dht_publickey;
|
||||
OPENDHT_C_PUBLIC dht_publickey* dht_publickey_import(const uint8_t* dat, size_t dat_size);
|
||||
OPENDHT_C_PUBLIC void dht_publickey_delete(dht_publickey* pk);
|
||||
OPENDHT_C_PUBLIC int dht_publickey_export(const dht_publickey* pk, char* out, size_t* out_size);
|
||||
OPENDHT_C_PUBLIC dht_blob* dht_publickey_export_blob(const dht_publickey* pk);
|
||||
OPENDHT_C_PUBLIC int dht_publickey_unpack(dht_publickey* pk, const uint8_t* data, size_t size);
|
||||
OPENDHT_C_PUBLIC dht_infohash dht_publickey_get_id(const dht_publickey* pk);
|
||||
OPENDHT_C_PUBLIC dht_pkid dht_publickey_get_long_id(const dht_publickey* pk);
|
||||
OPENDHT_C_PUBLIC bool dht_publickey_check_signature(const dht_publickey* pk, const char* data, size_t data_size, const char* signature, size_t signature_size);
|
||||
OPENDHT_C_PUBLIC bool dht_publickey_check_signature(
|
||||
const dht_publickey* pk, const char* data, size_t data_size, const char* signature, size_t signature_size);
|
||||
OPENDHT_C_PUBLIC dht_blob* dht_publickey_encrypt(const dht_publickey* pk, const char* data, size_t data_size);
|
||||
|
||||
// dht::crypto::PrivateKey
|
||||
struct OPENDHT_C_PUBLIC dht_privatekey;
|
||||
typedef struct dht_privatekey dht_privatekey;
|
||||
OPENDHT_C_PUBLIC dht_privatekey* dht_privatekey_generate(unsigned key_length_bits);
|
||||
OPENDHT_C_PUBLIC dht_privatekey* dht_privatekey_generate_ec(void);
|
||||
OPENDHT_C_PUBLIC dht_privatekey* dht_privatekey_import(const uint8_t* dat, size_t dat_size, const char* password);
|
||||
OPENDHT_C_PUBLIC int dht_privatekey_export(const dht_privatekey*, char* out, size_t* out_size, const char* password);
|
||||
OPENDHT_C_PUBLIC dht_blob* dht_privatekey_export_blob(const dht_privatekey*, const char* password);
|
||||
OPENDHT_C_PUBLIC dht_blob* dht_privatekey_sign(const dht_privatekey*, const uint8_t* data, size_t size);
|
||||
OPENDHT_C_PUBLIC dht_publickey* dht_privatekey_get_publickey(const dht_privatekey*);
|
||||
OPENDHT_C_PUBLIC dht_blob* dht_privatekey_decrypt(const dht_privatekey*, const char* data, size_t data_size);
|
||||
OPENDHT_C_PUBLIC void dht_privatekey_delete(dht_privatekey*);
|
||||
@@ -83,17 +101,21 @@ OPENDHT_C_PUBLIC void dht_privatekey_delete(dht_privatekey*);
|
||||
struct OPENDHT_C_PUBLIC dht_certificate;
|
||||
typedef struct dht_certificate dht_certificate;
|
||||
OPENDHT_C_PUBLIC dht_certificate* dht_certificate_import(const uint8_t* dat, size_t dat_size);
|
||||
OPENDHT_C_PUBLIC dht_blob* dht_certificate_export(const dht_certificate* certificate);
|
||||
OPENDHT_C_PUBLIC dht_certificate* dht_certificate_ref(const dht_certificate* certificate);
|
||||
OPENDHT_C_PUBLIC dht_infohash dht_certificate_get_id(const dht_certificate*);
|
||||
OPENDHT_C_PUBLIC dht_pkid dht_certificate_get_long_id(const dht_certificate*);
|
||||
OPENDHT_C_PUBLIC dht_publickey* dht_certificate_get_publickey(const dht_certificate*);
|
||||
OPENDHT_C_PUBLIC void dht_certificate_delete(dht_certificate*);
|
||||
|
||||
struct OPENDHT_PUBLIC dht_identity {
|
||||
struct OPENDHT_C_PUBLIC dht_identity
|
||||
{
|
||||
dht_privatekey* privatekey;
|
||||
dht_certificate* certificate;
|
||||
};
|
||||
typedef struct dht_identity dht_identity;
|
||||
OPENDHT_C_PUBLIC dht_identity dht_identity_generate(const char* common_name, const dht_identity* ca);
|
||||
OPENDHT_C_PUBLIC dht_identity dht_identity_generate_ec(const char* common_name, const dht_identity* ca);
|
||||
OPENDHT_C_PUBLIC void dht_identity_delete(dht_identity*);
|
||||
|
||||
// dht::Value
|
||||
@@ -101,8 +123,10 @@ struct OPENDHT_C_PUBLIC dht_value;
|
||||
typedef struct dht_value dht_value;
|
||||
typedef uint64_t dht_value_id;
|
||||
OPENDHT_C_PUBLIC dht_value* dht_value_new(const uint8_t* data, size_t size);
|
||||
OPENDHT_C_PUBLIC dht_value* dht_value_with_id_new(const uint8_t* data, size_t size, uint64_t value_id);
|
||||
OPENDHT_C_PUBLIC dht_value* dht_value_new_from_string(const char* str);
|
||||
OPENDHT_C_PUBLIC dht_value* dht_value_ref(const dht_value*);
|
||||
OPENDHT_C_PUBLIC dht_value* dht_value_copy(const dht_value*);
|
||||
OPENDHT_C_PUBLIC void dht_value_unref(dht_value*);
|
||||
OPENDHT_C_PUBLIC dht_data_view dht_value_get_data(const dht_value* data);
|
||||
OPENDHT_C_PUBLIC dht_value_id dht_value_get_id(const dht_value* data);
|
||||
@@ -110,19 +134,61 @@ OPENDHT_C_PUBLIC dht_publickey* dht_value_get_owner(const dht_value* data);
|
||||
OPENDHT_C_PUBLIC dht_infohash dht_value_get_recipient(const dht_value* data);
|
||||
OPENDHT_C_PUBLIC const char* dht_value_get_user_type(const dht_value* data);
|
||||
OPENDHT_C_PUBLIC void dht_value_set_user_type(dht_value* data, const char* user_type);
|
||||
OPENDHT_C_PUBLIC uint16_t dht_value_get_type(const dht_value* value);
|
||||
OPENDHT_C_PUBLIC void dht_value_set_type(dht_value* value, uint16_t type);
|
||||
OPENDHT_C_PUBLIC uint16_t dht_value_get_seq(const dht_value* value);
|
||||
OPENDHT_C_PUBLIC void dht_value_set_seq(dht_value* value, uint16_t seq);
|
||||
OPENDHT_C_PUBLIC unsigned dht_value_get_priority(const dht_value* value);
|
||||
OPENDHT_C_PUBLIC void dht_value_set_priority(dht_value* value, unsigned priority);
|
||||
OPENDHT_C_PUBLIC const char* dht_value_get_push_type(const dht_value* value);
|
||||
OPENDHT_C_PUBLIC void dht_value_set_push_type(dht_value* value, const char* push_type);
|
||||
|
||||
// callbacks
|
||||
typedef bool (*dht_get_cb)(const dht_value* value, void* user_data);
|
||||
typedef bool (*dht_value_cb)(const dht_value* value, bool expired, void* user_data);
|
||||
typedef void (*dht_done_cb)(bool ok, void* user_data);
|
||||
typedef void (*dht_shutdown_cb)(void* user_data);
|
||||
typedef void (*dht_status_cb)(int ipv4_status, int ipv6_status, void* user_data);
|
||||
typedef void (*dht_certificate_cb)(const dht_certificate* certificate, void* user_data);
|
||||
typedef void (*dht_certificate_store_cb)(const dht_pkid* id, dht_certificate_cb emit, void* emit_data, void* user_data);
|
||||
|
||||
typedef struct dht_runner_context
|
||||
{
|
||||
dht_status_cb status_cb;
|
||||
dht_certificate_store_cb certificate_store_cb;
|
||||
dht_shutdown_cb released_cb;
|
||||
void* user_data;
|
||||
} dht_runner_context;
|
||||
|
||||
enum dht_query_field {
|
||||
DHT_FIELD_ID = 1,
|
||||
DHT_FIELD_TYPE = 2,
|
||||
DHT_FIELD_SEQ = 4,
|
||||
DHT_FIELD_OWNER = 8,
|
||||
DHT_FIELD_USER_TYPE = 16
|
||||
};
|
||||
|
||||
typedef struct dht_query_result
|
||||
{
|
||||
uint32_t fields;
|
||||
uint64_t id;
|
||||
uint16_t value_type;
|
||||
uint16_t seq;
|
||||
dht_infohash owner;
|
||||
dht_data_view user_type;
|
||||
} dht_query_result;
|
||||
typedef bool (*dht_query_cb)(const dht_query_result* result, void* user_data);
|
||||
|
||||
struct dht_push_token;
|
||||
typedef struct dht_push_token dht_push_token;
|
||||
|
||||
struct OPENDHT_C_PUBLIC dht_op_token;
|
||||
typedef struct dht_op_token dht_op_token;
|
||||
OPENDHT_C_PUBLIC void dht_op_token_delete(dht_op_token* token);
|
||||
|
||||
// config
|
||||
struct OPENDHT_PUBLIC dht_node_config {
|
||||
struct OPENDHT_C_PUBLIC dht_node_config
|
||||
{
|
||||
dht_infohash node_id;
|
||||
uint32_t network;
|
||||
bool is_bootstrap;
|
||||
@@ -131,22 +197,28 @@ struct OPENDHT_PUBLIC dht_node_config {
|
||||
};
|
||||
typedef struct dht_node_config dht_node_config;
|
||||
|
||||
struct OPENDHT_PUBLIC dht_secure_config {
|
||||
struct OPENDHT_C_PUBLIC dht_secure_config
|
||||
{
|
||||
dht_node_config node_config;
|
||||
dht_identity id;
|
||||
};
|
||||
typedef struct dht_secure_config dht_secure_config;
|
||||
|
||||
struct OPENDHT_PUBLIC dht_runner_config {
|
||||
struct OPENDHT_C_PUBLIC dht_runner_config
|
||||
{
|
||||
dht_secure_config dht_config;
|
||||
bool threaded;
|
||||
const char* proxy_server;
|
||||
const char* push_node_id;
|
||||
const char* push_token;
|
||||
const char* push_topic;
|
||||
const char* push_platform;
|
||||
const char* proxy_user_agent;
|
||||
bool peer_discovery;
|
||||
bool peer_publish;
|
||||
dht_certificate* server_ca;
|
||||
dht_identity client_identity;
|
||||
bool log;
|
||||
};
|
||||
typedef struct dht_runner_config dht_runner_config;
|
||||
OPENDHT_C_PUBLIC void dht_runner_config_default(dht_runner_config* config);
|
||||
@@ -156,18 +228,70 @@ struct OPENDHT_C_PUBLIC dht_runner;
|
||||
typedef struct dht_runner dht_runner;
|
||||
OPENDHT_C_PUBLIC dht_runner* dht_runner_new(void);
|
||||
OPENDHT_C_PUBLIC void dht_runner_delete(dht_runner* runner);
|
||||
OPENDHT_C_PUBLIC int dht_runner_loop(dht_runner* runner);
|
||||
OPENDHT_C_PUBLIC int dht_runner_join(dht_runner* runner);
|
||||
/* Returns 0 on success, standard error code on failure */
|
||||
OPENDHT_C_PUBLIC int dht_runner_run(dht_runner* runner, in_port_t port);
|
||||
/* Returns 0 on success, standard error code on failure */
|
||||
OPENDHT_C_PUBLIC int dht_runner_run_config(dht_runner* runner, in_port_t port, const dht_runner_config* config);
|
||||
OPENDHT_C_PUBLIC void dht_runner_ping(dht_runner* runner, struct sockaddr* addr, socklen_t addr_len, dht_done_cb done_cb, void* cb_user_data);
|
||||
OPENDHT_C_PUBLIC int dht_runner_run_bind(dht_runner* runner,
|
||||
const char* ipv4,
|
||||
const char* ipv6,
|
||||
in_port_t port,
|
||||
const dht_runner_config* config,
|
||||
const dht_runner_context* context);
|
||||
OPENDHT_C_PUBLIC int dht_runner_connectivity_changed(dht_runner* runner);
|
||||
OPENDHT_C_PUBLIC int dht_runner_register_type(
|
||||
dht_runner* runner, uint16_t id, const char* name, uint64_t expiration_seconds, bool insecure);
|
||||
OPENDHT_C_PUBLIC dht_publickey* dht_runner_get_publickey(const dht_runner* runner);
|
||||
OPENDHT_C_PUBLIC void dht_runner_find_certificate(
|
||||
dht_runner* runner, const dht_pkid* id, dht_certificate_cb callback, dht_shutdown_cb released_cb, void* user_data);
|
||||
OPENDHT_C_PUBLIC int dht_runner_register_certificate(dht_runner* runner, const dht_certificate* certificate);
|
||||
OPENDHT_C_PUBLIC void dht_runner_ping(
|
||||
dht_runner* runner, struct sockaddr* addr, socklen_t addr_len, dht_done_cb done_cb, void* cb_user_data);
|
||||
OPENDHT_C_PUBLIC void dht_runner_bootstrap(dht_runner* runner, const char* host, const char* service);
|
||||
OPENDHT_C_PUBLIC void dht_runner_get(dht_runner* runner, const dht_infohash* hash, dht_get_cb cb, dht_done_cb done_cb, void* cb_user_data);
|
||||
OPENDHT_C_PUBLIC dht_op_token* dht_runner_listen(dht_runner* runner, const dht_infohash* hash, dht_value_cb cb, dht_shutdown_cb done_cb, void* cb_user_data);
|
||||
OPENDHT_C_PUBLIC void dht_runner_get(
|
||||
dht_runner* runner, const dht_infohash* hash, dht_get_cb cb, dht_done_cb done_cb, void* cb_user_data);
|
||||
OPENDHT_C_PUBLIC void dht_runner_get_filtered(dht_runner* runner,
|
||||
const dht_infohash* hash,
|
||||
const char* where,
|
||||
dht_get_cb cb,
|
||||
dht_done_cb done_cb,
|
||||
void* user_data);
|
||||
OPENDHT_C_PUBLIC void dht_runner_query(dht_runner* runner,
|
||||
const dht_infohash* hash,
|
||||
const char* query,
|
||||
dht_query_cb cb,
|
||||
dht_done_cb done_cb,
|
||||
void* user_data);
|
||||
OPENDHT_C_PUBLIC dht_op_token* dht_runner_listen(
|
||||
dht_runner* runner, const dht_infohash* hash, dht_value_cb cb, dht_shutdown_cb done_cb, void* cb_user_data);
|
||||
OPENDHT_C_PUBLIC dht_op_token* dht_runner_listen_filtered(dht_runner* runner,
|
||||
const dht_infohash* hash,
|
||||
const char* where,
|
||||
dht_value_cb cb,
|
||||
dht_shutdown_cb released_cb,
|
||||
void* user_data);
|
||||
OPENDHT_C_PUBLIC void dht_runner_cancel_listen(dht_runner* runner, const dht_infohash* hash, dht_op_token* token);
|
||||
OPENDHT_C_PUBLIC void dht_runner_put(dht_runner* runner, const dht_infohash* hash, const dht_value* value, dht_done_cb done_cb, void* cb_user_data, bool permanent);
|
||||
OPENDHT_C_PUBLIC void dht_runner_put_signed(dht_runner* runner, const dht_infohash* hash, const dht_value* value, dht_done_cb done_cb, void* cb_user_data, bool permanent);
|
||||
OPENDHT_C_PUBLIC void dht_runner_put_encrypted(dht_runner* runner, const dht_infohash* hash, const dht_infohash* to, const dht_value* value, dht_done_cb done_cb, void* cb_user_data, bool permanent);
|
||||
OPENDHT_C_PUBLIC void dht_runner_put(dht_runner* runner,
|
||||
const dht_infohash* hash,
|
||||
const dht_value* value,
|
||||
dht_done_cb done_cb,
|
||||
void* cb_user_data,
|
||||
bool permanent);
|
||||
OPENDHT_C_PUBLIC void dht_runner_put_signed(dht_runner* runner,
|
||||
const dht_infohash* hash,
|
||||
const dht_value* value,
|
||||
dht_done_cb done_cb,
|
||||
void* cb_user_data,
|
||||
bool permanent);
|
||||
OPENDHT_C_PUBLIC void dht_runner_put_encrypted(dht_runner* runner,
|
||||
const dht_infohash* hash,
|
||||
const dht_pkid* to,
|
||||
const dht_value* value,
|
||||
dht_done_cb done_cb,
|
||||
void* cb_user_data,
|
||||
bool permanent);
|
||||
OPENDHT_C_PUBLIC void dht_runner_cancel_put(dht_runner* runner, const dht_infohash* hash, dht_value_id value_id);
|
||||
OPENDHT_C_PUBLIC void dht_runner_shutdown(dht_runner* runner, dht_shutdown_cb done_cb, void* cb_user_data);
|
||||
OPENDHT_C_PUBLIC dht_infohash dht_runner_get_node_id(const dht_runner* runner);
|
||||
@@ -176,6 +300,16 @@ OPENDHT_C_PUBLIC bool dht_runner_is_running(const dht_runner* runner);
|
||||
OPENDHT_C_PUBLIC in_port_t dht_runner_get_bound_port(const dht_runner* runner, sa_family_t af);
|
||||
/** Returns null-terminated array that must be freed after use as well as each element */
|
||||
OPENDHT_C_PUBLIC struct sockaddr** dht_runner_get_public_address(const dht_runner* runner);
|
||||
OPENDHT_C_PUBLIC void dht_sockaddr_array_delete(struct sockaddr** addresses);
|
||||
OPENDHT_C_PUBLIC int dht_runner_set_push_notification_token(dht_runner* runner, const char* value);
|
||||
OPENDHT_C_PUBLIC int dht_runner_set_push_notification_topic(dht_runner* runner, const char* value);
|
||||
OPENDHT_C_PUBLIC int dht_runner_set_push_notification_platform(dht_runner* runner, const char* value);
|
||||
OPENDHT_C_PUBLIC dht_push_token* dht_runner_push_notification_received(dht_runner* runner,
|
||||
const char* const* keys,
|
||||
const char* const* values,
|
||||
size_t count);
|
||||
OPENDHT_C_PUBLIC int dht_push_token_poll(dht_push_token* token, int* result);
|
||||
OPENDHT_C_PUBLIC void dht_push_token_delete(dht_push_token* token);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
|
||||
+41
-15
@@ -2,6 +2,7 @@
|
||||
|
||||
INCLUDE(CheckCXXSourceCompiles)
|
||||
INCLUDE(CheckLibraryExists)
|
||||
INCLUDE("${CMAKE_CURRENT_LIST_DIR}/DetermineGCCCompatible.cmake")
|
||||
|
||||
# Sometimes linking against libatomic is required for atomic ops, if
|
||||
# the platform doesn't support lock-free atomics.
|
||||
@@ -32,6 +33,7 @@ function(check_working_cxx_atomics64 varname)
|
||||
std::atomic<uint64_t> x (0);
|
||||
int main() {
|
||||
uint64_t i = x.load(std::memory_order_relaxed);
|
||||
(void)i;
|
||||
return 0;
|
||||
}
|
||||
" ${varname})
|
||||
@@ -39,17 +41,23 @@ int main() {
|
||||
endfunction(check_working_cxx_atomics64)
|
||||
|
||||
|
||||
# This isn't necessary on MSVC, so avoid command-line switch annoyance
|
||||
# by only running on GCC-like hosts.
|
||||
if (LLVM_COMPILER_IS_GCC_COMPATIBLE)
|
||||
# Check for (non-64-bit) atomic operations.
|
||||
if(MSVC)
|
||||
set(HAVE_CXX_ATOMICS_WITHOUT_LIB True)
|
||||
elseif(LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL")
|
||||
# First check if atomics work without the library.
|
||||
check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITHOUT_LIB)
|
||||
# If not, check if the library exists, and atomics work with it.
|
||||
if(NOT HAVE_CXX_ATOMICS_WITHOUT_LIB)
|
||||
list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
|
||||
check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITH_LIB)
|
||||
if (NOT HAVE_CXX_ATOMICS_WITH_LIB)
|
||||
message(FATAL_ERROR "Host compiler must support std::atomic!")
|
||||
check_library_exists(atomic __atomic_fetch_add_4 "" HAVE_LIBATOMIC)
|
||||
if(HAVE_LIBATOMIC)
|
||||
list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
|
||||
check_working_cxx_atomics(HAVE_CXX_ATOMICS_WITH_LIB)
|
||||
if (NOT HAVE_CXX_ATOMICS_WITH_LIB)
|
||||
message(FATAL_ERROR "Host compiler must support std::atomic!")
|
||||
endif()
|
||||
else()
|
||||
#message(FATAL_ERROR "Host compiler appears to require libatomic, but unable to find it.")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
@@ -57,17 +65,35 @@ endif()
|
||||
# Check for 64 bit atomic operations.
|
||||
if(MSVC)
|
||||
set(HAVE_CXX_ATOMICS64_WITHOUT_LIB True)
|
||||
else()
|
||||
elseif(LLVM_COMPILER_IS_GCC_COMPATIBLE OR CMAKE_CXX_COMPILER_ID MATCHES "XL")
|
||||
# First check if atomics work without the library.
|
||||
check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITHOUT_LIB)
|
||||
# If not, check if the library exists, and atomics work with it.
|
||||
if(NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB)
|
||||
check_library_exists(atomic __atomic_load_8 "" HAVE_CXX_LIBATOMICS64)
|
||||
if(HAVE_CXX_LIBATOMICS64)
|
||||
list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
|
||||
check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITH_LIB)
|
||||
if (NOT HAVE_CXX_ATOMICS64_WITH_LIB)
|
||||
message(FATAL_ERROR "Host compiler must support 64-bit std::atomic!")
|
||||
endif()
|
||||
else()
|
||||
#message(FATAL_ERROR "Host compiler appears to require libatomic for 64-bit operations, but unable to find it.")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# If not, check if the library exists, and atomics work with it.
|
||||
if(NOT HAVE_CXX_ATOMICS64_WITHOUT_LIB)
|
||||
list(APPEND CMAKE_REQUIRED_LIBRARIES "atomic")
|
||||
check_working_cxx_atomics64(HAVE_CXX_ATOMICS64_WITH_LIB)
|
||||
if (NOT HAVE_CXX_ATOMICS64_WITH_LIB)
|
||||
message(FATAL_ERROR "Host compiler must support 64-bit std::atomic!")
|
||||
# Set variable LLVM_ATOMIC_LIB specifying flags for linking against libatomic.
|
||||
if(HAVE_CXX_ATOMICS_WITH_LIB OR HAVE_CXX_ATOMICS64_WITH_LIB)
|
||||
# Use options --push-state, --as-needed and --pop-state if linker is known to support them.
|
||||
# Use single option -Wl of compiler driver to avoid incorrect re-ordering of options by CMake.
|
||||
if(LLVM_LINKER_IS_GNULD OR LLVM_LINKER_IS_GOLD OR LLVM_LINKER_IS_LLD OR LLVM_LINKER_IS_MOLD)
|
||||
set(LLVM_ATOMIC_LIB "-Wl,--push-state,--as-needed,-latomic,--pop-state")
|
||||
else()
|
||||
set(LLVM_ATOMIC_LIB "-latomic")
|
||||
endif()
|
||||
else()
|
||||
set(LLVM_ATOMIC_LIB)
|
||||
endif()
|
||||
|
||||
## TODO: This define is only used for the legacy atomic operations in
|
||||
@@ -97,4 +123,4 @@ int main() {
|
||||
|
||||
if( NOT LLVM_HAS_ATOMICS )
|
||||
message(STATUS "Warning: LLVM will be built thread-unsafe because atomic builtins are missing")
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,13 @@
|
||||
# Determine if the compiler has GCC-compatible command-line syntax.
|
||||
|
||||
if(NOT DEFINED LLVM_COMPILER_IS_GCC_COMPATIBLE)
|
||||
if(CMAKE_COMPILER_IS_GNUCXX)
|
||||
set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON)
|
||||
elseif( MSVC )
|
||||
set(LLVM_COMPILER_IS_GCC_COMPATIBLE OFF)
|
||||
elseif( "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang" )
|
||||
set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON)
|
||||
elseif( "${CMAKE_CXX_COMPILER_ID}" MATCHES "Intel" )
|
||||
set(LLVM_COMPILER_IS_GCC_COMPATIBLE ON)
|
||||
endif()
|
||||
endif()
|
||||
@@ -10,7 +10,7 @@
|
||||
# READLINE_LIBRARIES - the Readline library plus the libraries it
|
||||
# depends on
|
||||
|
||||
# Copyright (C) 2009
|
||||
# Copyright (c) 2009
|
||||
# ASTRON (Netherlands Institute for Radio Astronomy)
|
||||
# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
|
||||
#
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Windows utility functions and macros
|
||||
|
||||
# Determine Windows NT version for compatibility
|
||||
# https://stackoverflow.com/a/40217291/9560245
|
||||
macro(get_WIN32_WINNT version)
|
||||
if(CMAKE_SYSTEM_VERSION)
|
||||
set(ver ${CMAKE_SYSTEM_VERSION})
|
||||
string(REGEX MATCH "^([0-9]+).([0-9])" ver ${ver})
|
||||
string(REGEX MATCH "^([0-9]+)" verMajor ${ver})
|
||||
# Check for Windows 10, b/c we'll need to convert to hex 'A'.
|
||||
if("${verMajor}" MATCHES "10")
|
||||
set(verMajor "A")
|
||||
string(REGEX REPLACE "^([0-9]+)" ${verMajor} ver ${ver})
|
||||
endif()
|
||||
# Remove all remaining '.' characters.
|
||||
string(REPLACE "." "" ver ${ver})
|
||||
# Prepend each digit with a zero.
|
||||
string(REGEX REPLACE "([0-9A-Z])" "0\\1" ver ${ver})
|
||||
set(${version} "0x${ver}")
|
||||
endif()
|
||||
endmacro()
|
||||
-208
@@ -1,208 +0,0 @@
|
||||
dnl define macros
|
||||
m4_define([opendht_major_version], 2)
|
||||
m4_define([opendht_minor_version], 4)
|
||||
m4_define([opendht_patch_version], 0)
|
||||
m4_define([opendht_version],
|
||||
[opendht_major_version.opendht_minor_version.opendht_patch_version])
|
||||
|
||||
AC_INIT(opendht, [opendht_version])
|
||||
AC_CONFIG_AUX_DIR(ac)
|
||||
AM_INIT_AUTOMAKE([foreign subdir-objects])
|
||||
AC_CONFIG_HEADERS([config.h])
|
||||
AC_CONFIG_MACRO_DIR([m4])
|
||||
AC_CANONICAL_HOST
|
||||
|
||||
AC_SUBST(OPENDHT_MAJOR_VERSION, opendht_major_version)
|
||||
AC_SUBST(OPENDHT_MINOR_VERSION, opendht_minor_version)
|
||||
AC_SUBST(OPENDHT_PATCH_VERSION, opendht_patch_version)
|
||||
|
||||
AC_ARG_ENABLE([debug], AS_HELP_STRING([--enable-debug], [Build in debug mode, adds stricter warnings, disables optimization]))
|
||||
AS_IF([test "x$enable_debug" = "xyes"],
|
||||
[CXXFLAGS="${CXXFLAGS} -g -Wno-return-type -Wall -Wextra -Wnon-virtual-dtor -O0 -pedantic-errors"],
|
||||
[CXXFLAGS="${CXXFLAGS} -O3 -pedantic-errors"])
|
||||
|
||||
AC_PROG_CXX
|
||||
AM_PROG_AR
|
||||
|
||||
dnl Check for logs
|
||||
AC_ARG_ENABLE([logs], [AS_HELP_STRING([--disable-logs], [Disable DHT logs])])
|
||||
AS_IF([test "x$enable_logs" != "xno"], [
|
||||
AC_DEFINE([OPENDHT_LOG], [true], [Define if DHT logs are enabled])
|
||||
], [
|
||||
AC_DEFINE([OPENDHT_LOG], [false], [Define if DHT logs are enabled])
|
||||
])
|
||||
|
||||
dnl Check for indexation
|
||||
AC_ARG_ENABLE([indexation], [AS_HELP_STRING([--disable-indexation], [Disable DHT indexation])])
|
||||
AM_CONDITIONAL(ENABLE_INDEXATION, test x$enable_indexation != "xno")
|
||||
AM_COND_IF(ENABLE_INDEXATION, [
|
||||
AC_DEFINE([OPENDHT_INDEXATION], [], [Define if DHT indexation is enabled])
|
||||
])
|
||||
|
||||
AC_ARG_ENABLE([peer-discovery], [AS_HELP_STRING([--disable-peer-discovery], [Disable peer-discovery])])
|
||||
AM_CONDITIONAL(ENABLE_PEER_DISCOVERY, test x$enable_peer_discovery != "xno")
|
||||
AM_COND_IF(ENABLE_PEER_DISCOVERY, [AC_DEFINE([OPENDHT_PEER_DISCOVERY], [], [Define if peer discovery is enabled])])
|
||||
|
||||
dnl Check for Doxygen
|
||||
AC_ARG_ENABLE([doc], AS_HELP_STRING([--enable-doc], [Enable documentation generation (doxygen)]))
|
||||
AS_IF([test "x$enable_doc" = "xyes"], [
|
||||
AC_CHECK_PROGS([DOXYGEN], [doxygen])
|
||||
AS_IF([test -z "$DOXYGEN"], [AC_MSG_WARN([Doxygen not found - continuing without Doxygen support])])
|
||||
])
|
||||
AM_CONDITIONAL([HAVE_DOXYGEN], [test -n "$DOXYGEN"])
|
||||
|
||||
dnl Check for Python
|
||||
AC_ARG_ENABLE([python], [AS_HELP_STRING([--disable-python], [Disble python binding])])
|
||||
AS_IF([test "x$enable_python" != "xno"], [
|
||||
AM_PATH_PYTHON([3.3],, [:])
|
||||
AS_IF([test -n "$PYTHON"],[
|
||||
echo 'import Cython' | $PYTHON
|
||||
AS_IF([test $? == 0],[CYTHON=yes],[AC_MSG_WARN([Cython not found - continuing without python support])])
|
||||
AC_CHECK_PROGS([PIP], [pip3])
|
||||
AS_IF([test -z "$PIP"],[AC_MSG_WARN([pip not found - continuing without python uninstall support])])
|
||||
])
|
||||
])
|
||||
AM_CONDITIONAL([USE_CYTHON], [test -n "$CYTHON"])
|
||||
AM_CONDITIONAL([HAVE_PIP], [test -n "$PIP"])
|
||||
|
||||
case "${host_os}" in
|
||||
"")
|
||||
SYS=unknown
|
||||
;;
|
||||
*android*)
|
||||
SYS=android
|
||||
;;
|
||||
linux*)
|
||||
SYS=linux
|
||||
;;
|
||||
darwin*)
|
||||
SYS=darwin
|
||||
;;
|
||||
mingw32*)
|
||||
SYS=mingw32
|
||||
WIN32=1
|
||||
AC_DEFINE([_POSIX_SOURCE], [1], [IEEE Std 1003.1.])
|
||||
AC_DEFINE([_POSIX_C_SOURCE], [200809L], [IEEE Std 1003.1.])
|
||||
AC_DEFINE([_XOPEN_SOURCE], [700], [POSIX and XPG 7th edition])
|
||||
AC_DEFINE([_XOPEN_SOURCE_EXTENDED], [1], [XPG things and X/Open Unix extensions.])
|
||||
AC_DEFINE([_BSD_SOURCE], [1], [ISO C, POSIX, and 4.3BSD things.])
|
||||
LDFLAGS="${LDFLAGS} -lws2_32"
|
||||
AC_SUBST(WINDOWS_ARCH)
|
||||
AC_SUBST(PROGRAMFILES)
|
||||
;;
|
||||
*)
|
||||
SYS="${host_os}"
|
||||
;;
|
||||
esac
|
||||
|
||||
AM_CONDITIONAL(WIN32, [test "x$SYS" = "xmingw32"])
|
||||
AS_IF([test "x$SYS" = "xandroid"],
|
||||
[], [LDFLAGS="${LDFLAGS} -lpthread"])
|
||||
|
||||
LT_INIT()
|
||||
LT_LANG(C++)
|
||||
|
||||
AX_CXX_COMPILE_STDCXX(17,[noext],[mandatory])
|
||||
|
||||
PKG_PROG_PKG_CONFIG()
|
||||
|
||||
AC_ARG_ENABLE([proxy_server], AS_HELP_STRING([--enable-proxy-server], [Enable proxy server ability]), proxy_server=yes, proxy_server=no)
|
||||
AM_CONDITIONAL(ENABLE_PROXY_SERVER, test x$proxy_server == xyes)
|
||||
|
||||
AC_ARG_ENABLE([push_notifications], AS_HELP_STRING([--enable-push-notifications], [Enable push notifications support]), push_notifications=yes, push_notifications=no)
|
||||
AM_CONDITIONAL(ENABLE_PUSH_NOTIFICATIONS, test x$push_notifications == xyes)
|
||||
|
||||
AC_ARG_ENABLE([proxy_server_identity], AS_HELP_STRING([--enable-proxy-server-identity],
|
||||
[Enable proxy server ability]), proxy_server_identity=yes, proxy_server_identity=no)
|
||||
AM_CONDITIONAL(ENABLE_PROXY_SERVER_IDENTITY, test x$proxy_server_identity == xyes -a x$proxy_server == xyes)
|
||||
AC_ARG_ENABLE([proxy_server_identity], AS_HELP_STRING([--enable-proxy-server-identity],
|
||||
[Enable proxy server ability]), proxy_server_identity=yes, proxy_server_identity=no)
|
||||
|
||||
AC_ARG_ENABLE([proxy_client], AS_HELP_STRING([--enable-proxy-client], [Enable proxy client ability]), proxy_client=yes, proxy_client=no)
|
||||
AM_CONDITIONAL(ENABLE_PROXY_CLIENT, test x$proxy_client == xyes)
|
||||
|
||||
AC_ARG_ENABLE([tests], AS_HELP_STRING([--enable-tests], [Enable tests]), build_tests=yes, build_tests=no)
|
||||
AM_CONDITIONAL(ENABLE_TESTS, test x$build_tests == xyes)
|
||||
AM_COND_IF([ENABLE_TESTS], [
|
||||
PKG_CHECK_MODULES([CppUnit], [cppunit >= 1.12])
|
||||
])
|
||||
|
||||
AM_CONDITIONAL(PROXY_CLIENT_OR_SERVER, test x$proxy_client == xyes || test x$proxy_server == xyes)
|
||||
|
||||
PKG_CHECK_MODULES([Nettle], [nettle >= 2.4])
|
||||
PKG_CHECK_MODULES([GnuTLS], [gnutls >= 3.3])
|
||||
PKG_CHECK_MODULES([MsgPack], [msgpack >= 1.2])
|
||||
PKG_CHECK_MODULES([Argon2], [libargon2])
|
||||
AC_SUBST(argon2_lib, [", libargon2"])
|
||||
|
||||
AC_ARG_WITH([jsoncpp], AS_HELP_STRING([--without-jsoncpp], [Build without JsonCpp support]))
|
||||
AS_IF([test "x$with_jsoncpp" != "xno"],
|
||||
[PKG_CHECK_MODULES([JsonCpp], [jsoncpp >= 1.7.2], [have_jsoncpp=yes], [have_jsoncpp=no])],
|
||||
[have_jsoncpp=no])
|
||||
AS_IF([test "x$have_jsoncpp" = "xyes"], [
|
||||
AC_MSG_NOTICE([Using JsonCpp])
|
||||
CPPFLAGS+=" -DOPENDHT_JSONCPP"
|
||||
AC_SUBST(jsoncpp_lib, [", jsoncpp"])
|
||||
], [
|
||||
AC_MSG_NOTICE([Not using JsonCpp])
|
||||
AM_COND_IF(PROXY_CLIENT_OR_SERVER, AC_MSG_ERROR(["JsonCpp is required for proxy/push notification support"]))
|
||||
])
|
||||
|
||||
AC_ARG_WITH([openssl], AS_HELP_STRING([--without-openssl], [Build with OpenSSL support]))
|
||||
AS_IF([test "x$with_openssl" != "xno"],
|
||||
[PKG_CHECK_MODULES([OpenSSL], [openssl >= 1.1], [have_openssl=yes], [have_openssl=no])],
|
||||
[have_openssl=no])
|
||||
AS_IF([test "x$have_openssl" = "xyes"], [
|
||||
AC_MSG_NOTICE([Using OpenSSL])
|
||||
AC_SUBST(openssl_lib, [", openssl"])
|
||||
], [
|
||||
AC_MSG_NOTICE([Not using OpenSSL])
|
||||
])
|
||||
|
||||
AM_COND_IF([PROXY_CLIENT_OR_SERVER], [
|
||||
AC_CHECK_HEADERS([asio.hpp], exit,, AC_MSG_ERROR([Missing Asio headers files]))
|
||||
CXXFLAGS="${CXXFLAGS} -DASIO_STANDALONE"
|
||||
PKG_CHECK_MODULES([Fmt], [fmt >= 5.3.0], [have_fmt=yes], [have_fmt=no])
|
||||
AS_IF([test "x$have_fmt" = "xyes"], [
|
||||
AC_MSG_NOTICE([Using libfmt])
|
||||
], [
|
||||
AC_MSG_NOTICE([Missing libfmt files])
|
||||
])
|
||||
# http_parser has no pkgconfig, instead we check with:
|
||||
AC_CHECK_LIB(http_parser, exit,, AC_MSG_ERROR([Missing HttpParser library files]))
|
||||
AC_CHECK_HEADERS([http_parser.h], [http_parser_headers=yes; break;])
|
||||
AC_SUBST(http_parser_lib, ["-lhttp_parser"])
|
||||
AS_IF([test "x$http_parser_headers" != "xyes"], AC_MSG_ERROR([Missing HttpParser headers files]))
|
||||
])
|
||||
|
||||
CXXFLAGS="${CXXFLAGS} -DMSGPACK_NO_BOOST -DMSGPACK_DISABLE_LEGACY_NIL -DMSGPACK_DISABLE_LEGACY_CONVERT"
|
||||
|
||||
AC_ARG_ENABLE([tools], AS_HELP_STRING([--disable-tools],[Disable tools (CLI DHT node)]),,build_tools=yes)
|
||||
AM_CONDITIONAL(ENABLE_TOOLS, test x$build_tools == xyes)
|
||||
AM_COND_IF([ENABLE_TOOLS], [
|
||||
AC_CHECK_HEADERS([readline/readline.h readline/history.h], [], [
|
||||
AC_MSG_ERROR([unable to find readline.h])
|
||||
])
|
||||
])
|
||||
|
||||
AM_COND_IF(ENABLE_PROXY_SERVER, AC_DEFINE([OPENDHT_PROXY_SERVER], [], [Building with proxy server]))
|
||||
AM_COND_IF(ENABLE_PROXY_CLIENT, AC_DEFINE([OPENDHT_PROXY_CLIENT], [], [Building with proxy client]))
|
||||
AM_COND_IF(ENABLE_PUSH_NOTIFICATIONS, [CPPFLAGS+=" -DOPENDHT_PUSH_NOTIFICATIONS"], [])
|
||||
AM_COND_IF(ENABLE_PROXY_SERVER_IDENTITY, [CPPFLAGS+=" -DOPENDHT_PROXY_SERVER_IDENTITY"], [])
|
||||
|
||||
dnl Configure setup.py if we build the python module
|
||||
AC_SUBST(CURRENT_SOURCE_DIR, ".")
|
||||
AC_SUBST(CURRENT_BINARY_DIR, ".")
|
||||
AC_SUBST(PROJECT_SOURCE_DIR, "..")
|
||||
AC_SUBST(PROJECT_BINARY_DIR, "../src/.libs")
|
||||
|
||||
AC_CONFIG_FILES([Makefile
|
||||
src/Makefile
|
||||
tools/Makefile
|
||||
python/Makefile
|
||||
python/setup.py
|
||||
tests/Makefile
|
||||
doc/Makefile
|
||||
doc/Doxyfile
|
||||
opendht.pc])
|
||||
AC_OUTPUT
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
if (OPENDHT_TOOLS)
|
||||
INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/dhtnode.1 DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man/man1)
|
||||
INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/dhtnode.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
|
||||
endif ()
|
||||
|
||||
if (OPENDHT_DOCUMENTATION)
|
||||
@@ -12,5 +12,5 @@ if (OPENDHT_DOCUMENTATION)
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
|
||||
COMMENT "Generating API documentation with Doxygen"
|
||||
VERBATIM)
|
||||
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html DESTINATION share/doc/opendht)
|
||||
install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/html DESTINATION ${CMAKE_INSTALL_DOCDIR}/opendht)
|
||||
endif()
|
||||
@@ -1,16 +0,0 @@
|
||||
dist_man1_MANS = dhtnode.1
|
||||
|
||||
noinst_HEADERS = \
|
||||
Doxyfile
|
||||
|
||||
if HAVE_DOXYGEN
|
||||
doxyfile.stamp: Doxyfile
|
||||
$(DOXYGEN) Doxyfile
|
||||
echo stamp > doxyfile.stamp
|
||||
|
||||
CLEANFILES = doxyfile.stamp
|
||||
|
||||
all-local: doxyfile.stamp
|
||||
clean-local:
|
||||
rm -rf $(top_srcdir)/doc/man $(top_srcdir)/doc/html
|
||||
endif
|
||||
+205
-55
@@ -1,101 +1,251 @@
|
||||
.TH DHTNODE 1 2019-06-08
|
||||
.TH DHTNODE 1 2026-04-18
|
||||
.SH NAME
|
||||
.B dhtnode
|
||||
- a simple OpenDHT command line node runner.
|
||||
.SH SYNOPSIS
|
||||
.B dhtnode
|
||||
[\fB\-h\fR]
|
||||
[\fB\-V\fR]
|
||||
[\fB\-v\fR [\fB\-l\fR \fIlogfile\fR] [\fB\-L\fR]]
|
||||
[\fB\-i\fR [\fB\-\-save\-identity\fR \fIfile\fR]]
|
||||
[\fB\-i\fR [\fB\-I\fR \fIfile\fR]]
|
||||
[\fB\-c\fR \fIfile\fR]
|
||||
[\fB\-k\fR \fIfile\fR]
|
||||
[\fB\-m\fR \fIpassword\fR]
|
||||
[\fB\-d\fR] [\fB\-s\fR]
|
||||
[\fB\-D\fR] [\fB\-U\fR] [\fB\-P\fR]
|
||||
[\fB\-n\fR \fInetwork_id\fR]
|
||||
[\fB\-p\fR \fIlocal_port\fR]
|
||||
[\fB\-b\fR \fIbootstrap_host\fR[:\fIport\fR]]
|
||||
[\fB\-\-certificate\fR \fIfile\fR]
|
||||
[\fB\-\-privkey\fR \fIfile\fR]
|
||||
[\fB\-\-privkey\-password\fR \fIpassword\fR]
|
||||
[\fB\-\-proxyserver\fR \fIport\fR]
|
||||
[\fB\-\-proxyclient\fR \fIserver\fR]
|
||||
[\fB\-f\fR \fIpath\fR]
|
||||
[\fB\-S\fR \fIport\fR]
|
||||
[\fB\-e\fR \fIport\fR]
|
||||
[\fB\-a\fR \fIaddress\fR]
|
||||
[\fB\-w\fR \fIfile\fR]
|
||||
[\fB\-K\fR \fIfile\fR]
|
||||
[\fB\-M\fR \fIpassword\fR]
|
||||
[\fB\-C\fR \fIserver\fR]
|
||||
[\fB\-y\fR \fIendpoint\fR]
|
||||
[\fB\-z\fR \fIkey\fR]
|
||||
[\fB\-u\fR \fIbundleid\fR]
|
||||
[\fB\-\-no\-encryption\fR]
|
||||
[\fB\-\-transport\-key\fR \fIfile\fR]
|
||||
[\fB\-\-network\-authority\fR \fIkey\fR]
|
||||
[\fB\-\-network\-credential\fR \fIfile\fR]
|
||||
.br
|
||||
.B dhtnode
|
||||
\fB\-\-gen\-network\-authority\fR \fIprefix\fR
|
||||
.br
|
||||
.B dhtnode
|
||||
\fB\-\-issue\-credential\fR \fIfile\fR
|
||||
\fB\-\-authority\-key\fR \fIfile\fR
|
||||
\fB\-\-transport\-key\fR \fIfile\fR
|
||||
[\fB\-\-validity\fR \fIdays\fR]
|
||||
.SH DESCRIPTION
|
||||
Runs an OpenDHT node, with a CLI (default) or as a daemon (with \fB'-d'\fP or \fB'-s'\fP).
|
||||
Runs an OpenDHT node, with an interactive CLI (default) or as a daemon (with \fB'-d'\fP or \fB'-s'\fP).
|
||||
Commands available in the interactive shell are:
|
||||
.EE
|
||||
.EX
|
||||
h, help Print this help message.
|
||||
q, quit Quit the program.
|
||||
x, quit Quit the program.
|
||||
log Start/stop printing DHT logs.
|
||||
|
||||
Node information:
|
||||
ll Print basic information and stats about the current node.
|
||||
ls Print basic information about current searches.
|
||||
ld Print basic information about currenty stored values on this node.
|
||||
lr Print the full current routing table of this node
|
||||
ls [key] Print basic information about current search(es).
|
||||
ld [key] Print basic information about currenty stored values on this
|
||||
node (or for a specific key).
|
||||
lr Print the full current routing table of this node.
|
||||
|
||||
Operations on the DHT:
|
||||
b ip:port Ping potential node at given IP address/port.
|
||||
g [key] Get values at [key].
|
||||
l [key] Listen for value changes at [key].
|
||||
p [key] [str] Put string value at [key].
|
||||
s [key] [str] Put string value at [key], signed with our generated
|
||||
private key.
|
||||
e [key] [dest] [str] Put string value at [key], encrypted for [dest] with
|
||||
its public key (if found).
|
||||
b <ip:port> Ping potential node at given IP address/port.
|
||||
g <key> Get values at <key>.
|
||||
l <key> Listen for value changes at <key>.
|
||||
cl <key> <token> Cancel listen for <token> and <key>.
|
||||
p <key> <str> Put string value at <key>.
|
||||
pp <key> <str> Put string value at <key> (persistent version).
|
||||
cpp <key> <id> Cancel persistent put operation for <key> and
|
||||
value <id>.
|
||||
s <key> <str> Put string value at <key>, signed with our
|
||||
generated private key.
|
||||
e <key> <dest> <str> Put string value at <key>, encrypted for <dest>
|
||||
with its public key (if found).
|
||||
cc Trigger connectivity changed signal.
|
||||
|
||||
Operations with the proxy (if compiled with proxy server support):
|
||||
pst [port] <pushServer> Start the proxy interface on port.
|
||||
psx [port] Start the proxy SSL interface on port.
|
||||
psp [port] Stop the proxy interface on port.
|
||||
|
||||
Operations with the proxy (if compiled with proxy client support):
|
||||
stt [server_address] <device_key> Start the proxy client.
|
||||
stp Stop the proxy client.
|
||||
rs [token] Resubscribe to opendht.
|
||||
rp [token] Inject a push notification.
|
||||
.EE
|
||||
.SH OPTIONS
|
||||
.TP
|
||||
\fB\-h\fP
|
||||
Prints some help.
|
||||
\fB\-h\fP, \fB\-\-help\fP
|
||||
Prints help and exits.
|
||||
.TP
|
||||
\fB\-v\fP
|
||||
Enable the verbose mode (log to stdout/stderr by default)
|
||||
\fB\-V\fP, \fB\-\-version\fP
|
||||
Prints version information and exits.
|
||||
.TP
|
||||
\fB\-l\fP \fIlog_file\fP
|
||||
Write log to file instead of stdout/stderr
|
||||
\fB\-v\fP, \fB\-\-verbose\fP
|
||||
Enable verbose mode (log to stdout/stderr by default).
|
||||
.TP
|
||||
\fB\-L\fP
|
||||
Write log to syslog instead of stdout/stderr
|
||||
\fB\-l\fP \fIlogfile\fP, \fB\-\-logfile\fP \fIlogfile\fP
|
||||
Write log to file instead of stdout/stderr.
|
||||
.TP
|
||||
\fB\-i\fP
|
||||
Generate cryptographic identity for the node.
|
||||
\fB\-L\fP, \fB\-\-syslog\fP
|
||||
Write log to syslog instead of stdout/stderr (enables verbose mode).
|
||||
.TP
|
||||
\fB\-\-save\-identity\fP \fIfile\fP
|
||||
\fB\-i\fP, \fB\-\-identity\fP
|
||||
Generate a cryptographic identity (RSA key pair and self-signed certificate)
|
||||
for the node. Required to perform cryptographic operations (encrypt/sign values)
|
||||
if no private key file is provided.
|
||||
.TP
|
||||
\fB\-I\fP \fIfile\fP, \fB\-\-save\-identity\fP \fIfile\fP
|
||||
Save generated identity (certificate and private key) to given file prefix.
|
||||
Files are saved as \fIfile\fP and \fIfile\fP_ca.
|
||||
.TP
|
||||
\fB\-\-certificate\fP \fIfile\fP
|
||||
Load identity certificate from given file.
|
||||
\fB\-c\fP \fIfile\fP, \fB\-\-certificate\fP \fIfile\fP
|
||||
Load identity certificate from given file. If specified, the certificate is
|
||||
published on the DHT.
|
||||
.TP
|
||||
\fB\-\-privkey\fP \fIfile\fP
|
||||
Load identity private key from given file.
|
||||
\fB\-k\fP \fIfile\fP, \fB\-\-privkey\fP \fIfile\fP
|
||||
Load identity private key from given file. Required to perform cryptographic
|
||||
operations if no identity is generated.
|
||||
.TP
|
||||
\fB\-\-privkey\-password\fP \fIpassword\fP
|
||||
\fB\-m\fP \fIpassword\fP, \fB\-\-privkey\-password\fP \fIpassword\fP
|
||||
Password to use for private key encryption or decryption (optional).
|
||||
.TP
|
||||
\fB\-d\fP
|
||||
Run the program in daemon mode (will fork in the background).
|
||||
\fB\-d\fP, \fB\-\-daemonize\fP
|
||||
Run the program in daemon mode (will fork in the background). When verbose mode
|
||||
is enabled, logs to syslog by default.
|
||||
.TP
|
||||
\fB\-s\fP
|
||||
\fB\-s\fP, \fB\-\-service\fP
|
||||
Run the program in service mode (non\-forking daemon).
|
||||
.TP
|
||||
\fB\-D\fP
|
||||
\fB\-D\fP, \fB\-\-peer\-discovery\fP
|
||||
Enables multicast automatic local peer discovery.
|
||||
.TP
|
||||
\fB\-f\fP \fIfile\fP
|
||||
Specify a file path to persist/load the node state.
|
||||
\fB\-U\fP, \fB\-\-no\-rate\-limit\fP
|
||||
Disable rate limiting (allows unlimited requests and storage).
|
||||
.TP
|
||||
\fB\-n\fP \fInetwork_id\fP
|
||||
Specify the network id. This let you connect to distinct networks and prevents
|
||||
the merge of two different networks (available since OpenDHT v0.6.1).
|
||||
\fB\-P\fP, \fB\-\-public\-stable\fP
|
||||
Enable public stable mode.
|
||||
.TP
|
||||
\fB\-p\fP \fIlocal_port\fP
|
||||
Use UDP port \fIlocal_port\fP for the program to bind to.
|
||||
\fB\-f\fP \fIpath\fP, \fB\-\-persist\fP \fIpath\fP
|
||||
Specify a file path to persist/load the node state (routing table, values and
|
||||
generated transport key). State is written to a temporary file and renamed
|
||||
over the destination only after the write succeeds. Save failures are logged.
|
||||
.TP
|
||||
\fB\-b\fP \fIbootstrap_host\fP[:\fIport\fP]
|
||||
The program needs to be given a node to connect to the network. You use this
|
||||
option to provide the ip address of that node.
|
||||
\fB\-n\fP \fInetwork_id\fP, \fB\-\-net\fP \fInetwork_id\fP
|
||||
Specify the network id. This lets you connect to distinct networks and prevents
|
||||
the merge of two different networks. Defaults to 0 (the main public network).
|
||||
.TP
|
||||
\fB\-\-proxyserver\fP \fIlocal_port\fP
|
||||
Run a proxy server bound to this DHT node on HTTP port \fIlocal_port\fP
|
||||
\fB\-p\fP \fIlocal_port\fP, \fB\-\-port\fP \fIlocal_port\fP
|
||||
Use UDP port \fIlocal_port\fP for the program to bind to. If not set, will use
|
||||
any available port. The default OpenDHT port for public nodes is 4222.
|
||||
.TP
|
||||
\fB\-\-proxyclient\fP \fIserver\fP
|
||||
Run this DHT node in proxy client mode, and connect to \fIserver\fP
|
||||
\fB\-b\fP \fIbootstrap_host\fP[:\fIport\fP], \fB\-\-bootstrap\fP \fIbootstrap_host\fP[:\fIport\fP]
|
||||
Specify a bootstrap node address to connect to the network.
|
||||
.TP
|
||||
\fB\-S\fP \fIlocal_port\fP, \fB\-\-proxyserver\fP \fIlocal_port\fP
|
||||
Run a REST API proxy server bound to this DHT node on HTTP port \fIlocal_port\fP.
|
||||
.TP
|
||||
\fB\-e\fP \fIlocal_port\fP, \fB\-\-proxyserverssl\fP \fIlocal_port\fP
|
||||
Run a REST API proxy server with SSL bound to this DHT node on HTTPS port \fIlocal_port\fP.
|
||||
.TP
|
||||
\fB\-a\fP \fIaddress\fP, \fB\-\-proxy\-addr\fP \fIaddress\fP
|
||||
Proxy server bind address.
|
||||
.TP
|
||||
\fB\-w\fP \fIfile\fP, \fB\-\-proxy\-certificate\fP \fIfile\fP
|
||||
Load proxy SSL certificate from given file.
|
||||
.TP
|
||||
\fB\-K\fP \fIfile\fP, \fB\-\-proxy\-privkey\fP \fIfile\fP
|
||||
Load proxy SSL private key from given file.
|
||||
.TP
|
||||
\fB\-M\fP \fIpassword\fP, \fB\-\-proxy\-privkey\-password\fP \fIpassword\fP
|
||||
Password for the proxy private key encryption or decryption (optional).
|
||||
.TP
|
||||
\fB\-C\fP \fIserver\fP, \fB\-\-proxyclient\fP \fIserver\fP
|
||||
Run this DHT node in proxy client mode, and connect to \fIserver\fP.
|
||||
.TP
|
||||
\fB\-y\fP \fIendpoint\fP, \fB\-\-pushserver\fP \fIendpoint\fP
|
||||
Push notification server endpoint.
|
||||
.TP
|
||||
\fB\-z\fP \fIkey\fP, \fB\-\-devicekey\fP \fIkey\fP
|
||||
Device key for push notifications.
|
||||
.TP
|
||||
\fB\-u\fP \fIbundleid\fP, \fB\-\-bundleid\fP \fIbundleid\fP
|
||||
Bundle ID for push notifications.
|
||||
.SH TRANSPORT ENCRYPTION
|
||||
The DHT protocol is encrypted with nodes supporting it, and stays in plaintext
|
||||
with older nodes. The node ID derives from the transport key.
|
||||
.TP
|
||||
\fB\-\-no\-encryption\fP
|
||||
Disable protocol encryption, using a random node ID like older versions.
|
||||
.TP
|
||||
\fB\-\-transport\-key\fP \fIfile\fP
|
||||
Load the transport key from \fIfile\fP, or create it if it doesn't exist.
|
||||
Keeps the same node ID across restarts. Otherwise, a key is generated and kept
|
||||
in the node state if \fB\-\-persist\fP is used, or generated on each start.
|
||||
.TP
|
||||
\fB\-\-network\-authority\fP \fIkey\fP
|
||||
Join a private network: only accept nodes with a credential issued by the
|
||||
authority with public key \fIkey\fP (hexadecimal). Can be repeated.
|
||||
Requires \fB\-\-network\-credential\fP and \fB\-\-transport\-key\fP.
|
||||
.TP
|
||||
\fB\-\-network\-credential\fP \fIfile\fP
|
||||
Credential of our transport key, issued by a network authority.
|
||||
.TP
|
||||
\fB\-\-gen\-network\-authority\fP \fIprefix\fP
|
||||
Generate a network authority, save its secret key to \fIprefix\fP.key and its
|
||||
public key to \fIprefix\fP.pub, and exit. Refuses to overwrite either existing
|
||||
output path, including a dangling symlink.
|
||||
.TP
|
||||
\fB\-\-issue\-credential\fP \fIfile\fP
|
||||
Issue a credential for the key in \fB\-\-transport\-key\fP (created if needed),
|
||||
signed with \fB\-\-authority\-key\fP, save it to \fIfile\fP and exit.
|
||||
.TP
|
||||
\fB\-\-authority\-key\fP \fIfile\fP
|
||||
Network authority secret key used to issue credentials.
|
||||
.TP
|
||||
\fB\-\-validity\fP \fIdays\fP
|
||||
Validity of issued credentials (default: 365 days).
|
||||
.SH EXAMPLES
|
||||
Run a node using bootstrap.jami.net as a bootstrap:
|
||||
.PP
|
||||
.EX
|
||||
dhtnode -b bootstrap.jami.net:4222
|
||||
.EE
|
||||
.PP
|
||||
Run a node as a non-forking daemon on port 4222:
|
||||
.PP
|
||||
.EX
|
||||
dhtnode -b bootstrap.jami.net -p 4222 -s
|
||||
.EE
|
||||
.PP
|
||||
Run a proxy server on port 8000:
|
||||
.PP
|
||||
.EX
|
||||
dhtnode -b bootstrap.jami.net:4222 --proxyserver 8000
|
||||
.EE
|
||||
.PP
|
||||
Use a proxy client to connect to a proxy server:
|
||||
.PP
|
||||
.EX
|
||||
dhtnode --proxyclient dhtproxy.jami.net:80
|
||||
.EE
|
||||
.PP
|
||||
Create a private network and run one of its nodes:
|
||||
.PP
|
||||
.EX
|
||||
dhtnode --gen-network-authority net
|
||||
dhtnode --issue-credential node1.cred --authority-key net.key --transport-key node1.key
|
||||
dhtnode --transport-key node1.key --network-credential node1.cred \\
|
||||
--network-authority $(cat net.pub) -b 192.0.2.1:4222
|
||||
.EE
|
||||
.SH AUTHORS
|
||||
.TP
|
||||
Program written by
|
||||
|
||||
+16
-12
@@ -1,16 +1,20 @@
|
||||
FROM ghcr.io/savoirfairelinux/opendht/opendht-deps:latest
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source https://github.com/savoirfairelinux/opendht
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN git clone https://github.com/savoirfairelinux/opendht.git \
|
||||
&& cd opendht && mkdir build && cd build \
|
||||
&& cmake .. -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=On \
|
||||
-DOPENDHT_C=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On \
|
||||
-DOPENDHT_PYTHON=On \
|
||||
-DOPENDHT_TOOLS=On \
|
||||
-DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On \
|
||||
&& make -j8 && make install \
|
||||
COPY . opendht
|
||||
|
||||
RUN cd opendht && mkdir build && cd build \
|
||||
&& cmake -GNinja .. -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DBUILD_TESTING=Off \
|
||||
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=On \
|
||||
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DOPENDHT_C=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On \
|
||||
-DOPENDHT_PYTHON=On \
|
||||
-DOPENDHT_TOOLS=On \
|
||||
-DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On \
|
||||
-DOPENDHT_SYSTEMD=On \
|
||||
&& ninja && ninja install \
|
||||
&& cd ../.. && rm -rf opendht
|
||||
@@ -0,0 +1,39 @@
|
||||
FROM ghcr.io/savoirfairelinux/opendht/opendht-deps-alpine:latest AS build
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
COPY . opendht
|
||||
|
||||
RUN mkdir /install
|
||||
ENV DESTDIR=/install
|
||||
|
||||
RUN cd opendht && mkdir build && cd build \
|
||||
&& cmake .. -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=On \
|
||||
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DBUILD_TESTING=Off \
|
||||
-DOPENDHT_C=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On \
|
||||
-DOPENDHT_PYTHON=On \
|
||||
-DOPENDHT_TOOLS=On \
|
||||
-DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On \
|
||||
-DOPENDHT_SYSTEMD=On \
|
||||
&& make -j8 && make install
|
||||
|
||||
FROM alpine:3.24 AS install
|
||||
COPY --from=build /install /
|
||||
RUN apk add --no-cache \
|
||||
libstdc++ \
|
||||
gnutls \
|
||||
nettle \
|
||||
openssl \
|
||||
argon2-dev \
|
||||
jsoncpp \
|
||||
llhttp \
|
||||
fmt \
|
||||
readline \
|
||||
ncurses
|
||||
CMD ["dhtnode", "-b", "bootstrap.jami.net", "-p", "4222", "--proxyserver", "8080"]
|
||||
EXPOSE 4222/udp
|
||||
EXPOSE 8080/tcp
|
||||
@@ -0,0 +1,40 @@
|
||||
FROM opendht-alpine-edge-deps:latest AS build
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
COPY . opendht
|
||||
|
||||
RUN mkdir /install
|
||||
ENV DESTDIR=/install
|
||||
|
||||
RUN cd opendht && mkdir build && cd build \
|
||||
&& cmake .. -GNinja -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DOPENDHT_DOWNLOAD_DEPS=Off \
|
||||
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=On \
|
||||
-DOPENDHT_C=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On \
|
||||
-DOPENDHT_PYTHON=On \
|
||||
-DOPENDHT_TOOLS=On \
|
||||
-DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On \
|
||||
-DOPENDHT_SYSTEMD=On \
|
||||
&& ninja && ninja install
|
||||
|
||||
FROM alpine:edge AS install
|
||||
COPY --from=build /install /
|
||||
RUN apk add --no-cache \
|
||||
libstdc++ \
|
||||
gnutls \
|
||||
nettle \
|
||||
openssl \
|
||||
argon2-dev \
|
||||
jsoncpp \
|
||||
llhttp \
|
||||
fmt \
|
||||
simdutf \
|
||||
readline \
|
||||
ncurses
|
||||
CMD ["dhtnode", "-b", "bootstrap.jami.net", "-p", "4222", "--proxyserver", "8080"]
|
||||
EXPOSE 4222/udp
|
||||
EXPOSE 8080/tcp
|
||||
+23
-17
@@ -1,28 +1,34 @@
|
||||
FROM ubuntu:20.04
|
||||
FROM ubuntu:26.04
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source https://github.com/savoirfairelinux/opendht
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
dialog apt-utils \
|
||||
dialog apt-utils \
|
||||
&& apt-get clean \
|
||||
&& echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential pkg-config cmake git wget \
|
||||
autotools-dev autoconf \
|
||||
cython3 python3-dev python3-setuptools \
|
||||
libncurses5-dev libreadline-dev nettle-dev libcppunit-dev \
|
||||
libgnutls28-dev libuv1-dev libjsoncpp-dev libargon2-dev \
|
||||
libssl-dev libfmt-dev libhttp-parser-dev libasio-dev libmsgpack-dev \
|
||||
build-essential pkg-config cmake git wget meson ninja-build \
|
||||
libtool \
|
||||
python3-dev python3-setuptools python3-build python3-virtualenv cython3 \
|
||||
libncurses5-dev libreadline-dev nettle-dev libcppunit-dev \
|
||||
libgnutls28-dev libuv1-dev libjsoncpp-dev libargon2-dev \
|
||||
libssl-dev libfmt-dev libasio-dev libmsgpack-cxx-dev \
|
||||
libllhttp-dev libsimdutf-dev \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/* /var/cache/apt/*
|
||||
|
||||
RUN mkdir /usr/include/nonstd \
|
||||
&& wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp \
|
||||
-O /usr/include/nonstd/expected.hpp
|
||||
|
||||
ARG RESTINIO_VERSION=0.7.10
|
||||
RUN echo "*** Downloading RESTinio ***" \
|
||||
&& mkdir restinio && cd restinio \
|
||||
&& wget https://github.com/aberaud/restinio/archive/e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz \
|
||||
&& ls -l && tar -xzf e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz \
|
||||
&& cd restinio-e0a261dd8488246a3cb8bbb3ea781ea5139c3c94/dev \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=OFF -DRESTINIO_SAMPLE=OFF \
|
||||
-DRESTINIO_INSTALL_SAMPLES=OFF -DRESTINIO_BENCH=OFF -DRESTINIO_INSTALL_BENCHES=OFF \
|
||||
-DRESTINIO_FIND_DEPS=ON -DRESTINIO_ALLOW_SOBJECTIZER=Off -DRESTINIO_USE_BOOST_ASIO=none . \
|
||||
&& make -j8 && make install \
|
||||
&& cd ../../.. && rm -rf restinio
|
||||
&& wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& ls -l && tar -xjf "restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& cd "restinio-${RESTINIO_VERSION}/dev" \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system . \
|
||||
&& make -j2 && make install \
|
||||
&& cd ../../ && rm -rf restinio*
|
||||
@@ -0,0 +1,28 @@
|
||||
FROM alpine:3.24
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN apk add --no-cache \
|
||||
build-base cmake ninja git wget \
|
||||
cython python3-dev py3-setuptools \
|
||||
ncurses-dev readline-dev nettle-dev \
|
||||
cppunit-dev gnutls-dev jsoncpp-dev \
|
||||
argon2-dev openssl-dev fmt-dev simdutf-dev \
|
||||
llhttp-dev asio-dev msgpack-cxx-dev \
|
||||
&& rm -rf /var/cache/apk/*
|
||||
|
||||
RUN mkdir /usr/include/nonstd \
|
||||
&& wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp \
|
||||
-O /usr/include/nonstd/expected.hpp
|
||||
|
||||
ARG RESTINIO_VERSION=0.7.10
|
||||
RUN echo "*** Downloading RESTinio ***" \
|
||||
&& mkdir restinio && cd restinio \
|
||||
&& wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& ls -l && tar -xjf "restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& cd "restinio-${RESTINIO_VERSION}/dev" \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system . \
|
||||
&& make -j2 && make install \
|
||||
&& cd ../../ && rm -rf restinio*
|
||||
@@ -0,0 +1,28 @@
|
||||
FROM alpine:edge
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN apk add --no-cache \
|
||||
build-base cmake ninja git wget \
|
||||
cython python3-dev py3-setuptools \
|
||||
ncurses-dev readline-dev nettle-dev \
|
||||
cppunit-dev gnutls-dev jsoncpp-dev \
|
||||
argon2-dev openssl-dev fmt-dev simdutf-dev \
|
||||
llhttp-dev asio-dev msgpack-cxx-dev \
|
||||
&& rm -rf /var/cache/apk/*
|
||||
|
||||
RUN mkdir /usr/include/nonstd \
|
||||
&& wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp \
|
||||
-O /usr/include/nonstd/expected.hpp
|
||||
|
||||
ARG RESTINIO_VERSION=0.7.10
|
||||
RUN echo "*** Downloading RESTinio ***" \
|
||||
&& mkdir restinio && cd restinio \
|
||||
&& wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& ls -l && tar -xjf "restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& cd "restinio-${RESTINIO_VERSION}/dev" \
|
||||
&& cmake -GNinja -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system . \
|
||||
&& ninja && ninja install \
|
||||
&& cd ../../ && rm -rf restinio*
|
||||
@@ -1,32 +0,0 @@
|
||||
FROM ubuntu:18.04
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN echo "APT::Acquire::Retries \"3\";" > /etc/apt/apt.conf.d/80-retries
|
||||
RUN apt-get update && apt-get install -y \
|
||||
apt-transport-https build-essential pkg-config git wget libncurses5-dev libreadline-dev nettle-dev \
|
||||
libgnutls28-dev libuv1-dev cython3 python3-dev python3-setuptools libcppunit-dev libjsoncpp-dev \
|
||||
libargon2-0-dev \
|
||||
autotools-dev autoconf libfmt-dev libhttp-parser-dev libmsgpack-dev libssl-dev python3-pip \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/* /var/cache/apt/*
|
||||
|
||||
RUN pip3 install --upgrade cmake
|
||||
|
||||
# libasio-dev (1.10) is too old
|
||||
RUN echo "** Building a recent version of asio ***" \
|
||||
&& wget https://github.com/aberaud/asio/archive/a7d66ef4017d8f1b7f2cef1bb4ba8e23b0961571.tar.gz \
|
||||
&& tar -xvf a7d66ef4017d8f1b7f2cef1bb4ba8e23b0961571.tar.gz && cd asio-a7d66ef4017d8f1b7f2cef1bb4ba8e23b0961571/asio \
|
||||
&& ./autogen.sh && ./configure --prefix=/usr --without-boost --disable-examples --disable-tests \
|
||||
&& make install \
|
||||
&& cd ../../ && rm -rf asio*
|
||||
|
||||
RUN echo "*** Downloading RESTinio ***" \
|
||||
&& mkdir restinio && cd restinio \
|
||||
&& wget https://github.com/aberaud/restinio/archive/8d5d3e8237e0947adb9ba1ffc8281f4ad7cb2a59.tar.gz \
|
||||
&& ls -l && tar -xzf 8d5d3e8237e0947adb9ba1ffc8281f4ad7cb2a59.tar.gz \
|
||||
&& cd restinio-8d5d3e8237e0947adb9ba1ffc8281f4ad7cb2a59/dev \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=OFF -DRESTINIO_SAMPLE=OFF \
|
||||
-DRESTINIO_INSTALL_SAMPLES=OFF -DRESTINIO_BENCH=OFF -DRESTINIO_INSTALL_BENCHES=OFF \
|
||||
-DRESTINIO_FIND_DEPS=ON -DRESTINIO_ALLOW_SOBJECTIZER=Off -DRESTINIO_USE_BOOST_ASIO=none . \
|
||||
&& make -j8 && make install \
|
||||
&& cd ../../ && rm -rf restinio*
|
||||
@@ -0,0 +1,48 @@
|
||||
FROM ubuntu:20.04
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
dialog apt-utils \
|
||||
&& apt-get clean \
|
||||
&& echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential pkg-config cmake git wget \
|
||||
libtool \
|
||||
python3-dev python3-setuptools python3-pip \
|
||||
libncurses5-dev libreadline-dev nettle-dev libcppunit-dev \
|
||||
libgnutls28-dev libuv1-dev libjsoncpp-dev libargon2-dev \
|
||||
libssl-dev libfmt-dev libasio-dev libmsgpack-dev \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/* /var/cache/apt/*
|
||||
|
||||
RUN pip3 install meson Cython
|
||||
|
||||
ARG SIMDUTF_VERSION=8.0.0
|
||||
RUN mkdir simdutf \
|
||||
&& wget -q "https://github.com/simdutf/simdutf/archive/refs/tags/v${SIMDUTF_VERSION}.tar.gz" -O simdutf.tar.gz \
|
||||
&& tar -xzf simdutf.tar.gz -C simdutf --strip-components=1 \
|
||||
&& cmake -S simdutf -B simdutf/build -DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr/local -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
|
||||
-DBUILD_SHARED_LIBS=OFF -DSIMDUTF_TESTS=OFF -DSIMDUTF_TOOLS=OFF \
|
||||
&& cmake --build simdutf/build --parallel 2 \
|
||||
&& cmake --install simdutf/build \
|
||||
&& install -D simdutf/LICENSE-MIT /usr/share/doc/simdutf/LICENSE-MIT \
|
||||
&& install -D simdutf/LICENSE-APACHE /usr/share/doc/simdutf/LICENSE-APACHE \
|
||||
&& rm -rf simdutf simdutf.tar.gz
|
||||
|
||||
RUN mkdir /usr/include/nonstd \
|
||||
&& wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp \
|
||||
-O /usr/include/nonstd/expected.hpp
|
||||
|
||||
ARG RESTINIO_VERSION=0.7.10
|
||||
RUN echo "*** Downloading RESTinio ***" \
|
||||
&& mkdir restinio && cd restinio \
|
||||
&& wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& ls -l && tar -xjf "restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& cd "restinio-${RESTINIO_VERSION}/dev" \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system . \
|
||||
&& make -j2 && make install \
|
||||
&& cd ../../ && rm -rf restinio*
|
||||
+25
-17
@@ -1,31 +1,39 @@
|
||||
FROM ubuntu:20.04
|
||||
FROM ubuntu:26.04
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source https://github.com/savoirfairelinux/opendht
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
dialog apt-utils \
|
||||
dialog apt-utils \
|
||||
&& apt-get clean \
|
||||
&& echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y llvm llvm-dev lldb clang gdb make cmake pkg-config git wget libncurses5-dev libreadline-dev \
|
||||
nettle-dev libgnutls28-dev libuv1-dev libmsgpack-dev libjsoncpp-dev cython3 python3-dev \
|
||||
python3-setuptools libcppunit-dev python3-pip \
|
||||
autotools-dev autoconf libssl-dev libargon2-dev \
|
||||
libfmt-dev libhttp-parser-dev libasio-dev \
|
||||
&& apt-get install -y llvm llvm-dev lldb clang gdb make cmake meson pkg-config \
|
||||
libtool git wget libncurses5-dev libreadline-dev \
|
||||
nettle-dev libgnutls28-dev libuv1-dev libmsgpack-cxx-dev libjsoncpp-dev python3-dev \
|
||||
python3-setuptools libcppunit-dev python3-pip python3-build python3-virtualenv \
|
||||
libssl-dev libargon2-dev libllhttp-dev libsimdutf-dev \
|
||||
libfmt-dev libasio-dev \
|
||||
&& apt-get remove -y gcc g++ && apt-get autoremove -y \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/* /var/cache/apt/*
|
||||
|
||||
ENV CC cc
|
||||
ENV CXX c++
|
||||
RUN pip3 install Cython --break-system-packages
|
||||
|
||||
ENV CC=cc
|
||||
ENV CXX=c++
|
||||
|
||||
RUN mkdir /usr/include/nonstd \
|
||||
&& wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp \
|
||||
-O /usr/include/nonstd/expected.hpp
|
||||
|
||||
ARG RESTINIO_VERSION=0.7.10
|
||||
RUN echo "*** Downloading RESTinio ***" \
|
||||
&& mkdir restinio && cd restinio \
|
||||
&& wget https://github.com/aberaud/restinio/archive/e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz \
|
||||
&& ls -l && tar -xzf e0a261dd8488246a3cb8bbb3ea781ea5139c3c94.tar.gz \
|
||||
&& cd restinio-e0a261dd8488246a3cb8bbb3ea781ea5139c3c94/dev \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=OFF -DRESTINIO_SAMPLE=OFF \
|
||||
-DRESTINIO_INSTALL_SAMPLES=OFF -DRESTINIO_BENCH=OFF -DRESTINIO_INSTALL_BENCHES=OFF \
|
||||
-DRESTINIO_FIND_DEPS=ON -DRESTINIO_ALLOW_SOBJECTIZER=Off -DRESTINIO_USE_BOOST_ASIO=none . \
|
||||
&& make -j8 && make install \
|
||||
&& wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& ls -l && tar -xjf "restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& cd "restinio-${RESTINIO_VERSION}/dev" \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system . \
|
||||
&& make -j2 && make install \
|
||||
&& cd ../../ && rm -rf restinio*
|
||||
@@ -0,0 +1,56 @@
|
||||
FROM ubuntu:24.04
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
dialog apt-utils \
|
||||
&& apt-get clean \
|
||||
&& echo 'debconf debconf/frontend select Noninteractive' | debconf-set-selections
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential pkg-config cmake git wget meson ninja-build patchelf \
|
||||
libtool \
|
||||
python3-dev python3-setuptools python3-build python3-virtualenv cython3 \
|
||||
libncurses5-dev libreadline-dev nettle-dev libcppunit-dev \
|
||||
libgnutls28-dev libuv1-dev libjsoncpp-dev libargon2-dev \
|
||||
libssl-dev libfmt-dev libasio-dev libmsgpack-cxx-dev \
|
||||
&& apt-get clean && rm -rf /var/lib/apt/lists/* /var/cache/apt/*
|
||||
|
||||
ARG LLHTTP_VERSION=9.2.1
|
||||
RUN mkdir llhttp \
|
||||
&& wget -q "https://github.com/nodejs/llhttp/archive/refs/tags/release/v${LLHTTP_VERSION}.tar.gz" -O llhttp.tar.gz \
|
||||
&& tar -xzf llhttp.tar.gz -C llhttp --strip-components=1 \
|
||||
&& cmake -S llhttp -B llhttp/build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
&& cmake --build llhttp/build --parallel 2 \
|
||||
&& cmake --install llhttp/build \
|
||||
&& rm -rf llhttp llhttp.tar.gz
|
||||
|
||||
ARG SIMDUTF_VERSION=8.0.0
|
||||
RUN mkdir simdutf \
|
||||
&& wget -q "https://github.com/simdutf/simdutf/archive/refs/tags/v${SIMDUTF_VERSION}.tar.gz" -O simdutf.tar.gz \
|
||||
&& tar -xzf simdutf.tar.gz -C simdutf --strip-components=1 \
|
||||
&& cmake -S simdutf -B simdutf/build -DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr/local -DCMAKE_POSITION_INDEPENDENT_CODE=ON \
|
||||
-DBUILD_SHARED_LIBS=OFF -DSIMDUTF_TESTS=OFF -DSIMDUTF_TOOLS=OFF \
|
||||
&& cmake --build simdutf/build --parallel 2 \
|
||||
&& cmake --install simdutf/build \
|
||||
&& install -D simdutf/LICENSE-MIT /usr/share/doc/simdutf/LICENSE-MIT \
|
||||
&& install -D simdutf/LICENSE-APACHE /usr/share/doc/simdutf/LICENSE-APACHE \
|
||||
&& rm -rf simdutf simdutf.tar.gz
|
||||
|
||||
RUN mkdir /usr/include/nonstd \
|
||||
&& wget https://raw.githubusercontent.com/martinmoene/expected-lite/master/include/nonstd/expected.hpp \
|
||||
-O /usr/include/nonstd/expected.hpp
|
||||
|
||||
ARG RESTINIO_VERSION=0.7.10
|
||||
RUN echo "*** Downloading RESTinio ***" \
|
||||
&& mkdir restinio && cd restinio \
|
||||
&& wget "https://github.com/Stiffstream/restinio/releases/download/v${RESTINIO_VERSION}/restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& ls -l && tar -xjf "restinio-${RESTINIO_VERSION}.tar.bz2" \
|
||||
&& cd "restinio-${RESTINIO_VERSION}/dev" \
|
||||
&& cmake -DCMAKE_INSTALL_PREFIX=/usr -DRESTINIO_TEST=Off -DRESTINIO_SAMPLE=Off -DRESTINIO_BENCHMARK=Off \
|
||||
-DRESTINIO_WITH_SOBJECTIZER=Off -DRESTINIO_DEP_STANDALONE_ASIO=system -DRESTINIO_DEP_LLHTTP=system \
|
||||
-DRESTINIO_DEP_FMT=system -DRESTINIO_DEP_EXPECTED_LITE=system . \
|
||||
&& make -j2 && make install \
|
||||
&& cd ../../ && rm -rf restinio* \
|
||||
&& ldconfig
|
||||
@@ -0,0 +1,4 @@
|
||||
FROM ghcr.io/savoirfairelinux/opendht/opendht:latest
|
||||
CMD ["dhtnode", "-b", "bootstrap.jami.net", "-p", "4222", "--proxyserver", "8080"]
|
||||
EXPOSE 4222/udp
|
||||
EXPOSE 8080/tcp
|
||||
@@ -1,11 +1,14 @@
|
||||
FROM ghcr.io/savoirfairelinux/opendht/opendht-deps-bionic:latest
|
||||
FROM ghcr.io/savoirfairelinux/opendht/opendht-deps-focal:latest
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source https://github.com/savoirfairelinux/opendht
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN git clone https://github.com/savoirfairelinux/opendht.git \
|
||||
&& cd opendht && mkdir build && cd build \
|
||||
COPY . opendht
|
||||
|
||||
RUN cd opendht && mkdir build && cd build \
|
||||
&& cmake .. -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DBUILD_TESTING=Off \
|
||||
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=On \
|
||||
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DOPENDHT_C=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On \
|
||||
-DOPENDHT_PYTHON=On \
|
||||
@@ -1,16 +1,19 @@
|
||||
FROM ghcr.io/savoirfairelinux/opendht/opendht-deps-llvm:latest
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source https://github.com/savoirfairelinux/opendht
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
RUN git clone https://github.com/savoirfairelinux/opendht.git \
|
||||
&& cd opendht && mkdir build && cd build \
|
||||
COPY . opendht
|
||||
|
||||
RUN cd opendht && mkdir build && cd build \
|
||||
&& cmake .. -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=On \
|
||||
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DOPENDHT_C=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On \
|
||||
-DOPENDHT_PYTHON=On \
|
||||
-DOPENDHT_TOOLS=On \
|
||||
-DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On \
|
||||
-DOPENDHT_SYSTEMD=On \
|
||||
&& make -j8 && make install \
|
||||
&& cd ../.. && rm -rf opendht
|
||||
@@ -0,0 +1,20 @@
|
||||
FROM ghcr.io/savoirfairelinux/opendht/opendht-deps-noble:latest
|
||||
LABEL maintainer="Adrien Béraud <adrien.beraud@savoirfairelinux.com>"
|
||||
LABEL org.opencontainers.image.source=https://github.com/savoirfairelinux/opendht
|
||||
|
||||
COPY . opendht
|
||||
|
||||
RUN cd opendht && mkdir build && cd build \
|
||||
&& cmake .. -DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DBUILD_TESTING=Off \
|
||||
-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=On \
|
||||
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
|
||||
-DOPENDHT_C=On \
|
||||
-DOPENDHT_PEER_DISCOVERY=On \
|
||||
-DOPENDHT_PYTHON=On \
|
||||
-DOPENDHT_TOOLS=On \
|
||||
-DOPENDHT_PROXY_SERVER=On \
|
||||
-DOPENDHT_PROXY_CLIENT=On \
|
||||
-DOPENDHT_SYSTEMD=On \
|
||||
&& make -j8 && make install \
|
||||
&& cd ../.. && rm -rf opendht
|
||||
@@ -0,0 +1,564 @@
|
||||
# Transport encryption: cryptographic design
|
||||
|
||||
This document specifies how OpenDHT encrypts and authenticates the UDP DHT protocol between nodes (the "transport"), and how private networks restrict participation with a small public-key infrastructure.
|
||||
|
||||
Implementation: [include/opendht/transport.h](../include/opendht/transport.h), [src/transport.cpp](../src/transport.cpp), and the send/receive paths in [src/network_engine.cpp](../src/network_engine.cpp).
|
||||
|
||||
## 1. Scope
|
||||
|
||||
### Goals
|
||||
|
||||
- **Confidentiality and integrity** of DHT protocol messages exchanged between two nodes that both support encryption.
|
||||
- **Authenticated node IDs**: a node can only send encrypted messages under the node ID that derives from its own key.
|
||||
- **Backward compatibility**: nodes without this feature keep working with new nodes, in plaintext.
|
||||
- **Optional private networks**: when configured, a node only talks to nodes holding a credential signed by a trusted authority.
|
||||
- **Permanent membership**: grants do not expire. Without a compromise or an intentional membership change, no grant renewal, authority rotation, or operator maintenance is required.
|
||||
- **Forward secrecy**: recorded traffic stays confidential after a node's long-term key is compromised, once the ephemeral keys used for it are erased (at most one hour later). The first packet to a peer has weaker guarantees ([§5.2](#52-key-schedule)).
|
||||
- **Address validation**: a Session or Data envelope proves that its sender receives packets at its source address. It replaces the legacy write tokens between encrypted nodes ([§6.6](#66-write-authorization)).
|
||||
- **Low cost**: routing discovery also establishes the session, with a few X25519 operations per peer every 30 minutes. Once a session is established, 30 bytes of overhead per packet, minus the 40-byte token in messages that carried one.
|
||||
|
||||
### Non-goals
|
||||
|
||||
- **End-to-end protection of values.** Encryption is hop-by-hop. Nodes storing a value see it in clear. Use `SecureDht` (signed or encrypted values) for end-to-end protection. `SecureDht` identities are unrelated to transport keys.
|
||||
- **Hiding metadata**: packet sizes, timing and addresses are visible, and so are the sender's public keys until a session is established.
|
||||
- The REST proxy (`DhtProxyServer`/`DhtProxyClient`) and local peer discovery are not covered.
|
||||
|
||||
## 2. Notation
|
||||
|
||||
| Notation | Meaning |
|
||||
|---|---|
|
||||
| `a ‖ b` | Concatenation of byte strings |
|
||||
| `"text"` | ASCII bytes, without terminator |
|
||||
| `u32be(x)` | Unsigned integer, big-endian, 4 bytes |
|
||||
| `sk_A`, `pk_A` | Static transport secret and public key of node A |
|
||||
| `esk_A`, `epk_A` | Ephemeral secret and public key of node A for the address of its peer |
|
||||
| `DH(x, Y)` | `X25519(x, Y)` |
|
||||
| `N` | Network ID (`Config::network`, 32-bit, `0` by default) |
|
||||
| `K_A→B` | Key encrypting envelopes from A to B |
|
||||
|
||||
All keys are 32 bytes. Integers on the wire are big-endian.
|
||||
|
||||
## 3. Primitives
|
||||
|
||||
| Purpose | Primitive | Reference |
|
||||
|---|---|---|
|
||||
| Key agreement | X25519 | RFC 7748 |
|
||||
| Key derivation | HKDF-SHA256 | RFC 5869 |
|
||||
| Packet encryption | ChaCha20-Poly1305 AEAD, 96-bit nonce, 128-bit tag | RFC 8439 |
|
||||
| Node ID | SHA-256, truncated to 160 bits | FIPS 180-4 |
|
||||
| Credential signature | Ed25519 | RFC 8032 |
|
||||
| Randomness | `gnutls_rnd` (`GNUTLS_RND_KEY` for keys, `GNUTLS_RND_NONCE` for nonces) | |
|
||||
|
||||
Primitives come from Nettle (libnettle and libhogweed) and GnuTLS, which OpenDHT already depends on. All primitives are used through their standard interfaces with no modification. The authentication tag is compared in constant time. Secret keys are erased with `gnutls_memset`.
|
||||
|
||||
## 4. Keys and identities
|
||||
|
||||
### 4.1 Transport key
|
||||
|
||||
Each node has a static X25519 key pair, its long-term identity:
|
||||
|
||||
```
|
||||
sk = 32 random bytes
|
||||
pk = X25519(sk, 9)
|
||||
```
|
||||
|
||||
The key is either given in `Config::transport.key`, or generated on start. A generated key is saved in the node state when `Config::persist_path` is set (see [§8](#8-key-persistence)). Otherwise, it changes on every restart, and so does the node ID.
|
||||
|
||||
The transport key is used only for the transport. It is independent of the `SecureDht` identity (an RSA certificate).
|
||||
|
||||
### 4.2 Node ID
|
||||
|
||||
When transport encryption is enabled, the node ID is derived from the public key:
|
||||
|
||||
```
|
||||
nodeId(pk) = SHA-256("opendht-node-id-v1" ‖ pk)[0..20)
|
||||
```
|
||||
|
||||
`Config::node_id` is ignored in that case. This binding is what authenticates node IDs: a receiver checks that the ID claimed inside a decrypted message equals `nodeId(pk)` of the static key the envelope was authenticated with (see [§6.5](#65-receiving)). Holding the ID therefore requires holding `sk`.
|
||||
|
||||
When encryption is disabled (`TransportConfig::enabled = false`), the node uses the legacy behavior: a random ID, or `Config::node_id`.
|
||||
|
||||
### 4.3 Network authority (private networks)
|
||||
|
||||
An authority is an Ed25519 key pair. Its secret is the 32-byte Ed25519 seed. Its public key identifies the private network, and nodes are configured with a list of trusted authority public keys (`TransportConfig::authorities`). A network is private if and only if this list is non-empty.
|
||||
|
||||
Any one trusted authority can grant membership. A node can trust multiple authorities simultaneously, allowing old and replacement grants to coexist during an explicit transition. There is no scheduled authority rotation.
|
||||
|
||||
### 4.4 Credential (private networks)
|
||||
|
||||
A membership grant, called a credential in the API and CLI, is an authority's signature over a transport public key. It never expires and contains no timestamp. It is 97 bytes:
|
||||
|
||||
```
|
||||
offset size field
|
||||
0 1 version = 0x02
|
||||
1 32 pk transport public key of the node
|
||||
33 64 signature Ed25519 signature by the authority
|
||||
```
|
||||
|
||||
The signature covers:
|
||||
|
||||
```
|
||||
"opendht-credential-v2" ‖ 0x02 ‖ pk
|
||||
```
|
||||
|
||||
A credential is **valid** when its signature verifies under at least one trusted authority. Admission does not depend on a system clock. The same grant can be reused across restarts and session-key rotations without an update.
|
||||
|
||||
Version 1 expiring credentials are rejected, not reinterpreted as permanent grants. Migrating from that format requires issuing a version 2 grant once.
|
||||
|
||||
Credentials are not bound to a network ID. An authority key therefore defines a network: use distinct authorities for distinct networks.
|
||||
|
||||
## 5. Key agreement
|
||||
|
||||
### 5.1 Ephemeral keys
|
||||
|
||||
Each node has an epoch secret `S`: 32 random bytes, replaced every 30 minutes (an *epoch*). Its ephemeral key for a peer at address `addr` derives from it:
|
||||
|
||||
```
|
||||
addr = IP (4 bytes for IPv4, including IPv4-mapped IPv6, else 16 bytes) ‖ port (2 bytes, network order)
|
||||
esk(addr) = HMAC-SHA256(key = S, "opendht-address-key-v1" ‖ addr)
|
||||
epk(addr) = X25519(esk(addr), 9)
|
||||
```
|
||||
|
||||
- The node always sends to `addr` with `epk(addr)` from its **current** epoch.
|
||||
- It still accepts envelopes addressed to its key from the **previous** epoch, so peers have one epoch to learn the new key.
|
||||
- On rotation, the previous epoch secret and every key derived from it are erased.
|
||||
|
||||
An ephemeral secret therefore lives at most one hour. Epoch secrets are never persisted, and a restart starts with a new one.
|
||||
|
||||
Nodes learn each other's ephemeral key from the header of every envelope ([§6.1](#61-envelope)). A node records a peer's ephemeral key only from an envelope it authenticated.
|
||||
|
||||
`epk(addr)` is only ever sent to `addr`. Learning it therefore requires receiving packets at `addr`, or observing the path to it. This is what makes a Session envelope a proof of address ([§6.6](#66-write-authorization)). Deriving keys per address costs one more X25519 base-point multiplication per new address, and nothing per packet.
|
||||
|
||||
### 5.2 Key schedule
|
||||
|
||||
Each envelope from a sender A to a receiver B is encrypted with a key `K_A→B`, derived with HKDF-SHA256 (RFC 5869):
|
||||
|
||||
```
|
||||
prk = HMAC-SHA256(key = "opendht-transport-v2", ikm)
|
||||
K_A→B = HMAC-SHA256(key = prk, info ‖ 0x01)
|
||||
```
|
||||
|
||||
The input keying material `ikm` and `info` depend on what A knows about B.
|
||||
|
||||
**Session**: A knows B's ephemeral key `epk_B`:
|
||||
|
||||
```
|
||||
ikm = DH(esk_A, epk_B) ‖ DH(esk_A, pk_B) ‖ DH(sk_A, epk_B) ‖ DH(sk_A, pk_B)
|
||||
info = u32be(N) ‖ 0x02 ‖ pk_A ‖ epk_A ‖ pk_B ‖ epk_B
|
||||
```
|
||||
|
||||
**Initial**: A doesn't know B's ephemeral key, typically on first contact:
|
||||
|
||||
```
|
||||
ikm = DH(esk_A, pk_B) ‖ DH(sk_A, pk_B)
|
||||
info = u32be(N) ‖ 0x01 ‖ pk_A ‖ epk_A ‖ pk_B
|
||||
```
|
||||
|
||||
B computes the same values with its own secrets, since `DH(x_A, Y_B) = DH(y_B, X_A)`. Any DH result equal to zero (a low-order public key) is rejected.
|
||||
|
||||
Properties:
|
||||
|
||||
- **Directional keys.** `info` orders the keys as sender, then receiver, so `K_A→B ≠ K_B→A`. Each node derives both from the same four DH values.
|
||||
- **Authentication.** Every key includes `DH(sk_A, pk_B)`, so only the holders of `sk_A` or `sk_B` can produce or read the envelope. Every envelope thus proves possession of the sender's static key.
|
||||
- **Forward secrecy.** A Session key includes `DH(esk_A, epk_B)`. Once both ephemeral secrets are erased, the key cannot be recomputed, even with both static secrets.
|
||||
- **Key-compromise impersonation resistance.** With `sk_B`, an attacker still cannot impersonate A to B in a Session envelope: it cannot compute `DH(sk_A, epk_B)` without `sk_A` or `esk_B`.
|
||||
- **Initial keys are weaker**, as for the first message of Noise IK. Without `epk_B`, an Initial key is only forward-secret against a later compromise of `sk_A`, not of `sk_B`. It also allows impersonating A to B with `sk_B`. Initial envelopes are only sent until A learns `epk_B`, usually for a single packet.
|
||||
- **Binding.** `info` includes `N`, the envelope type and all public keys involved. Nodes with different network IDs cannot decrypt each other's packets.
|
||||
- **Cost.** A Session key costs four X25519 operations, plus one for our ephemeral key. It is cached in the epoch, so it is derived once per peer address and ephemeral key pair, once the peer has proven to receive at that address ([§6.5](#65-receiving)). An Initial key costs two X25519 operations, plus one for our ephemeral key, and is not cached. Each epoch caches at most 16384 sessions, evicting the least recently used; beyond that, keys are derived for each packet.
|
||||
|
||||
## 6. Wire protocol
|
||||
|
||||
### 6.1 Envelope
|
||||
|
||||
Initial and Session envelopes carry the sender keys:
|
||||
|
||||
```
|
||||
offset size field
|
||||
0 1 marker = 0xC1
|
||||
1 1 type: 1 = Initial, 2 = Session, 3 = Hello; | 0x80 if a credential is included
|
||||
2 32 pk_sender
|
||||
34 32 epk_sender
|
||||
66 12 nonce (random)
|
||||
78 len ciphertext
|
||||
78+len 16 Poly1305 tag
|
||||
```
|
||||
|
||||
Once the session is confirmed ([§6.4](#64-sending)), Data envelopes leave them out. The receiver finds the session keys from the source address:
|
||||
|
||||
```
|
||||
offset size field
|
||||
0 1 marker = 0xC1
|
||||
1 1 type = 4 (Data), never with a credential
|
||||
2 12 nonce (random)
|
||||
14 len ciphertext
|
||||
14+len 16 Poly1305 tag
|
||||
```
|
||||
|
||||
- The ciphertext is `ChaCha20-Poly1305(K_sender→receiver, nonce, plaintext, aad = header)`.
|
||||
- The header is bytes `[0, 66)`, or `[0, 2)` for Data: marker, type, and the sender keys. Because it is the associated data, an attacker cannot change the type, the credential flag or the sender keys without the tag check failing.
|
||||
- The plaintext is the msgpack-encoded DHT message. With the credential flag, it is preceded by the sender's 97-byte credential.
|
||||
- The overhead is 30 bytes for Data, 94 bytes for Initial and Session, or 191 bytes with a credential.
|
||||
- Nonces are 96 bits from the system CSPRNG. For `n` packets under one key, the probability of a nonce collision is about $n^2 / 2^{97}$. Keys change at least every epoch, so this is negligible.
|
||||
|
||||
`0xC1` is the one byte value that msgpack never uses. Every legacy OpenDHT message is a msgpack map, which starts with `0x80`–`0x8F` or `0xDE`–`0xDF`. This marker therefore unambiguously separates envelopes from plaintext messages:
|
||||
- legacy nodes fail to parse an envelope and drop it, without blacklisting the sender;
|
||||
- new nodes still parse plaintext messages normally.
|
||||
|
||||
### 6.2 Hello (private networks only)
|
||||
|
||||
`Hello` introduces a node to a peer whose key is unknown. This happens when pinging a bare address, typically a bootstrap node. A Hello is **not encrypted**:
|
||||
|
||||
```
|
||||
0xC1 ‖ 0x03 ‖ pk_sender ‖ epk_sender ‖ credential (97 bytes) ‖ msgpack ping
|
||||
```
|
||||
|
||||
The sender cannot encrypt to a key it doesn't know, and X25519 keys cannot sign, so **a Hello proves nothing about its sender**. Its credential travels in clear and can be copied. The receiver therefore:
|
||||
|
||||
- answers only a ping, and only if the credential is valid for `pk_sender`;
|
||||
- answers with a Session envelope to `pk_sender` and `epk_sender`, so only the holder of `sk_sender` can read the answer;
|
||||
- keeps no state from the Hello: it does not add, move or authorize the claimed node.
|
||||
|
||||
The sender proves possession of its key with its next envelope.
|
||||
|
||||
### 6.3 Key advertisement in plaintext messages
|
||||
|
||||
New nodes add fields to plaintext msgpack messages. Legacy nodes ignore unknown fields.
|
||||
|
||||
| Field | Location | Content |
|
||||
|---|---|---|
|
||||
| `k` | top level | Sender's transport public key (bin, 32 bytes) |
|
||||
| `k4` | reply body, next to `n4` | Concatenated public keys of the listed IPv4 nodes, 32 bytes per node, all-zero if unknown |
|
||||
| `k6` | reply body, next to `n6` | Same for IPv6 |
|
||||
|
||||
Rules for using these fields:
|
||||
|
||||
- **`k` is sent only when it is needed**: in public mode, in plaintext messages to nodes whose key is not yet known. Encrypted messages do not need it, because the sender key is in the envelope header.
|
||||
- **Listed keys are checked before use.** A key from `k`, `k4` or `k6` is attached to a node only if `nodeId(key)` equals the node's ID. Otherwise it is ignored.
|
||||
- **The binding limits what a dishonest node can do with a node list.** It cannot attach a forged key to an existing node ID. It can still list a wrong address, which at worst causes encrypted packets to be sent to the wrong host. That host cannot read them.
|
||||
- `k4` and `k6` are omitted if no listed node has a known key. They are ignored if their length is not exactly 32 × the number of listed nodes.
|
||||
|
||||
### 6.4 Sending
|
||||
|
||||
To send a message to node B:
|
||||
|
||||
1. If transport encryption is disabled, send plaintext.
|
||||
2. If B's static key is known (B has a peer record), send an envelope with our ephemeral key for B's address:
|
||||
- a Data envelope if our session with B's address is **confirmed**;
|
||||
- otherwise a Session envelope if B's ephemeral key is known, or else an Initial envelope. In a private network, both include our credential.
|
||||
3. Else, in a private network:
|
||||
- if B's ID is unknown (a ping to a bare address), send a `Hello`;
|
||||
- otherwise refuse to send (`EPERM`).
|
||||
4. Else (public network, key unknown), send plaintext, including `k`.
|
||||
|
||||
Once a node's key is known, nothing is ever sent to it in plaintext. Failed key agreement, including a low-order public key, refuses the send (`EPERM`); it never falls back to plaintext.
|
||||
|
||||
**Confirmation.** A session with an address is confirmed when B shows that it holds the session keys and accepted us:
|
||||
- B answers, in a Session or Data envelope, a request we sent to its node ID **in a Session or Data envelope**. B cached the session when it opened our envelope ([§6.5](#65-receiving)), and answered with keys of our current epoch. Requests sent in an Initial envelope or a Hello are excluded: B answered them without caching a session, so our next request is a Session envelope, and its answer confirms;
|
||||
- or we receive a Data envelope under our current epoch. B only sends one after we confirmed it the same way.
|
||||
|
||||
The confirmation is lost when the session keys change: on epoch rotation, or when B's ephemeral key changes through accepted traffic. An Initial request leaves existing state untouched and is answered without reusing a cached session or its confirmation.
|
||||
|
||||
**Establishment.** Only `ping` and `find_node` requests may precede address validation. Application requests wait until B's ephemeral key is known, or a successful control reply identifies a genuinely keyless legacy peer. Learning the ephemeral from an accepted Initial reply is enough to send a Session: neither address-indexed cache admission nor Data confirmation requires another handshake. Direct NetworkEngine application requests share one engine-owned ping; canceling a caller's ping cannot strand them. Private bare-address bootstrap remains a ping-only Hello.
|
||||
|
||||
**Recovery.** At the first response timeout, a request forgets B's ephemeral key and starts recovering the session, for example after B restarts. Application requests to B are withheld, including new requests, while one internal ping retries in Initial envelopes (with our credential in a private network). `find_node` remains available and its successful reply can also release the waiters. An accepted reply completes its own request before held work is released, so a delayed original reply is not retransmitted during attachment. Released requests receive fresh response timers; withholding consumes no transmission attempts. The internal probe's first timeout notifies waiting operations so searches can replace unresponsive peers promptly. Probe exhaustion or rejection terminates the waiters. Their payloads never enter Initial envelopes, and no `401` challenge/retry exchange is used.
|
||||
|
||||
**Value searches.** A cold peer first receives `find_node(search_target)`. Its reply supplies its ephemeral and closer candidates in the same exchange. The existing distance-ordered search dispatch contacts closer candidates immediately, within the existing four-active-peer limit; it does not wait for a SELECT reply from the farther responder. This routing probe has separate state: it cannot satisfy a GET, pagination, or an empty-result callback. Responders remain eligible for subsequent value retrieval. A cold holder typically needs three exchanges (`find_node`, SELECT IDs, GET by ID), while a session-ready holder retains its usual two. A routing probe's first timeout frees its active search slot while protocol retries continue, rather than waiting for final expiration.
|
||||
|
||||
Value data is fragmented so that each packet fits in the 1280-byte IPv6 minimum MTU: `1280 − 40 − 8 = 1232` bytes of UDP payload, less 48 bytes reserved for the msgpack framing of a fragment, less the overhead of the envelope the fragments are sent in. Fragments carry `1184` bytes of value data in plaintext, `1154` in Data envelopes, `1090` in Initial or Session envelopes, and `993` with a credential.
|
||||
|
||||
This sizes value fragments only. Complete replies and node lists are not yet subject to a whole-datagram MTU budget; node-list trimming and packet-size enforcement remain separate work.
|
||||
|
||||
### 6.5 Receiving
|
||||
|
||||
For each received packet, a node applies the following checks in order:
|
||||
|
||||
1. **Address filters.** Drop the packet if it comes from a martian or blacklisted address. This is unchanged.
|
||||
|
||||
2. **Envelopes.** If the packet starts with `0xC1`:
|
||||
1. If encryption is disabled, drop it.
|
||||
2. Drop it if its type is unknown, or if `pk_sender` is our own key. This rejects reflected packets.
|
||||
3. **Hello:**
|
||||
- Drop it outside private networks, or if it carries no message.
|
||||
- Apply the public-key limit, then verify the credential: its key must equal `pk_sender` and it must be valid. Drop the packet on failure.
|
||||
- Continue with steps 4 and 5, then answer as described in [§6.2](#62-hello-private-networks-only). The Hello is not processed any further.
|
||||
4. **Initial:** apply the public-key limit, derive the Initial key from `pk_sender` and `epk_sender`, and decrypt.
|
||||
5. **Session:** first try the keys cached in each epoch for (source address, `pk_sender`, `epk_sender`). Otherwise, apply the public-key limit, then for our current epoch then the previous one: derive the keys with our ephemeral key for the source address, and decrypt. Keep newly derived keys pending until the packet passes authorization and message validation.
|
||||
6. **Data:** decrypt with the session cached for the source address in our current epoch, then in the previous one. Its `pk_sender` and `epk_sender` are those of the session. This needs no key derivation and no public-key limit.
|
||||
7. Drop the packet if it was not decrypted.
|
||||
8. **Credential flag:** strip the 97-byte credential. In a private network, verify it as for Hello, unless the peer is already authorized; on success, record the peer as authorized, without an expiry.
|
||||
**No credential:** in a private network, drop the packet unless the peer is already authorized.
|
||||
9. Record `epk_sender` on a temporary peer record. It is **validated for the source address** if the envelope was a Session or Data envelope: opening it required our ephemeral key for that address, which was only ever sent there. Existing peer state is updated only after parsing, ID binding and the processing checks below.
|
||||
|
||||
**Session cache.** The epoch caches one session per source address, including its verified admission in private networks. Authorization therefore survives the release of a client-mode peer's node record. Newly derived Session keys enter the cache only after credential authorization, parsing, network and node ID checks, and basic fragment validation. Replies must match a pending request or listener. Admission is per packet, so subsequent Data fragments can decrypt before the whole message is assembled. Sending to the exact address for which the peer's ephemeral key is validated can also cache a session. Answers to Initial and Hello envelopes never use or change cached sessions: their source address may be spoofed. If both the peer record and cached admission are lost, the same permanent credential is verified again; no replacement grant is needed.
|
||||
|
||||
3. **Plaintext in a private network.** Drop any packet that is not an envelope.
|
||||
|
||||
4. **Parsing.** Parse the msgpack message and apply the network ID check. This is unchanged.
|
||||
|
||||
5. **Envelope ID binding.** For an envelope, the message's node ID must equal `nodeId(pk_sender)`, otherwise drop the message. Value data fragments are exempt because they carry no node ID. Fragment buffers are keyed by source address, transaction ID and sender key, with a separate keyless buffer for plaintext. Only parts from the same sender can join a header, and a response header must match a pending request or listener. Foreign-key or plaintext parts cannot reserve the expected sender's buffer, even when they arrive first. Initial envelopes carrying value fragments or fragmented-message headers are dropped: encrypted value data requires a Session or Data envelope.
|
||||
|
||||
6. **Plaintext with `k`.** For a plaintext message carrying `k`, attach the key to the sender if it matches the sender's ID.
|
||||
|
||||
7. **Processing.**
|
||||
- A Session or Data envelope can move the sender's node record to the packet's source address.
|
||||
- Initial requests use transient node records. Only `ping` and `find_node` receive successful replies; GET (including SELECT) and writes receive a short `401` error, and value updates are dropped. Rejected GETs never invoke storage or serialize values. These requests do not add or move an established node, count as activity, or change its ephemeral key or session confirmation.
|
||||
- Initial replies and errors are accepted only for a pending request at the expected source address, never for a listener. They cannot move a known keyed node to a different address.
|
||||
- Replies and Data envelopes can confirm the session ([§6.4](#64-sending)).
|
||||
|
||||
A **plaintext** message claiming the ID of a node whose key is known is untrusted, even from that node's recorded address:
|
||||
- it does not move the node record and does not count as activity from that node;
|
||||
- replies, errors, value updates and writes are dropped;
|
||||
- `ping` and `find_node` receive control replies using a transient node record and an Initial envelope to the known key; GET receives a short `401`, even when the plaintext packet is the first advertisement of a matching `k`. Truly keyless legacy GETs remain unchanged.
|
||||
|
||||
**Rate limits.** A node keeps separate budgets, each with a global quota and a quota per source address (per /64 prefix for IPv6):
|
||||
- **Session requests:** requests in Session or Data envelopes, whose source address is validated. `Config::max_req_per_sec`, by default 8192 per second, and 1024 per address.
|
||||
- **Other requests:** plaintext requests and requests in Initial or Hello envelopes, whose source address can be spoofed. `Config::max_unauth_req_per_sec`, with the same defaults. A flood of them does not affect requests from established peers.
|
||||
- **Public-key work:** one unit per packet needing a key agreement or a signature verification, charged before that work. `Config::max_crypto_per_sec`, by default 512 per second, and 64 per address. A unit covers the packet and its answer, including credential verification:
|
||||
- each Initial envelope (two X25519 operations, and five more to answer a request);
|
||||
- each Session envelope from an uncached (address, `pk_sender`, `epk_sender`) triple (five X25519 operations per epoch tried);
|
||||
- each cached Session envelope whose peer has not yet been authorized and needs credential verification (one charge, not an additional charge for packets already admitted for key agreement);
|
||||
- each Hello (one Ed25519 verification, and the key derivation of its answer);
|
||||
- each plaintext request from a sender whose key is known or advertised, answered in an Initial envelope (three X25519 operations).
|
||||
|
||||
Initial and uncached Session envelopes from an address where we await an answer, from the sender's node record or from a request sent by address, use a separate budget of the same size. Our own key exchanges thus complete during a flood.
|
||||
|
||||
Packets from peers with cached session keys cost one AEAD operation, except when a private-network credential needs verification. Each epoch caches at most 16384 sessions, evicting the least recently used one to store a new one. An evicted peer recovers after one retransmission. Only a peer that received a packet from us at its address can take a cache slot, so a slot costs the attacker a reachable address and a round trip.
|
||||
|
||||
### 6.6 Write authorization
|
||||
|
||||
`put`, `refresh` and `listen` create state on the receiver, and `listen` makes it send value updates to the requester's address. The receiver therefore requires proof that the requester receives packets at its source address. Without it, an attacker could spoof a victim's address to fill its storage quota, or direct update traffic to it.
|
||||
|
||||
- **Encrypted requests** must arrive in a **Session** or **Data** envelope. Our ephemeral key for the source address is only sent to that address ([§5.1](#51-ephemeral-keys)), so opening the envelope proves the sender received one of our packets there. Requests in Initial envelopes are refused with error `401`; normal senders establish the session through `ping` or `find_node` before sending application requests.
|
||||
- **Plaintext requests** must carry a token, as in the legacy protocol. The token is sent in answers to `find`, `get` and `listen`, and in value updates, to the address of the node record:
|
||||
|
||||
```
|
||||
token(addr) = HMAC-SHA256(key = S, "opendht-address-token-v1" ‖ addr)
|
||||
```
|
||||
|
||||
A token is accepted in the epoch it was issued and the next one. Legacy nodes treat tokens as opaque, so changing their derivation keeps compatibility.
|
||||
|
||||
Messages to and from encrypted nodes carry no token. This saves 40 bytes in each answer to `find`, `get` and `listen`, and in each `put`, `refresh`, `listen` and value update. A node that receives an encrypted answer may write to its sender.
|
||||
|
||||
## 7. Message flows
|
||||
|
||||
### 7.1 Public network
|
||||
|
||||
Encryption is opportunistic, and keys travel with node IDs.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A as A (new)
|
||||
participant B as B (new)
|
||||
participant L as L (legacy)
|
||||
A->>B: plaintext ping + k = pk_A (B's key unknown)
|
||||
Note over B: attaches pk_A to A (nodeId check)
|
||||
B->>A: Initial envelope (pong)
|
||||
Note over A: decrypts, checks ID = nodeId(pk_B), learns epk_B
|
||||
A->>B: Session envelope (request)
|
||||
B->>A: Session envelope (reply)
|
||||
Note over A: session confirmed
|
||||
A->>B: Data envelope (request)
|
||||
Note over B: session confirmed
|
||||
B->>A: Data envelope (all further traffic)
|
||||
A->>L: plaintext + k (ignored by L)
|
||||
L->>A: plaintext
|
||||
```
|
||||
|
||||
- The first request to a node with an unknown key, typically a bootstrap ping, is in plaintext. Its reply is an Initial envelope. The next request and its reply use Session envelopes, and all later traffic uses Data envelopes.
|
||||
- Nodes learned through `k4`/`k6` get an Initial envelope as the first packet. Its answer is a Session envelope, but the answerer caches nothing yet: the next request is a Session envelope, and its answer confirms the session. Data envelopes follow.
|
||||
- Legacy nodes see plaintext from new nodes and are unaffected.
|
||||
|
||||
### 7.2 Private network
|
||||
|
||||
Only nodes with a credential participate. Nodes never send or accept plaintext.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant A
|
||||
participant B as B (bootstrap)
|
||||
A->>B: Hello(pk_A, epk_A, cred_A, ping)
|
||||
Note over B: verifies cred_A, keeps no state
|
||||
B->>A: Session(cred_B, pong)
|
||||
Note over A: verifies cred_B, authorizes B
|
||||
A->>B: Session(cred_A, request)
|
||||
Note over B: verifies cred_A, authorizes A, caches the session
|
||||
B->>A: Session(cred_B, reply)
|
||||
Note over A: session confirmed
|
||||
A->>B: Data (without credential)
|
||||
```
|
||||
|
||||
- **Credential exchange.** Each side attaches its credential to its Initial and Session envelopes. Data envelopes, sent once the peer has accepted us, never carry it.
|
||||
- **Authorization lifetime.** Admission does not expire. Session keys still rotate for forward secrecy, independently of membership. A lost admission record is recovered using the same grant, without operator action.
|
||||
- **Node lists.** Listed nodes without a valid matching key are discarded.
|
||||
- **Startup checks.** The node refuses to start (`DhtException`) if:
|
||||
- encryption is disabled while authorities are configured;
|
||||
- the configured credential does not match the transport key;
|
||||
- the credential is not valid for the configured authorities.
|
||||
|
||||
The credential and trusted authorities are read on start. Restart with the updated configuration when explicitly changing a grant or the trust set; this also discards cached admissions.
|
||||
|
||||
## 8. Key persistence
|
||||
|
||||
If the following conditions all hold, the static secret key is saved in the state file as the msgpack field `transport_key` (32 bytes):
|
||||
- encryption is enabled;
|
||||
- no key was configured;
|
||||
- `Config::persist_path` is set.
|
||||
|
||||
When the key is saved:
|
||||
- the state is written to a randomly named temporary file in the destination directory;
|
||||
- owner-only read/write permissions are requested before any secret data is written;
|
||||
- the temporary file is closed successfully before it is renamed over the state file;
|
||||
- a save failure is logged, the temporary file is removed, and the previous state file is left intact;
|
||||
- on start, the key is restored before any packet is exchanged, so the node keeps its ID across restarts.
|
||||
|
||||
The node also stores its ID in the state file, so older versions reading this state keep the same ID. A configured key is never written to the state file. Ephemeral keys and session keys are never persisted.
|
||||
|
||||
`dhtnode --transport-key <file>` loads the raw 32-byte secret from `<file>`. If the file does not exist, `dhtnode` creates it using the same temporary-file and permission handling. Unreadable or invalid existing keys are not replaced.
|
||||
|
||||
File operations use portable C++ filesystem APIs. Permission semantics depend on the platform; exclusive file creation and power-loss durability are not guaranteed. Use an owner-controlled directory and a single writer for each path.
|
||||
|
||||
## 9. Security analysis
|
||||
|
||||
### 9.1 Properties
|
||||
|
||||
Against an attacker who controls the network but holds no node's secret key:
|
||||
|
||||
- **Confidentiality and integrity.** Traffic between two nodes that know each other's keys is confidential and integrity-protected. The protection is IND-CCA2 and INT-CTXT, from ChaCha20-Poly1305 under keys derived from X25519.
|
||||
- **ID authentication.** An encrypted message under node ID `X` can only be produced by the holder of the static secret key behind `X`.
|
||||
- Producing a key for a given ID requires a SHA-256 preimage on 160 bits.
|
||||
- Choosing the first `b` bits of one's own ID costs about $2^b$ key generations. Legacy nodes choose their ID freely.
|
||||
- **Forward secrecy.** Session envelopes recorded by the attacker stay confidential if static keys are compromised later, once both ephemeral secrets are erased (at most one hour after use). Initial envelopes stay confidential if the sender's static key is compromised, but not the receiver's.
|
||||
- **Key-compromise impersonation.** With a node's static secret, an attacker can decrypt the Initial envelopes sent to it and impersonate other nodes to it in Initial envelopes, but not in Session envelopes.
|
||||
- **Address stickiness.** Spoofed plaintext, Hellos and replayed Initial envelopes cannot redirect a node record whose key is known. Moving it requires a Session or Data envelope from the new address (see [§6.2](#62-hello-private-networks-only) and [§6.5](#65-receiving)).
|
||||
- **Fragment integrity.** Once a fragmented message arrives in envelopes, only parts from the same sender key are merged. Spoofed plaintext or foreign-key parts cannot alter or block it ([§6.5](#65-receiving), step 5).
|
||||
- **Address validation.** Session and Data envelopes only open from the address our ephemeral key was sent to. An off-path attacker cannot send one from a spoofed address, even with its own valid static key, so it cannot `put`, `refresh` or `listen` on behalf of another address.
|
||||
- **Private-network admission.** Without a valid credential and its matching secret key, a node:
|
||||
- cannot read any traffic;
|
||||
- cannot get answers it can decrypt;
|
||||
- is never listed by honest nodes.
|
||||
- **Network separation.** Different network IDs derive different keys.
|
||||
- **DoS cost.** An unauthenticated Data envelope costs a lookup and at most two AEAD operations. Other envelopes pass the public-key limit before any key derivation or signature verification.
|
||||
|
||||
### 9.2 Limitations
|
||||
|
||||
Each item states who it applies to, what that party can do, and what it cannot do.
|
||||
|
||||
- **Encryption is hop-by-hop.** Nodes that store values read them. Only `SecureDht` protects values end to end ([§1](#1-scope)).
|
||||
|
||||
- **Public mode is trust on first use.** Applies in public networks, to an attacker who modifies traffic on the path between two nodes A and B before A knows B's key.
|
||||
- A node learns a peer's key from the first plaintext message that carries it with the peer's ID: `k` in a message from the peer, or `k4`/`k6` in a reply from any node. An attacker that removes these fields from every such message keeps A and B in plaintext, and reads and modifies their traffic. The downgrade ends with the first message carrying a key that the attacker misses: the node that receives it then sends only envelopes to that peer, which the attacker cannot alter, and treats plaintext claiming the peer's ID as untrusted ([§6.5](#65-receiving), step 7). The attacker can still drop their traffic.
|
||||
- The attacker cannot bind its own key to B's ID. It can rewrite B's plaintext messages under an ID and key of its own, so that A talks to the attacker's node at B's address, and the attacker relays to B. A then knows the attacker's node at that address, not B.
|
||||
- Until A knows a key for an ID, any plaintext sender can claim that ID from any address. The claim lasts until A learns the key: plaintext claiming the ID is untrusted from then on, and the first Session or Data envelope under it moves the node record to its sender's address.
|
||||
- A key received in an encrypted reply cannot be stripped. One received in a plaintext reply can, by an attacker on that reply's path.
|
||||
- The first request to a node with an unknown key, for example a bootstrap ping, is in plaintext.
|
||||
- Private networks are not affected: they never send or accept plaintext, and credentials authenticate keys.
|
||||
|
||||
- **Compromise of a static secret key.** Applies to whoever obtains `sk_B`, for example from B's key file or state file, for as long as B keeps that key.
|
||||
- It can act as B from any address, and talk to any node under B's ID.
|
||||
- It can read every Initial envelope ever sent to B, including recorded ones. Initial keys depend only on `sk_B` and the sender's public keys.
|
||||
- It can send Initial envelopes to B under any other node's ID. B answers `ping` and `find_node` in them, under keys the attacker cannot derive, and changes no state ([§6.5](#65-receiving), step 7). GET and writes are refused with `401`.
|
||||
- It cannot read Session or Data envelopes between B and other nodes, recorded or live, nor impersonate another node to B in them. That requires B's ephemeral secret, or the other node's static secret.
|
||||
- In a private network, it stays admitted for as long as B's granting authority is trusted. The credential is not secret: Hellos carry it in clear.
|
||||
- Compromise of a running node also exposes its epoch secrets, and with them all sessions of its current and previous epoch.
|
||||
|
||||
Recover by changing the key. This changes the node ID, and in a private network needs a new credential. Changing B's key alone does not exclude the compromised key: its grant remains valid until its authority is distrusted, as described below. The old key cannot be revoked in a public network.
|
||||
|
||||
- **Initial envelopes are not forward-secret against the receiver.** An Initial envelope stays confidential if the sender's static key is compromised later, but not if the receiver's is. Initial envelopes carry:
|
||||
- `ping` or `find_node` to a node whose ephemeral key is unknown, including their retransmissions;
|
||||
- control replies to plaintext requests advertising a key. Application requests wait for a Session ([§6.4](#64-sending)).
|
||||
|
||||
Routing targets and control traffic remain exposed to a later compromise of the receiver's static key. Application GET/SELECT and write payloads do not enter Initial envelopes. Answers to Initial envelopes are Session envelopes, and are forward-secret.
|
||||
|
||||
- **No replay protection.** Nodes keep no record of received nonces. A captured envelope is accepted again as long as the receiver holds the keys that open it:
|
||||
- **Initial envelopes** open from any address, for as long as the receiver's static key is unchanged. A replayed `ping` or `find_node` is answered again, to the replayer's source address, under keys the replayer cannot derive. GET and writes are refused with `401`, value updates are dropped, and replies and errors are accepted only for a request pending toward that address ([§6.5](#65-receiving), step 7). Reflection remains for control replies: anyone holding a captured Initial request, or a Hello, can make the receiver send an encrypted answer to an address of its choice. In a private network this includes outsiders, because the captured packet carries its sender's credential. Rate limits bound request frequency, not reply size; node-list packet-size limits remain separate work.
|
||||
- **Session and Data envelopes** open only from their original source address, which the replayer must spoof, and only until the epoch that opened them is erased: at most one hour. A replayed request is processed again as its sender, including a write the sender did make: a repeated `put`, `refresh` or `listen` extends the life of a value or of a listener. A replayed value update is accepted while its listen is open, and repeats it: the values it lists are added or refreshed again, and the expirations it announces are signaled again. A replayed reply or error is accepted only if its transaction ID is pending. Transaction IDs are 32-bit counters per peer with a random start, so an old ID is pending again only after $2^{32}$ requests to that peer.
|
||||
|
||||
- **On-path attackers get write authorization for the addresses they observe.** Applies to an attacker that reads the packets we send to an address `addr`. Our ephemeral key `epk(addr)` is in the clear header of every Initial and Session envelope we send there: at each first contact, retransmission and epoch rotation. Data envelopes do not carry it.
|
||||
- With its own key pair, the attacker can send us Session envelopes with source address `addr`, and they open. It then has what the owner of `addr` has: write authorization ([§6.6](#66-write-authorization)). Its `put` and `refresh` consume the storage quota of `addr`, and its `listen` directs value updates to `addr`, all under the attacker's own node ID. Each such envelope also replaces the session cached for `addr`, so Data envelopes from the real owner are dropped until its next retransmission establishes a new session ([§6.4](#64-sending), recovery).
|
||||
- It cannot impersonate the node at `addr`, nor read or alter its traffic. That requires the static secret of that node.
|
||||
- A captured `epk(addr)` is usable until the epoch that produced it is erased: at most one hour.
|
||||
- In a private network, the attacker's key must also hold a valid credential.
|
||||
|
||||
This is the same exposure as legacy tokens, which are sent in clear to the address they authorize. Address validation defends against off-path spoofing only.
|
||||
|
||||
- **Address changes.** Our ephemeral key for a peer is derived from its address. When a peer's address or port changes, for example after a NAT rebinding, its Session and Data envelopes to us no longer open, and ours no longer reach it. Its next retransmission is a ping in an Initial envelope, which starts a new session for the new address, and the request follows in a Session envelope ([§6.4](#64-sending), recovery).
|
||||
|
||||
- **No Sybil resistance.** An identity costs one key generation. Encryption prevents choosing a node ID ([§9.1](#91-properties)), not creating many of them. In public networks, legacy nodes still choose their IDs freely.
|
||||
|
||||
- **Denial of service.** Public-key operations on unauthenticated packets are bounded by the public-key limit ([§6.5](#65-receiving)): by default 512 packets per second globally, and 64 per source address or IPv6 /64 prefix.
|
||||
- An attacker spending that budget from many or spoofed addresses drops Initial, Hello and uncached Session envelopes from new peers, and plaintext requests from keyed senders. Answers to our own requests have a separate budget, which only an attacker spoofing the addresses of the peers we contact can spend. Data envelopes, cached sessions and requests from established peers are unaffected.
|
||||
- Likewise, a flood of plaintext or Initial requests drops other requests without a session, as in the legacy protocol, but not those of established peers.
|
||||
- A unit stands for three to ten X25519 operations, so the default allows about 5000 per second. `Config::max_crypto_per_sec` adapts it to the CPU available.
|
||||
- An attacker reachable at many addresses, for example an IPv6 prefix, can fill the session cache of an epoch: one slot costs it one round trip. Evicted peers have their Data envelopes dropped until their next retransmission, which starts a new session.
|
||||
|
||||
- **No per-grant revocation.** Applies to private networks. A grant is permanent: a compromised or excluded node can participate for as long as any authority that signed a grant for its key remains trusted. Compromise of an authority allows issuing arbitrary new grants. Exclusion requires every remaining node to remove the affected authority from its trust set and restart, discarding cached admissions. This also excludes every member relying only on that authority; retained members need grants from another trusted authority. Multiple accepted authorities provide a transition path, but do not neutralize a compromised authority while it is still trusted. There is no clock-based fallback, revocation list, or automatic expiry.
|
||||
|
||||
- **Metadata.** Anyone observing the traffic sees:
|
||||
- in Initial and Session envelopes, the sender's static key, hence its node ID, and its ephemeral key: who talks to whom, at each first contact, retransmission and epoch rotation;
|
||||
- in Data envelopes, only the type; the sender is still identified by its address, from the Session envelopes that preceded;
|
||||
- in every envelope, the type, the credential flag, the size and the timing, which can reveal the kind of message, for example fragmented value data;
|
||||
- Hello messages entirely, including the credential, which reveals the node's key. A copied credential is useless without the matching secret key;
|
||||
- in public networks, plaintext messages entirely, including node lists.
|
||||
|
||||
Node addresses are not hidden: they are in node lists, and on the packets themselves.
|
||||
|
||||
- **Node state.** The saved node list holds IDs and addresses, but no keys. In a public network, saved nodes are contacted again in plaintext, with the first-contact exposure above. In a private network, a saved node with an ID but no key cannot be contacted ([§6.4](#64-sending), step 3): a restarted node needs a bootstrap address to rejoin, and reuses saved nodes once it learns their keys from node lists.
|
||||
|
||||
## 10. Operating a private network
|
||||
|
||||
With `dhtnode`:
|
||||
|
||||
```sh
|
||||
# Once: create the authority (net.key = secret seed, net.pub = hex public key)
|
||||
dhtnode --gen-network-authority net
|
||||
|
||||
# Once per node: create its transport key and permanent membership grant
|
||||
dhtnode --transport-key node1.key --issue-credential node1.cred --authority-key net.key
|
||||
|
||||
# Run a node
|
||||
dhtnode --transport-key node1.key --network-credential node1.cred --network-authority $(cat net.pub)
|
||||
```
|
||||
|
||||
Authority generation refuses to run if either output path already exists, including a dangling symlink.
|
||||
|
||||
Keep the authority secret offline. Distribute only `net.pub` and the per-node credentials. Without a compromise or an intentional membership change, keep these keys, grants, and trust sets unchanged: there is no scheduled renewal or maintenance.
|
||||
|
||||
`--network-authority` can be repeated to trust several authorities during an explicit transition:
|
||||
|
||||
```sh
|
||||
dhtnode --transport-key node1.key --network-credential node1.cred \
|
||||
--network-authority $(cat net.pub) --network-authority $(cat replacement.pub)
|
||||
```
|
||||
|
||||
To move away from an authority:
|
||||
|
||||
1. Create a replacement authority and configure retained members to trust both old and replacement public keys. Restart them with this overlapping trust set.
|
||||
2. Issue replacement grants only to retained, uncompromised transport keys and restart those nodes with their new grants. Old and replacement grants interoperate while both authorities are trusted. A compromised transport key must be replaced as well.
|
||||
3. Remove the old authority from every retained node's configuration and restart them, clearing prior admissions. Only grants from the remaining trusted authorities are then accepted.
|
||||
|
||||
A compromised authority or a compromised key's old grant remains usable wherever the old authority is still trusted. The overlap is a transition mechanism, not immediate exclusion; it ends only when all retained nodes stop trusting the affected authority. Uncompromised grants from other authorities do not need updating.
|
||||
|
||||
From the library, set `Config::transport` before starting:
|
||||
- `authorities`;
|
||||
- `key`, which must be the key the credential was issued for;
|
||||
- `credential`.
|
||||
|
||||
## 11. Constants
|
||||
|
||||
| Name | Value |
|
||||
|---|---|
|
||||
| Envelope marker | `0xC1` |
|
||||
| Envelope types | `Initial = 1`, `Session = 2`, `Hello = 3`, `Data = 4` |
|
||||
| Credential flag | `0x80` |
|
||||
| Key, nonce, tag sizes | 32, 12, 16 bytes |
|
||||
| Envelope header | 66 bytes, 2 for Data |
|
||||
| Envelope overhead | 30 bytes for Data, 94 for Initial and Session (191 with credential) |
|
||||
| Epoch (ephemeral keys and tokens) | 30 minutes, previous epoch accepted for one more period |
|
||||
| Cached sessions per epoch | 16384, least recently used evicted |
|
||||
| Credential size, version | 97 bytes, `0x02` |
|
||||
| Node ID context | `"opendht-node-id-v1"` |
|
||||
| HKDF salt | `"opendht-transport-v2"` |
|
||||
| Credential signature context | `"opendht-credential-v2"` |
|
||||
| Ephemeral key, token contexts | `"opendht-address-key-v1"`, `"opendht-address-token-v1"` |
|
||||
| Token size | 32 bytes |
|
||||
| Value fragment size | 1184 bytes, less the envelope overhead (1154 to 993) |
|
||||
+2
-18
@@ -1,21 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "opendht/dhtrunner.h"
|
||||
|
||||
+85
-47
@@ -1,27 +1,10 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Authors: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
* Sébastien Blin <sebastien.blin@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "infohash.h"
|
||||
#include "value.h"
|
||||
#include "transport.h"
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
@@ -41,22 +24,20 @@ struct Node;
|
||||
*/
|
||||
enum class NodeStatus {
|
||||
Disconnected, // 0 nodes
|
||||
Connecting, // 1+ nodes
|
||||
Connecting, // bootstrap pending or 1+ nodes
|
||||
Connected // 1+ good nodes
|
||||
};
|
||||
|
||||
inline constexpr const char*
|
||||
statusToStr(NodeStatus status) {
|
||||
return status == NodeStatus::Connected ? "connected" : (
|
||||
status == NodeStatus::Connecting ? "connecting" :
|
||||
"disconnected");
|
||||
inline constexpr std::string_view
|
||||
statusToStr(NodeStatus status)
|
||||
{
|
||||
return status == NodeStatus::Connected ? "connected"sv
|
||||
: (status == NodeStatus::Connecting ? "connecting"sv : "disconnected"sv);
|
||||
}
|
||||
|
||||
struct OPENDHT_PUBLIC NodeStats {
|
||||
unsigned good_nodes {0},
|
||||
dubious_nodes {0},
|
||||
cached_nodes {0},
|
||||
incoming_nodes {0};
|
||||
struct OPENDHT_PUBLIC NodeStats
|
||||
{
|
||||
unsigned good_nodes {0}, dubious_nodes {0}, cached_nodes {0}, incoming_nodes {0};
|
||||
unsigned table_depth {0};
|
||||
unsigned searches {0};
|
||||
unsigned node_cache_size {0};
|
||||
@@ -76,12 +57,17 @@ struct OPENDHT_PUBLIC NodeStats {
|
||||
MSGPACK_DEFINE_MAP(good_nodes, dubious_nodes, cached_nodes, incoming_nodes, table_depth, searches, node_cache_size)
|
||||
};
|
||||
|
||||
struct OPENDHT_PUBLIC NodeInfo {
|
||||
struct OPENDHT_PUBLIC NodeInfo
|
||||
{
|
||||
InfoHash id;
|
||||
InfoHash node_id;
|
||||
NodeStats ipv4 {};
|
||||
NodeStats ipv6 {};
|
||||
size_t ongoing_ops {0};
|
||||
size_t storage_values {0};
|
||||
size_t storage_size {0};
|
||||
size_t local_storage_values {0};
|
||||
size_t local_storage_size {0};
|
||||
in_port_t bound4 {0};
|
||||
in_port_t bound6 {0};
|
||||
|
||||
@@ -94,14 +80,25 @@ struct OPENDHT_PUBLIC NodeInfo {
|
||||
explicit NodeInfo(const Json::Value& v);
|
||||
#endif
|
||||
|
||||
MSGPACK_DEFINE_MAP(id, node_id, ipv4, ipv6)
|
||||
MSGPACK_DEFINE_MAP(id,
|
||||
node_id,
|
||||
ipv4,
|
||||
ipv6,
|
||||
ongoing_ops,
|
||||
storage_values,
|
||||
storage_size,
|
||||
local_storage_values,
|
||||
local_storage_size,
|
||||
bound4,
|
||||
bound6)
|
||||
};
|
||||
|
||||
/**
|
||||
* Dht configuration.
|
||||
*/
|
||||
struct OPENDHT_PUBLIC Config {
|
||||
/** DHT node ID */
|
||||
struct OPENDHT_PUBLIC Config
|
||||
{
|
||||
/** DHT node ID. Ignored if transport encryption is enabled: the node ID derives from the transport key. */
|
||||
InfoHash node_id {};
|
||||
|
||||
/**
|
||||
@@ -126,18 +123,44 @@ struct OPENDHT_PUBLIC Config {
|
||||
/** If non-0, overrides the default per-IP address rate-limit. -1 means no limit. */
|
||||
ssize_t max_peer_req_per_sec {0};
|
||||
|
||||
/**
|
||||
* If non-0, override the rate-limits of requests from senders without an encrypted session
|
||||
* (default: same as above). -1 means no limit.
|
||||
*/
|
||||
ssize_t max_unauth_req_per_sec {0};
|
||||
ssize_t max_peer_unauth_req_per_sec {0};
|
||||
|
||||
/**
|
||||
* If non-0, override the rate-limits of packets needing a transport key agreement
|
||||
* or credential check. -1 means no limit.
|
||||
*/
|
||||
ssize_t max_crypto_per_sec {0};
|
||||
ssize_t max_peer_crypto_per_sec {0};
|
||||
|
||||
/* If non-0, overrides the default maximum number of searches. -1 means no limit. */
|
||||
ssize_t max_searches {0};
|
||||
|
||||
/* If non-0, overrides the default maximum store size. -1 means no limit. */
|
||||
/* If non-0, overrides the default maximum store size for remote values. -1 means no limit. */
|
||||
ssize_t max_store_size {0};
|
||||
|
||||
/* If non-0, overrides the default maximum store size for locally stored values. -1 means no limit. */
|
||||
ssize_t max_local_store_size {0};
|
||||
|
||||
/* If non-0, overrides the default maximum store key count. -1 means no limit. */
|
||||
ssize_t max_store_keys {0};
|
||||
|
||||
/**
|
||||
* Use appropriate bahavior for a public IP, stable node:
|
||||
* - No connectivity change triggered when a search fails
|
||||
* - Larger listen refresh time
|
||||
*/
|
||||
bool public_stable {false};
|
||||
|
||||
/* Client mode, node will not be used by other nodes to store data. */
|
||||
bool client_mode {false};
|
||||
|
||||
/** Encryption of the DHT protocol, and optional private network */
|
||||
TransportConfig transport {};
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -155,7 +178,22 @@ struct OPENDHT_PUBLIC SecureDhtConfig
|
||||
bool cert_cache_all {false};
|
||||
};
|
||||
|
||||
static constexpr size_t DEFAULT_STORAGE_LIMIT {1024 * 1024 * 64};
|
||||
enum class OPENDHT_PUBLIC PushNotificationResult : uint8_t {
|
||||
/* success codes */
|
||||
PutRefresh,
|
||||
ListenRefresh,
|
||||
Values,
|
||||
ValuesExpired,
|
||||
/* ignored/error codes */
|
||||
IgnoredWrongSession = 0x80,
|
||||
IgnoredNoOp,
|
||||
IgnoredStopped,
|
||||
IgnoredDisabled,
|
||||
Error
|
||||
};
|
||||
|
||||
static constexpr size_t STORAGE_LIMIT_DEFAULT {1024 * 1024 * 64};
|
||||
static constexpr size_t STORAGE_LIMIT_UNLIMITED {(size_t) -1};
|
||||
|
||||
using ValuesExport = std::pair<InfoHash, Blob>;
|
||||
|
||||
@@ -165,20 +203,20 @@ using ValueCallback = std::function<bool(const std::vector<std::shared_ptr<Value
|
||||
using GetCallbackSimple = std::function<bool(std::shared_ptr<Value> value)>;
|
||||
using ShutdownCallback = std::function<void()>;
|
||||
using IdentityAnnouncedCb = std::function<void(bool)>;
|
||||
using PublicAddressChangedCb = std::function<void(std::vector<SockAddr>)>;
|
||||
|
||||
using CertificateStoreQuery = std::function<std::vector<std::shared_ptr<crypto::Certificate>>(const InfoHash& pk_id)>;
|
||||
|
||||
typedef bool (*GetCallbackRaw)(std::shared_ptr<Value>, void *user_data);
|
||||
typedef bool (*ValueCallbackRaw)(std::shared_ptr<Value>, bool expired, void *user_data);
|
||||
using CertificateStoreQuery = std::function<std::vector<std::shared_ptr<crypto::Certificate>>(const PkId& pk_id)>;
|
||||
|
||||
using DoneCallback = std::function<void(bool success, const std::vector<std::shared_ptr<Node>>& nodes)>;
|
||||
typedef void (*DoneCallbackRaw)(bool, std::vector<std::shared_ptr<Node>>*, void *user_data);
|
||||
typedef void (*ShutdownCallbackRaw)(void *user_data);
|
||||
typedef void (*DoneCallbackSimpleRaw)(bool, void *user_data);
|
||||
typedef bool (*FilterRaw)(const Value&, void *user_data);
|
||||
|
||||
using DoneCallbackSimple = std::function<void(bool success)>;
|
||||
|
||||
typedef bool (*GetCallbackRaw)(std::shared_ptr<Value>, void* user_data);
|
||||
typedef bool (*ValueCallbackRaw)(std::shared_ptr<Value>, bool expired, void* user_data);
|
||||
typedef void (*DoneCallbackRaw)(bool, std::vector<std::shared_ptr<Node>>*, void* user_data);
|
||||
typedef void (*ShutdownCallbackRaw)(void* user_data);
|
||||
typedef void (*DoneCallbackSimpleRaw)(bool, void* user_data);
|
||||
typedef bool (*FilterRaw)(const Value&, void* user_data);
|
||||
|
||||
OPENDHT_PUBLIC GetCallbackSimple bindGetCb(GetCallbackRaw raw_cb, void* user_data);
|
||||
OPENDHT_PUBLIC GetCallback bindGetCb(GetCallbackSimple cb);
|
||||
OPENDHT_PUBLIC ValueCallback bindValueCb(ValueCallbackRaw raw_cb, void* user_data);
|
||||
@@ -188,4 +226,4 @@ OPENDHT_PUBLIC DoneCallback bindDoneCb(DoneCallbackRaw raw_cb, void* user_data);
|
||||
OPENDHT_PUBLIC DoneCallbackSimple bindDoneCbSimple(DoneCallbackSimpleRaw raw_cb, void* user_data);
|
||||
OPENDHT_PUBLIC Value::Filter bindFilterRaw(FilterRaw raw_filter, void* user_data);
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+273
-187
@@ -1,22 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Vsevolod Ivanov <vsevolod.ivanov@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "infohash.h"
|
||||
@@ -32,6 +15,9 @@ extern "C" {
|
||||
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string_view>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <iso646.h>
|
||||
@@ -44,10 +30,13 @@ namespace dht {
|
||||
*/
|
||||
namespace crypto {
|
||||
|
||||
class OPENDHT_PUBLIC CryptoException : public std::runtime_error {
|
||||
class OPENDHT_PUBLIC CryptoException : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
explicit CryptoException(const std::string& str) : std::runtime_error(str) {};
|
||||
explicit CryptoException(const char* str) : std::runtime_error(str) {};
|
||||
explicit CryptoException(const std::string& str)
|
||||
: std::runtime_error(str) {};
|
||||
explicit CryptoException(const char* str)
|
||||
: std::runtime_error(str) {};
|
||||
CryptoException(const CryptoException& e) noexcept = default;
|
||||
CryptoException& operator=(const CryptoException&) noexcept = default;
|
||||
};
|
||||
@@ -55,10 +44,13 @@ public:
|
||||
/**
|
||||
* Exception thrown when a decryption error happened.
|
||||
*/
|
||||
class OPENDHT_PUBLIC DecryptError : public CryptoException {
|
||||
class OPENDHT_PUBLIC DecryptError : public CryptoException
|
||||
{
|
||||
public:
|
||||
explicit DecryptError(const std::string& str) : CryptoException(str) {};
|
||||
explicit DecryptError(const char* str) : CryptoException(str) {};
|
||||
explicit DecryptError(const std::string& str)
|
||||
: CryptoException(str) {};
|
||||
explicit DecryptError(const char* str)
|
||||
: CryptoException(str) {};
|
||||
DecryptError(const DecryptError& e) noexcept = default;
|
||||
DecryptError& operator=(const DecryptError&) noexcept = default;
|
||||
};
|
||||
@@ -79,57 +71,63 @@ struct OPENDHT_PUBLIC PublicKey
|
||||
/**
|
||||
* Takes ownership of an existing gnutls_pubkey.
|
||||
*/
|
||||
PublicKey(gnutls_pubkey_t k) : pk(k) {}
|
||||
PublicKey(gnutls_pubkey_t k)
|
||||
: pk(k)
|
||||
{}
|
||||
|
||||
/** Import public key from serialized data */
|
||||
PublicKey(const uint8_t* dat, size_t dat_size);
|
||||
PublicKey(const Blob& pk) : PublicKey(pk.data(), pk.size()) {}
|
||||
PublicKey(PublicKey&& o) noexcept : pk(o.pk) { o.pk = nullptr; };
|
||||
PublicKey(const Blob& pk)
|
||||
: PublicKey(pk.data(), pk.size())
|
||||
{}
|
||||
PublicKey(std::string_view pk)
|
||||
: PublicKey((const uint8_t*) pk.data(), pk.size())
|
||||
{}
|
||||
PublicKey(PublicKey&& o) noexcept
|
||||
: pk(o.pk)
|
||||
{
|
||||
o.pk = nullptr;
|
||||
}
|
||||
|
||||
~PublicKey();
|
||||
explicit operator bool() const { return pk; }
|
||||
bool operator ==(const PublicKey& o) const {
|
||||
return pk == o.pk || getId() == o.getId();
|
||||
}
|
||||
bool operator !=(const PublicKey& o) const {
|
||||
return !(*this == o);
|
||||
}
|
||||
bool operator==(const PublicKey& o) const { return pk == o.pk || getLongId() == o.getLongId(); }
|
||||
bool operator!=(const PublicKey& o) const { return !(*this == o); }
|
||||
|
||||
PublicKey& operator=(PublicKey&& o) noexcept;
|
||||
|
||||
/**
|
||||
* Get public key fingerprint
|
||||
*/
|
||||
InfoHash getId() const;
|
||||
const InfoHash& getId() const;
|
||||
|
||||
/**
|
||||
* Get public key long fingerprint
|
||||
*/
|
||||
PkId getLongId() const;
|
||||
const PkId& getLongId() const;
|
||||
|
||||
bool checkSignature(const uint8_t* data, size_t data_len, const uint8_t* signature, size_t signature_len) const;
|
||||
inline bool checkSignature(const Blob& data, const Blob& signature) const {
|
||||
inline bool checkSignature(const Blob& data, const Blob& signature) const
|
||||
{
|
||||
return checkSignature(data.data(), data.size(), signature.data(), signature.size());
|
||||
}
|
||||
|
||||
Blob encrypt(const uint8_t* data, size_t data_len) const;
|
||||
inline Blob encrypt(const Blob& data) const {
|
||||
return encrypt(data.data(), data.size());
|
||||
}
|
||||
|
||||
inline Blob encrypt(const Blob& data) const { return encrypt(data.data(), data.size()); }
|
||||
inline Blob encrypt(std::string_view data) const { return encrypt((const uint8_t*) data.data(), data.size()); }
|
||||
void pack(Blob& b) const;
|
||||
int pack(uint8_t* out, size_t* out_len) const;
|
||||
void unpack(const uint8_t* dat, size_t dat_size);
|
||||
|
||||
std::string toString() const;
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& p) const
|
||||
{
|
||||
Blob b;
|
||||
pack(b);
|
||||
p.pack_bin(b.size());
|
||||
p.pack_bin_body((const char*)b.data(), b.size());
|
||||
p.pack_bin_body((const char*) b.data(), b.size());
|
||||
}
|
||||
|
||||
void msgpack_unpack(const msgpack::object& o);
|
||||
@@ -137,7 +135,13 @@ struct OPENDHT_PUBLIC PublicKey
|
||||
gnutls_digest_algorithm_t getPreferredDigest() const;
|
||||
|
||||
gnutls_pubkey_t pk {nullptr};
|
||||
|
||||
private:
|
||||
mutable InfoHash cachedId_ {};
|
||||
mutable PkId cachedLongId_ {};
|
||||
mutable std::atomic_bool idCached_ {false};
|
||||
mutable std::atomic_bool longIdCached_ {false};
|
||||
|
||||
PublicKey(const PublicKey&) = delete;
|
||||
PublicKey& operator=(const PublicKey&) = delete;
|
||||
void encryptBloc(const uint8_t* src, size_t src_size, uint8_t* dst, size_t dst_size) const;
|
||||
@@ -149,7 +153,7 @@ private:
|
||||
struct OPENDHT_PUBLIC PrivateKey
|
||||
{
|
||||
PrivateKey();
|
||||
//PrivateKey(gnutls_privkey_t k) : key(k) {}
|
||||
// PrivateKey(gnutls_privkey_t k) : key(k) {}
|
||||
|
||||
/**
|
||||
* Takes ownership of an existing gnutls_x509_privkey.
|
||||
@@ -160,7 +164,13 @@ struct OPENDHT_PUBLIC PrivateKey
|
||||
PrivateKey& operator=(PrivateKey&& o) noexcept;
|
||||
|
||||
PrivateKey(const uint8_t* src, size_t src_size, const char* password = nullptr);
|
||||
PrivateKey(const Blob& src, const std::string& password = {}) : PrivateKey(src.data(), src.size(), password.data()) {}
|
||||
PrivateKey(const Blob& src, const std::string& password = {})
|
||||
: PrivateKey(src.data(), src.size(), password.c_str())
|
||||
{}
|
||||
PrivateKey(std::string_view src, const std::string& password = {})
|
||||
: PrivateKey((const uint8_t*) src.data(), src.size(), password.c_str())
|
||||
{}
|
||||
|
||||
~PrivateKey();
|
||||
explicit operator bool() const { return key; }
|
||||
|
||||
@@ -175,6 +185,7 @@ struct OPENDHT_PUBLIC PrivateKey
|
||||
* @returns the signature data.
|
||||
*/
|
||||
Blob sign(const uint8_t* data, size_t data_len) const;
|
||||
inline Blob sign(std::string_view dat) const { return sign((const uint8_t*) dat.data(), dat.size()); }
|
||||
inline Blob sign(const Blob& dat) const { return sign(dat.data(), dat.size()); }
|
||||
|
||||
/**
|
||||
@@ -190,17 +201,26 @@ struct OPENDHT_PUBLIC PrivateKey
|
||||
* @param key_length : size of the modulus in bits
|
||||
* Minimim value: 2048
|
||||
* Recommended values: 4096, 8192
|
||||
* @param algo : the public key algorithm to use, GNUTLS_PK_RSA or GNUTLS_PK_RSA_OAEP
|
||||
*/
|
||||
static PrivateKey generate(unsigned key_length = 4096);
|
||||
static PrivateKey generateEC();
|
||||
static PrivateKey generate(unsigned key_length = 4096, gnutls_pk_algorithm_t algo = GNUTLS_PK_RSA);
|
||||
|
||||
/**
|
||||
* Generate a new EC key pair
|
||||
* @param curve : the elliptic curve to use. If GNUTLS_ECC_CURVE_INVALID is provided, the default curve will be used
|
||||
* (currently GNUTLS_ECC_CURVE_SECP384R1).
|
||||
*/
|
||||
static PrivateKey generateEC(gnutls_ecc_curve_t curve = GNUTLS_ECC_CURVE_INVALID);
|
||||
|
||||
gnutls_privkey_t key {};
|
||||
gnutls_x509_privkey_t x509_key {};
|
||||
|
||||
private:
|
||||
PrivateKey(const PrivateKey&) = delete;
|
||||
PrivateKey& operator=(const PrivateKey&) = delete;
|
||||
Blob decryptBloc(const uint8_t* src, size_t src_size) const;
|
||||
|
||||
mutable std::mutex publicKeyMutex_;
|
||||
mutable std::shared_ptr<PublicKey> publicKey_ {};
|
||||
};
|
||||
|
||||
@@ -209,28 +229,39 @@ class OPENDHT_PUBLIC RevocationList
|
||||
using clock = std::chrono::system_clock;
|
||||
using time_point = clock::time_point;
|
||||
using duration = clock::duration;
|
||||
|
||||
public:
|
||||
RevocationList();
|
||||
RevocationList(const Blob& b);
|
||||
RevocationList(RevocationList&& o) noexcept : crl(o.crl) { o.crl = nullptr; }
|
||||
RevocationList(RevocationList&& o) noexcept
|
||||
: crl(o.crl)
|
||||
{
|
||||
o.crl = nullptr;
|
||||
}
|
||||
~RevocationList();
|
||||
|
||||
RevocationList& operator=(RevocationList&& o) { crl = o.crl; o.crl = nullptr; return *this; }
|
||||
RevocationList& operator=(RevocationList&& o)
|
||||
{
|
||||
crl = o.crl;
|
||||
o.crl = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void pack(Blob& b) const;
|
||||
void unpack(const uint8_t* dat, size_t dat_size);
|
||||
Blob getPacked() const {
|
||||
Blob getPacked() const
|
||||
{
|
||||
Blob b;
|
||||
pack(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& p) const
|
||||
{
|
||||
Blob b = getPacked();
|
||||
p.pack_bin(b.size());
|
||||
p.pack_bin_body((const char*)b.data(), b.size());
|
||||
p.pack_bin_body((const char*) b.data(), b.size());
|
||||
}
|
||||
|
||||
void msgpack_unpack(const msgpack::object& o);
|
||||
@@ -242,9 +273,15 @@ public:
|
||||
/**
|
||||
* Sign this revocation list using provided key and certificate.
|
||||
* Validity_period sets the duration until next update (default to no next update).
|
||||
* If `number` is non-zero, it is stored verbatim (big-endian) as the CRL Number
|
||||
* extension. Otherwise the number is initialized randomly on the first signature
|
||||
* and incremented on subsequent ones.
|
||||
*/
|
||||
void sign(const PrivateKey&, const Certificate&, duration validity_period = {});
|
||||
void sign(const Identity& id) { sign(*id.first, *id.second); }
|
||||
void sign(const PrivateKey&, const Certificate&, duration validity_period = {}, uint64_t number = 0);
|
||||
void sign(const Identity& id, duration validity_period = {}, uint64_t number = 0)
|
||||
{
|
||||
sign(*id.first, *id.second, validity_period, number);
|
||||
}
|
||||
|
||||
bool isSignedBy(const Certificate& issuer) const;
|
||||
|
||||
@@ -265,7 +302,8 @@ public:
|
||||
time_point getNextUpdateTime() const;
|
||||
|
||||
gnutls_x509_crl_t get() { return crl; }
|
||||
gnutls_x509_crl_t getCopy() const {
|
||||
gnutls_x509_crl_t getCopy() const
|
||||
{
|
||||
if (not crl)
|
||||
return nullptr;
|
||||
auto copy = RevocationList(getPacked());
|
||||
@@ -282,13 +320,21 @@ private:
|
||||
|
||||
enum class NameType { UNKNOWN = 0, RFC822, DNS, URI, IP };
|
||||
|
||||
class OPENDHT_PUBLIC CertificateRequest {
|
||||
class OPENDHT_PUBLIC CertificateRequest
|
||||
{
|
||||
public:
|
||||
CertificateRequest();
|
||||
CertificateRequest(const uint8_t* data, size_t size);
|
||||
CertificateRequest(const Blob& data) : CertificateRequest(data.data(), data.size()) {}
|
||||
CertificateRequest(std::string_view src)
|
||||
: CertificateRequest((const uint8_t*) src.data(), src.size())
|
||||
{}
|
||||
CertificateRequest(const Blob& data)
|
||||
: CertificateRequest(data.data(), data.size())
|
||||
{}
|
||||
|
||||
CertificateRequest(CertificateRequest&& o) noexcept : request(std::move(o.request)) {
|
||||
CertificateRequest(CertificateRequest&& o) noexcept
|
||||
: request(std::move(o.request))
|
||||
{
|
||||
o.request = nullptr;
|
||||
}
|
||||
CertificateRequest& operator=(CertificateRequest&& o) noexcept;
|
||||
@@ -310,6 +356,7 @@ public:
|
||||
std::string toString() const;
|
||||
|
||||
gnutls_x509_crq_t get() const { return request; }
|
||||
|
||||
private:
|
||||
CertificateRequest(const CertificateRequest& o) = delete;
|
||||
CertificateRequest& operator=(const CertificateRequest& o) = delete;
|
||||
@@ -319,8 +366,13 @@ private:
|
||||
class OPENDHT_PUBLIC OcspRequest
|
||||
{
|
||||
public:
|
||||
OcspRequest(gnutls_ocsp_req_t r) : request(r) {};
|
||||
OcspRequest(gnutls_ocsp_req_t r)
|
||||
: request(r)
|
||||
{}
|
||||
OcspRequest(const uint8_t* dat_ptr, size_t dat_size);
|
||||
OcspRequest(std::string_view dat)
|
||||
: OcspRequest((const uint8_t*) dat.data(), dat.size())
|
||||
{}
|
||||
~OcspRequest();
|
||||
|
||||
/*
|
||||
@@ -330,6 +382,7 @@ public:
|
||||
|
||||
Blob pack() const;
|
||||
Blob getNonce() const;
|
||||
|
||||
private:
|
||||
gnutls_ocsp_req_t request;
|
||||
};
|
||||
@@ -338,7 +391,9 @@ class OPENDHT_PUBLIC OcspResponse
|
||||
{
|
||||
public:
|
||||
OcspResponse(const uint8_t* dat_ptr, size_t dat_size);
|
||||
OcspResponse(const std::string& response) : OcspResponse((const uint8_t*)response.data(), response.size()) {};
|
||||
OcspResponse(std::string_view response)
|
||||
: OcspResponse((const uint8_t*) response.data(), response.size())
|
||||
{}
|
||||
~OcspResponse();
|
||||
|
||||
Blob pack() const;
|
||||
@@ -365,34 +420,46 @@ private:
|
||||
gnutls_ocsp_resp_t response;
|
||||
};
|
||||
|
||||
struct OPENDHT_PUBLIC Certificate {
|
||||
struct OPENDHT_PUBLIC Certificate
|
||||
{
|
||||
Certificate() noexcept {}
|
||||
|
||||
/**
|
||||
* Take ownership of existing gnutls structure
|
||||
*/
|
||||
Certificate(gnutls_x509_crt_t crt) noexcept : cert(crt) {}
|
||||
Certificate(gnutls_x509_crt_t crt) noexcept
|
||||
: cert(crt)
|
||||
{}
|
||||
|
||||
Certificate(Certificate&& o) noexcept : cert(o.cert), issuer(std::move(o.issuer)) { o.cert = nullptr; };
|
||||
Certificate(Certificate&& o) noexcept
|
||||
: cert(o.cert)
|
||||
, issuer(std::move(o.issuer))
|
||||
, publicKey_(std::move(o.publicKey_))
|
||||
{
|
||||
o.cert = nullptr;
|
||||
};
|
||||
|
||||
/**
|
||||
* Import certificate (PEM or DER) or certificate chain (PEM),
|
||||
* ordered from subject to issuer
|
||||
*/
|
||||
Certificate(const Blob& crt);
|
||||
Certificate(const std::string& pem) : cert(nullptr) {
|
||||
unpack((const uint8_t*)pem.data(), pem.size());
|
||||
}
|
||||
Certificate(const uint8_t* dat, size_t dat_size) : cert(nullptr) {
|
||||
Certificate(const uint8_t* dat, size_t dat_size)
|
||||
: cert(nullptr)
|
||||
{
|
||||
unpack(dat, dat_size);
|
||||
}
|
||||
Certificate(std::string_view pem)
|
||||
: Certificate((const uint8_t*) pem.data(), pem.size())
|
||||
{}
|
||||
|
||||
/**
|
||||
* Import certificate chain (PEM or DER),
|
||||
* ordered from subject to issuer
|
||||
*/
|
||||
template<typename Iterator>
|
||||
Certificate(const Iterator& begin, const Iterator& end) {
|
||||
Certificate(const Iterator& begin, const Iterator& end)
|
||||
{
|
||||
unpack(begin, end);
|
||||
}
|
||||
|
||||
@@ -401,7 +468,8 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
* ordered from subject to issuer
|
||||
*/
|
||||
template<typename Iterator>
|
||||
Certificate(const std::vector<std::pair<Iterator, Iterator>>& certs) {
|
||||
Certificate(const std::vector<std::pair<Iterator, Iterator>>& certs)
|
||||
{
|
||||
unpack(certs);
|
||||
}
|
||||
|
||||
@@ -410,7 +478,8 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
|
||||
void pack(Blob& b) const;
|
||||
void unpack(const uint8_t* dat, size_t dat_size);
|
||||
Blob getPacked() const {
|
||||
Blob getPacked() const
|
||||
{
|
||||
Blob b;
|
||||
pack(b);
|
||||
return b;
|
||||
@@ -459,7 +528,7 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
for (auto li = certs.rbegin(); li != certs.rend(); ++li) {
|
||||
Certificate tmp_crt;
|
||||
gnutls_x509_crt_init(&tmp_crt.cert);
|
||||
const gnutls_datum_t crt_dt {(uint8_t*)&(*li->first), (unsigned)(li->second-li->first)};
|
||||
const gnutls_datum_t crt_dt {(uint8_t*) &(*li->first), (unsigned) (li->second - li->first)};
|
||||
int err = gnutls_x509_crt_import(tmp_crt.cert, &crt_dt, GNUTLS_X509_FMT_PEM);
|
||||
if (err != GNUTLS_E_SUCCESS)
|
||||
err = gnutls_x509_crt_import(tmp_crt.cert, &crt_dt, GNUTLS_X509_FMT_DER);
|
||||
@@ -471,33 +540,40 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
*this = tmp_issuer ? std::move(*tmp_issuer) : Certificate();
|
||||
}
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& p) const
|
||||
{
|
||||
Blob b;
|
||||
pack(b);
|
||||
p.pack_bin(b.size());
|
||||
p.pack_bin_body((const char*)b.data(), b.size());
|
||||
p.pack_bin_body((const char*) b.data(), b.size());
|
||||
}
|
||||
|
||||
void msgpack_unpack(const msgpack::object& o);
|
||||
|
||||
explicit operator bool() const { return cert; }
|
||||
PublicKey getPublicKey() const;
|
||||
const PublicKey& getPublicKey() const;
|
||||
const std::shared_ptr<PublicKey>& getSharedPublicKey() const;
|
||||
|
||||
/** Same as getPublicKey().getId() */
|
||||
InfoHash getId() const;
|
||||
const InfoHash& getId() const;
|
||||
/** Same as getPublicKey().getLongId() */
|
||||
PkId getLongId() const;
|
||||
const PkId& getLongId() const;
|
||||
|
||||
Blob getSerialNumber() const;
|
||||
|
||||
/** Read certificate full DN as described in RFC4514 */
|
||||
std::string getDN() const;
|
||||
|
||||
/** Read certificate Common Name (CN) */
|
||||
std::string getName() const;
|
||||
|
||||
/** Read certificate User ID (UID) */
|
||||
std::string getUID() const;
|
||||
|
||||
/** Read certificate issuer DN as described in RFC4514 */
|
||||
std::string getIssuerDN() const;
|
||||
|
||||
/** Read certificate issuer Common Name (CN) */
|
||||
std::string getIssuerName() const;
|
||||
|
||||
@@ -541,10 +617,15 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
void addRevocationList(RevocationList&&);
|
||||
void addRevocationList(std::shared_ptr<RevocationList>);
|
||||
|
||||
static Certificate generate(const PrivateKey& key, const std::string& name = "dhtnode", const Identity& ca = {}, bool is_ca = false, int64_t validity = 0);
|
||||
static Certificate generate(const PrivateKey& key,
|
||||
const std::string& name = "dhtnode",
|
||||
const Identity& ca = {},
|
||||
bool is_ca = false,
|
||||
int64_t validity = 0);
|
||||
static Certificate generate(const CertificateRequest& request, const Identity& ca, int64_t validity = 0);
|
||||
|
||||
gnutls_x509_crt_t getCopy() const {
|
||||
gnutls_x509_crt_t getCopy() const
|
||||
{
|
||||
if (not cert)
|
||||
return nullptr;
|
||||
auto copy = Certificate(getPacked());
|
||||
@@ -553,8 +634,7 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::vector<gnutls_x509_crt_t>
|
||||
getChain(bool copy = false) const
|
||||
std::vector<gnutls_x509_crt_t> getChain(bool copy = false) const
|
||||
{
|
||||
if (not cert)
|
||||
return {};
|
||||
@@ -564,11 +644,8 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
return crts;
|
||||
}
|
||||
|
||||
std::pair<
|
||||
std::vector<gnutls_x509_crt_t>,
|
||||
std::vector<gnutls_x509_crl_t>
|
||||
>
|
||||
getChainWithRevocations(bool copy = false) const
|
||||
std::pair<std::vector<gnutls_x509_crt_t>, std::vector<gnutls_x509_crl_t>> getChainWithRevocations(
|
||||
bool copy = false) const
|
||||
{
|
||||
if (not cert)
|
||||
return {};
|
||||
@@ -601,35 +678,46 @@ struct OPENDHT_PUBLIC Certificate {
|
||||
gnutls_x509_crt_t cert {nullptr};
|
||||
std::shared_ptr<Certificate> issuer {};
|
||||
std::shared_ptr<OcspResponse> ocspResponse;
|
||||
|
||||
private:
|
||||
Certificate(const Certificate&) = delete;
|
||||
Certificate& operator=(const Certificate&) = delete;
|
||||
mutable InfoHash cachedId_ {};
|
||||
mutable PkId cachedLongId_ {};
|
||||
mutable std::atomic_bool idCached_ {false};
|
||||
mutable std::atomic_bool longIdCached_ {false};
|
||||
|
||||
struct crlNumberCmp {
|
||||
bool operator() (const std::shared_ptr<RevocationList>& lhs, const std::shared_ptr<RevocationList>& rhs) const {
|
||||
struct crlNumberCmp
|
||||
{
|
||||
bool operator()(const std::shared_ptr<RevocationList>& lhs, const std::shared_ptr<RevocationList>& rhs) const
|
||||
{
|
||||
return lhs->getNumber() < rhs->getNumber();
|
||||
}
|
||||
};
|
||||
|
||||
std::set<std::shared_ptr<RevocationList>, crlNumberCmp> revocation_lists;
|
||||
|
||||
mutable std::mutex publicKeyMutex_;
|
||||
mutable std::shared_ptr<PublicKey> publicKey_ {};
|
||||
};
|
||||
|
||||
struct OPENDHT_PUBLIC TrustList
|
||||
{
|
||||
struct VerifyResult {
|
||||
struct VerifyResult
|
||||
{
|
||||
int ret;
|
||||
unsigned result;
|
||||
bool hasError() const { return ret < 0; }
|
||||
bool isValid() const { return !hasError() and !(result & GNUTLS_CERT_INVALID); }
|
||||
explicit operator bool() const { return isValid(); }
|
||||
std::string toString() const;
|
||||
OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const VerifyResult& h);
|
||||
OPENDHT_PUBLIC std::string toString() const;
|
||||
OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const VerifyResult& h);
|
||||
};
|
||||
|
||||
TrustList();
|
||||
TrustList(TrustList&& o) noexcept : trust(std::move(o.trust)) {
|
||||
TrustList(TrustList&& o) noexcept
|
||||
: trust(std::move(o.trust))
|
||||
{
|
||||
o.trust = nullptr;
|
||||
}
|
||||
TrustList& operator=(TrustList&& o) noexcept;
|
||||
@@ -645,94 +733,6 @@ private:
|
||||
gnutls_x509_trust_list_t trust {nullptr};
|
||||
};
|
||||
|
||||
template <class T>
|
||||
class OPENDHT_PUBLIC secure_vector
|
||||
{
|
||||
public:
|
||||
secure_vector() {}
|
||||
secure_vector(secure_vector<T> const&) = default;
|
||||
secure_vector(secure_vector<T> &&) = default;
|
||||
explicit secure_vector(unsigned size): data_(size) {}
|
||||
explicit secure_vector(unsigned size, T _item): data_(size, _item) {}
|
||||
explicit secure_vector(const std::vector<T>& c): data_(c) {}
|
||||
secure_vector(std::vector<T>&& c): data_(std::move(c)) {}
|
||||
~secure_vector() { clean(); }
|
||||
|
||||
static secure_vector<T> getRandom(size_t size) {
|
||||
secure_vector<T> ret(size);
|
||||
crypto::random_device rdev;
|
||||
#ifdef _WIN32
|
||||
std::uniform_int_distribution<int> rand_byte{ 0, std::numeric_limits<uint8_t>::max() };
|
||||
#else
|
||||
std::uniform_int_distribution<uint8_t> rand_byte;
|
||||
#endif
|
||||
std::generate_n((uint8_t*)ret.data_.data(), ret.size()*sizeof(T), std::bind(rand_byte, std::ref(rdev)));
|
||||
return ret;
|
||||
}
|
||||
secure_vector<T>& operator=(const secure_vector<T>& c) {
|
||||
if (&c == this)
|
||||
return *this;
|
||||
clean();
|
||||
data_ = c.data_;
|
||||
return *this;
|
||||
}
|
||||
secure_vector<T>& operator=(secure_vector<T>&& c) {
|
||||
if (&c == this)
|
||||
return *this;
|
||||
clean();
|
||||
data_ = std::move(c.data_);
|
||||
return *this;
|
||||
}
|
||||
secure_vector<T>& operator=(std::vector<T>&& c) {
|
||||
clean();
|
||||
data_ = std::move(c);
|
||||
return *this;
|
||||
}
|
||||
std::vector<T>& writable() { clean(); return data_; }
|
||||
const std::vector<T>& makeInsecure() const { return data_; }
|
||||
const uint8_t* data() const { return data_.data(); }
|
||||
|
||||
void clean() {
|
||||
clean(data_.begin(), data_.end());
|
||||
}
|
||||
|
||||
void clear() { clean(); data_.clear(); }
|
||||
|
||||
size_t size() const { return data_.size(); }
|
||||
bool empty() const { return data_.empty(); }
|
||||
|
||||
void swap(secure_vector<T>& other) { data_.swap(other.data_); }
|
||||
void resize(size_t s) {
|
||||
if (s == data_.size()) return;
|
||||
if (s < data_.size()) {
|
||||
//shrink
|
||||
clean(data_.begin()+s, data_.end());
|
||||
data_.resize(s);
|
||||
} else {
|
||||
//grow
|
||||
auto data = std::move(data_); // move protected data
|
||||
clear();
|
||||
data_.resize(s);
|
||||
std::copy(data.begin(), data.end(), data_.begin());
|
||||
clean(data.begin(), data.end());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* Securely wipe memory
|
||||
*/
|
||||
static void clean(const typename std::vector<T>::iterator& i, const typename std::vector<T>::iterator& j) {
|
||||
volatile uint8_t* b = reinterpret_cast<uint8_t*>(&*i);
|
||||
volatile uint8_t* e = reinterpret_cast<uint8_t*>(&*j);
|
||||
std::fill(b, e, 0);
|
||||
}
|
||||
|
||||
std::vector<T> data_;
|
||||
};
|
||||
|
||||
using SecureBlob = secure_vector<uint8_t>;
|
||||
|
||||
/**
|
||||
* Generate an RSA key pair (4096 bits) and a certificate.
|
||||
* @param name the name used in the generated certificate
|
||||
@@ -741,12 +741,15 @@ using SecureBlob = secure_vector<uint8_t>;
|
||||
* @param key_length stength of the generated private key (bits).
|
||||
*/
|
||||
OPENDHT_PUBLIC Identity generateIdentity(const std::string& name, const Identity& ca, unsigned key_length, bool is_ca);
|
||||
OPENDHT_PUBLIC Identity generateIdentity(const std::string& name = "dhtnode", const Identity& ca = {}, unsigned key_length = 4096);
|
||||
OPENDHT_PUBLIC Identity generateIdentity(const std::string& name = "dhtnode",
|
||||
const Identity& ca = {},
|
||||
unsigned key_length = 4096);
|
||||
|
||||
OPENDHT_PUBLIC Identity generateEcIdentity(const std::string& name, const Identity& ca, bool is_ca);
|
||||
OPENDHT_PUBLIC Identity generateEcIdentity(const std::string& name = "dhtnode", const Identity& ca = {});
|
||||
|
||||
OPENDHT_PUBLIC void saveIdentity(const Identity& id, const std::string& path, const std::string& privkey_password = {});
|
||||
OPENDHT_PUBLIC Identity loadIdentity(const std::string& path, const std::string& privkey_password = {});
|
||||
|
||||
/**
|
||||
* Performs SHA512, SHA256 or SHA1, depending on hash_length.
|
||||
@@ -756,7 +759,7 @@ OPENDHT_PUBLIC void saveIdentity(const Identity& id, const std::string& path, co
|
||||
* will use SHA256 for hash_length up to 32 bytes,
|
||||
* will use SHA512 for hash_length of 33 bytes and more.
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob hash(const Blob& data, size_t hash_length = 512/8);
|
||||
OPENDHT_PUBLIC Blob hash(const Blob& data, size_t hash_length = 512 / 8);
|
||||
|
||||
OPENDHT_PUBLIC void hash(const uint8_t* data, size_t data_length, uint8_t* hash, size_t hash_length);
|
||||
|
||||
@@ -767,24 +770,107 @@ OPENDHT_PUBLIC void hash(const uint8_t* data, size_t data_length, uint8_t* hash,
|
||||
* that can be transmitted in clear, and will be generated if
|
||||
* not provided (32 bytes).
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob stretchKey(const std::string& password, Blob& salt, size_t key_length = 512/8);
|
||||
OPENDHT_PUBLIC Blob stretchKey(std::string_view password, Blob& salt, size_t key_length = 512 / 8);
|
||||
|
||||
/**
|
||||
* AES-GCM encryption. Key must be 128, 192 or 256 bits long (16, 24 or 32 bytes).
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob aesEncrypt(const uint8_t* data, size_t data_length, const Blob& key);
|
||||
OPENDHT_PUBLIC inline Blob aesEncrypt(const Blob& data, const Blob& key) {
|
||||
OPENDHT_PUBLIC inline Blob
|
||||
aesEncrypt(const Blob& data, const Blob& key)
|
||||
{
|
||||
return aesEncrypt(data.data(), data.size(), key);
|
||||
}
|
||||
OPENDHT_PUBLIC Blob aesEncrypt(const Blob& data, const std::string& password);
|
||||
/**
|
||||
* AES-GCM encryption with argon2 key derivation.
|
||||
* This function uses `stretchKey` to generate an AES key from the password and a random salt.
|
||||
* The result is a bundle including the salt that can be decrypted with `aesDecrypt(data, password)`.
|
||||
* If needed, the salt or encrypted data can be individually extracted from the bundle with `aesGetSalt` and
|
||||
* `aesGetEncrypted`.
|
||||
* @param data: data to encrypt
|
||||
* @param password: password to encrypt the data with
|
||||
* @param salt: optional salt to use for key derivation. If not provided, a random salt will be generated.
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob aesEncrypt(const Blob& data, std::string_view password, const Blob& salt = {});
|
||||
|
||||
/**
|
||||
* AES-GCM decryption.
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob aesDecrypt(const uint8_t* data, size_t data_length, const Blob& key);
|
||||
OPENDHT_PUBLIC inline Blob aesDecrypt(const Blob& data, const Blob& key) { return aesDecrypt(data.data(), data.size(), key); }
|
||||
OPENDHT_PUBLIC Blob aesDecrypt(const uint8_t* data, size_t data_length, const std::string& password);
|
||||
OPENDHT_PUBLIC inline Blob aesDecrypt(const Blob& data, const std::string& password) { return aesDecrypt(data.data(), data.size(), password); }
|
||||
OPENDHT_PUBLIC inline Blob
|
||||
aesDecrypt(const Blob& data, const Blob& key)
|
||||
{
|
||||
return aesDecrypt(data.data(), data.size(), key);
|
||||
}
|
||||
OPENDHT_PUBLIC inline Blob
|
||||
aesDecrypt(std::string_view data, const Blob& key)
|
||||
{
|
||||
return aesDecrypt((uint8_t*) data.data(), data.size(), key);
|
||||
}
|
||||
|
||||
OPENDHT_PUBLIC Blob aesDecrypt(const uint8_t* data, size_t data_length, std::string_view password);
|
||||
OPENDHT_PUBLIC inline Blob
|
||||
aesDecrypt(const Blob& data, std::string_view password)
|
||||
{
|
||||
return aesDecrypt(data.data(), data.size(), password);
|
||||
}
|
||||
OPENDHT_PUBLIC inline Blob
|
||||
aesDecrypt(std::string_view data, std::string_view password)
|
||||
{
|
||||
return aesDecrypt((uint8_t*) data.data(), data.size(), password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get raw AES key from password and salt stored with the encrypted data.
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob aesGetKey(const uint8_t* data, size_t data_length, std::string_view password);
|
||||
OPENDHT_PUBLIC Blob inline aesGetKey(const Blob& data, std::string_view password)
|
||||
{
|
||||
return aesGetKey(data.data(), data.size(), password);
|
||||
}
|
||||
/** Get the salt part of data password-encrypted with `aesEncrypt(data, password)` */
|
||||
OPENDHT_PUBLIC Blob aesGetSalt(const uint8_t* data, size_t data_length);
|
||||
OPENDHT_PUBLIC Blob inline aesGetSalt(const Blob& data)
|
||||
{
|
||||
return aesGetSalt(data.data(), data.size());
|
||||
}
|
||||
/** Get the encrypted data (ciphertext) part of data password-encrypted with `aesEncrypt(data, password)` */
|
||||
OPENDHT_PUBLIC std::string_view aesGetEncrypted(const uint8_t* data, size_t data_length);
|
||||
OPENDHT_PUBLIC std::string_view inline aesGetEncrypted(const Blob& data)
|
||||
{
|
||||
return aesGetEncrypted(data.data(), data.size());
|
||||
}
|
||||
|
||||
/** Build an encrypted bundle that can be decrypted with aesDecrypt(data, password).
|
||||
* @param encryptedData: result of `aesEncrypt(data, key)` or `aesGetEncrypted`
|
||||
* @param salt: should match the encryption key and password so that `stretchKey(password, salk) == key`.
|
||||
* Can be obtained from an existing bundle with `aesGetSalt`.
|
||||
**/
|
||||
OPENDHT_PUBLIC Blob aesBuildEncrypted(const uint8_t* encryptedData, size_t data_length, const Blob& salt);
|
||||
OPENDHT_PUBLIC Blob inline aesBuildEncrypted(const Blob& encryptedData, const Blob& salt)
|
||||
{
|
||||
return aesBuildEncrypted(encryptedData.data(), encryptedData.size(), salt);
|
||||
}
|
||||
OPENDHT_PUBLIC Blob inline aesBuildEncrypted(std::string_view encryptedData, const Blob& salt)
|
||||
{
|
||||
return aesBuildEncrypted((const uint8_t*) encryptedData.data(), encryptedData.size(), salt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypts a payload for WebPush (RFC 8291).
|
||||
* @param p256dh: The user's P-256 public key (uncompressed, 65 bytes).
|
||||
* @param auth: The user's authentication secret (16 bytes).
|
||||
* @param payload: The data to encrypt.
|
||||
* @param privKey: (Optional) The sender's private key (for testing).
|
||||
* @param salt: (Optional) The salt to use (for testing).
|
||||
* @return The encrypted body (including salt, record size, keyid).
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob webPushEncrypt(const Blob& p256dh,
|
||||
const Blob& auth,
|
||||
const uint8_t* payload,
|
||||
size_t payload_length,
|
||||
const PrivateKey& privKey = {},
|
||||
const Blob& salt = {});
|
||||
|
||||
} // namespace crypto
|
||||
} // namespace dht
|
||||
@@ -0,0 +1,121 @@
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <random>
|
||||
|
||||
namespace dht {
|
||||
namespace crypto {
|
||||
|
||||
template<class T>
|
||||
class secure_vector
|
||||
{
|
||||
public:
|
||||
secure_vector() {}
|
||||
secure_vector(secure_vector<T> const&) = default;
|
||||
secure_vector(secure_vector<T>&&) = default;
|
||||
explicit secure_vector(unsigned size)
|
||||
: data_(size)
|
||||
{}
|
||||
explicit secure_vector(unsigned size, T _item)
|
||||
: data_(size, _item)
|
||||
{}
|
||||
explicit secure_vector(const std::vector<T>& c)
|
||||
: data_(c)
|
||||
{}
|
||||
secure_vector(std::vector<T>&& c)
|
||||
: data_(std::move(c))
|
||||
{}
|
||||
~secure_vector() { clean(); }
|
||||
|
||||
static secure_vector<T> getRandom(size_t size)
|
||||
{
|
||||
secure_vector<T> ret(size);
|
||||
std::random_device rdev;
|
||||
#ifdef _WIN32
|
||||
std::uniform_int_distribution<int> rand_byte {0, std::numeric_limits<uint8_t>::max()};
|
||||
#else
|
||||
std::uniform_int_distribution<uint8_t> rand_byte;
|
||||
#endif
|
||||
std::generate_n((uint8_t*) ret.data_.data(), ret.size() * sizeof(T), std::bind(rand_byte, std::ref(rdev)));
|
||||
return ret;
|
||||
}
|
||||
secure_vector<T>& operator=(const secure_vector<T>& c)
|
||||
{
|
||||
if (&c == this)
|
||||
return *this;
|
||||
clean();
|
||||
data_ = c.data_;
|
||||
return *this;
|
||||
}
|
||||
secure_vector<T>& operator=(secure_vector<T>&& c)
|
||||
{
|
||||
if (&c == this)
|
||||
return *this;
|
||||
clean();
|
||||
data_ = std::move(c.data_);
|
||||
return *this;
|
||||
}
|
||||
secure_vector<T>& operator=(std::vector<T>&& c)
|
||||
{
|
||||
clean();
|
||||
data_ = std::move(c);
|
||||
return *this;
|
||||
}
|
||||
std::vector<T>& writable()
|
||||
{
|
||||
clean();
|
||||
return data_;
|
||||
}
|
||||
const std::vector<T>& makeInsecure() const { return data_; }
|
||||
const uint8_t* data() const { return data_.data(); }
|
||||
|
||||
void clean() { clean(data_.begin(), data_.end()); }
|
||||
|
||||
void clear()
|
||||
{
|
||||
clean();
|
||||
data_.clear();
|
||||
}
|
||||
|
||||
size_t size() const { return data_.size(); }
|
||||
bool empty() const { return data_.empty(); }
|
||||
|
||||
void swap(secure_vector<T>& other) { data_.swap(other.data_); }
|
||||
void resize(size_t s)
|
||||
{
|
||||
if (s == data_.size())
|
||||
return;
|
||||
if (s < data_.size()) {
|
||||
// shrink
|
||||
clean(data_.begin() + s, data_.end());
|
||||
data_.resize(s);
|
||||
} else {
|
||||
// grow
|
||||
auto data = std::move(data_); // move protected data
|
||||
clear();
|
||||
data_.resize(s);
|
||||
std::copy(data.begin(), data.end(), data_.begin());
|
||||
clean(data.begin(), data.end());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
/**
|
||||
* Securely wipe memory
|
||||
*/
|
||||
static void clean(const typename std::vector<T>::iterator& i, const typename std::vector<T>::iterator& j)
|
||||
{
|
||||
volatile uint8_t* b = reinterpret_cast<uint8_t*>(&*i);
|
||||
volatile uint8_t* e = reinterpret_cast<uint8_t*>(&*j);
|
||||
std::fill(b, e, 0);
|
||||
}
|
||||
|
||||
std::vector<T> data_;
|
||||
};
|
||||
|
||||
using SecureBlob = secure_vector<uint8_t>;
|
||||
|
||||
} // namespace crypto
|
||||
} // namespace dht
|
||||
@@ -1,33 +1,12 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "value.h"
|
||||
#include "sockaddr.h"
|
||||
|
||||
namespace dht {
|
||||
enum class ImStatus : uint8_t {
|
||||
NONE = 0,
|
||||
TYPING,
|
||||
RECEIVED,
|
||||
READ
|
||||
};
|
||||
enum class ImStatus : uint8_t { NONE = 0, TYPING, RECEIVED, READ };
|
||||
}
|
||||
MSGPACK_ADD_ENUM(dht::ImStatus)
|
||||
|
||||
@@ -38,11 +17,12 @@ class OPENDHT_PUBLIC DhtMessage : public Value::Serializable<DhtMessage>
|
||||
public:
|
||||
static const ValueType TYPE;
|
||||
|
||||
DhtMessage(const std::string& s = {}, const Blob& msg = {}) : service(s), data(msg) {}
|
||||
DhtMessage(const std::string& s = {}, const Blob& msg = {})
|
||||
: service(s)
|
||||
, data(msg)
|
||||
{}
|
||||
|
||||
std::string getService() const {
|
||||
return service;
|
||||
}
|
||||
std::string getService() const { return service; }
|
||||
|
||||
static Value::Filter getFilter() { return {}; }
|
||||
|
||||
@@ -51,61 +31,67 @@ public:
|
||||
static Value::Filter ServiceFilter(const std::string& s);
|
||||
|
||||
/** print value for debugging */
|
||||
friend std::ostream& operator<< (std::ostream&, const DhtMessage&);
|
||||
friend std::ostream& operator<<(std::ostream&, const DhtMessage&);
|
||||
|
||||
std::string service;
|
||||
Blob data;
|
||||
MSGPACK_DEFINE(service, data)
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class OPENDHT_PUBLIC SignedValue : public Value::Serializable<T>
|
||||
template<typename T>
|
||||
class SignedValue : public Value::Serializable<T>
|
||||
{
|
||||
private:
|
||||
using BaseClass = Value::Serializable<T>;
|
||||
|
||||
public:
|
||||
virtual void unpackValue(const Value& v) override {
|
||||
virtual void unpackValue(const Value& v) override
|
||||
{
|
||||
if (v.owner) {
|
||||
owner = v.owner;
|
||||
from = v.owner->getId();
|
||||
} else {
|
||||
throw std::runtime_error("Value has no owner");
|
||||
}
|
||||
BaseClass::unpackValue(v);
|
||||
}
|
||||
|
||||
static Value::Filter getFilter() {
|
||||
return [](const Value& v){ return v.isSigned(); };
|
||||
static Value::Filter getFilter()
|
||||
{
|
||||
return [](const Value& v) {
|
||||
return v.isSigned();
|
||||
};
|
||||
}
|
||||
|
||||
Sp<crypto::PublicKey> owner;
|
||||
dht::InfoHash from;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class OPENDHT_PUBLIC EncryptedValue : public SignedValue<T>
|
||||
template<typename T>
|
||||
class EncryptedValue : public SignedValue<T>
|
||||
{
|
||||
public:
|
||||
using BaseClass = SignedValue<T>;
|
||||
|
||||
public:
|
||||
virtual void unpackValue(const Value& v) override {
|
||||
virtual void unpackValue(const Value& v) override
|
||||
{
|
||||
if (!v.recipient) {
|
||||
throw std::runtime_error("Value has no recipient");
|
||||
}
|
||||
to = v.recipient;
|
||||
BaseClass::unpackValue(v);
|
||||
}
|
||||
|
||||
static Value::Filter getFilter() {
|
||||
return Value::Filter::chain(
|
||||
BaseClass::getFilter(),
|
||||
[](const Value& v) { return static_cast<bool>(v.recipient); }
|
||||
);
|
||||
static Value::Filter getFilter()
|
||||
{
|
||||
return Value::Filter::chain(BaseClass::getFilter(),
|
||||
[](const Value& v) { return static_cast<bool>(v.recipient); });
|
||||
}
|
||||
|
||||
dht::InfoHash to;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
class OPENDHT_PUBLIC ImMessage : public SignedValue<ImMessage>
|
||||
{
|
||||
private:
|
||||
@@ -116,17 +102,32 @@ public:
|
||||
|
||||
ImMessage() {}
|
||||
ImMessage(dht::Value::Id id, std::string&& m, long d = 0)
|
||||
: id(id), msg(std::move(m)), date(d) {}
|
||||
ImMessage(dht::Value::Id id, std::string &&dt, std::string &&m, long d = 0)
|
||||
: id(id), msg(std::move(m)), datatype(std::move(dt)), date(d) {}
|
||||
ImMessage(dht::Value::Id id, std::string &&dt, std::string &&m, std::map<std::string, std::string> &&md, long d = 0)
|
||||
: id(id), msg(std::move(m)), datatype(std::move(dt)), metadatas(std::move(md)), date(d) {}
|
||||
: id(id)
|
||||
, msg(std::move(m))
|
||||
, date(d)
|
||||
{}
|
||||
ImMessage(dht::Value::Id id, std::string&& dt, std::string&& m, long d = 0)
|
||||
: id(id)
|
||||
, msg(std::move(m))
|
||||
, datatype(std::move(dt))
|
||||
, date(d)
|
||||
{}
|
||||
ImMessage(dht::Value::Id id, std::string&& dt, std::string&& m, std::map<std::string, std::string>&& md, long d = 0)
|
||||
: id(id)
|
||||
, msg(std::move(m))
|
||||
, datatype(std::move(dt))
|
||||
, metadatas(std::move(md))
|
||||
, date(d)
|
||||
{}
|
||||
|
||||
virtual void unpackValue(const Value& v) override {
|
||||
virtual void unpackValue(const Value& v) override
|
||||
{
|
||||
to = v.recipient;
|
||||
SignedValue::unpackValue(v);
|
||||
}
|
||||
|
||||
static Value::Filter getFilter() { return SignedValue::getFilter(); }
|
||||
|
||||
dht::InfoHash to;
|
||||
dht::Value::Id id {0};
|
||||
std::string msg;
|
||||
@@ -147,13 +148,24 @@ public:
|
||||
static const ValueType TYPE;
|
||||
|
||||
TrustRequest() {}
|
||||
TrustRequest(std::string s, std::string ci = {}) : service(s), conversationId(ci) {}
|
||||
TrustRequest(std::string s, std::string ci, const Blob& d) : service(s), conversationId(ci), payload(d) {}
|
||||
TrustRequest(std::string s, std::string ci = {})
|
||||
: service(s)
|
||||
, conversationId(ci)
|
||||
{}
|
||||
TrustRequest(std::string s, std::string ci, const Blob& d)
|
||||
: service(s)
|
||||
, conversationId(ci)
|
||||
, payload(d)
|
||||
{}
|
||||
|
||||
static Value::Filter getFilter() {
|
||||
return EncryptedValue::getFilter();
|
||||
static Value::Filter getFilter() { return EncryptedValue::getFilter(); }
|
||||
virtual void unpackValue(const dht::Value& v) override
|
||||
{
|
||||
BaseClass::unpackValue(v);
|
||||
id = v.id;
|
||||
}
|
||||
|
||||
dht::Value::Id id {0}; /// Value ID of the trust request, used for deserialization only.
|
||||
std::string service;
|
||||
std::string conversationId;
|
||||
Blob payload;
|
||||
@@ -170,20 +182,21 @@ public:
|
||||
static const ValueType TYPE;
|
||||
|
||||
IceCandidates() {}
|
||||
IceCandidates(Value::Id msg_id, Blob ice) : id(msg_id), ice_data(ice) {}
|
||||
IceCandidates(Value::Id msg_id, Blob ice)
|
||||
: id(msg_id)
|
||||
, ice_data(ice)
|
||||
{}
|
||||
|
||||
static Value::Filter getFilter() {
|
||||
return EncryptedValue::getFilter();
|
||||
}
|
||||
static Value::Filter getFilter() { return EncryptedValue::getFilter(); }
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& pk) const
|
||||
{
|
||||
pk.pack_array(2);
|
||||
pk.pack(id);
|
||||
#if 1
|
||||
pk.pack_bin(ice_data.size());
|
||||
pk.pack_bin_body((const char*)ice_data.data(), ice_data.size());
|
||||
pk.pack_bin_body((const char*) ice_data.data(), ice_data.size());
|
||||
#else
|
||||
// hack for backward compatibility with old opendht compiled with msgpack 1.0
|
||||
// remove when enough people have moved to new versions
|
||||
@@ -195,8 +208,10 @@ public:
|
||||
|
||||
virtual void msgpack_unpack(const msgpack::object& o)
|
||||
{
|
||||
if (o.type != msgpack::type::ARRAY) throw msgpack::type_error();
|
||||
if (o.via.array.size < 2) throw msgpack::type_error();
|
||||
if (o.type != msgpack::type::ARRAY)
|
||||
throw msgpack::type_error();
|
||||
if (o.via.array.size < 2)
|
||||
throw msgpack::type_error();
|
||||
id = o.via.array.ptr[0].as<Value::Id>();
|
||||
ice_data = unpackBlob(o.via.array.ptr[1]);
|
||||
}
|
||||
@@ -215,59 +230,51 @@ private:
|
||||
public:
|
||||
static const ValueType TYPE;
|
||||
|
||||
IpServiceAnnouncement(sa_family_t family = AF_UNSPEC, in_port_t p = 0) {
|
||||
IpServiceAnnouncement(sa_family_t family = AF_UNSPEC, in_port_t p = 0)
|
||||
{
|
||||
addr.setFamily(family);
|
||||
addr.setPort(p);
|
||||
}
|
||||
|
||||
IpServiceAnnouncement(const SockAddr& sa) : addr(sa) {}
|
||||
IpServiceAnnouncement(const SockAddr& sa)
|
||||
: addr(sa)
|
||||
{}
|
||||
|
||||
IpServiceAnnouncement(const Blob& b) {
|
||||
msgpack_unpack(unpackMsg(b).get());
|
||||
}
|
||||
IpServiceAnnouncement(const Blob& b) { msgpack_unpack(unpackMsg(b).get()); }
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& pk) const
|
||||
{
|
||||
pk.pack_bin(addr.getLength());
|
||||
pk.pack_bin_body((const char*)addr.get(), addr.getLength());
|
||||
pk.pack_bin_body((const char*) addr.get(), addr.getLength());
|
||||
}
|
||||
|
||||
virtual void msgpack_unpack(const msgpack::object& o)
|
||||
{
|
||||
if (o.type == msgpack::type::BIN)
|
||||
addr = {(sockaddr*)o.via.bin.ptr, (socklen_t)o.via.bin.size};
|
||||
addr = {(sockaddr*) o.via.bin.ptr, (socklen_t) o.via.bin.size};
|
||||
else
|
||||
throw msgpack::type_error();
|
||||
}
|
||||
|
||||
in_port_t getPort() const {
|
||||
return addr.getPort();
|
||||
}
|
||||
void setPort(in_port_t p) {
|
||||
addr.setPort(p);
|
||||
}
|
||||
in_port_t getPort() const { return addr.getPort(); }
|
||||
void setPort(in_port_t p) { addr.setPort(p); }
|
||||
|
||||
const SockAddr& getPeerAddr() const {
|
||||
return addr;
|
||||
}
|
||||
const SockAddr& getPeerAddr() const { return addr; }
|
||||
|
||||
virtual const ValueType& getType() const {
|
||||
return TYPE;
|
||||
}
|
||||
virtual const ValueType& getType() const { return TYPE; }
|
||||
|
||||
static bool storePolicy(InfoHash, std::shared_ptr<Value>&, const InfoHash&, const SockAddr&);
|
||||
|
||||
/** print value for debugging */
|
||||
friend std::ostream& operator<< (std::ostream&, const IpServiceAnnouncement&);
|
||||
friend std::ostream& operator<<(std::ostream&, const IpServiceAnnouncement&);
|
||||
|
||||
private:
|
||||
SockAddr addr;
|
||||
};
|
||||
|
||||
|
||||
OPENDHT_PUBLIC extern const std::array<std::reference_wrapper<const ValueType>, 5> DEFAULT_TYPES;
|
||||
|
||||
OPENDHT_PUBLIC extern const std::array<std::reference_wrapper<const ValueType>, 1> DEFAULT_INSECURE_TYPES;
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+162
-154
@@ -1,23 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Authors: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
* Sébastien Blin <sebastien.blin@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "infohash.h"
|
||||
@@ -59,16 +41,17 @@ struct LocalListener;
|
||||
* Must be given open UDP sockets and ::periodic must be
|
||||
* called regularly.
|
||||
*/
|
||||
class OPENDHT_PUBLIC Dht final : public DhtInterface {
|
||||
class OPENDHT_PUBLIC Dht final : public DhtInterface
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Initialise the Dht with two open sockets (for IPv4 and IP6)
|
||||
* and an ID for the node.
|
||||
*/
|
||||
Dht(std::unique_ptr<net::DatagramSocket>&& sock, const Config& config, const Sp<Logger>& l = {});
|
||||
|
||||
Dht(std::unique_ptr<net::DatagramSocket>&& sock, const Config& config, const Logger& l = {})
|
||||
: Dht(std::move(sock), config, std::make_shared<Logger>(l)) {}
|
||||
Dht(std::unique_ptr<net::DatagramSocket>&& sock,
|
||||
const Config& config,
|
||||
const Sp<Logger>& l = {},
|
||||
std::unique_ptr<std::mt19937_64>&& rd = {});
|
||||
|
||||
virtual ~Dht();
|
||||
|
||||
@@ -76,19 +59,16 @@ public:
|
||||
* Get the ID of the node.
|
||||
*/
|
||||
inline const InfoHash& getNodeId() const override { return myid; }
|
||||
void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { publicAddressChangedCb_ = std::move(cb); }
|
||||
|
||||
NodeStatus updateStatus(sa_family_t af) override;
|
||||
|
||||
/**
|
||||
* Get the current status of the node for the given family.
|
||||
*/
|
||||
NodeStatus getStatus(sa_family_t af) const override {
|
||||
return dht(af).status;
|
||||
}
|
||||
NodeStatus getStatus(sa_family_t af) const override { return dht(af).status; }
|
||||
|
||||
NodeStatus getStatus() const override {
|
||||
return std::max(getStatus(AF_INET), getStatus(AF_INET6));
|
||||
}
|
||||
NodeStatus getStatus() const override { return std::max(getStatus(AF_INET), getStatus(AF_INET6)); }
|
||||
|
||||
net::DatagramSocket* getSocket() const override { return network_engine.getSocket(); };
|
||||
|
||||
@@ -105,21 +85,16 @@ public:
|
||||
*/
|
||||
bool isRunning(sa_family_t af = 0) const override;
|
||||
|
||||
virtual void registerType(const ValueType& type) override {
|
||||
types.registerType(type);
|
||||
}
|
||||
const ValueType& getType(ValueType::Id type_id) const override {
|
||||
return types.getType(type_id);
|
||||
}
|
||||
virtual void registerType(const ValueType& type) override { types.registerType(type); }
|
||||
const ValueType& getType(ValueType::Id type_id) const override { return types.getType(type_id); }
|
||||
|
||||
void addBootstrap(const std::string& host, const std::string& service) override {
|
||||
void addBootstrap(const std::string& host, const std::string& service) override
|
||||
{
|
||||
bootstrap_nodes.emplace_back(host, service);
|
||||
startBootstrap();
|
||||
}
|
||||
|
||||
void clearBootstrap() override {
|
||||
bootstrap_nodes.clear();
|
||||
}
|
||||
void clearBootstrap() override { bootstrap_nodes.clear(); }
|
||||
|
||||
/**
|
||||
* Insert a node in the main routing table.
|
||||
@@ -127,14 +102,14 @@ public:
|
||||
* used to bootstrap efficiently from previously known nodes.
|
||||
*/
|
||||
void insertNode(const InfoHash& id, const SockAddr&) override;
|
||||
void insertNode(const NodeExport& n) override {
|
||||
insertNode(n.id, SockAddr(n.ss, n.sslen));
|
||||
}
|
||||
void insertNode(const NodeExport& n) override { insertNode(n.id, n.addr); }
|
||||
|
||||
void pingNode(SockAddr, DoneCallbackSimple&& cb={}) override;
|
||||
void pingNode(SockAddr, DoneCallbackSimple&& cb = {}) override;
|
||||
|
||||
time_point periodic(const uint8_t *buf, size_t buflen, SockAddr, const time_point& now) override;
|
||||
time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override {
|
||||
time_point periodic(const uint8_t* buf, size_t buflen, SockAddr, const time_point& now) override;
|
||||
time_point periodic(
|
||||
const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override
|
||||
{
|
||||
return periodic(buf, buflen, SockAddr(from, fromlen), now);
|
||||
}
|
||||
|
||||
@@ -148,14 +123,30 @@ public:
|
||||
cb and donecb won't be called again afterward.
|
||||
* @param f a filter function used to prefilter values.
|
||||
*/
|
||||
virtual void get(const InfoHash& key, GetCallback cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override;
|
||||
virtual void get(const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
virtual void get(
|
||||
const InfoHash& key, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) override;
|
||||
virtual void get(const InfoHash& key,
|
||||
GetCallback cb,
|
||||
DoneCallbackSimple donecb = {},
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, cb, bindDoneCb(donecb), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
virtual void get(const InfoHash& key,
|
||||
GetCallbackSimple cb,
|
||||
DoneCallback donecb = {},
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, bindGetCb(cb), donecb, std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
virtual void get(const InfoHash& key,
|
||||
GetCallbackSimple cb,
|
||||
DoneCallbackSimple donecb,
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, bindGetCb(cb), bindDoneCb(donecb), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
/**
|
||||
@@ -169,7 +160,8 @@ public:
|
||||
* response.
|
||||
*/
|
||||
virtual void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override;
|
||||
virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override {
|
||||
virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override
|
||||
{
|
||||
query(key, cb, bindDoneCb(done_cb), std::forward<Query>(q));
|
||||
}
|
||||
|
||||
@@ -190,32 +182,32 @@ public:
|
||||
* The done callback will be called once, when the first announce succeeds, or fails.
|
||||
*/
|
||||
void put(const InfoHash& key,
|
||||
Sp<Value>,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override;
|
||||
Sp<Value>,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override;
|
||||
void put(const InfoHash& key,
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
put(key, v, bindDoneCb(cb), created, permanent);
|
||||
}
|
||||
|
||||
void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
Value&& v,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
put(key, std::make_shared<Value>(std::move(v)), cb, created, permanent);
|
||||
}
|
||||
void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
put(key, std::forward<Value>(v), bindDoneCb(cb), created, permanent);
|
||||
}
|
||||
@@ -243,16 +235,22 @@ public:
|
||||
*
|
||||
* @return a token to cancel the listener later.
|
||||
*/
|
||||
size_t listen(const InfoHash&, ValueCallback, Value::Filter={}, Where={}) override;
|
||||
size_t listen(const InfoHash&, ValueCallback, Value::Filter = {}, Where = {}) override;
|
||||
|
||||
size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f={}, Where w={}) override {
|
||||
return listen(key, [cb](const std::vector<Sp<Value>>& vals, bool expired){
|
||||
if (not expired)
|
||||
return cb(vals);
|
||||
return true;
|
||||
}, std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f = {}, Where w = {}) override
|
||||
{
|
||||
return listen(
|
||||
key,
|
||||
[cb](const std::vector<Sp<Value>>& vals, bool expired) {
|
||||
if (not expired)
|
||||
return cb(vals);
|
||||
return true;
|
||||
},
|
||||
std::forward<Value::Filter>(f),
|
||||
std::forward<Where>(w));
|
||||
}
|
||||
size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w={}) override {
|
||||
size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override
|
||||
{
|
||||
return listen(key, bindGetCb(cb), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
|
||||
@@ -264,8 +262,8 @@ public:
|
||||
* The DHT will recontact neighbor nodes, re-register for listen ops etc.
|
||||
*/
|
||||
void connectivityChanged(sa_family_t) override;
|
||||
void connectivityChanged() override {
|
||||
reported_addr.clear();
|
||||
void connectivityChanged() override
|
||||
{
|
||||
connectivityChanged(AF_INET);
|
||||
connectivityChanged(AF_INET6);
|
||||
}
|
||||
@@ -279,9 +277,6 @@ public:
|
||||
std::vector<ValuesExport> exportValues() const override;
|
||||
void importValues(const std::vector<ValuesExport>&) override;
|
||||
|
||||
void saveState(const std::string& path) const;
|
||||
void loadState(const std::string& path);
|
||||
|
||||
NodeStats getNodesStats(sa_family_t af) const override;
|
||||
|
||||
std::string getStorageLog() const override;
|
||||
@@ -292,32 +287,43 @@ public:
|
||||
std::string getSearchLog(const InfoHash&, sa_family_t af = AF_UNSPEC) const override;
|
||||
|
||||
void dumpTables() const override;
|
||||
std::vector<unsigned> getNodeMessageStats(bool in = false) override {
|
||||
std::vector<unsigned> getNodeMessageStats(bool in = false) override
|
||||
{
|
||||
return network_engine.getNodeMessageStats(in);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the in-memory storage limit in bytes
|
||||
* Set the in-memory storage limit in bytes for remote values
|
||||
*/
|
||||
void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override {
|
||||
max_store_size = limit;
|
||||
void setStorageLimit(size_t limit = 0) override { max_store_size = limit == 0 ? STORAGE_LIMIT_DEFAULT : limit; }
|
||||
size_t getStorageLimit() const override { return max_store_size; }
|
||||
|
||||
/**
|
||||
* Set the in-memory storage limit in bytes for locally stored values
|
||||
*/
|
||||
void setLocalStorageLimit(size_t limit = 0) override
|
||||
{
|
||||
max_local_store_size = limit == 0 ? STORAGE_LIMIT_UNLIMITED : limit;
|
||||
}
|
||||
size_t getLocalStorageLimit() const override { return max_local_store_size; }
|
||||
|
||||
/**
|
||||
* Returns the total memory usage of stored values and the number
|
||||
* of stored values.
|
||||
*/
|
||||
std::pair<size_t, size_t> getStoreSize() const override {
|
||||
return {total_store_size, total_values};
|
||||
}
|
||||
std::pair<size_t, size_t> getStoreSize() const override { return {total_store_size, total_values}; }
|
||||
|
||||
std::pair<size_t, size_t> getLocalStoreSize() const override;
|
||||
|
||||
std::vector<SockAddr> getPublicAddress(sa_family_t family = 0) override;
|
||||
|
||||
void pushNotificationReceived(const std::map<std::string, std::string>&) override {}
|
||||
PushNotificationResult pushNotificationReceived(const std::map<std::string, std::string>&) override
|
||||
{
|
||||
return PushNotificationResult::IgnoredDisabled;
|
||||
}
|
||||
void resubscribe(unsigned) {}
|
||||
|
||||
private:
|
||||
|
||||
/* When performing a search, we search for up to SEARCH_NODES closest nodes
|
||||
to the destination, and use the additional ones to backtrack if any of
|
||||
the target 8 turn out to be dead. */
|
||||
@@ -340,7 +346,7 @@ private:
|
||||
static constexpr unsigned LISTEN_NODES {4};
|
||||
|
||||
/* The maximum number of hashes we're willing to track. */
|
||||
static constexpr unsigned MAX_HASHES {1024 * 1024};
|
||||
static constexpr unsigned MAX_HASHES {1024 * 1024 * 1024};
|
||||
|
||||
/* The maximum number of searches we keep data about. */
|
||||
static constexpr unsigned MAX_SEARCHES {1024 * 1024};
|
||||
@@ -358,8 +364,6 @@ private:
|
||||
|
||||
static constexpr std::chrono::seconds BOOTSTRAP_PERIOD {10};
|
||||
|
||||
static constexpr size_t TOKEN_SIZE {32};
|
||||
|
||||
// internal structures
|
||||
struct SearchNode;
|
||||
struct Get;
|
||||
@@ -370,22 +374,27 @@ private:
|
||||
Dht(const Dht&) = delete;
|
||||
Dht& operator=(const Dht&) = delete;
|
||||
|
||||
std::mt19937_64 rd {crypto::getSeededRandomEngine<std::mt19937_64>()};
|
||||
void saveState(const std::string& path) const;
|
||||
/* Only called on construction: may replace the transport key */
|
||||
void loadState(const std::string& path);
|
||||
|
||||
std::mt19937_64 rd;
|
||||
|
||||
InfoHash myid {};
|
||||
|
||||
uint64_t secret {};
|
||||
uint64_t oldsecret {};
|
||||
|
||||
// registred types
|
||||
TypeStore types;
|
||||
|
||||
using SearchMap = std::map<InfoHash, Sp<Search>>;
|
||||
struct Kad {
|
||||
using ReportedAddr = std::pair<unsigned, SockAddr>;
|
||||
|
||||
struct Kad
|
||||
{
|
||||
RoutingTable buckets {};
|
||||
SearchMap searches {};
|
||||
unsigned pending_pings {0};
|
||||
NodeStatus status;
|
||||
std::vector<ReportedAddr> reported_addr;
|
||||
|
||||
NodeStatus getStatus(time_point now) const;
|
||||
NodeStats getNodesStats(time_point now, const InfoHash& myid) const;
|
||||
@@ -393,17 +402,21 @@ private:
|
||||
|
||||
Kad dht4 {};
|
||||
Kad dht6 {};
|
||||
PublicAddressChangedCb publicAddressChangedCb_ {};
|
||||
|
||||
std::vector<std::pair<std::string,std::string>> bootstrap_nodes {};
|
||||
std::vector<std::pair<std::string, std::string>> bootstrap_nodes {};
|
||||
std::chrono::steady_clock::duration bootstrap_period {BOOTSTRAP_PERIOD};
|
||||
Sp<Scheduler::Job> bootstrapJob {};
|
||||
bool bootstrap_pending {false};
|
||||
|
||||
std::map<InfoHash, Storage> store;
|
||||
std::map<SockAddr, StorageBucket, SockAddr::ipCmp> store_quota;
|
||||
std::unique_ptr<StorageBucket> local_store_quota;
|
||||
size_t total_values {0};
|
||||
size_t total_store_size {0};
|
||||
size_t max_store_keys {MAX_HASHES};
|
||||
size_t max_store_size {DEFAULT_STORAGE_LIMIT};
|
||||
size_t max_store_size {STORAGE_LIMIT_DEFAULT};
|
||||
size_t max_local_store_size {STORAGE_LIMIT_UNLIMITED};
|
||||
|
||||
size_t max_searches {MAX_SEARCHES};
|
||||
size_t search_id {0};
|
||||
@@ -413,17 +426,16 @@ private:
|
||||
std::map<size_t, std::tuple<size_t, size_t, size_t>> listeners {};
|
||||
size_t listener_token {1};
|
||||
|
||||
|
||||
// timing
|
||||
Scheduler scheduler;
|
||||
Sp<Scheduler::Job> nextNodesConfirmation {};
|
||||
Sp<Scheduler::Job> nextStorageMaintenance {};
|
||||
|
||||
net::NetworkEngine network_engine;
|
||||
using ReportedAddr = std::pair<unsigned, SockAddr>;
|
||||
std::vector<ReportedAddr> reported_addr;
|
||||
|
||||
std::string persistPath;
|
||||
/* The transport key was generated: keep it in the persisted state */
|
||||
bool persistTransportKey {false};
|
||||
|
||||
// are we a bootstrap node ?
|
||||
// note: Any running node can be used as a bootstrap node.
|
||||
@@ -433,27 +445,28 @@ private:
|
||||
const bool maintain_storage {false};
|
||||
const bool public_stable {false};
|
||||
|
||||
inline const duration& getListenExpiration() const {
|
||||
inline const duration& getListenExpiration() const
|
||||
{
|
||||
return public_stable ? LISTEN_EXPIRE_TIME_PUBLIC : LISTEN_EXPIRE_TIME;
|
||||
}
|
||||
|
||||
void rotateSecrets();
|
||||
|
||||
Blob makeToken(const SockAddr&, bool old) const;
|
||||
bool tokenMatch(const Blob& token, const SockAddr&) const;
|
||||
|
||||
void reportedAddr(const SockAddr&);
|
||||
|
||||
// Storage
|
||||
void storageAddListener(const InfoHash& id, const Sp<Node>& node, size_t tid, Query&& = {}, int version = 0);
|
||||
bool storageStore(const InfoHash& id, const Sp<Value>& value, time_point created, const SockAddr& sa = {}, bool permanent = false);
|
||||
bool storageErase(const InfoHash& id, Value::Id vid);
|
||||
bool storageStore(const InfoHash& id,
|
||||
const Sp<Value>& value,
|
||||
time_point created,
|
||||
const SockAddr& sa = {},
|
||||
bool permanent = false,
|
||||
time_point expiration = time_point::min());
|
||||
bool storageRefresh(const InfoHash& id, Value::Id vid);
|
||||
void expireStore();
|
||||
void expireStorage(InfoHash h);
|
||||
void expireStore(decltype(store)::iterator);
|
||||
|
||||
void storageChanged(const InfoHash& id, Storage& st, ValueStorage&, bool newValue);
|
||||
void storageRemoved(const InfoHash& id, Storage& st, const std::vector<Sp<Value>>& values, size_t totalSize);
|
||||
void storageChanged(const InfoHash& id, Storage& st, const Sp<Value>&, bool newValue);
|
||||
std::string printStorageLog(const decltype(store)::value_type&) const;
|
||||
|
||||
/**
|
||||
@@ -462,19 +475,21 @@ private:
|
||||
* nodes.
|
||||
*/
|
||||
void dataPersistence(InfoHash id);
|
||||
size_t maintainStorage(decltype(store)::value_type&, bool force=false, const DoneCallback& donecb={});
|
||||
size_t maintainStorage(decltype(store)::value_type&, bool force = false, const DoneCallback& donecb = {});
|
||||
|
||||
// Buckets
|
||||
Kad& dht(sa_family_t af) { return af == AF_INET ? dht4 : dht6; }
|
||||
const Kad& dht(sa_family_t af) const { return af == AF_INET ? dht4 : dht6; }
|
||||
RoutingTable& buckets(sa_family_t af) { return dht(af).buckets; }
|
||||
const RoutingTable& buckets(sa_family_t af) const { return dht(af).buckets; }
|
||||
Bucket* findBucket(const InfoHash& id, sa_family_t af) {
|
||||
Bucket* findBucket(const InfoHash& id, sa_family_t af)
|
||||
{
|
||||
auto& b = buckets(af);
|
||||
auto it = b.findBucket(id);
|
||||
return it == b.end() ? nullptr : &(*it);
|
||||
}
|
||||
const Bucket* findBucket(const InfoHash& id, sa_family_t af) const {
|
||||
const Bucket* findBucket(const InfoHash& id, sa_family_t af) const
|
||||
{
|
||||
return const_cast<Dht*>(this)->findBucket(id, af);
|
||||
}
|
||||
|
||||
@@ -499,9 +514,20 @@ private:
|
||||
* Low-level method that will perform a search on the DHT for the specified
|
||||
* infohash (id), using the specified IP version (IPv4 or IPv6).
|
||||
*/
|
||||
Sp<Search> search(const InfoHash& id, sa_family_t af, GetCallback = {}, QueryCallback = {}, DoneCallback = {}, Value::Filter = {}, const Sp<Query>& q = {});
|
||||
Sp<Search> search(const InfoHash& id,
|
||||
sa_family_t af,
|
||||
GetCallback = {},
|
||||
QueryCallback = {},
|
||||
DoneCallback = {},
|
||||
Value::Filter = {},
|
||||
const Sp<Query>& q = {});
|
||||
|
||||
void announce(const InfoHash& id, sa_family_t af, Sp<Value> value, DoneCallback callback, time_point created=time_point::max(), bool permanent = false);
|
||||
void announce(const InfoHash& id,
|
||||
sa_family_t af,
|
||||
Sp<Value> value,
|
||||
DoneCallback callback,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false);
|
||||
size_t listenTo(const InfoHash& id, sa_family_t af, ValueCallback cb, Value::Filter f = {}, const Sp<Query>& q = {});
|
||||
|
||||
/**
|
||||
@@ -529,9 +555,9 @@ private:
|
||||
* @param query The query sent to the node.
|
||||
*/
|
||||
void searchNodeGetDone(const net::Request& status,
|
||||
net::RequestAnswer&& answer,
|
||||
std::weak_ptr<Search> ws,
|
||||
Sp<Query> query);
|
||||
net::RequestAnswer&& answer,
|
||||
std::weak_ptr<Search> ws,
|
||||
Sp<Query> query);
|
||||
|
||||
/**
|
||||
* Generic function to execute when a 'get' request expires.
|
||||
@@ -543,6 +569,8 @@ private:
|
||||
* @param query The query sent to the node.
|
||||
*/
|
||||
void searchNodeGetExpired(const net::Request& status, bool over, std::weak_ptr<Search> ws, Sp<Query> query);
|
||||
void searchNodeRoutingDone(const net::Request& req, net::RequestAnswer&& answer, std::weak_ptr<Search> ws);
|
||||
void searchNodeRoutingExpired(const net::Request& req, bool over, std::weak_ptr<Search> ws);
|
||||
|
||||
/**
|
||||
* This method recovers sends individual request for values per id.
|
||||
@@ -556,7 +584,7 @@ private:
|
||||
/**
|
||||
* If update is true, this method will also send message to synced but non-updated search nodes.
|
||||
*/
|
||||
SearchNode* searchSendGetValues(Sp<Search> sr, SearchNode *n = nullptr, bool update = true);
|
||||
SearchNode* searchSendGetValues(Sp<Search> sr, SearchNode* n = nullptr, bool update = true);
|
||||
|
||||
/**
|
||||
* Forwards an 'announce' request for a list of nodes to the network engine.
|
||||
@@ -564,7 +592,7 @@ private:
|
||||
* @param sr The search for which we want to announce a value.
|
||||
* @param announce The 'announce' structure.
|
||||
*/
|
||||
void searchSendAnnounceValue(const Sp<Search>& sr);
|
||||
void searchSendAnnounceValue(const Sp<Search>& sr, unsigned syncLevel = TARGET_NODES);
|
||||
|
||||
/**
|
||||
* Main process of a Search's operations. This function will demand the
|
||||
@@ -588,41 +616,21 @@ private:
|
||||
net::RequestAnswer onPing(Sp<Node> node);
|
||||
/* when we receive a "find node" request */
|
||||
net::RequestAnswer onFindNode(Sp<Node> node, const InfoHash& hash, want_t want);
|
||||
void onFindNodeDone(const Sp<Node>& status,
|
||||
net::RequestAnswer& a,
|
||||
Sp<Search> sr);
|
||||
void onFindNodeDone(const Sp<Node>& status, net::RequestAnswer& a, Sp<Search> sr);
|
||||
/* when we receive a "get values" request */
|
||||
net::RequestAnswer onGetValues(Sp<Node> node,
|
||||
const InfoHash& hash,
|
||||
want_t want,
|
||||
const Query& q);
|
||||
void onGetValuesDone(const Sp<Node>& status,
|
||||
net::RequestAnswer& a,
|
||||
Sp<Search>& sr,
|
||||
const Sp<Query>& orig_query);
|
||||
net::RequestAnswer onGetValues(Sp<Node> node, const InfoHash& hash, want_t want, const Query& q);
|
||||
void onGetValuesDone(const Sp<Node>& status, net::RequestAnswer& a, Sp<Search>& sr, const Sp<Query>& orig_query);
|
||||
/* when we receive a listen request */
|
||||
net::RequestAnswer onListen(Sp<Node> node,
|
||||
const InfoHash& hash,
|
||||
const Blob& token,
|
||||
size_t socket_id,
|
||||
const Query& query,
|
||||
int version = 0);
|
||||
void onListenDone(const Sp<Node>& status,
|
||||
net::RequestAnswer& a,
|
||||
Sp<Search>& sr);
|
||||
net::RequestAnswer onListen(
|
||||
Sp<Node> node, const InfoHash& hash, size_t socket_id, const Query& query, int version = 0);
|
||||
void onListenDone(const Sp<Node>& node, net::RequestAnswer& a, Sp<Search>& sr);
|
||||
/* when we receive an announce request */
|
||||
net::RequestAnswer onAnnounce(Sp<Node> node,
|
||||
const InfoHash& hash,
|
||||
const Blob& token,
|
||||
const std::vector<Sp<Value>>& v,
|
||||
const time_point& created);
|
||||
net::RequestAnswer onRefresh(Sp<Node> node,
|
||||
const InfoHash& hash,
|
||||
const Blob& token,
|
||||
const Value::Id& vid);
|
||||
void onAnnounceDone(const Sp<Node>& status,
|
||||
net::RequestAnswer& a,
|
||||
Sp<Search>& sr);
|
||||
const InfoHash& hash,
|
||||
const std::vector<Sp<Value>>& v,
|
||||
const time_point& created);
|
||||
net::RequestAnswer onRefresh(Sp<Node> node, const InfoHash& hash, const Value::Id& vid);
|
||||
void onAnnounceDone(const Sp<Node>& status, net::RequestAnswer& a, Sp<Search>& sr);
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
@@ -1,39 +1,26 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "infohash.h"
|
||||
#include "log_enable.h"
|
||||
#include "logger.h"
|
||||
#include "node_export.h"
|
||||
|
||||
#include <queue>
|
||||
|
||||
namespace dht {
|
||||
|
||||
namespace net {
|
||||
class DatagramSocket;
|
||||
class DatagramSocket;
|
||||
}
|
||||
|
||||
class OPENDHT_PUBLIC DhtInterface {
|
||||
class OPENDHT_PUBLIC DhtInterface
|
||||
{
|
||||
public:
|
||||
DhtInterface() = default;
|
||||
DhtInterface(const Logger& l) : logger_(std::make_shared<Logger>(l)) {};
|
||||
DhtInterface(const std::shared_ptr<Logger>& l) : logger_(l) {};
|
||||
DhtInterface(const std::shared_ptr<Logger>& l)
|
||||
: logger_(l)
|
||||
{}
|
||||
virtual ~DhtInterface() = default;
|
||||
|
||||
// [[deprecated]]
|
||||
@@ -44,15 +31,14 @@ public:
|
||||
/**
|
||||
* Get the current status of the node for the given family.
|
||||
*/
|
||||
virtual NodeStatus updateStatus(sa_family_t af) { return getStatus(af); };
|
||||
virtual NodeStatus updateStatus(sa_family_t af) { return getStatus(af); }
|
||||
virtual NodeStatus getStatus(sa_family_t af) const = 0;
|
||||
virtual NodeStatus getStatus() const = 0;
|
||||
|
||||
void addOnConnectedCallback(std::function<void()> cb) {
|
||||
onConnectCallbacks_.emplace(std::move(cb));
|
||||
}
|
||||
void addOnConnectedCallback(std::function<void()> cb) { onConnectCallbacks_.emplace(std::move(cb)); }
|
||||
virtual void setOnPublicAddressChanged(PublicAddressChangedCb) {}
|
||||
|
||||
virtual net::DatagramSocket* getSocket() const { return {}; };
|
||||
virtual net::DatagramSocket* getSocket() const { return {}; }
|
||||
|
||||
/**
|
||||
* Get the ID of the DHT node.
|
||||
@@ -89,10 +75,12 @@ public:
|
||||
virtual void insertNode(const InfoHash& id, const SockAddr&) = 0;
|
||||
virtual void insertNode(const NodeExport& n) = 0;
|
||||
|
||||
virtual void pingNode(SockAddr, DoneCallbackSimple&& cb={}) = 0;
|
||||
virtual void pingNode(SockAddr, DoneCallbackSimple&& cb = {}) = 0;
|
||||
|
||||
virtual time_point periodic(const uint8_t *buf, size_t buflen, SockAddr, const time_point& now) = 0;
|
||||
virtual time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) = 0;
|
||||
virtual time_point periodic(const uint8_t* buf, size_t buflen, SockAddr, const time_point& now) = 0;
|
||||
virtual time_point periodic(
|
||||
const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now)
|
||||
= 0;
|
||||
|
||||
/**
|
||||
* Get a value by searching on all available protocols (IPv4, IPv6),
|
||||
@@ -104,10 +92,18 @@ public:
|
||||
cb and donecb won't be called again afterward.
|
||||
* @param f a filter function used to prefilter values.
|
||||
*/
|
||||
virtual void get(const InfoHash& key, GetCallback cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0;
|
||||
virtual void get(const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0;
|
||||
virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0;
|
||||
virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) = 0;
|
||||
virtual void get(
|
||||
const InfoHash& key, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {})
|
||||
= 0;
|
||||
virtual void get(
|
||||
const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb = {}, Value::Filter&& f = {}, Where&& w = {})
|
||||
= 0;
|
||||
virtual void get(
|
||||
const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {})
|
||||
= 0;
|
||||
virtual void get(
|
||||
const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f = {}, Where&& w = {})
|
||||
= 0;
|
||||
|
||||
/**
|
||||
* Similar to Dht::get, but sends a Query to filter data remotely.
|
||||
@@ -139,25 +135,29 @@ public:
|
||||
* The done callback will be called once, when the first announce succeeds, or fails.
|
||||
*/
|
||||
virtual void put(const InfoHash& key,
|
||||
Sp<Value>,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) = 0;
|
||||
Sp<Value>,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false)
|
||||
= 0;
|
||||
virtual void put(const InfoHash& key,
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) = 0;
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false)
|
||||
= 0;
|
||||
virtual void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) = 0;
|
||||
Value&& v,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false)
|
||||
= 0;
|
||||
virtual void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) = 0;
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false)
|
||||
= 0;
|
||||
|
||||
/**
|
||||
* Get data currently being put at the given hash.
|
||||
@@ -182,9 +182,9 @@ public:
|
||||
*
|
||||
* @return a token to cancel the listener later.
|
||||
*/
|
||||
virtual size_t listen(const InfoHash&, GetCallback, Value::Filter={}, Where w = {}) = 0;
|
||||
virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w = {}) = 0;
|
||||
virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter={}, Where w = {}) = 0;
|
||||
virtual size_t listen(const InfoHash&, GetCallback, Value::Filter = {}, Where w = {}) = 0;
|
||||
virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) = 0;
|
||||
virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter = {}, Where w = {}) = 0;
|
||||
|
||||
virtual bool cancelListen(const InfoHash&, size_t token) = 0;
|
||||
|
||||
@@ -218,9 +218,16 @@ public:
|
||||
virtual std::vector<unsigned> getNodeMessageStats(bool in = false) = 0;
|
||||
|
||||
/**
|
||||
* Set the in-memory storage limit in bytes
|
||||
* Set the in-memory storage limit in bytes for remote values
|
||||
*/
|
||||
virtual void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) = 0;
|
||||
virtual void setStorageLimit(size_t limit = 0) = 0;
|
||||
virtual size_t getStorageLimit() const = 0;
|
||||
|
||||
/**
|
||||
* Set the in-memory storage limit in bytes for locally stored values
|
||||
*/
|
||||
virtual void setLocalStorageLimit(size_t limit = 0) = 0;
|
||||
virtual size_t getLocalStorageLimit() const = 0;
|
||||
|
||||
/**
|
||||
* Returns the total memory usage of stored values and the number
|
||||
@@ -228,30 +235,11 @@ public:
|
||||
*/
|
||||
virtual std::pair<size_t, size_t> getStoreSize() const = 0;
|
||||
|
||||
virtual std::pair<size_t, size_t> getLocalStoreSize() const = 0;
|
||||
|
||||
virtual std::vector<SockAddr> getPublicAddress(sa_family_t family = 0) = 0;
|
||||
|
||||
/**
|
||||
* Enable or disable logging of DHT internal messages
|
||||
*/
|
||||
virtual void setLoggers(LogMethod error = {}, LogMethod warn = {}, LogMethod debug = {}) {
|
||||
if (logger_) {
|
||||
logger_->DBG = std::move(debug);
|
||||
logger_->WARN = std::move(warn);
|
||||
logger_->ERR = std::move(error);
|
||||
} else
|
||||
logger_= std::make_shared<Logger>(std::move(error), std::move(warn), std::move(debug));
|
||||
}
|
||||
|
||||
virtual void setLogger(const Logger& l) {
|
||||
if (logger_)
|
||||
*logger_ = l;
|
||||
else
|
||||
logger_= std::make_shared<Logger>(l);
|
||||
}
|
||||
|
||||
virtual void setLogger(const std::shared_ptr<Logger>& l) {
|
||||
logger_ = l;
|
||||
}
|
||||
virtual void setLogger(const std::shared_ptr<Logger>& l) { logger_ = l; }
|
||||
|
||||
/**
|
||||
* Only print logs related to the given InfoHash (if given), or disable filter (if zeroes).
|
||||
@@ -264,11 +252,14 @@ public:
|
||||
|
||||
virtual void setPushNotificationToken(const std::string&) {};
|
||||
|
||||
virtual void setPushNotificationTopic(const std::string&) {};
|
||||
virtual void setPushNotificationPlatform(const std::string&) {};
|
||||
|
||||
/**
|
||||
* Call linked callback with a push notification
|
||||
* @param notification to process
|
||||
*/
|
||||
virtual void pushNotificationReceived(const std::map<std::string, std::string>& data) = 0;
|
||||
virtual PushNotificationResult pushNotificationReceived(const std::map<std::string, std::string>& data) = 0;
|
||||
|
||||
protected:
|
||||
std::shared_ptr<Logger> logger_ {};
|
||||
|
||||
@@ -1,23 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com>
|
||||
* Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Vsevolod Ivanov <vsevolod.ivanov@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
@@ -43,27 +25,45 @@ class Value;
|
||||
namespace http {
|
||||
class Resolver;
|
||||
class Request;
|
||||
}
|
||||
} // namespace http
|
||||
|
||||
namespace dht {
|
||||
|
||||
class OPENDHT_PUBLIC DhtProxyClient final : public DhtInterface {
|
||||
class OPENDHT_PUBLIC DhtProxyClient final : public DhtInterface
|
||||
{
|
||||
public:
|
||||
|
||||
DhtProxyClient();
|
||||
|
||||
explicit DhtProxyClient(
|
||||
std::shared_ptr<crypto::Certificate> serverCA, crypto::Identity clientIdentity,
|
||||
std::function<void()> loopSignal, const std::string& serverHost,
|
||||
const std::string& pushClientId = "", std::shared_ptr<Logger> logger = {});
|
||||
explicit DhtProxyClient(std::shared_ptr<crypto::Certificate> serverCA,
|
||||
crypto::Identity clientIdentity,
|
||||
std::function<void()> loopSignal,
|
||||
const std::string& serverHost,
|
||||
const std::string& userAgent = "",
|
||||
const std::string& pushClientId = "",
|
||||
const std::string& pushToken = "",
|
||||
const std::string& pushTopic = "",
|
||||
const std::string& pushPlatform = "",
|
||||
std::shared_ptr<Logger> logger = {});
|
||||
|
||||
void setHeaderFields(http::Request& request);
|
||||
|
||||
virtual void setPushNotificationToken(const std::string& token) override {
|
||||
virtual void setPushNotificationToken(const std::string& token) override;
|
||||
|
||||
virtual void setPushNotificationTopic(const std::string& topic) override
|
||||
{
|
||||
#ifdef OPENDHT_PUSH_NOTIFICATIONS
|
||||
deviceKey_ = token;
|
||||
notificationTopic_ = topic;
|
||||
#else
|
||||
(void) token;
|
||||
(void) topic;
|
||||
#endif
|
||||
}
|
||||
|
||||
virtual void setPushNotificationPlatform(const std::string& platform) override
|
||||
{
|
||||
#ifdef OPENDHT_PUSH_NOTIFICATIONS
|
||||
platform_ = platform;
|
||||
#else
|
||||
(void) platform;
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -73,14 +73,13 @@ public:
|
||||
* Get the ID of the node.
|
||||
*/
|
||||
inline const InfoHash& getNodeId() const override { return myid; }
|
||||
void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { publicAddressChangedCb_ = std::move(cb); }
|
||||
|
||||
/**
|
||||
* Get the current status of the node for the given family.
|
||||
*/
|
||||
NodeStatus getStatus(sa_family_t af) const override;
|
||||
NodeStatus getStatus() const override {
|
||||
return std::max(getStatus(AF_INET), getStatus(AF_INET6));
|
||||
}
|
||||
NodeStatus getStatus() const override { return std::max(getStatus(AF_INET), getStatus(AF_INET6)); }
|
||||
|
||||
/**
|
||||
* Performs final operations before quitting.
|
||||
@@ -105,14 +104,30 @@ public:
|
||||
cb and donecb won't be called again afterward.
|
||||
* @param f a filter function used to prefilter values.
|
||||
*/
|
||||
virtual void get(const InfoHash& key, GetCallback cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override;
|
||||
virtual void get(const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
virtual void get(
|
||||
const InfoHash& key, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) override;
|
||||
virtual void get(const InfoHash& key,
|
||||
GetCallback cb,
|
||||
DoneCallbackSimple donecb = {},
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, cb, bindDoneCb(std::move(donecb)), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
virtual void get(const InfoHash& key,
|
||||
GetCallbackSimple cb,
|
||||
DoneCallback donecb = {},
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, bindGetCb(cb), std::move(donecb), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
virtual void get(const InfoHash& key,
|
||||
GetCallbackSimple cb,
|
||||
DoneCallbackSimple donecb,
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, bindGetCb(cb), bindDoneCb(std::move(donecb)), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
|
||||
@@ -124,32 +139,32 @@ public:
|
||||
* NOTE: For now, created parameter is ignored.
|
||||
*/
|
||||
void put(const InfoHash& key,
|
||||
Sp<Value>,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override;
|
||||
Sp<Value>,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override;
|
||||
void put(const InfoHash& key,
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
put(key, v, bindDoneCb(std::move(cb)), created, permanent);
|
||||
}
|
||||
|
||||
void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
Value&& v,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
put(key, std::make_shared<Value>(std::move(v)), std::move(cb), created, permanent);
|
||||
}
|
||||
void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
put(key, std::forward<Value>(v), bindDoneCb(std::move(cb)), created, permanent);
|
||||
}
|
||||
@@ -173,16 +188,22 @@ public:
|
||||
*
|
||||
* @return a token to cancel the listener later.
|
||||
*/
|
||||
virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter={}, Where={}) override;
|
||||
virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter = {}, Where = {}) override;
|
||||
|
||||
virtual size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f={}, Where w={}) override {
|
||||
return listen(key, [cb=std::move(cb)](const std::vector<Sp<Value>>& vals, bool expired){
|
||||
if (not expired)
|
||||
return cb(vals);
|
||||
return true;
|
||||
}, std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
virtual size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f = {}, Where w = {}) override
|
||||
{
|
||||
return listen(
|
||||
key,
|
||||
[cb = std::move(cb)](const std::vector<Sp<Value>>& vals, bool expired) {
|
||||
if (not expired)
|
||||
return cb(vals);
|
||||
return true;
|
||||
},
|
||||
std::forward<Value::Filter>(f),
|
||||
std::forward<Where>(w));
|
||||
}
|
||||
virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w={}) override {
|
||||
virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override
|
||||
{
|
||||
return listen(key, bindGetCb(std::move(cb)), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
/*
|
||||
@@ -195,10 +216,12 @@ public:
|
||||
* Call linked callback with a push notification
|
||||
* @param notification to process
|
||||
*/
|
||||
void pushNotificationReceived(const std::map<std::string, std::string>& notification) override;
|
||||
PushNotificationResult pushNotificationReceived(const std::map<std::string, std::string>& notification) override;
|
||||
|
||||
time_point periodic(const uint8_t*, size_t, SockAddr, const time_point& now) override;
|
||||
time_point periodic(const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override {
|
||||
time_point periodic(
|
||||
const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override
|
||||
{
|
||||
return periodic(buf, buflen, SockAddr(from, fromlen), now);
|
||||
}
|
||||
|
||||
@@ -212,8 +235,13 @@ public:
|
||||
* @param q a query used to filter values on the remotes before they send a
|
||||
* response.
|
||||
*/
|
||||
virtual void query(const InfoHash& /*key*/, QueryCallback /*cb*/, DoneCallback /*done_cb*/ = {}, Query&& /*q*/ = {}) override { }
|
||||
virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override {
|
||||
virtual void query(const InfoHash& /*key*/,
|
||||
QueryCallback /*cb*/,
|
||||
DoneCallback /*done_cb*/ = {},
|
||||
Query&& /*q*/ = {}) override
|
||||
{}
|
||||
virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override
|
||||
{
|
||||
query(key, cb, bindDoneCb(std::move(done_cb)), std::forward<Query>(q));
|
||||
}
|
||||
|
||||
@@ -233,14 +261,10 @@ public:
|
||||
*/
|
||||
bool cancelPut(const InfoHash&, const Value::Id&) override;
|
||||
|
||||
void pingNode(SockAddr, DoneCallbackSimple&& /*cb*/={}) override { }
|
||||
void pingNode(SockAddr, DoneCallbackSimple&& /*cb*/ = {}) override {}
|
||||
|
||||
virtual void registerType(const ValueType& type) override {
|
||||
types.registerType(type);
|
||||
}
|
||||
const ValueType& getType(ValueType::Id type_id) const override {
|
||||
return types.getType(type_id);
|
||||
}
|
||||
virtual void registerType(const ValueType& type) override { types.registerType(type); }
|
||||
const ValueType& getType(ValueType::Id type_id) const override { return types.getType(type_id); }
|
||||
|
||||
std::vector<Sp<Value>> getLocal(const InfoHash& k, const Value::Filter& filter) const override;
|
||||
Sp<Value> getLocalById(const InfoHash& k, Value::Id id) const override;
|
||||
@@ -249,9 +273,10 @@ public:
|
||||
* NOTE: The following methods will not be implemented because the
|
||||
* DhtProxyClient doesn't have any storage nor synchronization process
|
||||
*/
|
||||
void insertNode(const InfoHash&, const SockAddr&) override { }
|
||||
void insertNode(const NodeExport&) override { }
|
||||
void insertNode(const InfoHash&, const SockAddr&) override {}
|
||||
void insertNode(const NodeExport&) override {}
|
||||
std::pair<size_t, size_t> getStoreSize() const override { return {}; }
|
||||
std::pair<size_t, size_t> getLocalStoreSize() const override { return {}; }
|
||||
std::vector<NodeExport> exportNodes() const override { return {}; }
|
||||
std::vector<ValuesExport> exportValues() const override { return {}; }
|
||||
void importValues(const std::vector<ValuesExport>&) override {}
|
||||
@@ -263,14 +288,19 @@ public:
|
||||
void dumpTables() const override {}
|
||||
std::vector<unsigned> getNodeMessageStats(bool) override { return {}; }
|
||||
void setStorageLimit(size_t) override {}
|
||||
void connectivityChanged(sa_family_t) override {
|
||||
getProxyInfos();
|
||||
}
|
||||
void connectivityChanged() override {
|
||||
virtual size_t getStorageLimit() const override { return 0; }
|
||||
void setLocalStorageLimit(size_t) override {}
|
||||
virtual size_t getLocalStorageLimit() const override { return STORAGE_LIMIT_UNLIMITED; }
|
||||
void connectivityChanged(sa_family_t) override { getProxyInfos(); }
|
||||
void connectivityChanged() override
|
||||
{
|
||||
getProxyInfos();
|
||||
loopSignal_();
|
||||
}
|
||||
|
||||
void listenKeepIdle(uint32_t seconds) { listenKeepIdle_ = seconds; }
|
||||
inline uint32_t listenKeepIdle() { return listenKeepIdle_; }
|
||||
|
||||
private:
|
||||
/**
|
||||
* Start the connection with a server.
|
||||
@@ -284,13 +314,15 @@ private:
|
||||
*/
|
||||
struct InfoState;
|
||||
void getProxyInfos();
|
||||
void queryProxyInfo(const std::shared_ptr<InfoState>& infoState, const std::shared_ptr<http::Resolver>& resolver, sa_family_t family);
|
||||
void queryProxyInfo(const std::shared_ptr<InfoState>& infoState,
|
||||
const std::shared_ptr<http::Resolver>& resolver,
|
||||
sa_family_t family);
|
||||
void onProxyInfos(const Json::Value& val, const sa_family_t family);
|
||||
SockAddr parsePublicAddress(const Json::Value& val);
|
||||
|
||||
void opFailed();
|
||||
|
||||
void handleExpireListener(const asio::error_code &ec, const InfoHash& key);
|
||||
void handleExpireListener(const asio::error_code& ec, const InfoHash& key);
|
||||
|
||||
struct Listener;
|
||||
struct OperationState;
|
||||
@@ -299,15 +331,21 @@ private:
|
||||
SUBSCRIBE,
|
||||
RESUBSCRIBE,
|
||||
};
|
||||
using CacheValueCallback = std::function<bool(const std::vector<std::shared_ptr<Value>>& values, bool expired, system_clock::time_point)>;
|
||||
using CacheValueCallback
|
||||
= std::function<bool(const std::vector<std::shared_ptr<Value>>& values, bool expired, system_clock::time_point)>;
|
||||
|
||||
/**
|
||||
* Send Listen with httpClient_
|
||||
*/
|
||||
void sendListen(const restinio::http_request_header_t& header, const CacheValueCallback& cb,
|
||||
const Sp<OperationState>& opstate, Listener& listener, ListenMethod method = ListenMethod::LISTEN);
|
||||
void handleResubscribe(const asio::error_code& ec, const InfoHash& key,
|
||||
const size_t token, std::shared_ptr<OperationState> opstate);
|
||||
void sendListen(const restinio::http_request_header_t& header,
|
||||
const CacheValueCallback& cb,
|
||||
const Sp<OperationState>& opstate,
|
||||
Listener& listener,
|
||||
ListenMethod method = ListenMethod::LISTEN);
|
||||
void handleResubscribe(const asio::error_code& ec,
|
||||
const InfoHash& key,
|
||||
const size_t token,
|
||||
std::shared_ptr<OperationState> opstate);
|
||||
|
||||
void doPut(const InfoHash&, Sp<Value>, DoneCallbackSimple, time_point created, bool permanent);
|
||||
void handleRefreshPut(const asio::error_code& ec, InfoHash key, Value::Id id);
|
||||
@@ -326,7 +364,7 @@ private:
|
||||
std::string proxyUrl_;
|
||||
dht::crypto::Identity clientIdentity_;
|
||||
std::shared_ptr<dht::crypto::Certificate> serverCertificate_;
|
||||
//std::pair<std::string, std::string> serverHostService_;
|
||||
std::string userAgent_ {"OpenDHT"};
|
||||
std::string pushClientId_;
|
||||
std::string pushSessionId_;
|
||||
|
||||
@@ -335,9 +373,12 @@ private:
|
||||
NodeStatus statusIpv6_ {NodeStatus::Disconnected};
|
||||
NodeStats stats4_ {};
|
||||
NodeStats stats6_ {};
|
||||
SockAddr localAddrv4_;
|
||||
SockAddr localAddrv6_;
|
||||
SockAddr publicAddressV4_;
|
||||
SockAddr publicAddressV6_;
|
||||
std::atomic_bool launchConnectedCbs_ {false};
|
||||
PublicAddressChangedCb publicAddressChangedCb_ {};
|
||||
|
||||
InfoHash myid {};
|
||||
|
||||
@@ -349,6 +390,7 @@ private:
|
||||
* Note: Each context is used in one thread only
|
||||
*/
|
||||
asio::io_context httpContext_;
|
||||
mutable std::mutex resolverLock_;
|
||||
std::shared_ptr<http::Resolver> resolver_;
|
||||
|
||||
mutable std::mutex requestLock_;
|
||||
@@ -367,6 +409,11 @@ private:
|
||||
size_t listenerToken_ {0};
|
||||
std::map<InfoHash, ProxySearch> searches_;
|
||||
|
||||
/**
|
||||
* Keepalive idle time for listen
|
||||
*/
|
||||
uint32_t listenKeepIdle_ {120};
|
||||
|
||||
/**
|
||||
* Callbacks should be executed in the main thread.
|
||||
*/
|
||||
@@ -378,14 +425,14 @@ private:
|
||||
/**
|
||||
* Retrieve if we can connect to the proxy (update statusIpvX_)
|
||||
*/
|
||||
void handleProxyConfirm(const asio::error_code &ec);
|
||||
void handleProxyConfirm(const asio::error_code& ec);
|
||||
std::unique_ptr<asio::steady_timer> nextProxyConfirmationTimer_;
|
||||
std::unique_ptr<asio::steady_timer> listenerRestartTimer_;
|
||||
|
||||
/**
|
||||
* Relaunch LISTEN requests if the client disconnect/reconnect.
|
||||
*/
|
||||
void restartListeners(const asio::error_code &ec);
|
||||
void restartListeners(const asio::error_code& ec);
|
||||
|
||||
/**
|
||||
* Refresh a listen via a token
|
||||
@@ -399,6 +446,25 @@ private:
|
||||
*/
|
||||
std::string deviceKey_ {};
|
||||
|
||||
/**
|
||||
* Notification topic for ios notifications.
|
||||
*/
|
||||
std::string notificationTopic_ {};
|
||||
|
||||
/**
|
||||
* Platform for push notifications (supported android, ios, unifiedpush)
|
||||
*/
|
||||
std::string platform_
|
||||
#ifdef __ANDROID__
|
||||
{"android"};
|
||||
#else
|
||||
#ifdef __APPLE__
|
||||
{"ios"};
|
||||
#else
|
||||
{};
|
||||
#endif
|
||||
#endif
|
||||
|
||||
const std::function<void()> loopSignal_;
|
||||
|
||||
#ifdef OPENDHT_PUSH_NOTIFICATIONS
|
||||
@@ -412,4 +478,4 @@ private:
|
||||
std::shared_ptr<http::Request> buildRequest(const std::string& target = {});
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+194
-134
@@ -1,23 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com>
|
||||
* Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Vsevolod Ivanov <vsevolod.ivanov@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "callbacks.h"
|
||||
@@ -37,35 +19,36 @@
|
||||
#include <mutex>
|
||||
|
||||
namespace dht {
|
||||
enum class PushType {
|
||||
None = 0,
|
||||
Android,
|
||||
iOS
|
||||
};
|
||||
// Appended only: the values are serialized as integers by MSGPACK_ADD_ENUM,
|
||||
// so reordering would break compatibility with deployed proxies.
|
||||
enum class PushType { None = 0, Android, iOS, UnifiedPush, Huawei };
|
||||
}
|
||||
MSGPACK_ADD_ENUM(dht::PushType)
|
||||
|
||||
namespace http {
|
||||
class Request;
|
||||
struct ListenerSession;
|
||||
}
|
||||
|
||||
namespace Json {
|
||||
class Value;
|
||||
}
|
||||
|
||||
namespace dht {
|
||||
|
||||
namespace http {
|
||||
class Request;
|
||||
struct ListenerSession;
|
||||
} // namespace http
|
||||
|
||||
class DhtRunner;
|
||||
|
||||
using RestRouter = restinio::router::express_router_t<>;
|
||||
using RequestStatus = restinio::request_handling_status_t;
|
||||
|
||||
struct ProxyServerConfig {
|
||||
struct OPENDHT_PUBLIC ProxyServerConfig
|
||||
{
|
||||
std::string address {};
|
||||
in_port_t port {8000};
|
||||
std::string pushServer {};
|
||||
std::string persistStatePath {};
|
||||
dht::crypto::Identity identity {};
|
||||
std::string bundleId {};
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -83,8 +66,8 @@ public:
|
||||
* it will fails silently
|
||||
*/
|
||||
DhtProxyServer(const std::shared_ptr<DhtRunner>& dht,
|
||||
const ProxyServerConfig& config = {},
|
||||
const std::shared_ptr<dht::Logger>& logger = {});
|
||||
const ProxyServerConfig& config = {},
|
||||
const std::shared_ptr<log::Logger>& logger = {});
|
||||
|
||||
virtual ~DhtProxyServer();
|
||||
|
||||
@@ -95,7 +78,44 @@ public:
|
||||
|
||||
asio::io_context& io_context() const;
|
||||
|
||||
struct ServerStats {
|
||||
// Monotonic clock for elapsed-time statistics (request rate, uptime).
|
||||
// Must stay on steady_clock so NTP/wall-clock corrections don't skew durations.
|
||||
using clock = std::chrono::steady_clock;
|
||||
using time_point = clock::time_point;
|
||||
// Wall clock for persisted subscribe/permanent-put lease expirations,
|
||||
// so they map directly to epoch time and survive restarts.
|
||||
using sys_clock = std::chrono::system_clock;
|
||||
using sys_time_point = sys_clock::time_point;
|
||||
|
||||
struct PushStats
|
||||
{
|
||||
uint64_t highPriorityCount {0};
|
||||
uint64_t normalPriorityCount {0};
|
||||
|
||||
void increment(bool highPriority)
|
||||
{
|
||||
if (highPriority)
|
||||
highPriorityCount++;
|
||||
else
|
||||
normalPriorityCount++;
|
||||
}
|
||||
|
||||
Json::Value toJson() const
|
||||
{
|
||||
Json::Value val;
|
||||
val["highPriorityCount"] = static_cast<Json::UInt64>(highPriorityCount);
|
||||
val["normalPriorityCount"] = static_cast<Json::UInt64>(normalPriorityCount);
|
||||
return val;
|
||||
}
|
||||
|
||||
std::string toString() const
|
||||
{
|
||||
return fmt::format("{} high priority, {} normal priority", highPriorityCount, normalPriorityCount);
|
||||
}
|
||||
};
|
||||
|
||||
struct OPENDHT_PUBLIC ServerStats
|
||||
{
|
||||
/** Current number of listen operations */
|
||||
size_t listenCount {0};
|
||||
/** Current number of permanent put operations (hash used) */
|
||||
@@ -104,40 +124,29 @@ public:
|
||||
size_t totalPermanentPuts {0};
|
||||
/** Current number of push tokens with at least one listen operation */
|
||||
size_t pushListenersCount {0};
|
||||
|
||||
/** Time at which the server was started */
|
||||
time_point serverStartTime;
|
||||
/** Last time at which the stats were updated */
|
||||
time_point lastUpdated;
|
||||
/** Total number of push notification requests that the server attempted to
|
||||
* send since being started, broken down by type and priority level */
|
||||
PushStats androidPush;
|
||||
PushStats iosPush;
|
||||
PushStats unifiedPush;
|
||||
PushStats huaweiPush;
|
||||
|
||||
/** Average requests per second */
|
||||
double requestRate {0};
|
||||
/** Node Info **/
|
||||
std::shared_ptr<NodeInfo> nodeInfo {};
|
||||
|
||||
std::string toString() const {
|
||||
std::ostringstream ss;
|
||||
ss << "Listens: " << listenCount << " Puts: " << putCount << " PushListeners: " << pushListenersCount << std::endl;
|
||||
ss << "Requests: " << requestRate << " per second." << std::endl;
|
||||
if (nodeInfo) {
|
||||
auto& ipv4 = nodeInfo->ipv4;
|
||||
if (ipv4.table_depth > 1)
|
||||
ss << "IPv4 Network estimation: " << ipv4.getNetworkSizeEstimation() << std::endl;;
|
||||
auto& ipv6 = nodeInfo->ipv6;
|
||||
if (ipv6.table_depth > 1)
|
||||
ss << "IPv6 Network estimation: " << ipv6.getNetworkSizeEstimation() << std::endl;;
|
||||
}
|
||||
return ss.str();
|
||||
}
|
||||
std::string toString() const;
|
||||
|
||||
/**
|
||||
* Build a json object from a NodeStats
|
||||
*/
|
||||
Json::Value toJson() const {
|
||||
Json::Value result;
|
||||
result["listenCount"] = static_cast<Json::UInt64>(listenCount);
|
||||
result["putCount"] = static_cast<Json::UInt64>(putCount);
|
||||
result["totalPermanentPuts"] = static_cast<Json::UInt64>(totalPermanentPuts);
|
||||
result["pushListenersCount"] = static_cast<Json::UInt64>(pushListenersCount);
|
||||
result["requestRate"] = requestRate;
|
||||
if (nodeInfo)
|
||||
result["nodeInfo"] = nodeInfo->toJson();
|
||||
return result;
|
||||
}
|
||||
Json::Value toJson() const;
|
||||
};
|
||||
|
||||
std::shared_ptr<ServerStats> stats() const { return stats_; }
|
||||
@@ -151,13 +160,12 @@ private:
|
||||
struct RestRouterTraitsTls;
|
||||
struct RestRouterTraits;
|
||||
|
||||
template <typename HttpResponse>
|
||||
template<typename HttpResponse>
|
||||
static HttpResponse initHttpResponse(HttpResponse response);
|
||||
static restinio::request_handling_status_t serverError(restinio::request_t& request);
|
||||
|
||||
template< typename ServerSettings >
|
||||
void addServerSettings(ServerSettings& serverSettings,
|
||||
const unsigned int max_pipelined_requests = 16);
|
||||
template<typename ServerSettings>
|
||||
void addServerSettings(ServerSettings& serverSettings, const unsigned int max_pipelined_requests = 16);
|
||||
|
||||
std::unique_ptr<RestRouter> createRestRouter();
|
||||
|
||||
@@ -170,8 +178,7 @@ private:
|
||||
* On error: HTTP 503, body: {"err":"xxxx"}
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus getNodeInfo(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params) const;
|
||||
RequestStatus getNodeInfo(restinio::request_handle_t request, restinio::router::route_params_t params) const;
|
||||
|
||||
/**
|
||||
* Return ServerStats in JSON format
|
||||
@@ -179,8 +186,7 @@ private:
|
||||
* Result: HTTP 200, body: Node infos in JSON format
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus getStats(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus getStats(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
/**
|
||||
* Return Values of an infoHash
|
||||
@@ -192,8 +198,7 @@ private:
|
||||
* On error: HTTP 503, body: {"err":"xxxx"}
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus get(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus get(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
/**
|
||||
* Listen incoming Values of an infoHash.
|
||||
@@ -205,8 +210,7 @@ private:
|
||||
* On error: HTTP 503, body: {"err":"xxxx"}
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus listen(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus listen(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
/**
|
||||
* Put a value on the DHT
|
||||
@@ -217,10 +221,9 @@ private:
|
||||
* HTTP 400, body: {"err":"xxxx"} if bad json or HTTP 502 if put fails
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus put(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus put(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
void handleCancelPermamentPut(const asio::error_code &ec, const InfoHash& key, Value::Id vid);
|
||||
void handleCancelPermamentPut(const asio::error_code& ec, const InfoHash& key, Value::Id vid);
|
||||
|
||||
#ifdef OPENDHT_PROXY_SERVER_IDENTITY
|
||||
/**
|
||||
@@ -232,8 +235,7 @@ private:
|
||||
* HTTP 400, body: {"err":"xxxx"} if bad json
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus putSigned(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params) const;
|
||||
RequestStatus putSigned(restinio::request_handle_t request, restinio::router::route_params_t params) const;
|
||||
|
||||
/**
|
||||
* Put a value to encrypt by the proxy on the DHT
|
||||
@@ -244,8 +246,7 @@ private:
|
||||
* HTTP 400, body: {"err":"xxxx"} if bad json
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus putEncrypted(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus putEncrypted(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
#endif // OPENDHT_PROXY_SERVER_IDENTITY
|
||||
|
||||
@@ -259,8 +260,7 @@ private:
|
||||
* On error: HTTP 503, body: {"err":"xxxx"}
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus getFiltered(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus getFiltered(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
/**
|
||||
* Respond allowed Methods
|
||||
@@ -269,10 +269,25 @@ private:
|
||||
* See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus options(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus options(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
struct PushSessionContext
|
||||
{
|
||||
std::mutex lock;
|
||||
std::string sessionId;
|
||||
/** Where to push: follows the latest subscription refresh of the device. */
|
||||
PushType type {PushType::None};
|
||||
std::string topic;
|
||||
PushSessionContext(const std::string& id)
|
||||
: sessionId(id)
|
||||
{}
|
||||
};
|
||||
|
||||
#ifdef OPENDHT_PUSH_NOTIFICATIONS
|
||||
PushType getTypeFromString(const std::string& type);
|
||||
std::string getDefaultTopic(PushType type);
|
||||
|
||||
RequestStatus pingPush(restinio::request_handle_t request, restinio::router::route_params_t /*params*/);
|
||||
/**
|
||||
* Subscribe to push notifications for an iOS or Android device.
|
||||
* Method: SUBSCRIBE "/{InfoHash: .*}"
|
||||
@@ -282,8 +297,7 @@ private:
|
||||
* so you need to refresh the operation each six hours.
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus subscribe(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus subscribe(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
/**
|
||||
* Unsubscribe to push notifications for an iOS or Android device.
|
||||
@@ -292,15 +306,15 @@ private:
|
||||
* Return: nothing
|
||||
* @param session
|
||||
*/
|
||||
RequestStatus unsubscribe(restinio::request_handle_t request,
|
||||
restinio::router::route_params_t params);
|
||||
RequestStatus unsubscribe(restinio::request_handle_t request, restinio::router::route_params_t params);
|
||||
|
||||
/**
|
||||
* Send a push notification via a gorush push gateway
|
||||
* @param key of the device
|
||||
* @param json, the content to send
|
||||
*/
|
||||
void sendPushNotification(const std::string& key, Json::Value&& json, PushType type, bool highPriority);
|
||||
void sendPushNotification(
|
||||
const std::string& key, Json::Value&& json, PushType type, bool highPriority, const std::string& topic);
|
||||
|
||||
/**
|
||||
* Send push notification with an expire timeout.
|
||||
@@ -308,9 +322,13 @@ private:
|
||||
* @param pushToken
|
||||
* @param json
|
||||
* @param type
|
||||
* @param topic
|
||||
*/
|
||||
void handleNotifyPushListenExpire(const asio::error_code &ec, const std::string pushToken,
|
||||
std::function<Json::Value()> json, PushType type);
|
||||
void handleNotifyPushListenExpire(const asio::error_code& ec,
|
||||
const std::string pushToken,
|
||||
std::function<Json::Value()> json,
|
||||
PushType type,
|
||||
const std::string& topic);
|
||||
|
||||
/**
|
||||
* Remove a push listener between a client and a hash
|
||||
@@ -319,23 +337,40 @@ private:
|
||||
* @param key
|
||||
* @param clientId
|
||||
*/
|
||||
void handleCancelPushListen(const asio::error_code &ec, const std::string pushToken,
|
||||
const InfoHash key, const std::string clientId);
|
||||
void handleCancelPushListen(const asio::error_code& ec,
|
||||
const std::string pushToken,
|
||||
const InfoHash key,
|
||||
const std::string clientId);
|
||||
|
||||
#endif //OPENDHT_PUSH_NOTIFICATIONS
|
||||
/**
|
||||
* Handles a push listen request.
|
||||
*
|
||||
* @param infoHash The information hash associated with the push listen request.
|
||||
* @param pushToken The push token associated with the push listen request.
|
||||
* @param clientId The client ID associated with the push listen request.
|
||||
* @param sessionCtx The push session context of the listener, giving the session, push type and topic to use.
|
||||
* @param values The vector of shared pointers to values associated with the push listen request.
|
||||
* @param expired A boolean indicating whether the push listen request has expired.
|
||||
* @return true.
|
||||
*/
|
||||
bool handlePushListen(const InfoHash& infoHash,
|
||||
const std::string& pushToken,
|
||||
const std::string& clientId,
|
||||
const std::shared_ptr<DhtProxyServer::PushSessionContext>& sessionCtx,
|
||||
const std::vector<std::shared_ptr<Value>>& values,
|
||||
bool expired);
|
||||
|
||||
void handlePrintStats(const asio::error_code &ec);
|
||||
#endif // OPENDHT_PUSH_NOTIFICATIONS
|
||||
|
||||
void handlePrintStats(const asio::error_code& ec);
|
||||
void updateStats();
|
||||
|
||||
template <typename Os>
|
||||
template<typename Os>
|
||||
void saveState(Os& stream);
|
||||
|
||||
template <typename Is>
|
||||
template<typename Is>
|
||||
void loadState(Is& is, size_t size);
|
||||
|
||||
using clock = std::chrono::steady_clock;
|
||||
using time_point = clock::time_point;
|
||||
|
||||
std::shared_ptr<asio::io_context> ioContext_;
|
||||
std::shared_ptr<DhtRunner> dht_;
|
||||
Json::StreamWriterBuilder jsonBuilder_;
|
||||
@@ -355,11 +390,17 @@ private:
|
||||
mutable std::mutex requestLock_;
|
||||
std::map<unsigned int /*id*/, std::shared_ptr<http::Request>> requests_;
|
||||
|
||||
std::shared_ptr<dht::Logger> logger_;
|
||||
std::shared_ptr<log::Logger> logger_;
|
||||
|
||||
std::shared_ptr<ServerStats> stats_;
|
||||
std::shared_ptr<NodeInfo> nodeInfo_ {};
|
||||
std::unique_ptr<asio::steady_timer> printStatsTimer_;
|
||||
const time_point serverStartTime_;
|
||||
mutable std::mutex pushStatsMutex_;
|
||||
PushStats androidPush_;
|
||||
PushStats iosPush_;
|
||||
PushStats unifiedPush_;
|
||||
PushStats huaweiPush_;
|
||||
|
||||
// Thread-safe access to listeners map.
|
||||
std::mutex lockListener_;
|
||||
@@ -367,44 +408,52 @@ private:
|
||||
std::map<restinio::connection_id_t, http::ListenerSession> listeners_;
|
||||
// Connection Listener observing conn state changes.
|
||||
std::shared_ptr<ConnectionListener> connListener_;
|
||||
|
||||
struct PushSessionContext {
|
||||
std::mutex lock;
|
||||
std::string sessionId;
|
||||
PushSessionContext(const std::string& id) : sessionId(id) {}
|
||||
};
|
||||
struct PermanentPut {
|
||||
time_point expiration;
|
||||
struct PermanentPut
|
||||
{
|
||||
sys_time_point expiration;
|
||||
std::string pushToken;
|
||||
std::string clientId;
|
||||
std::shared_ptr<PushSessionContext> sessionCtx;
|
||||
std::unique_ptr<asio::steady_timer> expireTimer;
|
||||
std::unique_ptr<asio::steady_timer> expireNotifyTimer;
|
||||
std::unique_ptr<asio::system_timer> expireTimer;
|
||||
std::unique_ptr<asio::system_timer> expireNotifyTimer;
|
||||
Sp<Value> value;
|
||||
PushType type;
|
||||
std::string topic;
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& p) const
|
||||
{
|
||||
p.pack_map(2 + (sessionCtx ? 1 : 0) + (clientId.empty() ? 0 : 1) + (type == PushType::None ? 0 : 2));
|
||||
p.pack("value"); p.pack(value);
|
||||
p.pack("exp"); p.pack(to_time_t(expiration));
|
||||
p.pack_map(2 + (sessionCtx ? 1 : 0) + (clientId.empty() ? 0 : 1) + (type == PushType::None ? 0 : 2)
|
||||
+ (topic.empty() ? 0 : 1));
|
||||
p.pack("value");
|
||||
p.pack(value);
|
||||
p.pack("exp");
|
||||
p.pack(sys_clock::to_time_t(expiration));
|
||||
if (not clientId.empty()) {
|
||||
p.pack("cid"); p.pack(clientId);
|
||||
p.pack("cid");
|
||||
p.pack(clientId);
|
||||
}
|
||||
if (sessionCtx) {
|
||||
std::lock_guard<std::mutex> l(sessionCtx->lock);
|
||||
p.pack("sid"); p.pack(sessionCtx->sessionId);
|
||||
std::lock_guard l(sessionCtx->lock);
|
||||
p.pack("sid");
|
||||
p.pack(sessionCtx->sessionId);
|
||||
}
|
||||
if (type != PushType::None) {
|
||||
p.pack("t"); p.pack(type);
|
||||
p.pack("token"); p.pack(pushToken);
|
||||
p.pack("t");
|
||||
p.pack(type);
|
||||
p.pack("token");
|
||||
p.pack(pushToken);
|
||||
}
|
||||
if (not topic.empty()) {
|
||||
p.pack("top");
|
||||
p.pack(topic);
|
||||
}
|
||||
}
|
||||
|
||||
void msgpack_unpack(const msgpack::object& o);
|
||||
};
|
||||
struct SearchPuts {
|
||||
struct SearchPuts
|
||||
{
|
||||
std::map<dht::Value::Id, PermanentPut> puts;
|
||||
MSGPACK_DEFINE_ARRAY(puts)
|
||||
};
|
||||
@@ -415,39 +464,50 @@ private:
|
||||
mutable std::atomic<time_point> lastStatsReset_ {time_point::min()};
|
||||
|
||||
std::string pushServer_;
|
||||
std::string bundleId_;
|
||||
|
||||
#ifdef OPENDHT_PUSH_NOTIFICATIONS
|
||||
struct Listener {
|
||||
time_point expiration;
|
||||
struct Listener
|
||||
{
|
||||
sys_time_point expiration;
|
||||
std::string clientId;
|
||||
std::shared_ptr<PushSessionContext> sessionCtx;
|
||||
std::future<size_t> internalToken;
|
||||
std::unique_ptr<asio::steady_timer> expireTimer;
|
||||
std::unique_ptr<asio::steady_timer> expireNotifyTimer;
|
||||
std::unique_ptr<asio::system_timer> expireTimer;
|
||||
std::unique_ptr<asio::system_timer> expireNotifyTimer;
|
||||
PushType type;
|
||||
std::string topic;
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& p) const
|
||||
{
|
||||
p.pack_map(sessionCtx ? 4 : 3);
|
||||
p.pack("cid"); p.pack(clientId);
|
||||
p.pack("exp"); p.pack(to_time_t(expiration));
|
||||
p.pack_map(3 + (sessionCtx ? 1 : 0) + (topic.empty() ? 0 : 1));
|
||||
p.pack("cid");
|
||||
p.pack(clientId);
|
||||
p.pack("exp");
|
||||
p.pack(sys_clock::to_time_t(expiration));
|
||||
if (sessionCtx) {
|
||||
std::lock_guard<std::mutex> l(sessionCtx->lock);
|
||||
p.pack("sid"); p.pack(sessionCtx->sessionId);
|
||||
std::lock_guard l(sessionCtx->lock);
|
||||
p.pack("sid");
|
||||
p.pack(sessionCtx->sessionId);
|
||||
}
|
||||
p.pack("t");
|
||||
p.pack(type);
|
||||
if (!topic.empty()) {
|
||||
p.pack("top");
|
||||
p.pack(topic);
|
||||
}
|
||||
p.pack("t"); p.pack(type);
|
||||
}
|
||||
|
||||
void msgpack_unpack(const msgpack::object& o);
|
||||
};
|
||||
struct PushListener {
|
||||
struct PushListener
|
||||
{
|
||||
std::map<InfoHash, std::vector<Listener>> listeners;
|
||||
MSGPACK_DEFINE_ARRAY(listeners)
|
||||
};
|
||||
std::map<std::string, PushListener> pushListeners_;
|
||||
proxy::ListenToken tokenPushNotif_ {0};
|
||||
#endif //OPENDHT_PUSH_NOTIFICATIONS
|
||||
#endif // OPENDHT_PUSH_NOTIFICATIONS
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+257
-192
@@ -1,23 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Authors: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
* Sébastien Blin <sebastien.blin@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
@@ -25,8 +7,9 @@
|
||||
#include "value.h"
|
||||
#include "callbacks.h"
|
||||
#include "sockaddr.h"
|
||||
#include "log_enable.h"
|
||||
#include "logger.h"
|
||||
#include "network_utils.h"
|
||||
#include "node_export.h"
|
||||
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
@@ -50,17 +33,21 @@ struct SecureDhtConfig;
|
||||
* either wait for (expectedly frequent) calls to ::loop() or start an internal
|
||||
* thread that will update the DHT when appropriate.
|
||||
*/
|
||||
class OPENDHT_PUBLIC DhtRunner {
|
||||
|
||||
class OPENDHT_PUBLIC DhtRunner
|
||||
{
|
||||
public:
|
||||
using StatusCallback = std::function<void(NodeStatus, NodeStatus)>;
|
||||
|
||||
struct Config {
|
||||
struct Config
|
||||
{
|
||||
SecureDhtConfig dht_config {};
|
||||
bool threaded {true};
|
||||
std::string proxy_server {};
|
||||
std::string push_node_id {};
|
||||
std::string push_token {};
|
||||
std::string push_topic {};
|
||||
std::string push_platform {};
|
||||
std::string proxy_user_agent {};
|
||||
bool peer_discovery {false};
|
||||
bool peer_publish {false};
|
||||
std::shared_ptr<dht::crypto::Certificate> server_ca;
|
||||
@@ -68,218 +55,292 @@ public:
|
||||
SockAddr bind4 {}, bind6 {};
|
||||
};
|
||||
|
||||
struct Context {
|
||||
struct Context
|
||||
{
|
||||
std::shared_ptr<Logger> logger {};
|
||||
std::unique_ptr<net::DatagramSocket> sock;
|
||||
std::shared_ptr<PeerDiscovery> peerDiscovery {};
|
||||
StatusCallback statusChangedCallback {};
|
||||
CertificateStoreQuery certificateStore {};
|
||||
IdentityAnnouncedCb identityAnnouncedCb {};
|
||||
PublicAddressChangedCb publicAddressChangedCb {};
|
||||
std::unique_ptr<std::mt19937_64> rng {};
|
||||
Context() {}
|
||||
};
|
||||
|
||||
DhtRunner();
|
||||
virtual ~DhtRunner();
|
||||
|
||||
void get(InfoHash id, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter f = {}, Where w = {}) {
|
||||
void get(InfoHash id, GetCallbackSimple cb, DoneCallback donecb = {}, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
get(id, bindGetCb(cb), donecb, f, w);
|
||||
}
|
||||
|
||||
void get(InfoHash id, GetCallbackSimple cb, DoneCallbackSimple donecb={}, Value::Filter f = {}, Where w = {}) {
|
||||
void get(InfoHash id, GetCallbackSimple cb, DoneCallbackSimple donecb = {}, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
get(id, bindGetCb(cb), donecb, f, w);
|
||||
}
|
||||
|
||||
void get(InfoHash hash, GetCallback vcb, DoneCallback dcb, Value::Filter f={}, Where w = {});
|
||||
void get(InfoHash hash, GetCallback vcb, DoneCallback dcb, Value::Filter f = {}, Where w = {});
|
||||
|
||||
void get(InfoHash id, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter f = {}, Where w = {}) {
|
||||
void get(InfoHash id, GetCallback cb, DoneCallbackSimple donecb = {}, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
get(id, cb, bindDoneCb(donecb), f, w);
|
||||
}
|
||||
void get(const std::string& key, GetCallback vcb, DoneCallbackSimple dcb={}, Value::Filter f = {}, Where w = {});
|
||||
void get(const std::string& key, GetCallback vcb, DoneCallbackSimple dcb = {}, Value::Filter f = {}, Where w = {});
|
||||
|
||||
template <class T>
|
||||
void get(InfoHash hash, std::function<bool(std::vector<T>&&)> cb, DoneCallbackSimple dcb={})
|
||||
template<class T>
|
||||
void get(InfoHash hash, std::function<bool(std::vector<T>&&)> cb, DoneCallbackSimple dcb = {})
|
||||
{
|
||||
get(hash, [cb=std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) {
|
||||
return cb(unpackVector<T>(vals));
|
||||
},
|
||||
dcb,
|
||||
getFilterSet<T>());
|
||||
get(
|
||||
hash,
|
||||
[cb = std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) { return cb(unpackVector<T>(vals)); },
|
||||
dcb,
|
||||
getFilterSet<T>());
|
||||
}
|
||||
template <class T>
|
||||
void get(InfoHash hash, std::function<bool(T&&)> cb, DoneCallbackSimple dcb={})
|
||||
template<class T>
|
||||
void get(InfoHash hash, std::function<bool(T&&)> cb, DoneCallbackSimple dcb = {})
|
||||
{
|
||||
get(hash, [cb=std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) {
|
||||
for (const auto& v : vals) {
|
||||
try {
|
||||
if (not cb(Value::unpack<T>(*v)))
|
||||
return false;
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
get(
|
||||
hash,
|
||||
[cb = std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) {
|
||||
for (const auto& v : vals) {
|
||||
try {
|
||||
if (not cb(Value::unpack<T>(*v)))
|
||||
return false;
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
dcb,
|
||||
getFilterSet<T>());
|
||||
return true;
|
||||
},
|
||||
dcb,
|
||||
getFilterSet<T>());
|
||||
}
|
||||
|
||||
std::future<std::vector<std::shared_ptr<dht::Value>>> get(InfoHash key, Value::Filter f = {}, Where w = {}) {
|
||||
auto p = std::make_shared<std::promise<std::vector<std::shared_ptr< dht::Value >>>>();
|
||||
auto values = std::make_shared<std::vector<std::shared_ptr< dht::Value >>>();
|
||||
get(key, [=](const std::vector<std::shared_ptr<dht::Value>>& vlist) {
|
||||
values->insert(values->end(), vlist.begin(), vlist.end());
|
||||
return true;
|
||||
}, [=](bool) {
|
||||
p->set_value(std::move(*values));
|
||||
},
|
||||
f, w);
|
||||
std::future<std::vector<std::shared_ptr<dht::Value>>> get(InfoHash key, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
auto p = std::make_shared<std::promise<std::vector<std::shared_ptr<dht::Value>>>>();
|
||||
auto values = std::make_shared<std::vector<std::shared_ptr<dht::Value>>>();
|
||||
get(
|
||||
key,
|
||||
[=](const std::vector<std::shared_ptr<dht::Value>>& vlist) {
|
||||
values->insert(values->end(), vlist.begin(), vlist.end());
|
||||
return true;
|
||||
},
|
||||
[=](bool) { p->set_value(std::move(*values)); },
|
||||
f,
|
||||
w);
|
||||
return p->get_future();
|
||||
}
|
||||
|
||||
template <class T>
|
||||
std::future<std::vector<T>> get(InfoHash key) {
|
||||
template<class T>
|
||||
std::future<std::vector<T>> get(InfoHash key)
|
||||
{
|
||||
auto p = std::make_shared<std::promise<std::vector<T>>>();
|
||||
auto values = std::make_shared<std::vector<T>>();
|
||||
get<T>(key, [=](T&& v) {
|
||||
values->emplace_back(std::move(v));
|
||||
return true;
|
||||
}, [=](bool) {
|
||||
p->set_value(std::move(*values));
|
||||
});
|
||||
get<T>(
|
||||
key,
|
||||
[=](T&& v) {
|
||||
values->emplace_back(std::move(v));
|
||||
return true;
|
||||
},
|
||||
[=](bool) { p->set_value(std::move(*values)); });
|
||||
return p->get_future();
|
||||
}
|
||||
|
||||
void query(const InfoHash& hash, QueryCallback cb, DoneCallback done_cb = {}, Query q = {});
|
||||
void query(const InfoHash& hash, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query q = {}) {
|
||||
void query(const InfoHash& hash, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query q = {})
|
||||
{
|
||||
query(hash, cb, bindDoneCb(done_cb), q);
|
||||
}
|
||||
|
||||
std::future<size_t> listen(InfoHash key, ValueCallback vcb, Value::Filter f = {}, Where w = {});
|
||||
|
||||
std::future<size_t> listen(InfoHash key, GetCallback cb, Value::Filter f={}, Where w={}) {
|
||||
return listen(key, [cb=std::move(cb)](const std::vector<Sp<Value>>& vals, bool expired){
|
||||
if (not expired)
|
||||
return cb(vals);
|
||||
return true;
|
||||
}, std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
std::future<size_t> listen(InfoHash key, GetCallback cb, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
return listen(
|
||||
key,
|
||||
[cb = std::move(cb)](const std::vector<Sp<Value>>& vals, bool expired) {
|
||||
if (not expired)
|
||||
return cb(vals);
|
||||
return true;
|
||||
},
|
||||
std::forward<Value::Filter>(f),
|
||||
std::forward<Where>(w));
|
||||
}
|
||||
std::future<size_t> listen(const std::string& key, GetCallback vcb, Value::Filter f = {}, Where w = {});
|
||||
std::future<size_t> listen(InfoHash key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) {
|
||||
std::future<size_t> listen(InfoHash key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
return listen(key, bindGetCb(cb), f, w);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
template<class T>
|
||||
std::future<size_t> listen(InfoHash hash, std::function<bool(std::vector<T>&&)> cb)
|
||||
{
|
||||
return listen(hash, [cb=std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) {
|
||||
return cb(unpackVector<T>(vals));
|
||||
},
|
||||
getFilterSet<T>());
|
||||
return listen(
|
||||
hash,
|
||||
[cb = std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) { return cb(unpackVector<T>(vals)); },
|
||||
getFilterSet<T>());
|
||||
}
|
||||
template <class T>
|
||||
template<class T>
|
||||
std::future<size_t> listen(InfoHash hash, std::function<bool(std::vector<T>&&, bool)> cb)
|
||||
{
|
||||
return listen(hash, [cb=std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals, bool expired) {
|
||||
return cb(unpackVector<T>(vals), expired);
|
||||
},
|
||||
getFilterSet<T>());
|
||||
return listen(
|
||||
hash,
|
||||
[cb = std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals, bool expired) {
|
||||
return cb(unpackVector<T>(vals), expired);
|
||||
},
|
||||
getFilterSet<T>());
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
template<typename T>
|
||||
std::future<size_t> listen(InfoHash hash, std::function<bool(T&&)> cb, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
return listen(hash, [cb=std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) {
|
||||
for (const auto& v : vals) {
|
||||
try {
|
||||
if (not cb(Value::unpack<T>(*v)))
|
||||
return false;
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
return listen(
|
||||
hash,
|
||||
[cb = std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals) {
|
||||
for (const auto& v : vals) {
|
||||
try {
|
||||
if (not cb(Value::unpack<T>(*v)))
|
||||
return false;
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
getFilterSet<T>(f), w);
|
||||
return true;
|
||||
},
|
||||
getFilterSet<T>(f),
|
||||
w);
|
||||
}
|
||||
template <typename T>
|
||||
template<typename T>
|
||||
std::future<size_t> listen(InfoHash hash, std::function<bool(T&&, bool)> cb, Value::Filter f = {}, Where w = {})
|
||||
{
|
||||
return listen(hash, [cb=std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals, bool expired) {
|
||||
for (const auto& v : vals) {
|
||||
try {
|
||||
if (not cb(Value::unpack<T>(*v), expired))
|
||||
return false;
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
return listen(
|
||||
hash,
|
||||
[cb = std::move(cb)](const std::vector<std::shared_ptr<Value>>& vals, bool expired) {
|
||||
for (const auto& v : vals) {
|
||||
try {
|
||||
if (not cb(Value::unpack<T>(*v), expired))
|
||||
return false;
|
||||
} catch (const std::exception&) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
},
|
||||
getFilterSet<T>(f), w);
|
||||
return true;
|
||||
},
|
||||
getFilterSet<T>(f),
|
||||
w);
|
||||
}
|
||||
|
||||
void cancelListen(InfoHash h, size_t token);
|
||||
void cancelListen(InfoHash h, std::shared_future<size_t> token);
|
||||
|
||||
void put(InfoHash hash, std::shared_ptr<Value> value, DoneCallback cb={}, time_point created=time_point::max(), bool permanent = false);
|
||||
void put(InfoHash hash, std::shared_ptr<Value> value, DoneCallbackSimple cb, time_point created=time_point::max(), bool permanent = false) {
|
||||
void put(InfoHash hash,
|
||||
std::shared_ptr<Value> value,
|
||||
DoneCallback cb = {},
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false);
|
||||
void put(InfoHash hash,
|
||||
std::shared_ptr<Value> value,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false)
|
||||
{
|
||||
put(hash, value, bindDoneCb(cb), created, permanent);
|
||||
}
|
||||
|
||||
void put(InfoHash hash, Value&& value, DoneCallback cb={}, time_point created=time_point::max(), bool permanent = false);
|
||||
void put(InfoHash hash, Value&& value, DoneCallbackSimple cb, time_point created=time_point::max(), bool permanent = false) {
|
||||
void put(InfoHash hash,
|
||||
Value&& value,
|
||||
DoneCallback cb = {},
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false);
|
||||
void put(InfoHash hash,
|
||||
Value&& value,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false)
|
||||
{
|
||||
put(hash, std::forward<Value>(value), bindDoneCb(cb), created, permanent);
|
||||
}
|
||||
void put(const std::string& key, Value&& value, DoneCallbackSimple cb={}, time_point created=time_point::max(), bool permanent = false);
|
||||
void put(const std::string& key,
|
||||
Value&& value,
|
||||
DoneCallbackSimple cb = {},
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false);
|
||||
|
||||
void cancelPut(const InfoHash& h, Value::Id id);
|
||||
void cancelPut(const InfoHash& h, const std::shared_ptr<Value>& value);
|
||||
|
||||
void putSigned(InfoHash hash, std::shared_ptr<Value> value, DoneCallback cb={}, bool permanent = false);
|
||||
void putSigned(InfoHash hash, std::shared_ptr<Value> value, DoneCallbackSimple cb, bool permanent = false) {
|
||||
void putSigned(InfoHash hash, std::shared_ptr<Value> value, DoneCallback cb = {}, bool permanent = false);
|
||||
void putSigned(InfoHash hash, std::shared_ptr<Value> value, DoneCallbackSimple cb, bool permanent = false)
|
||||
{
|
||||
putSigned(hash, value, bindDoneCb(cb), permanent);
|
||||
}
|
||||
|
||||
void putSigned(InfoHash hash, Value&& value, DoneCallback cb={}, bool permanent = false);
|
||||
void putSigned(InfoHash hash, Value&& value, DoneCallbackSimple cb, bool permanent = false) {
|
||||
void putSigned(InfoHash hash, Value&& value, DoneCallback cb = {}, bool permanent = false);
|
||||
void putSigned(InfoHash hash, Value&& value, DoneCallbackSimple cb, bool permanent = false)
|
||||
{
|
||||
putSigned(hash, std::forward<Value>(value), bindDoneCb(cb), permanent);
|
||||
}
|
||||
void putSigned(const std::string& key, Value&& value, DoneCallbackSimple cb={}, bool permanent = false);
|
||||
void putSigned(const std::string& key, Value&& value, DoneCallbackSimple cb = {}, bool permanent = false);
|
||||
|
||||
void putEncrypted(InfoHash hash, InfoHash to, std::shared_ptr<Value> value, DoneCallback cb={}, bool permanent = false);
|
||||
void putEncrypted(InfoHash hash, InfoHash to, std::shared_ptr<Value> value, DoneCallbackSimple cb, bool permanent = false) {
|
||||
void putEncrypted(InfoHash hash,
|
||||
const std::shared_ptr<crypto::PublicKey>& to,
|
||||
std::shared_ptr<Value> value,
|
||||
DoneCallback cb = {},
|
||||
bool permanent = false);
|
||||
void putEncrypted(InfoHash hash,
|
||||
const std::shared_ptr<crypto::PublicKey>& to,
|
||||
std::shared_ptr<Value> value,
|
||||
DoneCallbackSimple cb,
|
||||
bool permanent = false)
|
||||
{
|
||||
putEncrypted(hash, to, value, bindDoneCb(cb), permanent);
|
||||
}
|
||||
|
||||
void putEncrypted(InfoHash hash, InfoHash to, Value&& value, DoneCallback cb={}, bool permanent = false);
|
||||
void putEncrypted(InfoHash hash, InfoHash to, Value&& value, DoneCallbackSimple cb, bool permanent = false) {
|
||||
void putEncrypted(InfoHash hash,
|
||||
const std::shared_ptr<crypto::PublicKey>& to,
|
||||
Value&& value,
|
||||
DoneCallback cb = {},
|
||||
bool permanent = false);
|
||||
void putEncrypted(InfoHash hash,
|
||||
const std::shared_ptr<crypto::PublicKey>& to,
|
||||
Value&& value,
|
||||
DoneCallbackSimple cb,
|
||||
bool permanent = false)
|
||||
{
|
||||
putEncrypted(hash, to, std::forward<Value>(value), bindDoneCb(cb), permanent);
|
||||
}
|
||||
void putEncrypted(const std::string& key, InfoHash to, Value&& value, DoneCallback cb={}, bool permanent = false);
|
||||
|
||||
void putEncrypted(InfoHash hash, const std::shared_ptr<crypto::PublicKey>& to, std::shared_ptr<Value> value, DoneCallback cb={}, bool permanent = false);
|
||||
void putEncrypted(InfoHash hash, const std::shared_ptr<crypto::PublicKey>& to, std::shared_ptr<Value> value, DoneCallbackSimple cb, bool permanent = false) {
|
||||
void putEncrypted(
|
||||
InfoHash hash, const PkId& to, std::shared_ptr<Value> value, DoneCallback cb = {}, bool permanent = false);
|
||||
void putEncrypted(
|
||||
InfoHash hash, const PkId& to, std::shared_ptr<Value> value, DoneCallbackSimple cb, bool permanent = false)
|
||||
{
|
||||
putEncrypted(hash, to, value, bindDoneCb(cb), permanent);
|
||||
}
|
||||
|
||||
void putEncrypted(InfoHash hash, const std::shared_ptr<crypto::PublicKey>& to, Value&& value, DoneCallback cb={}, bool permanent = false);
|
||||
void putEncrypted(InfoHash hash, const std::shared_ptr<crypto::PublicKey>& to, Value&& value, DoneCallbackSimple cb, bool permanent = false) {
|
||||
putEncrypted(hash, to, std::forward<Value>(value), bindDoneCb(cb), permanent);
|
||||
void putEncrypted(InfoHash hash, const PkId& to, Value&& value, DoneCallback cb = {}, bool permanent = false)
|
||||
{
|
||||
putEncrypted(hash, to, std::make_shared<Value>(std::move(value)), std::move(cb), permanent);
|
||||
}
|
||||
void putEncrypted(InfoHash hash, const PkId& to, Value&& value, DoneCallbackSimple cb, bool permanent = false)
|
||||
{
|
||||
putEncrypted(hash, to, std::make_shared<Value>(std::move(value)), bindDoneCb(cb), permanent);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Insert known nodes to the routing table, without necessarly ping them.
|
||||
* Usefull to restart a node and get things running fast without putting load on the network.
|
||||
*/
|
||||
void bootstrap(std::vector<SockAddr> nodes, DoneCallbackSimple cb={});
|
||||
void bootstrap(const SockAddr& addr, DoneCallbackSimple cb={});
|
||||
void bootstrap(std::vector<SockAddr> nodes, DoneCallbackSimple cb = {});
|
||||
void bootstrap(SockAddr addr, DoneCallbackSimple cb = {});
|
||||
|
||||
/**
|
||||
* Insert known nodes to the routing table, without necessarly ping them.
|
||||
* Usefull to restart a node and get things running fast without putting load on the network.
|
||||
*/
|
||||
void bootstrap(const std::vector<NodeExport>& nodes);
|
||||
void bootstrap(std::vector<NodeExport> nodes);
|
||||
|
||||
/**
|
||||
* Add host:service to bootstrap nodes, and ping this node.
|
||||
@@ -313,7 +374,7 @@ public:
|
||||
/**
|
||||
* Get the public key fingerprint if an identity is used with this node, 0 otherwise.
|
||||
*/
|
||||
InfoHash getId() const;
|
||||
[[deprecated("Use getPublicKey()->getLongId() instead")]] InfoHash getId() const;
|
||||
std::shared_ptr<crypto::PublicKey> getPublicKey() const;
|
||||
|
||||
/**
|
||||
@@ -335,17 +396,17 @@ public:
|
||||
|
||||
std::pair<size_t, size_t> getStoreSize() const;
|
||||
|
||||
void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT);
|
||||
size_t getStorageLimit() const;
|
||||
void setStorageLimit(size_t limit = 0);
|
||||
|
||||
size_t getLocalStorageLimit() const;
|
||||
void setLocalStorageLimit(size_t limit = 0);
|
||||
|
||||
std::vector<NodeExport> exportNodes() const;
|
||||
|
||||
std::vector<ValuesExport> exportValues() const;
|
||||
|
||||
void setLogger(const Sp<Logger>& logger = {});
|
||||
void setLogger(const Logger& logger) {
|
||||
setLogger(std::make_shared<Logger>(logger));
|
||||
}
|
||||
void setLoggers(LogMethod err = {}, LogMethod warn = {}, LogMethod debug = {});
|
||||
|
||||
/**
|
||||
* Only print logs related to the given InfoHash (if given), or disable filter (if zeroes).
|
||||
@@ -353,15 +414,18 @@ public:
|
||||
void setLogFilter(const InfoHash& f = {});
|
||||
|
||||
void registerType(const ValueType& type);
|
||||
void registerInsecureType(const ValueType& type);
|
||||
|
||||
void importValues(const std::vector<ValuesExport>& values);
|
||||
|
||||
bool isRunning() const {
|
||||
return running != State::Idle;
|
||||
}
|
||||
bool isRunning() const { return running != State::Idle; }
|
||||
|
||||
NodeStats getNodesStats(sa_family_t af) const;
|
||||
unsigned getNodesStats(sa_family_t af, unsigned *good_return, unsigned *dubious_return, unsigned *cached_return, unsigned *incoming_return) const;
|
||||
unsigned getNodesStats(sa_family_t af,
|
||||
unsigned* good_return,
|
||||
unsigned* dubious_return,
|
||||
unsigned* cached_return,
|
||||
unsigned* incoming_return) const;
|
||||
NodeInfo getNodeInfo() const;
|
||||
void getNodeInfo(std::function<void(std::shared_ptr<NodeInfo>)>);
|
||||
|
||||
@@ -371,14 +435,14 @@ public:
|
||||
std::string getRoutingTablesLog(sa_family_t af) const;
|
||||
std::string getSearchesLog(sa_family_t af = AF_UNSPEC) const;
|
||||
std::string getSearchLog(const InfoHash&, sa_family_t af = AF_UNSPEC) const;
|
||||
std::vector<SockAddr> getPublicAddress(sa_family_t af = AF_UNSPEC);
|
||||
std::vector<std::string> getPublicAddressStr(sa_family_t af = AF_UNSPEC);
|
||||
std::vector<SockAddr> getPublicAddress(sa_family_t af = AF_UNSPEC) const;
|
||||
std::vector<std::string> getPublicAddressStr(sa_family_t af = AF_UNSPEC) const;
|
||||
void getPublicAddress(std::function<void(std::vector<SockAddr>&&)>, sa_family_t af = AF_UNSPEC);
|
||||
|
||||
// securedht methods
|
||||
void findCertificate(PkId hash, std::function<void(const std::shared_ptr<crypto::Certificate>&)>);
|
||||
|
||||
void findCertificate(InfoHash hash, std::function<void(const std::shared_ptr<crypto::Certificate>&)>);
|
||||
void registerCertificate(std::shared_ptr<crypto::Certificate> cert);
|
||||
void registerCertificate(const std::shared_ptr<crypto::Certificate>& cert);
|
||||
void setLocalCertificateStore(CertificateStoreQuery&& query_method);
|
||||
|
||||
/**
|
||||
@@ -387,7 +451,11 @@ public:
|
||||
* @param threaded: If false, ::loop() must be called periodically. Otherwise a thread is launched.
|
||||
* @param cb: Optional callback to receive general state information.
|
||||
*/
|
||||
void run(in_port_t port = dht::net::DHT_DEFAULT_PORT, const crypto::Identity& identity = {}, bool threaded = true, NetId network = 0) {
|
||||
void run(in_port_t port = dht::net::DHT_DEFAULT_PORT,
|
||||
const crypto::Identity& identity = {},
|
||||
bool threaded = true,
|
||||
NetId network = 0)
|
||||
{
|
||||
Config config;
|
||||
config.dht_config.node_config.network = network;
|
||||
config.dht_config.id = identity;
|
||||
@@ -397,14 +465,17 @@ public:
|
||||
void run(in_port_t port, Config& config, Context&& context = {});
|
||||
|
||||
/**
|
||||
* Same as @run(sockaddr_in, sockaddr_in6, Identity, bool, StatusCallback), but with string IP addresses and service (port).
|
||||
* Same as @run(sockaddr_in, sockaddr_in6, Identity, bool, StatusCallback), but with string IP addresses and service
|
||||
* (port).
|
||||
*/
|
||||
void run(const char* ip4, const char* ip6, const char* service, Config& config, Context&& context = {});
|
||||
|
||||
void run(const Config& config, Context&& context);
|
||||
|
||||
void setOnStatusChanged(StatusCallback&& cb) {
|
||||
statusCb = std::move(cb);
|
||||
void setOnStatusChanged(StatusCallback&& cb)
|
||||
{
|
||||
if (cb)
|
||||
statusCbs.emplace_back(std::move(cb));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -412,8 +483,9 @@ public:
|
||||
* regularly and everytime a new packet is received.
|
||||
* @return the next op
|
||||
*/
|
||||
time_point loop() {
|
||||
std::lock_guard<std::mutex> lck(dht_mtx);
|
||||
time_point loop()
|
||||
{
|
||||
std::lock_guard lck(dht_mtx);
|
||||
return loop_();
|
||||
}
|
||||
|
||||
@@ -423,9 +495,11 @@ public:
|
||||
void shutdown(ShutdownCallback cb = {}, bool stop = false);
|
||||
|
||||
/**
|
||||
* Quit and wait for all threads to terminate.
|
||||
* No callbacks will be called after this method returns.
|
||||
* All internal state will be lost. The DHT can then be run again with @run().
|
||||
* Stop the node and wait for all threads to terminate.
|
||||
* The node is reset to its default state. The DHT can then be run again with @run().
|
||||
* No DHT callbacks will run after this method returns.
|
||||
* Calling this method is optional. It allows to ensure the destructor won't block.
|
||||
* This method is unable to be called from a DHT callback.
|
||||
*/
|
||||
void join();
|
||||
|
||||
@@ -436,7 +510,6 @@ public:
|
||||
/**
|
||||
* Start or stop the proxy
|
||||
* @param proxify if we want to use the proxy
|
||||
* @param deviceKey non empty to enable push notifications
|
||||
*/
|
||||
void enableProxy(bool proxify);
|
||||
|
||||
@@ -448,37 +521,40 @@ public:
|
||||
void setPushNotificationToken(const std::string& token);
|
||||
|
||||
/**
|
||||
* Insert a push notification to process for OpenDHT
|
||||
* Sets the push notification topic
|
||||
*/
|
||||
void pushNotificationReceived(const std::map<std::string, std::string>& data);
|
||||
void setPushNotificationTopic(const std::string& topic);
|
||||
|
||||
/**
|
||||
* Sets the push notification platform
|
||||
*/
|
||||
void setPushNotificationPlatform(const std::string& platform);
|
||||
|
||||
/**
|
||||
* Insert a push notification to process for OpenDHT
|
||||
* Returns an immediately ready future with IgnoredStopped if the runner is idle,
|
||||
* or IgnoredDisabled if push notification support is disabled at build time.
|
||||
*/
|
||||
std::future<PushNotificationResult> pushNotificationReceived(const std::map<std::string, std::string>& data);
|
||||
|
||||
/* Proxy server mothods */
|
||||
void forwardAllMessages(bool forward);
|
||||
|
||||
private:
|
||||
enum class State {
|
||||
Idle,
|
||||
Running,
|
||||
Stopping
|
||||
};
|
||||
enum class State { Idle, Running, Stopping };
|
||||
|
||||
time_point loop_();
|
||||
|
||||
NodeStatus getStatus() const {
|
||||
return std::max(status4, status6);
|
||||
}
|
||||
NodeStatus getStatus() const { return std::max(status4, status6); }
|
||||
|
||||
bool checkShutdown();
|
||||
void opEnded();
|
||||
DoneCallback bindOpDoneCallback(DoneCallback&& cb);
|
||||
DoneCallbackSimple bindOpDoneCallback(DoneCallbackSimple&& cb);
|
||||
|
||||
/** Local DHT instance */
|
||||
/** DHT instance */
|
||||
std::unique_ptr<SecureDht> dht_;
|
||||
|
||||
/** Proxy client instance */
|
||||
std::unique_ptr<SecureDht> dht_via_proxy_;
|
||||
|
||||
/** true if we are currently using a proxy */
|
||||
std::atomic_bool use_proxy {false};
|
||||
|
||||
@@ -490,36 +566,25 @@ private:
|
||||
* reset dht clients
|
||||
*/
|
||||
void resetDht();
|
||||
/**
|
||||
* @return the current active DHT
|
||||
*/
|
||||
SecureDht* activeDht() const;
|
||||
|
||||
/**
|
||||
* Store current listeners and translates global tokens for each client.
|
||||
*/
|
||||
struct Listener;
|
||||
std::map<size_t, Listener> listeners_;
|
||||
size_t listener_token_ {1};
|
||||
|
||||
mutable std::mutex dht_mtx {};
|
||||
mutable std::mutex dht_mtx;
|
||||
std::thread dht_thread {};
|
||||
std::condition_variable cv {};
|
||||
std::mutex sock_mtx {};
|
||||
std::mutex sock_mtx;
|
||||
net::PacketList rcv {};
|
||||
decltype(rcv) rcv_free {};
|
||||
|
||||
std::queue<std::function<void(SecureDht&)>> pending_ops_prio {};
|
||||
std::queue<std::function<void(SecureDht&)>> pending_ops {};
|
||||
std::mutex storage_mtx {};
|
||||
std::mutex storage_mtx;
|
||||
|
||||
std::atomic<State> running {State::Idle};
|
||||
std::atomic_size_t ongoing_ops {0};
|
||||
std::vector<ShutdownCallback> shutdownCallbacks_;
|
||||
|
||||
NodeStatus status4 {NodeStatus::Disconnected},
|
||||
status6 {NodeStatus::Disconnected};
|
||||
StatusCallback statusCb {nullptr};
|
||||
NodeStatus status4 {NodeStatus::Disconnected}, status6 {NodeStatus::Disconnected};
|
||||
|
||||
std::vector<StatusCallback> statusCbs {};
|
||||
|
||||
/** PeerDiscovery Parameters */
|
||||
std::shared_ptr<PeerDiscovery> peerDiscovery_;
|
||||
@@ -531,4 +596,4 @@ private:
|
||||
std::shared_ptr<dht::Logger> logger_;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+108
-110
@@ -1,21 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author: Vsevolod Ivanov <vsevolod.ivanov@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
@@ -25,35 +9,34 @@
|
||||
// some libraries may try to redefine snprintf
|
||||
// but restinio will use it in std namespace
|
||||
#ifdef _MSC_VER
|
||||
# undef snprintf
|
||||
# define snprintf snprintf
|
||||
#undef snprintf
|
||||
#define snprintf snprintf
|
||||
#endif
|
||||
|
||||
#include <asio/ip/tcp.hpp>
|
||||
#include <asio/streambuf.hpp>
|
||||
#include <asio/ssl/context.hpp>
|
||||
#include <restinio/http_headers.hpp>
|
||||
#include <restinio/message_builders.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <future>
|
||||
|
||||
namespace Json {
|
||||
class Value;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
struct http_parser;
|
||||
struct http_parser_settings;
|
||||
}
|
||||
|
||||
namespace restinio {
|
||||
namespace impl {
|
||||
class tls_socket_t;
|
||||
}
|
||||
}
|
||||
} // namespace restinio
|
||||
|
||||
namespace dht {
|
||||
namespace log {
|
||||
struct Logger;
|
||||
}
|
||||
|
||||
namespace crypto {
|
||||
struct Certificate;
|
||||
@@ -63,24 +46,25 @@ namespace http {
|
||||
|
||||
using HandlerCb = std::function<void(const asio::error_code& ec)>;
|
||||
using BytesHandlerCb = std::function<void(const asio::error_code& ec, size_t bytes)>;
|
||||
using ConnectHandlerCb = std::function<void(const asio::error_code& ec,
|
||||
const asio::ip::tcp::endpoint& endpoint)>;
|
||||
using ConnectHandlerCb = std::function<void(const asio::error_code& ec, const asio::ip::tcp::endpoint& endpoint)>;
|
||||
|
||||
using ssl_socket_t = restinio::impl::tls_socket_t;
|
||||
using socket_t = asio::ip::tcp::socket;
|
||||
|
||||
class OPENDHT_PUBLIC Url
|
||||
struct OPENDHT_PUBLIC Url
|
||||
{
|
||||
public:
|
||||
Url() = default;
|
||||
Url(const std::string& url);
|
||||
Url(std::string url);
|
||||
|
||||
std::string url;
|
||||
std::string protocol {"http"};
|
||||
std::string host;
|
||||
std::string service;
|
||||
std::string_view user;
|
||||
std::string_view password;
|
||||
std::string_view host;
|
||||
std::string_view service;
|
||||
std::string target;
|
||||
std::string query;
|
||||
std::string fragment;
|
||||
std::string_view query;
|
||||
std::string_view fragment;
|
||||
|
||||
std::string toString() const;
|
||||
};
|
||||
@@ -88,12 +72,14 @@ public:
|
||||
class OPENDHT_PUBLIC Connection : public std::enable_shared_from_this<Connection>
|
||||
{
|
||||
public:
|
||||
Connection(asio::io_context& ctx, const bool ssl = true, std::shared_ptr<dht::Logger> l = {});
|
||||
Connection(asio::io_context& ctx, std::shared_ptr<dht::crypto::Certificate> server_ca,
|
||||
const dht::crypto::Identity& identity, std::shared_ptr<dht::Logger> l = {});
|
||||
Connection(asio::io_context& ctx, const bool ssl = true, std::shared_ptr<log::Logger> l = {});
|
||||
Connection(asio::io_context& ctx,
|
||||
std::shared_ptr<dht::crypto::Certificate> server_ca,
|
||||
const dht::crypto::Identity& identity,
|
||||
std::shared_ptr<log::Logger> l = {});
|
||||
~Connection();
|
||||
|
||||
inline unsigned int id() const { return id_; };
|
||||
inline unsigned int id() const { return id_; };
|
||||
bool is_open() const;
|
||||
bool is_ssl() const;
|
||||
void checkOcsp(bool check = true) { checkOcsp_ = check; }
|
||||
@@ -114,14 +100,26 @@ public:
|
||||
void async_read(size_t bytes, BytesHandlerCb cb);
|
||||
void async_read_some(size_t bytes, BytesHandlerCb cb);
|
||||
|
||||
void timeout(const std::chrono::seconds timeout, HandlerCb cb = {});
|
||||
void set_keepalive(uint32_t seconds);
|
||||
|
||||
const asio::ip::address& local_address() const;
|
||||
|
||||
void timeout(const std::chrono::seconds& timeout, HandlerCb cb = {});
|
||||
|
||||
/**
|
||||
* Close the underlying socket.
|
||||
* Safe to call from any thread: the actual close is dispatched to
|
||||
* the thread running the io_context.
|
||||
*/
|
||||
void close();
|
||||
|
||||
private:
|
||||
void doClose();
|
||||
|
||||
template<typename T>
|
||||
T wrapCallabck(T cb) const {
|
||||
return [t=shared_from_this(),cb=std::move(cb)](auto ...params) {
|
||||
T wrapCallback(T cb) const
|
||||
{
|
||||
return [t = shared_from_this(), cb = std::move(cb)](auto... params) {
|
||||
cb(params...);
|
||||
};
|
||||
}
|
||||
@@ -142,20 +140,11 @@ private:
|
||||
asio::streambuf read_buf_;
|
||||
std::istream istream_;
|
||||
|
||||
std::unique_ptr<asio::steady_timer> timeout_timer_;
|
||||
std::shared_ptr<dht::Logger> logger_;
|
||||
bool checkOcsp_ {false};
|
||||
};
|
||||
asio::ip::address local_address_;
|
||||
|
||||
/**
|
||||
* Session value associated with a connection_id_t key.
|
||||
*/
|
||||
struct ListenerSession
|
||||
{
|
||||
ListenerSession() = default;
|
||||
dht::InfoHash hash;
|
||||
std::future<size_t> token;
|
||||
std::shared_ptr<restinio::response_builder_t<restinio::chunked_output_t>> response;
|
||||
std::unique_ptr<asio::steady_timer> timeout_timer_;
|
||||
std::shared_ptr<log::Logger> logger_;
|
||||
bool checkOcsp_ {false};
|
||||
};
|
||||
|
||||
/* @class Resolver
|
||||
@@ -164,33 +153,34 @@ struct ListenerSession
|
||||
class OPENDHT_PUBLIC Resolver
|
||||
{
|
||||
public:
|
||||
using ResolverCb = std::function<void(const asio::error_code& ec,
|
||||
const std::vector<asio::ip::tcp::endpoint>& endpoints)>;
|
||||
using ResolverCb
|
||||
= std::function<void(const asio::error_code& ec, const std::vector<asio::ip::tcp::endpoint>& endpoints)>;
|
||||
|
||||
Resolver(asio::io_context& ctx, const std::string& url, std::shared_ptr<dht::Logger> logger = {});
|
||||
Resolver(asio::io_context& ctx, const std::string& host, const std::string& service,
|
||||
const bool ssl = false, std::shared_ptr<dht::Logger> logger = {});
|
||||
Resolver(asio::io_context& ctx, std::string url, std::shared_ptr<log::Logger> logger = {});
|
||||
Resolver(asio::io_context& ctx,
|
||||
std::string_view host,
|
||||
std::string_view service,
|
||||
const bool ssl = false,
|
||||
std::shared_ptr<log::Logger> logger = {});
|
||||
|
||||
// use already resolved endpoints with classes using this resolver
|
||||
Resolver(asio::io_context& ctx, std::vector<asio::ip::tcp::endpoint> endpoints,
|
||||
const bool ssl = false, std::shared_ptr<dht::Logger> logger = {});
|
||||
Resolver(asio::io_context& ctx, const std::string& url, std::vector<asio::ip::tcp::endpoint> endpoints,
|
||||
std::shared_ptr<dht::Logger> logger = {});
|
||||
Resolver(asio::io_context& ctx,
|
||||
std::vector<asio::ip::tcp::endpoint> endpoints,
|
||||
const bool ssl = false,
|
||||
std::shared_ptr<log::Logger> logger = {});
|
||||
|
||||
~Resolver();
|
||||
|
||||
inline const Url& get_url() const {
|
||||
return url_;
|
||||
}
|
||||
inline const Url& get_url() const { return url_; }
|
||||
|
||||
void add_callback(ResolverCb cb, sa_family_t family = AF_UNSPEC);
|
||||
|
||||
std::shared_ptr<Logger> getLogger() const {
|
||||
return logger_;
|
||||
}
|
||||
std::shared_ptr<log::Logger> getLogger() const { return logger_; }
|
||||
|
||||
void cancel();
|
||||
|
||||
private:
|
||||
void resolve(const std::string& host, const std::string& service);
|
||||
void resolve(std::string_view host, std::string_view service);
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
@@ -203,7 +193,7 @@ private:
|
||||
bool completed_ {false};
|
||||
std::queue<ResolverCb> cbs_;
|
||||
|
||||
std::shared_ptr<dht::Logger> logger_;
|
||||
std::shared_ptr<log::Logger> logger_;
|
||||
};
|
||||
|
||||
class Request;
|
||||
@@ -220,13 +210,7 @@ struct Response
|
||||
class OPENDHT_PUBLIC Request : public std::enable_shared_from_this<Request>
|
||||
{
|
||||
public:
|
||||
enum class State {
|
||||
CREATED,
|
||||
SENDING,
|
||||
HEADER_RECEIVED,
|
||||
RECEIVING,
|
||||
DONE
|
||||
};
|
||||
enum class State { CREATED, SENDING, HEADER_RECEIVED, RECEIVING, DONE };
|
||||
using OnStatusCb = std::function<void(unsigned status_code)>;
|
||||
using OnDataCb = std::function<void(const char* at, size_t length)>;
|
||||
using OnStateChangeCb = std::function<void(State state, const Response& response)>;
|
||||
@@ -234,45 +218,55 @@ public:
|
||||
using OnDoneCb = std::function<void(const Response& response)>;
|
||||
|
||||
// resolves implicitly
|
||||
Request(asio::io_context& ctx, const std::string& url, const Json::Value& json, OnJsonCb jsoncb,
|
||||
std::shared_ptr<dht::Logger> logger = {});
|
||||
Request(asio::io_context& ctx, const std::string& url, OnJsonCb jsoncb,
|
||||
std::shared_ptr<dht::Logger> logger = {});
|
||||
Request(asio::io_context& ctx,
|
||||
std::string url,
|
||||
const Json::Value& json,
|
||||
OnJsonCb jsoncb,
|
||||
std::shared_ptr<log::Logger> logger = {});
|
||||
Request(asio::io_context& ctx, std::string url, OnJsonCb jsoncb, std::shared_ptr<log::Logger> logger = {});
|
||||
|
||||
Request(asio::io_context& ctx, const std::string& url, std::shared_ptr<dht::Logger> logger = {});
|
||||
Request(asio::io_context& ctx, const std::string& host, const std::string& service,
|
||||
const bool ssl = false, std::shared_ptr<dht::Logger> logger = {});
|
||||
Request(asio::io_context& ctx, const std::string& url, OnDoneCb onDone, std::shared_ptr<dht::Logger> logger = {});
|
||||
Request(asio::io_context& ctx, std::string url, std::shared_ptr<log::Logger> logger = {});
|
||||
Request(asio::io_context& ctx,
|
||||
std::string_view host,
|
||||
std::string_view service,
|
||||
const bool ssl = false,
|
||||
std::shared_ptr<log::Logger> logger = {});
|
||||
Request(asio::io_context& ctx, std::string url, OnDoneCb onDone, std::shared_ptr<log::Logger> logger = {});
|
||||
|
||||
// user defined resolver
|
||||
Request(asio::io_context& ctx, std::shared_ptr<Resolver> resolver, sa_family_t family = AF_UNSPEC);
|
||||
Request(asio::io_context& ctx, std::shared_ptr<Resolver> resolver, const std::string& target, sa_family_t family = AF_UNSPEC);
|
||||
Request(asio::io_context& ctx,
|
||||
std::shared_ptr<Resolver> resolver,
|
||||
const std::string& target,
|
||||
sa_family_t family = AF_UNSPEC);
|
||||
|
||||
// user defined resolved endpoints
|
||||
Request(asio::io_context& ctx, std::vector<asio::ip::tcp::endpoint>&& endpoints,
|
||||
const bool ssl = false, std::shared_ptr<dht::Logger> logger = {});
|
||||
Request(asio::io_context& ctx,
|
||||
std::vector<asio::ip::tcp::endpoint>&& endpoints,
|
||||
const bool ssl = false,
|
||||
std::shared_ptr<log::Logger> logger = {});
|
||||
|
||||
~Request();
|
||||
|
||||
inline unsigned int id() const { return id_; };
|
||||
inline unsigned int id() const { return id_; };
|
||||
void set_connection(std::shared_ptr<Connection> connection);
|
||||
std::shared_ptr<Connection> get_connection() const;
|
||||
inline const Url& get_url() const {
|
||||
return resolver_->get_url();
|
||||
};
|
||||
inline const Url& get_url() const { return resolver_->get_url(); };
|
||||
|
||||
void timeout(const std::chrono::seconds& timeout, HandlerCb cb = {})
|
||||
{
|
||||
timeout_ = timeout;
|
||||
timeoutCb_ = cb;
|
||||
}
|
||||
|
||||
/** The previous request in case of redirect following */
|
||||
std::shared_ptr<Request> getPrevious() const {
|
||||
return prev_.lock();
|
||||
}
|
||||
std::shared_ptr<Request> getPrevious() const { return prev_.lock(); }
|
||||
|
||||
inline std::string& to_string() {
|
||||
return request_;
|
||||
}
|
||||
inline std::string& to_string() { return request_; }
|
||||
|
||||
void set_certificate_authority(std::shared_ptr<dht::crypto::Certificate> certificate);
|
||||
void set_identity(const dht::crypto::Identity& identity);
|
||||
void set_logger(std::shared_ptr<dht::Logger> logger);
|
||||
void set_logger(std::shared_ptr<log::Logger> logger);
|
||||
|
||||
/**
|
||||
* Define the HTTP header/body as per https://tools.ietf.org/html/rfc7230.
|
||||
@@ -283,6 +277,7 @@ public:
|
||||
void set_header_field(restinio::http_field_t field, std::string value);
|
||||
void set_connection_type(restinio::http_connection_header_t connection);
|
||||
void set_body(std::string body);
|
||||
void set_body(const uint8_t* data, size_t length);
|
||||
void set_auth(const std::string& username, const std::string& password);
|
||||
|
||||
void add_on_status_callback(OnStatusCb cb);
|
||||
@@ -304,7 +299,8 @@ public:
|
||||
private:
|
||||
using OnCompleteCb = std::function<void()>;
|
||||
|
||||
struct Callbacks {
|
||||
struct Callbacks
|
||||
{
|
||||
OnStatusCb on_status;
|
||||
OnDataCb on_header_field;
|
||||
OnDataCb on_header_value;
|
||||
@@ -318,9 +314,11 @@ private:
|
||||
|
||||
void build();
|
||||
|
||||
static std::string url_encode(std::string_view value);
|
||||
|
||||
void init_default_headers();
|
||||
/**
|
||||
* Initialized and wraps the http_parser callbacks with our user defined callbacks.
|
||||
* Initialized and wraps the llhttp callbacks with our user defined callbacks.
|
||||
*/
|
||||
void init_parser();
|
||||
|
||||
@@ -337,7 +335,7 @@ private:
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
|
||||
std::shared_ptr<dht::Logger> logger_;
|
||||
std::shared_ptr<log::Logger> logger_;
|
||||
|
||||
restinio::http_request_header_t header_;
|
||||
std::map<restinio::http_field_t, std::string> headers_;
|
||||
@@ -349,8 +347,6 @@ private:
|
||||
|
||||
dht::crypto::Identity client_identity_;
|
||||
std::shared_ptr<dht::crypto::Certificate> server_ca_;
|
||||
std::string service_;
|
||||
std::string host_;
|
||||
|
||||
unsigned int id_;
|
||||
static std::atomic_uint ids_;
|
||||
@@ -362,16 +358,18 @@ private:
|
||||
Response response_ {};
|
||||
std::string request_;
|
||||
std::atomic<bool> finishing_ {false};
|
||||
std::unique_ptr<http_parser> parser_;
|
||||
std::unique_ptr<http_parser_settings> parser_s_;
|
||||
std::unique_ptr<llhttp_t> parser_;
|
||||
std::unique_ptr<llhttp_settings_t> parser_s_;
|
||||
|
||||
// Next request in case of redirect following
|
||||
std::shared_ptr<Request> next_;
|
||||
std::weak_ptr<Request> prev_;
|
||||
unsigned num_redirect {0};
|
||||
bool follow_redirect {true};
|
||||
|
||||
HandlerCb timeoutCb_ {};
|
||||
std::chrono::seconds timeout_ {0};
|
||||
};
|
||||
|
||||
} // namespace http
|
||||
} // namespace dht
|
||||
|
||||
+141
-136
@@ -1,23 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
* Nicolas Reynaud <nicolas.reynaud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
@@ -46,25 +28,32 @@ namespace indexation {
|
||||
* the node in question is a leaf, *the label is a prefix of all the keys
|
||||
* contained in the leaf*.
|
||||
*/
|
||||
struct OPENDHT_PUBLIC Prefix {
|
||||
struct OPENDHT_PUBLIC Prefix
|
||||
{
|
||||
Prefix() {}
|
||||
Prefix(InfoHash h) : size_(h.size() * 8), content_(h.begin(), h.end()) { }
|
||||
Prefix(const Blob& d, const Blob& f={}) : size_(d.size()*8), flags_(f), content_(d) { }
|
||||
Prefix(InfoHash h)
|
||||
: size_(h.size() * 8)
|
||||
, content_(h.begin(), h.end())
|
||||
{}
|
||||
Prefix(const Blob& d, const Blob& f = {})
|
||||
: size_(d.size() * 8)
|
||||
, flags_(f)
|
||||
, content_(d)
|
||||
{}
|
||||
|
||||
Prefix(const Prefix& p, size_t first) :
|
||||
size_(std::min(first, p.content_.size()*8)),
|
||||
content_(Blob(p.content_.begin(), p.content_.begin()+size_/8))
|
||||
Prefix(const Prefix& p, size_t first)
|
||||
: size_(std::min(first, p.content_.size() * 8))
|
||||
, content_(Blob(p.content_.begin(), p.content_.begin() + size_ / 8))
|
||||
{
|
||||
|
||||
auto rem = size_ % 8;
|
||||
if ( not p.flags_.empty() ) {
|
||||
flags_ = Blob(p.flags_.begin(), p.flags_.begin()+size_/8);
|
||||
if (not p.flags_.empty()) {
|
||||
flags_ = Blob(p.flags_.begin(), p.flags_.begin() + size_ / 8);
|
||||
if (rem)
|
||||
flags_.push_back(p.flags_[size_/8] & (0xFF << (8 - rem)));
|
||||
flags_.push_back(p.flags_[size_ / 8] & (0xFF << (8 - rem)));
|
||||
}
|
||||
|
||||
if (rem)
|
||||
content_.push_back(p.content_[size_/8] & (0xFF << (8 - rem)));
|
||||
content_.push_back(p.content_[size_ / 8] & (0xFF << (8 - rem)));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,8 +68,9 @@ struct OPENDHT_PUBLIC Prefix {
|
||||
*
|
||||
* @throw out_of_range if len is larger than size of the content
|
||||
*/
|
||||
Prefix getPrefix(ssize_t len) const {
|
||||
if ((size_t)std::abs(len) >= content_.size() * 8)
|
||||
Prefix getPrefix(ssize_t len) const
|
||||
{
|
||||
if ((size_t) std::abs(len) >= content_.size() * 8)
|
||||
throw std::out_of_range("len larger than prefix size.");
|
||||
if (len < 0)
|
||||
len += size_;
|
||||
@@ -94,33 +84,31 @@ struct OPENDHT_PUBLIC Prefix {
|
||||
ee *
|
||||
* @see isActiveBit in private function
|
||||
*/
|
||||
bool isFlagActive(size_t pos) const {
|
||||
return flags_.empty() or isActiveBit(flags_, pos);
|
||||
}
|
||||
bool isFlagActive(size_t pos) const { return flags_.empty() or isActiveBit(flags_, pos); }
|
||||
|
||||
/**
|
||||
* @see isActiveBit in private function
|
||||
*/
|
||||
bool isContentBitActive(size_t pos) const {
|
||||
return isActiveBit(content_, pos);
|
||||
}
|
||||
bool isContentBitActive(size_t pos) const { return isActiveBit(content_, pos); }
|
||||
|
||||
Prefix getFullSize() { return Prefix(*this, content_.size()*8); }
|
||||
Prefix getFullSize() { return Prefix(*this, content_.size() * 8); }
|
||||
|
||||
/**
|
||||
* This methods gets the prefix of its sibling in the PHT structure.
|
||||
*
|
||||
* @return The prefix of this sibling.
|
||||
*/
|
||||
Prefix getSibling() const {
|
||||
Prefix getSibling() const
|
||||
{
|
||||
Prefix copy = *this;
|
||||
if ( size_ )
|
||||
if (size_)
|
||||
copy.swapContentBit(size_ - 1);
|
||||
|
||||
return copy;
|
||||
}
|
||||
|
||||
InfoHash hash() const {
|
||||
InfoHash hash() const
|
||||
{
|
||||
Blob copy(content_);
|
||||
copy.push_back(size_);
|
||||
return InfoHash::get(copy);
|
||||
@@ -133,69 +121,53 @@ ee *
|
||||
* @param p2 second prefix to compared
|
||||
* @return Lenght of the larger common prefix between both
|
||||
*/
|
||||
static inline unsigned commonBits(const Prefix& p1, const Prefix& p2) {
|
||||
unsigned i, j;
|
||||
uint8_t x;
|
||||
static inline unsigned commonBits(const Prefix& p1, const Prefix& p2)
|
||||
{
|
||||
/* size_ counts bits, so the comparison walks bits: reading it as a
|
||||
byte count would run past the end of the shorter content. */
|
||||
auto longest_prefix_size = std::min(p1.size_, p2.size_);
|
||||
|
||||
for (i = 0; i < longest_prefix_size; i++) {
|
||||
if (p1.content_.data()[i] != p2.content_.data()[i]
|
||||
or not p1.isFlagActive(i)
|
||||
or not p2.isFlagActive(i) ) {
|
||||
|
||||
break;
|
||||
}
|
||||
unsigned common = 0;
|
||||
while (common < longest_prefix_size) {
|
||||
if (not p1.isFlagActive(common) or not p2.isFlagActive(common)
|
||||
or p1.isContentBitActive(common) != p2.isContentBitActive(common))
|
||||
break;
|
||||
common++;
|
||||
}
|
||||
|
||||
if (i == longest_prefix_size)
|
||||
return 8*longest_prefix_size;
|
||||
|
||||
x = p1.content_.data()[i] ^ p2.content_.data()[i];
|
||||
|
||||
j = 0;
|
||||
while ((x & 0x80) == 0) {
|
||||
x <<= 1;
|
||||
j++;
|
||||
}
|
||||
|
||||
return 8 * i + j;
|
||||
return common;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see doc of swap private function
|
||||
*/
|
||||
void swapContentBit(size_t bit) {
|
||||
swapBit(content_, bit);
|
||||
}
|
||||
void swapContentBit(size_t bit) { swapBit(content_, bit); }
|
||||
|
||||
/**
|
||||
* @see doc of swap private function
|
||||
*/
|
||||
void swapFlagBit(size_t bit) {
|
||||
swapBit(flags_, bit);
|
||||
}
|
||||
void swapFlagBit(size_t bit) { swapBit(flags_, bit); }
|
||||
|
||||
/**
|
||||
* @see doc of addPadding private function
|
||||
*/
|
||||
void addPaddingContent(size_t size) {
|
||||
content_ = addPadding(content_, size);
|
||||
}
|
||||
void addPaddingContent(size_t size) { content_ = addPadding(content_, size); }
|
||||
|
||||
void updateFlags() {
|
||||
void updateFlags()
|
||||
{
|
||||
/* Fill first known bit */
|
||||
auto csize = size_ - flags_.size() * 8;
|
||||
while(csize >= 8) {
|
||||
while (csize >= 8) {
|
||||
flags_.push_back(0xFF);
|
||||
csize -= 8;
|
||||
}
|
||||
|
||||
/* if needed fill remaining bit */
|
||||
if ( csize )
|
||||
if (csize)
|
||||
flags_.push_back(0xFF << (8 - csize));
|
||||
|
||||
/* Complet vector space missing */
|
||||
for ( auto i = flags_.size(); i < content_.size(); i++ )
|
||||
for (auto i = flags_.size(); i < content_.size(); i++)
|
||||
flags_.push_back(0xFF);
|
||||
}
|
||||
|
||||
@@ -210,7 +182,6 @@ ee *
|
||||
Blob content_ {};
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* Add a padding to the input blob
|
||||
*
|
||||
@@ -219,12 +190,13 @@ private:
|
||||
*
|
||||
* @return Copy of the input Blob but with a padding
|
||||
*/
|
||||
Blob addPadding(Blob toP, size_t size) {
|
||||
Blob addPadding(Blob toP, size_t size)
|
||||
{
|
||||
Blob copy = toP;
|
||||
for ( auto i = copy.size(); i < size; i++ )
|
||||
for (auto i = copy.size(); i < size; i++)
|
||||
copy.push_back(0);
|
||||
|
||||
swapBit(copy, size_ + 1);
|
||||
swapBit(copy, size_);
|
||||
return copy;
|
||||
}
|
||||
|
||||
@@ -238,11 +210,12 @@ private:
|
||||
*
|
||||
* @throw out_of_range if bit is superior to blob size * 8
|
||||
*/
|
||||
bool isActiveBit(const Blob &b, size_t pos) const {
|
||||
if ( pos >= content_.size() * 8 )
|
||||
bool isActiveBit(const Blob& b, size_t pos) const
|
||||
{
|
||||
if (pos >= content_.size() * 8)
|
||||
throw std::out_of_range("Can't detect active bit at pos, pos larger than prefix size or empty prefix");
|
||||
|
||||
return ((b[pos / 8] >> (7 - (pos % 8)) ) & 1) == 1;
|
||||
return ((b[pos / 8] >> (7 - (pos % 8))) & 1) == 1;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -255,25 +228,30 @@ private:
|
||||
*
|
||||
* @throw out_of_range if bit is superior to blob size * 8
|
||||
*/
|
||||
void swapBit(Blob &b, size_t bit) {
|
||||
if ( bit >= b.size() * 8 )
|
||||
void swapBit(Blob& b, size_t bit)
|
||||
{
|
||||
if (bit >= b.size() * 8)
|
||||
throw std::out_of_range("bit larger than prefix size.");
|
||||
|
||||
size_t offset_bit = (8 - bit) % 8;
|
||||
b[bit / 8] ^= (1 << offset_bit);
|
||||
/* Bit 0 is the most significant one of the first byte, as
|
||||
isActiveBit reads it. */
|
||||
b[bit / 8] ^= (1 << (7 - (bit % 8)));
|
||||
}
|
||||
};
|
||||
|
||||
using Value = std::pair<InfoHash, dht::Value::Id>;
|
||||
struct OPENDHT_PUBLIC IndexEntry : public dht::Value::Serializable<IndexEntry> {
|
||||
static const ValueType TYPE;
|
||||
struct OPENDHT_PUBLIC IndexEntry : public dht::Value::Serializable<IndexEntry>
|
||||
{
|
||||
static const ValueType& TYPE;
|
||||
|
||||
virtual void unpackValue(const dht::Value& v) {
|
||||
virtual void unpackValue(const dht::Value& v)
|
||||
{
|
||||
Serializable<IndexEntry>::unpackValue(v);
|
||||
name = v.user_type;
|
||||
}
|
||||
|
||||
virtual dht::Value packValue() const {
|
||||
virtual dht::Value packValue() const
|
||||
{
|
||||
auto pack = Serializable<IndexEntry>::packValue();
|
||||
pack.user_type = name;
|
||||
return pack;
|
||||
@@ -285,14 +263,14 @@ struct OPENDHT_PUBLIC IndexEntry : public dht::Value::Serializable<IndexEntry> {
|
||||
MSGPACK_DEFINE_MAP(prefix, value)
|
||||
};
|
||||
|
||||
class OPENDHT_PUBLIC Pht {
|
||||
class OPENDHT_PUBLIC Pht
|
||||
{
|
||||
static constexpr const char* INVALID_KEY = "Key does not match the PHT key spec.";
|
||||
|
||||
/* Prefixes the user_type for all dht values put on the DHT */
|
||||
static constexpr const char* INDEX_PREFIX = "index.pht.";
|
||||
|
||||
public:
|
||||
|
||||
/* This is the maximum number of entries per node. This parameter is
|
||||
* critical and influences the traffic a lot during a lookup operation.
|
||||
*/
|
||||
@@ -306,28 +284,34 @@ public:
|
||||
using KeySpec = std::map<std::string, size_t>;
|
||||
using LookupCallback = std::function<void(std::vector<std::shared_ptr<Value>>& values, const Prefix& p)>;
|
||||
|
||||
typedef void (*LookupCallbackRaw)(std::vector<std::shared_ptr<Value>>* values, Prefix* p, void *user_data);
|
||||
static LookupCallback
|
||||
bindLookupCb(LookupCallbackRaw raw_cb, void* user_data) {
|
||||
if (not raw_cb) return {};
|
||||
typedef void (*LookupCallbackRaw)(std::vector<std::shared_ptr<Value>>* values, Prefix* p, void* user_data);
|
||||
static LookupCallback bindLookupCb(LookupCallbackRaw raw_cb, void* user_data)
|
||||
{
|
||||
if (not raw_cb)
|
||||
return {};
|
||||
return [=](std::vector<std::shared_ptr<Value>>& values, const Prefix& p) {
|
||||
raw_cb((std::vector<std::shared_ptr<Value>>*) &values, (Prefix*) &p, user_data);
|
||||
};
|
||||
}
|
||||
using LookupCallbackSimple = std::function<void(std::vector<std::shared_ptr<Value>>& values)>;
|
||||
typedef void (*LookupCallbackSimpleRaw)(std::vector<std::shared_ptr<Value>>* values, void *user_data);
|
||||
static LookupCallbackSimple
|
||||
bindLookupCbSimple(LookupCallbackSimpleRaw raw_cb, void* user_data) {
|
||||
if (not raw_cb) return {};
|
||||
typedef void (*LookupCallbackSimpleRaw)(std::vector<std::shared_ptr<Value>>* values, void* user_data);
|
||||
static LookupCallbackSimple bindLookupCbSimple(LookupCallbackSimpleRaw raw_cb, void* user_data)
|
||||
{
|
||||
if (not raw_cb)
|
||||
return {};
|
||||
return [=](std::vector<std::shared_ptr<Value>>& values) {
|
||||
raw_cb((std::vector<std::shared_ptr<Value>>*) &values, user_data);
|
||||
};
|
||||
}
|
||||
|
||||
Pht(std::string name, KeySpec k_spec, std::shared_ptr<DhtRunner> dht)
|
||||
: name_(INDEX_PREFIX + name), canary_(name_ + ".canary"), keySpec_(k_spec), dht_(dht) {}
|
||||
: name_(INDEX_PREFIX + name)
|
||||
, canary_(name_ + ".canary")
|
||||
, keySpec_(k_spec)
|
||||
, dht_(dht)
|
||||
{}
|
||||
|
||||
virtual ~Pht () { }
|
||||
virtual ~Pht() {}
|
||||
|
||||
/**
|
||||
* Lookup a key for a value.
|
||||
@@ -335,7 +319,11 @@ public:
|
||||
void lookup(Key k, LookupCallback cb = {}, DoneCallbackSimple done_cb = {}, bool exact_match = true);
|
||||
void lookup(Key k, LookupCallbackSimple cb = {}, DoneCallbackSimple done_cb = {}, bool exact_match = true)
|
||||
{
|
||||
lookup(k, [cb=std::move(cb)](std::vector<std::shared_ptr<Value>>& values, Prefix) { cb(values); }, done_cb, exact_match);
|
||||
lookup(
|
||||
k,
|
||||
[cb = std::move(cb)](std::vector<std::shared_ptr<Value>>& values, Prefix) { cb(values); },
|
||||
done_cb,
|
||||
exact_match);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -345,7 +333,8 @@ public:
|
||||
* @param v : Value to insert
|
||||
* @param done_cb : Callbakc which going to be call when all the insert is done
|
||||
*/
|
||||
void insert(Key k, Value v, DoneCallbackSimple done_cb = {}) {
|
||||
void insert(Key k, Value v, DoneCallbackSimple done_cb = {})
|
||||
{
|
||||
Prefix p = linearize(k);
|
||||
|
||||
auto lo = std::make_shared<int>(0);
|
||||
@@ -360,7 +349,6 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* Insert function which really insert onto the pht
|
||||
*
|
||||
@@ -373,10 +361,16 @@ private:
|
||||
* @param done_cb : Callback to call when the insert is done
|
||||
*/
|
||||
|
||||
void insert(const Prefix& kp, IndexEntry entry, std::shared_ptr<int> lo, std::shared_ptr<int> hi, time_point time_p,
|
||||
bool check_split, DoneCallbackSimple done_cb = {});
|
||||
void insert(const Prefix& kp,
|
||||
IndexEntry entry,
|
||||
std::shared_ptr<int> lo,
|
||||
std::shared_ptr<int> hi,
|
||||
time_point time_p,
|
||||
bool check_split,
|
||||
DoneCallbackSimple done_cb = {});
|
||||
|
||||
class Cache {
|
||||
class Cache
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Insert all needed node into the tree according to a prefix
|
||||
@@ -398,18 +392,19 @@ private:
|
||||
static constexpr const size_t MAX_ELEMENT {1024};
|
||||
static constexpr const std::chrono::minutes NODE_EXPIRE_TIME {5};
|
||||
|
||||
struct Node {
|
||||
struct Node
|
||||
{
|
||||
time_point last_reply; /* Made the assocation between leaves and leaves multimap */
|
||||
std::shared_ptr<Node> parent; /* Share_ptr to the parent, it allow the self destruction of tree */
|
||||
std::weak_ptr<Node> left_child; /* Left child, for bit equal to 1 */
|
||||
std::weak_ptr<Node> right_child; /* Right child, for bit equal to 0 */
|
||||
};
|
||||
|
||||
std::weak_ptr<Node> root_; /* Root of the tree */
|
||||
std::weak_ptr<Node> root_; /* Root of the tree */
|
||||
|
||||
/**
|
||||
* This mutlimap contains all prefix insert in the tree in time order
|
||||
* We could then delete the last one if there is too much node
|
||||
* We could then delete the last one if there are too many nodes
|
||||
* The tree will self destroy is branch ( thanks to share_ptr )
|
||||
*/
|
||||
std::multimap<time_point, std::shared_ptr<Node>> leaves_;
|
||||
@@ -430,14 +425,19 @@ private:
|
||||
* @param cb : Callback to use at the end of the lookupStep (call on the value of vals)
|
||||
* @param done_cb : Callback at the end of the lookupStep
|
||||
* @param max_common_prefix_len: used in the inexacte lookup match case, indicate the longest common prefix found
|
||||
* @param start : If start is set then lo and hi will be ignore for the first step, if the step fail lo and hi will be used
|
||||
* @param start : If start is set then lo and hi will be ignore for the first step, if the step fail lo and hi
|
||||
* will be used
|
||||
* @param all_values : If all value is true then all value met during the lookupstep will be in the vector vals
|
||||
*/
|
||||
void lookupStep(Prefix k, std::shared_ptr<int> lo, std::shared_ptr<int> hi,
|
||||
std::shared_ptr<std::vector<std::shared_ptr<IndexEntry>>> vals,
|
||||
LookupCallbackWrapper cb, DoneCallbackSimple done_cb,
|
||||
std::shared_ptr<unsigned> max_common_prefix_len,
|
||||
int start = -1, bool all_values = false);
|
||||
void lookupStep(Prefix k,
|
||||
std::shared_ptr<int> lo,
|
||||
std::shared_ptr<int> hi,
|
||||
std::shared_ptr<std::vector<std::shared_ptr<IndexEntry>>> vals,
|
||||
LookupCallbackWrapper cb,
|
||||
DoneCallbackSimple done_cb,
|
||||
std::shared_ptr<unsigned> max_common_prefix_len,
|
||||
int start = -1,
|
||||
bool all_values = false);
|
||||
|
||||
/**
|
||||
* Apply the zcurve algorithm on the list of input prefix
|
||||
@@ -466,7 +466,7 @@ private:
|
||||
* @param entry The entry to put at the prefix p
|
||||
* @param end_cb Callback to use at the end of counting
|
||||
*/
|
||||
void getRealPrefix(const std::shared_ptr<Prefix>& p, IndexEntry entry, RealInsertCallback end_cb );
|
||||
void getRealPrefix(const std::shared_ptr<Prefix>& p, IndexEntry entry, RealInsertCallback end_cb);
|
||||
|
||||
/**
|
||||
* Looking where to put the data cause if there is free space on the node
|
||||
@@ -485,10 +485,11 @@ private:
|
||||
* @param vals : The vector of values to compare with comapred
|
||||
* @return position compared diverge from all others
|
||||
*/
|
||||
static size_t findSplitLocation(const Prefix& compared, const std::vector<std::shared_ptr<IndexEntry>>& vals) {
|
||||
for ( size_t i = 0; i < compared.content_.size() * 8 - 1; i++ )
|
||||
for ( auto const& v : vals)
|
||||
if ( Prefix(v->prefix).isContentBitActive(i) != compared.isContentBitActive(i) )
|
||||
static size_t findSplitLocation(const Prefix& compared, const std::vector<std::shared_ptr<IndexEntry>>& vals)
|
||||
{
|
||||
for (size_t i = 0; i < compared.content_.size() * 8 - 1; i++)
|
||||
for (auto const& v : vals)
|
||||
if (Prefix(v->prefix).isContentBitActive(i) != compared.isContentBitActive(i))
|
||||
return i + 1;
|
||||
return compared.content_.size() * 8 - 1;
|
||||
}
|
||||
@@ -501,18 +502,23 @@ private:
|
||||
* @param entry : Entry to put on the pht
|
||||
* @param end_cb : Callback to apply to the insert prefi (here does the insert)
|
||||
*/
|
||||
void split(const Prefix& insert, const std::vector<std::shared_ptr<IndexEntry>>& vals, IndexEntry entry, RealInsertCallback end_cb);
|
||||
void split(const Prefix& insert,
|
||||
const std::vector<std::shared_ptr<IndexEntry>>& vals,
|
||||
IndexEntry entry,
|
||||
RealInsertCallback end_cb);
|
||||
|
||||
/**
|
||||
* Tells if the key is valid according to the key spec.
|
||||
*/
|
||||
bool validKey(const Key& k) const {
|
||||
return k.size() == keySpec_.size() and
|
||||
std::equal(k.begin(), k.end(), keySpec_.begin(),
|
||||
[&](const Key::value_type& key, const KeySpec::value_type& key_spec) {
|
||||
return key.first == key_spec.first and key.second.size() <= key_spec.second;
|
||||
}
|
||||
);
|
||||
bool validKey(const Key& k) const
|
||||
{
|
||||
return k.size() == keySpec_.size()
|
||||
and std::equal(k.begin(),
|
||||
k.end(),
|
||||
keySpec_.begin(),
|
||||
[&](const Key::value_type& key, const KeySpec::value_type& key_spec) {
|
||||
return key.first == key_spec.first and key.second.size() <= key_spec.second;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -528,6 +534,5 @@ private:
|
||||
std::shared_ptr<DhtRunner> dht_;
|
||||
};
|
||||
|
||||
} /* indexation */
|
||||
} /* dht */
|
||||
|
||||
} // namespace indexation
|
||||
} // namespace dht
|
||||
+199
-165
@@ -1,27 +1,12 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
#include "rng.h"
|
||||
|
||||
#include <msgpack.hpp>
|
||||
#include <fmt/core.h>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <netinet/in.h>
|
||||
@@ -44,6 +29,7 @@ typedef uint16_t in_port_t;
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <sstream>
|
||||
|
||||
#include <cstring>
|
||||
#include <cstddef>
|
||||
|
||||
@@ -52,84 +38,83 @@ namespace dht {
|
||||
using byte = uint8_t;
|
||||
|
||||
namespace crypto {
|
||||
OPENDHT_PUBLIC void hash(const uint8_t* data, size_t data_length, uint8_t* hash, size_t hash_length);
|
||||
OPENDHT_PUBLIC void hash(const uint8_t* data, size_t data_length, uint8_t* hash, size_t hash_length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents an Hash,
|
||||
* a byte array of N bytes.
|
||||
* Represents an Hash, a byte array of N bytes.
|
||||
* Hashes identify nodes and values in the Dht.
|
||||
*/
|
||||
template <size_t N>
|
||||
class OPENDHT_PUBLIC Hash {
|
||||
template<size_t N>
|
||||
class Hash
|
||||
{
|
||||
public:
|
||||
using T = std::array<uint8_t, N>;
|
||||
typedef typename T::iterator iterator;
|
||||
typedef typename T::const_iterator const_iterator;
|
||||
|
||||
Hash() noexcept {
|
||||
data_.fill(0);
|
||||
}
|
||||
Hash(const uint8_t* h, size_t data_len) {
|
||||
if (data_len < N)
|
||||
data_.fill(0);
|
||||
else
|
||||
std::copy_n(h, N, data_.begin());
|
||||
}
|
||||
constexpr Hash() noexcept
|
||||
: data_ {}
|
||||
{}
|
||||
constexpr Hash(const uint8_t* h, size_t data_len)
|
||||
: data_(fromBytes(h, data_len))
|
||||
{}
|
||||
/**
|
||||
* Constructor from an hexadecimal string (without "0x").
|
||||
* hex must be at least 2.HASH_LEN characters long.
|
||||
* If too long, only the first 2.HASH_LEN characters are read.
|
||||
* hex must be at least 2.N characters long.
|
||||
* If too long, only the first 2.N characters are read.
|
||||
*/
|
||||
explicit Hash(std::string_view hex) {
|
||||
if (hex.size() < 2*N)
|
||||
data_.fill(0);
|
||||
else
|
||||
fromString(hex.data());
|
||||
}
|
||||
explicit constexpr Hash(std::string_view hex)
|
||||
: data_(fromString(hex))
|
||||
{}
|
||||
|
||||
Hash(const msgpack::object& o) {
|
||||
msgpack_unpack(o);
|
||||
}
|
||||
Hash(const msgpack::object& o) { msgpack_unpack(o); }
|
||||
|
||||
static constexpr size_t size() noexcept { return N; }
|
||||
const uint8_t* data() const { return data_.data(); }
|
||||
constexpr const uint8_t* data() const { return data_.data(); }
|
||||
uint8_t* data() { return data_.data(); }
|
||||
iterator begin() { return data_.begin(); }
|
||||
const_iterator cbegin() const { return data_.cbegin(); }
|
||||
iterator end() { return data_.end(); }
|
||||
const_iterator cend() const { return data_.cend(); }
|
||||
|
||||
static constexpr inline Hash zero() noexcept { return Hash{}; }
|
||||
static constexpr inline Hash zero() noexcept { return Hash {}; }
|
||||
|
||||
bool operator==(const Hash& h) const {
|
||||
auto a = reinterpret_cast<const uint32_t*>(data_.data());
|
||||
auto b = reinterpret_cast<const uint32_t*>(h.data_.data());
|
||||
constexpr unsigned n = N / sizeof(uint32_t);
|
||||
for (unsigned i=0; i < n; i++)
|
||||
if (a[i] != b[i])
|
||||
constexpr bool operator==(const Hash& h) const
|
||||
{
|
||||
#if __cplusplus >= 202002L
|
||||
return data_ == h.data_;
|
||||
#else
|
||||
for (size_t i = 0; i < N; ++i) {
|
||||
if (data_[i] != h.data_[i])
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
bool operator!=(const Hash& h) const { return !(*this == h); }
|
||||
constexpr bool operator!=(const Hash& h) const { return !(*this == h); }
|
||||
|
||||
bool operator<(const Hash& o) const {
|
||||
for(unsigned i = 0; i < N; i++) {
|
||||
if(data_[i] != o.data_[i])
|
||||
constexpr bool operator<(const Hash& o) const
|
||||
{
|
||||
for (unsigned i = 0; i < N; i++) {
|
||||
if (data_[i] != o.data_[i])
|
||||
return data_[i] < o.data_[i];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Hash operator^(const Hash& o) const {
|
||||
constexpr Hash operator^(const Hash& o) const
|
||||
{
|
||||
Hash result;
|
||||
for(auto i = 0u; i < N; i++) {
|
||||
for (auto i = 0u; i < N; i++) {
|
||||
result[i] = data_[i] ^ o.data_[i];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
explicit operator bool() const {
|
||||
explicit constexpr operator bool() const
|
||||
{
|
||||
#if __cplusplus >= 202002L
|
||||
auto a = reinterpret_cast<const uint32_t*>(data_.data());
|
||||
auto b = reinterpret_cast<const uint32_t*>(data_.data() + N);
|
||||
for (; a != b; a++) {
|
||||
@@ -137,50 +122,58 @@ public:
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
#else
|
||||
for (size_t i = 0; i < N; ++i) {
|
||||
if (data_[i] != 0)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
uint8_t& operator[](size_t index) { return data_[index]; }
|
||||
const uint8_t& operator[](size_t index) const { return data_[index]; }
|
||||
constexpr const uint8_t& operator[](size_t index) const { return data_[index]; }
|
||||
|
||||
/**
|
||||
* Find the lowest 1 bit in an id.
|
||||
* Result will allways be lower than 8*N
|
||||
*/
|
||||
inline int lowbit() const {
|
||||
int i, j;
|
||||
for(i = N-1; i >= 0; i--)
|
||||
if(data_[i] != 0)
|
||||
constexpr int lowbit() const
|
||||
{
|
||||
int i = N - 1;
|
||||
for (; i >= 0; i--)
|
||||
if (data_[i] != 0)
|
||||
break;
|
||||
if(i < 0)
|
||||
if (i < 0)
|
||||
return -1;
|
||||
for(j = 7; j >= 0; j--)
|
||||
if((data_[i] & (0x80 >> j)) != 0)
|
||||
int j = 7;
|
||||
for (; j >= 0; j--)
|
||||
if ((data_[i] & (0x80 >> j)) != 0)
|
||||
break;
|
||||
return 8 * i + j;
|
||||
}
|
||||
|
||||
static inline int cmp(const Hash& id1, const Hash& id2) {
|
||||
static inline int cmp(const Hash& id1, const Hash& id2)
|
||||
{
|
||||
return std::memcmp(id1.data_.data(), id2.data_.data(), N);
|
||||
}
|
||||
|
||||
/** Find how many bits two ids have in common. */
|
||||
static inline unsigned
|
||||
commonBits(const Hash& id1, const Hash& id2)
|
||||
static constexpr inline unsigned commonBits(const Hash& id1, const Hash& id2)
|
||||
{
|
||||
unsigned i, j;
|
||||
uint8_t x;
|
||||
for(i = 0; i < N; i++) {
|
||||
if(id1.data_[i] != id2.data_[i])
|
||||
unsigned i = 0;
|
||||
for (; i < N; i++) {
|
||||
if (id1.data_[i] != id2.data_[i])
|
||||
break;
|
||||
}
|
||||
|
||||
if(i == N)
|
||||
return 8*N;
|
||||
if (i == N)
|
||||
return 8 * N;
|
||||
|
||||
x = id1.data_[i] ^ id2.data_[i];
|
||||
uint8_t x = id1.data_[i] ^ id2.data_[i];
|
||||
|
||||
j = 0;
|
||||
while((x & 0x80) == 0) {
|
||||
unsigned j = 0;
|
||||
while ((x & 0x80) == 0) {
|
||||
x <<= 1;
|
||||
j++;
|
||||
}
|
||||
@@ -189,11 +182,10 @@ public:
|
||||
}
|
||||
|
||||
/** Determine whether id1 or id2 is closer to this */
|
||||
int
|
||||
xorCmp(const Hash& id1, const Hash& id2) const
|
||||
constexpr int xorCmp(const Hash& id1, const Hash& id2) const
|
||||
{
|
||||
for (unsigned i = 0; i < N; i++) {
|
||||
if(id1.data_[i] == id2.data_[i])
|
||||
if (id1.data_[i] == id2.data_[i])
|
||||
continue;
|
||||
uint8_t xor1 = id1.data_[i] ^ data_[i];
|
||||
uint8_t xor2 = id2.data_[i] ^ data_[i];
|
||||
@@ -202,36 +194,37 @@ public:
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool
|
||||
getBit(unsigned nbit) const
|
||||
constexpr bool getBit(unsigned nbit) const
|
||||
{
|
||||
auto& num = *(data_.cbegin()+(nbit/8));
|
||||
auto& num = *(data_.cbegin() + (nbit / 8));
|
||||
unsigned bit = 7 - (nbit % 8);
|
||||
return (num >> bit) & 1;
|
||||
}
|
||||
|
||||
void
|
||||
setBit(unsigned nbit, bool b)
|
||||
void setBit(unsigned nbit, bool b)
|
||||
{
|
||||
auto& num = data_[nbit/8];
|
||||
auto& num = data_[nbit / 8];
|
||||
unsigned bit = 7 - (nbit % 8);
|
||||
num ^= (-b ^ num) & (1 << bit);
|
||||
}
|
||||
|
||||
double toFloat() const {
|
||||
double toFloat() const
|
||||
{
|
||||
using D = size_t;
|
||||
double v = 0.;
|
||||
for (size_t i = 0; i < std::min<size_t>(N, sizeof(D)-1); i++)
|
||||
v += *(data_.cbegin()+i) / (double)((D)1 << 8*(i+1));
|
||||
for (size_t i = 0; i < std::min<size_t>(N, sizeof(D) - 1); i++)
|
||||
v += *(data_.cbegin() + i) / (double) ((D) 1 << 8 * (i + 1));
|
||||
return v;
|
||||
}
|
||||
|
||||
static inline Hash get(std::string_view data) {
|
||||
return get((const uint8_t*)data.data(), data.size());
|
||||
}
|
||||
static inline Hash get(std::string_view data) { return get((const uint8_t*) data.data(), data.size()); }
|
||||
|
||||
static inline Hash get(const std::vector<uint8_t>& data) {
|
||||
return get(data.data(), data.size());
|
||||
static inline Hash get(const std::vector<uint8_t>& data) { return get(data.data(), data.size()); }
|
||||
|
||||
template<size_t H>
|
||||
static Hash get(const Hash<H>& o)
|
||||
{
|
||||
return get(o.data(), o.size());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -246,34 +239,39 @@ public:
|
||||
|
||||
static Hash getRandom();
|
||||
|
||||
template <typename Rd>
|
||||
template<typename Rd>
|
||||
static Hash getRandom(Rd&);
|
||||
|
||||
template <size_t M>
|
||||
OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const Hash<M>& h);
|
||||
template<size_t M>
|
||||
friend std::ostream& operator<<(std::ostream& s, const Hash<M>& h);
|
||||
|
||||
template <size_t M>
|
||||
OPENDHT_PUBLIC friend std::istream& operator>> (std::istream& s, Hash<M>& h);
|
||||
template<size_t M>
|
||||
friend std::istream& operator>>(std::istream& s, Hash<M>& h);
|
||||
|
||||
/** Returns view to thread-allocated memory, only valid until the next call to this function. */
|
||||
std::string_view to_view() const { return std::string_view(to_c_str(), N * 2); }
|
||||
const char* to_c_str() const;
|
||||
|
||||
std::string toString() const;
|
||||
|
||||
template <typename Packer>
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& pk) const
|
||||
{
|
||||
pk.pack_bin(N);
|
||||
pk.pack_bin_body((char*)data_.data(), N);
|
||||
pk.pack_bin_body((char*) data_.data(), N);
|
||||
}
|
||||
|
||||
void msgpack_unpack(msgpack::object o) {
|
||||
void msgpack_unpack(msgpack::object o)
|
||||
{
|
||||
if (o.type != msgpack::type::BIN or o.via.bin.size != N)
|
||||
throw msgpack::type_error();
|
||||
std::copy_n(o.via.bin.ptr, N, data_.data());
|
||||
}
|
||||
|
||||
private:
|
||||
T data_;
|
||||
void fromString(const char*);
|
||||
alignas(alignof(uint32_t)) T data_;
|
||||
static constexpr T fromBytes(const uint8_t*, size_t);
|
||||
static constexpr T fromString(std::string_view);
|
||||
};
|
||||
|
||||
#define HASH_LEN 20u
|
||||
@@ -281,46 +279,74 @@ using InfoHash = Hash<HASH_LEN>;
|
||||
using h256 = Hash<32>;
|
||||
using PkId = h256;
|
||||
|
||||
template <size_t N>
|
||||
std::ostream& operator<< (std::ostream& s, const Hash<N>& h)
|
||||
template<size_t N>
|
||||
std::ostream&
|
||||
operator<<(std::ostream& s, const Hash<N>& h)
|
||||
{
|
||||
s.write(h.to_c_str(), N*2);
|
||||
s.write(h.to_c_str(), N * 2);
|
||||
return s;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
std::istream& operator>> (std::istream& s, Hash<N>& h)
|
||||
template<size_t N>
|
||||
std::istream&
|
||||
operator>>(std::istream& s, Hash<N>& h)
|
||||
{
|
||||
std::array<char, h.size()*2> dat;
|
||||
std::array<char, h.size() * 2> dat;
|
||||
s.exceptions(std::istream::eofbit | std::istream::failbit);
|
||||
s.read(&(*dat.begin()), dat.size());
|
||||
fromString(dat.data());
|
||||
h = Hash<N>(std::string_view(dat.data(), dat.size()));
|
||||
return s;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
void
|
||||
Hash<N>::fromString(const char* in) {
|
||||
auto hex2bin = [](char c) -> uint8_t {
|
||||
if (c >= 'a' and c <= 'f') return 10 + c - 'a';
|
||||
else if (c >= 'A' and c <= 'F') return 10 + c - 'A';
|
||||
else if (c >= '0' and c <= '9') return c - '0';
|
||||
else throw std::domain_error("not an hex character");
|
||||
};
|
||||
try {
|
||||
for (size_t i=0; i<N; i++)
|
||||
data_[i] = (hex2bin(in[2*i]) << 4) | hex2bin(in[2*i+1]);
|
||||
} catch (const std::domain_error&) {
|
||||
data_.fill(0);
|
||||
}
|
||||
template<size_t N>
|
||||
constexpr typename Hash<N>::T
|
||||
Hash<N>::fromBytes(const uint8_t* in, size_t size)
|
||||
{
|
||||
T data {};
|
||||
if (size < N)
|
||||
return data;
|
||||
for (size_t i = 0; i < N; ++i)
|
||||
data[i] = in[i];
|
||||
return data;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
template<size_t N>
|
||||
constexpr typename Hash<N>::T
|
||||
Hash<N>::fromString(std::string_view in)
|
||||
{
|
||||
T data {};
|
||||
if (in.size() < 2 * N)
|
||||
return data;
|
||||
|
||||
constexpr auto hex2bin = [](char c, bool& valid) -> uint8_t {
|
||||
if (c >= 'a' and c <= 'f')
|
||||
return 10 + c - 'a';
|
||||
else if (c >= 'A' and c <= 'F')
|
||||
return 10 + c - 'A';
|
||||
else if (c >= '0' and c <= '9')
|
||||
return c - '0';
|
||||
else {
|
||||
valid = false;
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
bool valid = true;
|
||||
for (size_t i = 0; i < N && valid; i++) {
|
||||
uint8_t high = hex2bin(in[2 * i], valid);
|
||||
uint8_t low = hex2bin(in[2 * i + 1], valid);
|
||||
data[i] = (high << 4) | low;
|
||||
}
|
||||
if (!valid)
|
||||
return {};
|
||||
return data;
|
||||
}
|
||||
|
||||
template<size_t N>
|
||||
Hash<N>
|
||||
Hash<N>::getRandom()
|
||||
{
|
||||
Hash h;
|
||||
crypto::random_device rdev;
|
||||
std::random_device rdev;
|
||||
std::uniform_int_distribution<uint32_t> rand_int;
|
||||
auto a = reinterpret_cast<uint32_t*>(h.data());
|
||||
auto b = reinterpret_cast<uint32_t*>(h.data() + h.size());
|
||||
@@ -328,8 +354,8 @@ Hash<N>::getRandom()
|
||||
return h;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
template <typename Rd>
|
||||
template<size_t N>
|
||||
template<typename Rd>
|
||||
Hash<N>
|
||||
Hash<N>::getRandom(Rd& rdev)
|
||||
{
|
||||
@@ -341,75 +367,83 @@ Hash<N>::getRandom(Rd& rdev)
|
||||
return h;
|
||||
}
|
||||
|
||||
struct alignas(std::max_align_t) HexMap : public std::array<std::array<char, 2>, 256> {
|
||||
HexMap() {
|
||||
for (size_t i=0; i<size(); i++) {
|
||||
struct alignas(std::max_align_t) HexMap : public std::array<std::array<char, 2>, 256>
|
||||
{
|
||||
constexpr HexMap()
|
||||
: std::array<std::array<char, 2>, 256>()
|
||||
{
|
||||
for (size_t i = 0; i < size(); i++) {
|
||||
auto& e = (*this)[i];
|
||||
e[0] = hex_digits[(i >> 4) & 0x0F];
|
||||
e[1] = hex_digits[i & 0x0F];
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr const char* hex_digits = "0123456789abcdef";
|
||||
};
|
||||
|
||||
OPENDHT_PUBLIC extern const HexMap hex_map;
|
||||
inline constexpr HexMap hex_map {};
|
||||
|
||||
inline std::string
|
||||
toHex(const uint8_t* data, size_t size) {
|
||||
toHex(const uint8_t* data, size_t size)
|
||||
{
|
||||
std::string ret(size * 2, '\0');
|
||||
for (size_t i=0; i<size; i++) {
|
||||
auto b = ret.data()+i*2;
|
||||
for (size_t i = 0; i < size; i++) {
|
||||
auto b = ret.data() + i * 2;
|
||||
const auto& m = hex_map[data[i]];
|
||||
*((uint16_t*)b) = *((uint16_t*)&m);
|
||||
*((uint16_t*) b) = *((uint16_t*) &m);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
inline std::string
|
||||
toHex(const std::vector<uint8_t>& data) {
|
||||
toHex(const std::vector<uint8_t>& data)
|
||||
{
|
||||
return toHex(data.data(), data.size());
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
template<size_t N>
|
||||
constexpr std::array<char, N * 2>
|
||||
toHexArray(const Hash<N>& h)
|
||||
{
|
||||
std::array<char, N * 2> ret {};
|
||||
for (size_t i = 0; i < N; i++) {
|
||||
const auto& m = hex_map[h[i]];
|
||||
ret[i * 2] = m[0];
|
||||
ret[i * 2 + 1] = m[1];
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
template<size_t N>
|
||||
const char*
|
||||
Hash<N>::to_c_str() const
|
||||
{
|
||||
alignas(std::max_align_t) thread_local std::array<char, N*2+1> buf;
|
||||
for (size_t i=0; i<N; i++) {
|
||||
auto b = buf.data()+i*2;
|
||||
alignas(std::max_align_t) thread_local std::array<char, N * 2 + 1> buf;
|
||||
for (size_t i = 0; i < N; i++) {
|
||||
auto b = buf.data() + i * 2;
|
||||
const auto& m = hex_map[data_[i]];
|
||||
*((uint16_t*)b) = *((uint16_t*)&m);
|
||||
*((uint16_t*) b) = *((uint16_t*) &m);
|
||||
}
|
||||
buf[N * 2] = '\0';
|
||||
return buf.data();
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
template<size_t N>
|
||||
std::string
|
||||
Hash<N>::toString() const
|
||||
{
|
||||
return std::string(to_c_str(), N*2);
|
||||
return std::string(to_c_str(), N * 2);
|
||||
}
|
||||
|
||||
struct OPENDHT_PUBLIC NodeExport {
|
||||
InfoHash id;
|
||||
sockaddr_storage ss;
|
||||
socklen_t sslen;
|
||||
} // namespace dht
|
||||
|
||||
template <typename Packer>
|
||||
void msgpack_pack(Packer& pk) const
|
||||
template<size_t N>
|
||||
struct fmt::formatter<dht::Hash<N>> : formatter<string_view>
|
||||
{
|
||||
constexpr auto format(const dht::Hash<N>& c, format_context& ctx) const
|
||||
{
|
||||
pk.pack_map(2);
|
||||
pk.pack(std::string("id"));
|
||||
pk.pack(id);
|
||||
pk.pack(std::string("addr"));
|
||||
pk.pack_bin(sslen);
|
||||
pk.pack_bin_body((char*)&ss, sslen);
|
||||
return formatter<string_view>::format(c.to_view(), ctx);
|
||||
}
|
||||
|
||||
void msgpack_unpack(msgpack::object o);
|
||||
|
||||
OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const NodeExport& h);
|
||||
};
|
||||
|
||||
}
|
||||
+10
-67
@@ -1,26 +1,9 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
*
|
||||
* Author: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
#include "log_enable.h"
|
||||
#include "logger.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
@@ -34,62 +17,22 @@ class DhtRunner;
|
||||
*/
|
||||
namespace log {
|
||||
|
||||
/**
|
||||
* Terminal colors for logging
|
||||
*/
|
||||
namespace Color {
|
||||
enum Code {
|
||||
FG_RED = 31,
|
||||
FG_GREEN = 32,
|
||||
FG_YELLOW = 33,
|
||||
FG_BLUE = 34,
|
||||
FG_DEFAULT = 39,
|
||||
BG_RED = 41,
|
||||
BG_GREEN = 42,
|
||||
BG_BLUE = 44,
|
||||
BG_DEFAULT = 49
|
||||
};
|
||||
class Modifier {
|
||||
const Code code;
|
||||
public:
|
||||
constexpr Modifier(Code pCode) : code(pCode) {}
|
||||
friend std::ostream&
|
||||
operator<<(std::ostream& os, const Modifier& mod) {
|
||||
return os << "\033[" << mod.code << 'm';
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
constexpr const Color::Modifier def(Color::FG_DEFAULT);
|
||||
constexpr const Color::Modifier red(Color::FG_RED);
|
||||
constexpr const Color::Modifier yellow(Color::FG_YELLOW);
|
||||
|
||||
/**
|
||||
* Print va_list to std::ostream (used for logging).
|
||||
*/
|
||||
OPENDHT_PUBLIC void
|
||||
printLog(std::ostream &s, char const *m, va_list args);
|
||||
|
||||
OPENDHT_PUBLIC
|
||||
std::shared_ptr<Logger> getStdLogger();
|
||||
|
||||
OPENDHT_PUBLIC
|
||||
std::shared_ptr<Logger> getFileLogger(const std::string &path);
|
||||
std::shared_ptr<Logger> getFileLogger(const std::string& path);
|
||||
|
||||
OPENDHT_PUBLIC
|
||||
std::shared_ptr<Logger> getSyslogLogger(const char* name);
|
||||
|
||||
OPENDHT_PUBLIC void
|
||||
enableLogging(dht::DhtRunner &dht);
|
||||
OPENDHT_PUBLIC void enableLogging(dht::DhtRunner& dht);
|
||||
|
||||
OPENDHT_PUBLIC void
|
||||
enableFileLogging(dht::DhtRunner &dht, const std::string &path);
|
||||
OPENDHT_PUBLIC void enableFileLogging(dht::DhtRunner& dht, const std::string& path);
|
||||
|
||||
OPENDHT_PUBLIC void
|
||||
disableLogging(dht::DhtRunner &dht);
|
||||
OPENDHT_PUBLIC void disableLogging(dht::DhtRunner& dht);
|
||||
|
||||
OPENDHT_PUBLIC void
|
||||
enableSyslog(dht::DhtRunner &dht, const char* name);
|
||||
OPENDHT_PUBLIC void enableSyslog(dht::DhtRunner& dht, const char* name);
|
||||
|
||||
} /* log */
|
||||
} /* dht */
|
||||
} // namespace log
|
||||
} // namespace dht
|
||||
@@ -1,191 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include "config.h"
|
||||
#endif
|
||||
|
||||
#include "infohash.h"
|
||||
|
||||
#include <cstdarg>
|
||||
|
||||
#ifndef OPENDHT_LOG
|
||||
#define OPENDHT_LOG true
|
||||
#endif
|
||||
|
||||
namespace dht {
|
||||
|
||||
// Logging related utility functions
|
||||
|
||||
/**
|
||||
* Wrapper for logging methods
|
||||
*/
|
||||
struct LogMethod {
|
||||
LogMethod() = default;
|
||||
|
||||
LogMethod(LogMethod&& l) : func(std::move(l.func)) {}
|
||||
LogMethod(const LogMethod& l) : func(l.func) {}
|
||||
|
||||
LogMethod& operator=(dht::LogMethod&& l) {
|
||||
func = std::forward<LogMethod>(l.func);
|
||||
return *this;
|
||||
}
|
||||
LogMethod& operator=(const dht::LogMethod& l) {
|
||||
func = l.func;
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
explicit LogMethod(T&& t) : func(std::forward<T>(t)) {}
|
||||
|
||||
template<typename T>
|
||||
LogMethod(const T& t) : func(t) {}
|
||||
|
||||
void operator()(char const* format, ...) const {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
func(format, args);
|
||||
va_end(args);
|
||||
}
|
||||
inline void log(char const* format, va_list args) const {
|
||||
func(format, args);
|
||||
}
|
||||
explicit operator bool() const {
|
||||
return (bool)func;
|
||||
}
|
||||
|
||||
void logPrintable(const uint8_t *buf, size_t buflen) const {
|
||||
std::string buf_clean(buflen, '\0');
|
||||
for (size_t i=0; i<buflen; i++)
|
||||
buf_clean[i] = isprint(buf[i]) ? buf[i] : '.';
|
||||
(*this)("%s", buf_clean.c_str());
|
||||
}
|
||||
private:
|
||||
std::function<void(char const*, va_list)> func;
|
||||
};
|
||||
|
||||
struct Logger {
|
||||
LogMethod ERR = {};
|
||||
LogMethod WARN = {};
|
||||
LogMethod DBG = {};
|
||||
|
||||
Logger() = default;
|
||||
Logger(LogMethod&& err, LogMethod&& warn, LogMethod&& dbg)
|
||||
: ERR(std::move(err)), WARN(std::move(warn)), DBG(std::move(dbg)) {}
|
||||
void setFilter(const InfoHash& f) {
|
||||
filter_ = f;
|
||||
filterEnable_ = static_cast<bool>(filter_);
|
||||
}
|
||||
inline void log0(const LogMethod& logger, char const* format, va_list args) const {
|
||||
#if OPENDHT_LOG
|
||||
if (logger and not filterEnable_)
|
||||
logger.log(format, args);
|
||||
#endif
|
||||
}
|
||||
inline void log1(const LogMethod& logger, const InfoHash& f, char const* format, va_list args) const {
|
||||
#if OPENDHT_LOG
|
||||
if (logger and (not filterEnable_ or f == filter_))
|
||||
logger.log(format, args);
|
||||
#endif
|
||||
}
|
||||
inline void log2(const LogMethod& logger, const InfoHash& f1, const InfoHash& f2, char const* format, va_list args) const {
|
||||
#if OPENDHT_LOG
|
||||
if (logger and (not filterEnable_ or f1 == filter_ or f2 == filter_))
|
||||
logger.log(format, args);
|
||||
#endif
|
||||
}
|
||||
inline void d(char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log0(DBG, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void d(const InfoHash& f, char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log1(DBG, f, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void d(const InfoHash& f1, const InfoHash& f2, char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log2(DBG, f1, f2, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void w(char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log0(WARN, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void w(const InfoHash& f, char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log1(WARN, f, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void w(const InfoHash& f1, const InfoHash& f2, char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log2(WARN, f1, f2, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void e(char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log0(ERR, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void e(const InfoHash& f, char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log1(ERR, f, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
inline void e(const InfoHash& f1, const InfoHash& f2, char const* format, ...) const {
|
||||
#if OPENDHT_LOG
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log2(ERR, f1, f2, format, args);
|
||||
va_end(args);
|
||||
#endif
|
||||
}
|
||||
private:
|
||||
bool filterEnable_ {false};
|
||||
InfoHash filter_ {};
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "infohash.h"
|
||||
|
||||
#include <fmt/format.h>
|
||||
#include <fmt/printf.h>
|
||||
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <cstdarg>
|
||||
|
||||
#if __cplusplus >= 202002L
|
||||
#include <source_location>
|
||||
#endif
|
||||
|
||||
namespace dht {
|
||||
namespace log {
|
||||
|
||||
#if __cplusplus >= 202002L
|
||||
/**
|
||||
* Extracts the filename from a full file path at compile time.
|
||||
*/
|
||||
consteval std::string_view
|
||||
getfilename(std::string_view path)
|
||||
{
|
||||
size_t pos = path.size();
|
||||
for (size_t i = path.size(); i-- > 0;) {
|
||||
if (path[i] == '/' || path[i] == '\\') {
|
||||
pos = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return path.substr(pos);
|
||||
}
|
||||
|
||||
consteval std::string_view
|
||||
getfunctionname(std::string_view path)
|
||||
{
|
||||
size_t pos = 0;
|
||||
size_t end = path.size();
|
||||
for (size_t i = 0; i < path.size(); i++) {
|
||||
if (path[i] == ' ' || path[i] == '\t' || path[i] == ':') {
|
||||
pos = i + 1;
|
||||
} else if (path[i] == '(') {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return path.substr(pos, end - pos);
|
||||
}
|
||||
#endif
|
||||
|
||||
struct source_loc
|
||||
{
|
||||
std::string_view file;
|
||||
std::uint_least32_t line;
|
||||
std::string_view function;
|
||||
|
||||
#if __cplusplus >= 202002L
|
||||
consteval source_loc(const std::source_location& loc)
|
||||
: file(getfilename(loc.file_name()))
|
||||
, line(loc.line())
|
||||
, function(getfunctionname(loc.function_name()))
|
||||
{}
|
||||
#else
|
||||
constexpr source_loc()
|
||||
: file()
|
||||
, line(0)
|
||||
, function()
|
||||
{}
|
||||
#endif
|
||||
};
|
||||
|
||||
enum class LogLevel { debug, warning, error };
|
||||
|
||||
using LogMethod = std::function<void(source_loc, LogLevel, std::string_view, std::string&&)>;
|
||||
|
||||
template<typename... Args>
|
||||
struct LogFormat
|
||||
{
|
||||
fmt::format_string<Args...> fmt;
|
||||
source_loc loc;
|
||||
|
||||
#if __cplusplus >= 202002L
|
||||
template<typename S>
|
||||
consteval LogFormat(const S& s, const std::source_location& l = std::source_location::current())
|
||||
: fmt(s)
|
||||
, loc(l)
|
||||
{}
|
||||
#else
|
||||
template<typename S>
|
||||
constexpr LogFormat(const S& s)
|
||||
: fmt(s)
|
||||
, loc()
|
||||
{}
|
||||
#endif
|
||||
};
|
||||
|
||||
#if __cplusplus < 202002L
|
||||
template<class _Tp>
|
||||
struct type_identity
|
||||
{
|
||||
typedef _Tp type;
|
||||
};
|
||||
template<class _Tp>
|
||||
using type_identity_t = typename type_identity<_Tp>::type;
|
||||
#else
|
||||
using std::type_identity_t;
|
||||
#endif
|
||||
|
||||
struct OPENDHT_PUBLIC Logger
|
||||
{
|
||||
Logger() = delete;
|
||||
Logger(LogMethod&& l, std::string tag = "")
|
||||
: logger_(std::move(l))
|
||||
, tag_(std::move(tag))
|
||||
, prefix_(tag_.empty() ? "" : fmt::format("[{}] ", tag_))
|
||||
{
|
||||
if (!logger_)
|
||||
throw std::invalid_argument {"logger must be set"};
|
||||
}
|
||||
Logger(const Logger& parent, std::string tag)
|
||||
: logger_(parent.logger_)
|
||||
, tag_(std::move(tag))
|
||||
, prefix_(fmt::format("{}[{}] ", parent.prefix_, tag_))
|
||||
{}
|
||||
|
||||
std::shared_ptr<Logger> createChild(std::string tag)
|
||||
{
|
||||
std::lock_guard lock {children_mutex_};
|
||||
auto child = std::make_shared<Logger>(*this, std::move(tag));
|
||||
children_.push_back(child);
|
||||
return child;
|
||||
}
|
||||
|
||||
void setFilter(std::string_view filter)
|
||||
{
|
||||
std::lock_guard lock {children_mutex_};
|
||||
enable_ = filter.empty() or tag_.find(filter) != std::string_view::npos;
|
||||
for (auto it = children_.begin(); it != children_.end();) {
|
||||
if (auto c = it->lock()) {
|
||||
c->setFilter(enable_ ? std::string_view {} : filter);
|
||||
++it;
|
||||
} else {
|
||||
it = children_.erase(it);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setFilter(const InfoHash& f) { setFilter(f.to_view()); }
|
||||
|
||||
inline void log0(source_loc loc, LogLevel level, fmt::string_view format, fmt::printf_args args) const
|
||||
{
|
||||
if (enable_)
|
||||
logger_(loc, level, prefix_, fmt::vsprintf(format, args));
|
||||
}
|
||||
template<typename... Args>
|
||||
inline void debug(LogFormat<type_identity_t<Args>...> format, Args&&... args) const
|
||||
{
|
||||
if (enable_)
|
||||
logger_(format.loc, LogLevel::debug, prefix_, fmt::format(format.fmt, std::forward<Args>(args)...));
|
||||
}
|
||||
template<typename... Args>
|
||||
inline void warn(LogFormat<type_identity_t<Args>...> format, Args&&... args) const
|
||||
{
|
||||
if (enable_)
|
||||
logger_(format.loc, LogLevel::warning, prefix_, fmt::format(format.fmt, std::forward<Args>(args)...));
|
||||
}
|
||||
template<typename... Args>
|
||||
inline void error(LogFormat<type_identity_t<Args>...> format, Args&&... args) const
|
||||
{
|
||||
if (enable_)
|
||||
logger_(format.loc, LogLevel::error, prefix_, fmt::format(format.fmt, std::forward<Args>(args)...));
|
||||
}
|
||||
template<typename... T>
|
||||
inline void d(LogFormat<type_identity_t<T>...> format, T&&... args) const
|
||||
{
|
||||
log0(format.loc, LogLevel::debug, format.fmt, fmt::make_printf_args(args...));
|
||||
}
|
||||
template<typename... T>
|
||||
inline void w(LogFormat<type_identity_t<T>...> format, T&&... args) const
|
||||
{
|
||||
log0(format.loc, LogLevel::warning, format.fmt, fmt::make_printf_args(args...));
|
||||
}
|
||||
template<typename... T>
|
||||
inline void e(LogFormat<type_identity_t<T>...> format, T&&... args) const
|
||||
{
|
||||
log0(format.loc, LogLevel::error, format.fmt, fmt::make_printf_args(args...));
|
||||
}
|
||||
|
||||
private:
|
||||
const LogMethod logger_ = {};
|
||||
const std::string tag_ {};
|
||||
const std::string prefix_ {};
|
||||
std::mutex children_mutex_;
|
||||
std::vector<std::weak_ptr<Logger>> children_ {};
|
||||
bool enable_ {true};
|
||||
};
|
||||
|
||||
} // namespace log
|
||||
using Logger = log::Logger;
|
||||
} // namespace dht
|
||||
+310
-158
@@ -1,22 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "node_cache.h"
|
||||
@@ -27,15 +10,18 @@
|
||||
#include "utils.h"
|
||||
#include "rng.h"
|
||||
#include "rate_limiter.h"
|
||||
#include "log_enable.h"
|
||||
#include "logger.h"
|
||||
#include "network_utils.h"
|
||||
#include "transport.h"
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include <algorithm>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <queue>
|
||||
#include <tuple>
|
||||
|
||||
namespace dht {
|
||||
namespace net {
|
||||
@@ -48,33 +34,49 @@ struct TransId;
|
||||
#define MSG_CONFIRM 0
|
||||
#endif
|
||||
|
||||
struct NetworkConfig {
|
||||
struct NetworkConfig
|
||||
{
|
||||
NetId network {0};
|
||||
/* Requests in Session or Data envelopes, from a validated address */
|
||||
ssize_t max_req_per_sec {0};
|
||||
ssize_t max_peer_req_per_sec {0};
|
||||
/* Other requests. 0: same as above */
|
||||
ssize_t max_unauth_req_per_sec {0};
|
||||
ssize_t max_peer_unauth_req_per_sec {0};
|
||||
/* Packets needing a key agreement or signature check. 0: same as max_req_per_sec */
|
||||
ssize_t max_crypto_per_sec {0};
|
||||
ssize_t max_peer_crypto_per_sec {0};
|
||||
bool is_client {false};
|
||||
/** Transport encryption is used only if enabled and a key is set */
|
||||
TransportConfig transport {};
|
||||
};
|
||||
|
||||
class DhtProtocolException : public DhtException {
|
||||
class DhtProtocolException : public DhtException
|
||||
{
|
||||
public:
|
||||
// sent to another peer (http-like).
|
||||
static const constexpr uint16_t NON_AUTHORITATIVE_INFORMATION {203}; /* incomplete request packet. */
|
||||
static const constexpr uint16_t UNAUTHORIZED {401}; /* wrong tokens. */
|
||||
static const constexpr uint16_t UNAUTHORIZED {401}; /* incorrect tokens. */
|
||||
static const constexpr uint16_t NOT_FOUND {404}; /* storage not found */
|
||||
// for internal use (custom).
|
||||
static const constexpr uint16_t INVALID_TID_SIZE {421}; /* id was truncated. */
|
||||
static const constexpr uint16_t UNKNOWN_TID {422}; /* unknown tid */
|
||||
static const constexpr uint16_t WRONG_NODE_INFO_BUF_LEN {423}; /* node info length is wrong */
|
||||
static const constexpr uint16_t INVALID_TID_SIZE {421}; /* id was truncated. */
|
||||
static const constexpr uint16_t UNKNOWN_TID {422}; /* unknown tid */
|
||||
static const constexpr uint16_t WRONG_NODE_INFO_BUF_LEN {423}; /* node info length is incorrect */
|
||||
|
||||
static const std::string GET_NO_INFOHASH; /* received "get" request with no infohash */
|
||||
static const std::string LISTEN_NO_INFOHASH; /* got "listen" request without infohash */
|
||||
static const std::string LISTEN_WRONG_TOKEN; /* wrong token in "listen" request */
|
||||
static const std::string LISTEN_WRONG_TOKEN; /* incorrect token in "listen" request */
|
||||
static const std::string PUT_NO_INFOHASH; /* no infohash in "put" request */
|
||||
static const std::string PUT_WRONG_TOKEN; /* got "put" request with wrong token */
|
||||
static const std::string PUT_WRONG_TOKEN; /* got "put" request with incorrect token */
|
||||
static const std::string STORAGE_NOT_FOUND; /* got access request for an unknown storage */
|
||||
static const std::string PUT_INVALID_ID; /* invalid id in "put" request */
|
||||
|
||||
DhtProtocolException(uint16_t code, const std::string& msg="", InfoHash failing_node_id={})
|
||||
: DhtException(msg), msg(msg), code(code), failing_node_id(failing_node_id) {}
|
||||
DhtProtocolException(uint16_t code, const std::string& msg = "", InfoHash failing_node_id = {})
|
||||
: DhtException(msg)
|
||||
, msg(msg)
|
||||
, code(code)
|
||||
, failing_node_id(failing_node_id)
|
||||
{}
|
||||
|
||||
const std::string& getMsg() const { return msg; }
|
||||
uint16_t getCode() const { return code; }
|
||||
@@ -91,8 +93,10 @@ struct ParsedMessage;
|
||||
/**
|
||||
* Answer for a request.
|
||||
*/
|
||||
struct RequestAnswer {
|
||||
Blob ntoken {};
|
||||
struct RequestAnswer
|
||||
{
|
||||
/* Write token of the node; empty if it needs none (encrypted), nullopt if not granted. */
|
||||
std::optional<Blob> ntoken {};
|
||||
Value::Id vid {};
|
||||
std::vector<Sp<Value>> values {};
|
||||
std::vector<Value::Id> refreshed_values {};
|
||||
@@ -169,72 +173,66 @@ private:
|
||||
*/
|
||||
std::function<RequestAnswer(Sp<Node>, const InfoHash&, want_t, const Query&)> onGetValues {};
|
||||
/**
|
||||
* Called on listen request.
|
||||
* Called on listen request, from a node proven to receive at its address.
|
||||
*
|
||||
* @param node (type: Sp<Node>) the requesting node.
|
||||
* @param h (type: InfoHash) hash of the value of interest.
|
||||
* @param token (type: Blob) security token.
|
||||
* @param rid (type: uint16_t) request id.
|
||||
*/
|
||||
std::function<RequestAnswer(Sp<Node>,
|
||||
const InfoHash&,
|
||||
const Blob&,
|
||||
Tid,
|
||||
const Query&,
|
||||
int)> onListen {};
|
||||
std::function<RequestAnswer(Sp<Node>, const InfoHash&, Tid, const Query&, int)> onListen {};
|
||||
/**
|
||||
* Called on announce request.
|
||||
* Called on announce request, from a node proven to receive at its address.
|
||||
*
|
||||
* @param node (type: Sp<Node>) the requesting node.
|
||||
* @param h (type: InfoHash) hash of the value of interest.
|
||||
* @param token (type: Blob) security token.
|
||||
* @param values (type: std::vector<Sp<Value>>) values to store.
|
||||
* @param created (type: time_point) time when the value was created.
|
||||
*/
|
||||
std::function<RequestAnswer(Sp<Node>,
|
||||
const InfoHash&,
|
||||
const Blob&,
|
||||
const std::vector<Sp<Value>>&,
|
||||
const time_point&)> onAnnounce {};
|
||||
std::function<RequestAnswer(Sp<Node>, const InfoHash&, const std::vector<Sp<Value>>&, const time_point&)>
|
||||
onAnnounce {};
|
||||
/**
|
||||
* Called on refresh request.
|
||||
* Called on refresh request, from a node proven to receive at its address.
|
||||
*
|
||||
* @param node (type: Sp<Node>) the requesting node.
|
||||
* @param h (type: InfoHash) hash of the value of interest.
|
||||
* @param token (type: Blob) security token.
|
||||
* @param vid (type: Value::id) the value id.
|
||||
*/
|
||||
std::function<RequestAnswer(Sp<Node>,
|
||||
const InfoHash&,
|
||||
const Blob&,
|
||||
const Value::Id&)> onRefresh {};
|
||||
std::function<RequestAnswer(Sp<Node>, const InfoHash&, const Value::Id&)> onRefresh {};
|
||||
|
||||
public:
|
||||
using RequestCb = std::function<void(const Request&, RequestAnswer&&)>;
|
||||
using RequestErrorCb = std::function<bool(const Request&, DhtProtocolException&&)>;
|
||||
using RequestExpiredCb = std::function<void(const Request&, bool)>;
|
||||
|
||||
NetworkEngine(
|
||||
InfoHash& myid,
|
||||
NetworkConfig config,
|
||||
std::unique_ptr<DatagramSocket>&& sock,
|
||||
const Sp<Logger>& log,
|
||||
std::mt19937_64& rd,
|
||||
Scheduler& scheduler,
|
||||
decltype(NetworkEngine::onError)&& onError,
|
||||
decltype(NetworkEngine::onNewNode)&& onNewNode,
|
||||
decltype(NetworkEngine::onReportedAddr)&& onReportedAddr,
|
||||
decltype(NetworkEngine::onPing)&& onPing,
|
||||
decltype(NetworkEngine::onFindNode)&& onFindNode,
|
||||
decltype(NetworkEngine::onGetValues)&& onGetValues,
|
||||
decltype(NetworkEngine::onListen)&& onListen,
|
||||
decltype(NetworkEngine::onAnnounce)&& onAnnounce,
|
||||
decltype(NetworkEngine::onRefresh)&& onRefresh);
|
||||
NetworkEngine(InfoHash& myid,
|
||||
NetworkConfig config,
|
||||
std::unique_ptr<DatagramSocket>&& sock,
|
||||
const Sp<Logger>& log,
|
||||
std::mt19937_64& rd,
|
||||
Scheduler& scheduler,
|
||||
decltype(NetworkEngine::onError)&& onError,
|
||||
decltype(NetworkEngine::onNewNode)&& onNewNode,
|
||||
decltype(NetworkEngine::onReportedAddr)&& onReportedAddr,
|
||||
decltype(NetworkEngine::onPing)&& onPing,
|
||||
decltype(NetworkEngine::onFindNode)&& onFindNode,
|
||||
decltype(NetworkEngine::onGetValues)&& onGetValues,
|
||||
decltype(NetworkEngine::onListen)&& onListen,
|
||||
decltype(NetworkEngine::onAnnounce)&& onAnnounce,
|
||||
decltype(NetworkEngine::onRefresh)&& onRefresh);
|
||||
|
||||
~NetworkEngine();
|
||||
|
||||
net::DatagramSocket* getSocket() const { return dht_socket.get(); };
|
||||
|
||||
/** Our transport key, or nullptr if transport encryption is disabled */
|
||||
const transport::KeyPair* getTransportKey() const { return transport_ ? &config.transport.key : nullptr; }
|
||||
/** Replaces our transport key. Only valid before any message is exchanged. */
|
||||
void setTransportKey(const transport::KeyPair& key)
|
||||
{
|
||||
if (transport_)
|
||||
config.transport.key = key;
|
||||
}
|
||||
|
||||
void clear();
|
||||
|
||||
/**
|
||||
@@ -246,21 +244,34 @@ public:
|
||||
* @param socket_id The tid to use to write to the request socket.
|
||||
* @param hash The hash key of the value.
|
||||
* @param want Wether to send ipv4 and/or ipv6 nodes.
|
||||
* @param ntoken Listen security token.
|
||||
* @param nodes The ipv4 closest nodes.
|
||||
* @param nodes6 The ipv6 closest nodes.
|
||||
* @param values The values to send.
|
||||
* @param version If version = 1, a request will be used to answer to the listener
|
||||
*/
|
||||
void tellListener(Sp<Node> n, Tid socket_id, const InfoHash& hash, want_t want, const Blob& ntoken,
|
||||
std::vector<Sp<Node>>&& nodes, std::vector<Sp<Node>>&& nodes6,
|
||||
std::vector<Sp<Value>>&& values, const Query& q, int version);
|
||||
void tellListener(const Sp<Node>& n,
|
||||
Tid socket_id,
|
||||
const InfoHash& hash,
|
||||
want_t want,
|
||||
std::vector<Sp<Node>>&& nodes,
|
||||
std::vector<Sp<Node>>&& nodes6,
|
||||
std::vector<Sp<Value>>&& values,
|
||||
const Query& q,
|
||||
int version);
|
||||
|
||||
void tellListenerRefreshed(Sp<Node> n, Tid socket_id, const InfoHash& hash, const Blob& ntoken, const std::vector<Value::Id>& values, int version);
|
||||
void tellListenerExpired(Sp<Node> n, Tid socket_id, const InfoHash& hash, const Blob& ntoken, const std::vector<Value::Id>& values, int version);
|
||||
void tellListenerRefreshed(const Sp<Node>& n,
|
||||
Tid socket_id,
|
||||
const InfoHash& hash,
|
||||
const std::vector<Value::Id>& values,
|
||||
int version);
|
||||
void tellListenerExpired(const Sp<Node>& n,
|
||||
Tid socket_id,
|
||||
const InfoHash& hash,
|
||||
const std::vector<Value::Id>& values,
|
||||
int version);
|
||||
|
||||
bool isRunning(sa_family_t af) const;
|
||||
inline want_t want () const { return dht_socket->hasIPv4() and dht_socket->hasIPv6() ? (WANT4 | WANT6) : -1; }
|
||||
inline want_t want() const { return dht_socket->hasIPv4() and dht_socket->hasIPv6() ? (WANT4 | WANT6) : -1; }
|
||||
|
||||
void connectivityChanged(sa_family_t);
|
||||
|
||||
@@ -268,6 +279,8 @@ public:
|
||||
* Requests *
|
||||
**************/
|
||||
|
||||
bool needsSession(const Node& node) const;
|
||||
|
||||
/**
|
||||
* Send a "ping" request to a given node.
|
||||
*
|
||||
@@ -277,8 +290,7 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request>
|
||||
sendPing(Sp<Node> n, RequestCb&& on_done, RequestExpiredCb&& on_expired);
|
||||
Sp<Request> sendPing(const Sp<Node>& n, RequestCb&& on_done, RequestExpiredCb&& on_expired);
|
||||
|
||||
/**
|
||||
* Send a "ping" request to a given node.
|
||||
@@ -290,11 +302,11 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request>
|
||||
sendPing(SockAddr&& sa, RequestCb&& on_done, RequestExpiredCb&& on_expired) {
|
||||
Sp<Request> sendPing(SockAddr&& sa, RequestCb&& on_done, RequestExpiredCb&& on_expired)
|
||||
{
|
||||
return sendPing(std::make_shared<Node>(InfoHash::zero(), std::move(sa), rd),
|
||||
std::forward<RequestCb>(on_done),
|
||||
std::forward<RequestExpiredCb>(on_expired));
|
||||
std::forward<RequestCb>(on_done),
|
||||
std::forward<RequestExpiredCb>(on_expired));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -309,7 +321,7 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request> sendFindNode(Sp<Node> n,
|
||||
Sp<Request> sendFindNode(const Sp<Node>& n,
|
||||
const InfoHash& hash,
|
||||
want_t want = -1,
|
||||
RequestCb&& on_done = {},
|
||||
@@ -328,7 +340,7 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request> sendGetValues(Sp<Node> n,
|
||||
Sp<Request> sendGetValues(const Sp<Node>& n,
|
||||
const InfoHash& hash,
|
||||
const Query& query,
|
||||
want_t want,
|
||||
@@ -344,11 +356,11 @@ public:
|
||||
* @param previous The previous request "listen" sent to this node.
|
||||
* @param socket **UNUSED** The socket for further response.
|
||||
*
|
||||
* For backward compatibility purpose, sendListen has to
|
||||
* handle creation of the socket. Therefor, you cannot
|
||||
* use openSocket yourself. TODO: Once we don't support
|
||||
* the old "listen" negociation, sendListen shall not
|
||||
* create the socket itself.
|
||||
* For backward compatibility purposes, sendListen has to
|
||||
* handle creation of the socket. Therefore, you are unable to
|
||||
* use openSocket yourself.
|
||||
* TODO: Once we don't support the old "listen" negotiation,
|
||||
* sendListen shall not create the socket itself.
|
||||
*
|
||||
* @param on_done Request callback when the request is completed.
|
||||
* @param on_expired Request callback when the request expires.
|
||||
@@ -357,7 +369,7 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request> sendListen(Sp<Node> n,
|
||||
Sp<Request> sendListen(const Sp<Node>& n,
|
||||
const InfoHash& hash,
|
||||
const Query& query,
|
||||
const Blob& token,
|
||||
@@ -377,7 +389,7 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request> sendAnnounceValue(Sp<Node> n,
|
||||
Sp<Request> sendAnnounceValue(const Sp<Node>& n,
|
||||
const InfoHash& hash,
|
||||
const Sp<Value>& v,
|
||||
time_point created,
|
||||
@@ -397,7 +409,7 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request> sendRefreshValue(Sp<Node> n,
|
||||
Sp<Request> sendRefreshValue(const Sp<Node>& n,
|
||||
const InfoHash& hash,
|
||||
const Value::Id& vid,
|
||||
const Blob& token,
|
||||
@@ -416,12 +428,19 @@ public:
|
||||
*
|
||||
* @return the request with information concerning its success.
|
||||
*/
|
||||
Sp<Request> sendUpdateValues(Sp<Node> n,
|
||||
void sendUpdateValues(const Sp<Node>& n,
|
||||
const InfoHash& infohash,
|
||||
std::vector<Sp<Value>>&& values,
|
||||
time_point created,
|
||||
const Blob& token,
|
||||
size_t sid);
|
||||
Sp<Request> sendUpdateValues(const Sp<Node>& n,
|
||||
const InfoHash& infohash,
|
||||
const std::vector<Sp<Value>>& values,
|
||||
std::vector<Sp<Value>>::iterator begin,
|
||||
std::vector<Sp<Value>>::iterator end,
|
||||
time_point created,
|
||||
const Blob& token,
|
||||
const size_t& sid);
|
||||
size_t sid);
|
||||
|
||||
/**
|
||||
* Parses a message and calls appropriate callbacks.
|
||||
@@ -432,44 +451,41 @@ public:
|
||||
* @param fromlen The length of the corresponding sockaddr structure.
|
||||
* @param now The time to adjust the clock in the network engine.
|
||||
*/
|
||||
void processMessage(const uint8_t *buf, size_t buflen, SockAddr addr);
|
||||
void processMessage(const uint8_t* buf, size_t buflen, SockAddr addr);
|
||||
|
||||
Sp<Node> insertNode(const InfoHash& id, const SockAddr& addr) {
|
||||
Sp<Node> insertNode(const InfoHash& id, const SockAddr& addr)
|
||||
{
|
||||
auto n = cache.getNode(id, addr, scheduler.time(), 0);
|
||||
onNewNode(n, 0);
|
||||
return n;
|
||||
}
|
||||
|
||||
std::vector<unsigned> getNodeMessageStats(bool in) {
|
||||
std::vector<unsigned> getNodeMessageStats(bool in)
|
||||
{
|
||||
auto& st = in ? in_stats : out_stats;
|
||||
std::vector<unsigned> stats {st.ping, st.find, st.get, st.listen, st.put};
|
||||
std::vector<unsigned> stats {st.ping, st.find, st.get, st.listen, st.put};
|
||||
st = {};
|
||||
return stats;
|
||||
}
|
||||
|
||||
void blacklistNode(const Sp<Node>& n);
|
||||
|
||||
std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count) {
|
||||
std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count)
|
||||
{
|
||||
return cache.getCachedNodes(id, sa_f, count);
|
||||
}
|
||||
|
||||
size_t getNodeCacheSize() const {
|
||||
return cache.size();
|
||||
}
|
||||
size_t getNodeCacheSize(sa_family_t af) const {
|
||||
return cache.size(af);
|
||||
size_t getNodeCacheSize() const { return cache.size(); }
|
||||
size_t getNodeCacheSize(sa_family_t af) const { return cache.size(af); }
|
||||
|
||||
size_t getRateLimiterSize() const
|
||||
{
|
||||
return requestLimiter_.size() + unauthLimiter_.size() + cryptoLimiter_.size() + replyCryptoLimiter_.size();
|
||||
}
|
||||
|
||||
size_t getRateLimiterSize() const {
|
||||
return address_rate_limiter.size();
|
||||
}
|
||||
|
||||
size_t getPartialCount() const {
|
||||
return partial_messages.size();
|
||||
}
|
||||
size_t getPartialCount() const { return partial_messages.size(); }
|
||||
|
||||
private:
|
||||
|
||||
struct PartialMessage;
|
||||
|
||||
/***************
|
||||
@@ -490,19 +506,136 @@ private:
|
||||
reason to increase this value. */
|
||||
static constexpr unsigned BLACKLISTED_MAX {10};
|
||||
|
||||
static constexpr size_t MTU {1280};
|
||||
/* IPv6 minimum MTU, less the IPv6 and UDP headers */
|
||||
static constexpr size_t MAX_PACKET_SIZE {1280 - 40 - 8};
|
||||
/* Upper bound of the msgpack framing around a value fragment */
|
||||
static constexpr size_t FRAGMENT_HEADER_SIZE {48};
|
||||
/* Value fragment sizes keeping each packet within the minimum MTU, less the envelope */
|
||||
static constexpr size_t FRAGMENT_SIZE {MAX_PACKET_SIZE - FRAGMENT_HEADER_SIZE};
|
||||
static constexpr size_t ENCRYPTED_FRAGMENT_SIZE {FRAGMENT_SIZE - transport::MAX_ENVELOPE_OVERHEAD};
|
||||
static constexpr size_t MAX_PACKET_VALUE_SIZE {600};
|
||||
static constexpr size_t MAX_MESSAGE_VALUE_SIZE {56 * 1024};
|
||||
static constexpr size_t RX_MAX_EARLY_BYTES {MAX_MESSAGE_VALUE_SIZE + MAX_VALUE_SIZE + 32};
|
||||
static constexpr size_t RX_MAX_EARLY_PARTS {RX_MAX_EARLY_BYTES / ENCRYPTED_FRAGMENT_SIZE + 2};
|
||||
/* Lifetime of ephemeral transport keys and write tokens: in use for one period, then accepted for another */
|
||||
static constexpr std::chrono::minutes EPOCH_DURATION {30};
|
||||
/* Cached session keys per epoch */
|
||||
static constexpr size_t MAX_SESSIONS {16 * 1024};
|
||||
static constexpr size_t TOKEN_SIZE {transport::KEY_SIZE};
|
||||
|
||||
static const std::string my_v;
|
||||
struct Session
|
||||
{
|
||||
/* our ephemeral key for the peer address */
|
||||
transport::Key ephemeral;
|
||||
transport::Key peer;
|
||||
transport::Key peerEphemeral;
|
||||
transport::SessionKeys keys;
|
||||
/* the peer has these keys and accepted us: send Data envelopes */
|
||||
bool confirmed {false};
|
||||
bool authorized {false};
|
||||
};
|
||||
/* The secret from which ephemeral keys and tokens derive, and session keys, all erased together.
|
||||
* A session is cached for an address only once its peer proved to receive there: it opened an envelope
|
||||
* encrypted with our key for that address. Replies to Initial and Hello envelopes never cache one,
|
||||
* since their source address can be spoofed. */
|
||||
struct Epoch
|
||||
{
|
||||
struct Entry
|
||||
{
|
||||
Session session;
|
||||
std::list<SockAddr>::iterator used;
|
||||
};
|
||||
transport::Key secret {};
|
||||
std::map<SockAddr, Entry> sessions {};
|
||||
/* most recently used first */
|
||||
std::list<SockAddr> used {};
|
||||
|
||||
explicit operator bool() const { return secret != transport::Key {}; }
|
||||
transport::KeyPair ephemeral(const SockAddr& addr) const;
|
||||
Blob token(const SockAddr& addr) const;
|
||||
/* Marks the session as used */
|
||||
Session* find(const SockAddr& addr);
|
||||
Session* find(const SockAddr& addr, const transport::Key& peer, const transport::Key& peerEphemeral);
|
||||
/* Evicts the least recently used session when full */
|
||||
void store(const SockAddr& addr, const Session& session);
|
||||
void wipe();
|
||||
};
|
||||
struct PendingSession
|
||||
{
|
||||
Epoch* epoch;
|
||||
Session session;
|
||||
};
|
||||
void rotateEpoch();
|
||||
/* Session with the peer at `addr`, or nullopt for an invalid peer key. Cached if the peer ephemeral key is validated. */
|
||||
std::optional<Session> session(const transport::Peer& peer, const SockAddr& addr);
|
||||
std::optional<Blob> openSession(const transport::Header& header,
|
||||
const uint8_t* buf,
|
||||
size_t buflen,
|
||||
const SockAddr& from,
|
||||
std::optional<PendingSession>& pending,
|
||||
Session*& cached);
|
||||
/* Fills the sender keys of `header` from the session */
|
||||
std::optional<Blob> openData(
|
||||
transport::Header& header, const uint8_t* buf, size_t buflen, const SockAddr& from, Session*& cached);
|
||||
|
||||
struct OpenedEnvelope
|
||||
{
|
||||
Sp<transport::Peer> peer;
|
||||
Blob payload;
|
||||
/* unauthenticated */
|
||||
bool hello {false};
|
||||
/* Session or Data envelope: the sender got our ephemeral key for its address */
|
||||
bool session {false};
|
||||
std::optional<PendingSession> pending {};
|
||||
Session* cached {};
|
||||
};
|
||||
std::optional<OpenedEnvelope> openEnvelope(const uint8_t* buf, size_t buflen, const SockAddr& from);
|
||||
bool authorize(transport::Peer& peer, const uint8_t* credential, size_t size) const;
|
||||
void attachPeer(Node& node, const Sp<transport::Peer>& peer);
|
||||
Sp<transport::Peer> makePeer(const InfoHash& id, const transport::Key& key) const;
|
||||
void processHello(const ParsedMessage& msg, const Sp<transport::Peer>& peer, const SockAddr& from);
|
||||
|
||||
/* Advertise our transport key in plaintext messages to nodes not known to support encryption */
|
||||
bool advertiseKey(const Node& node) const
|
||||
{
|
||||
return transport_ and not config.transport.isPrivate() and not node.getTransport();
|
||||
}
|
||||
/* Messages to the node are encrypted */
|
||||
bool encrypts(const Node& node) const { return transport_ and node.getTransport(); }
|
||||
/* Token granting writes to a plaintext node. Encrypted nodes need none. */
|
||||
Blob writeToken(const Node& node) const { return encrypts(node) ? Blob {} : epoch_.token(node.getAddr()); }
|
||||
bool tokenMatch(const Blob& token, const SockAddr& addr) const;
|
||||
/* Writes need proof that the sender receives at its address: a Session envelope, or else a token */
|
||||
void authorizeWrite(const ParsedMessage& msg, const Node& node, const std::string& error) const;
|
||||
/* Number of optional top-level fields packed by packOptionalFields */
|
||||
unsigned optionalFields(bool key) const
|
||||
{
|
||||
return (config.network ? 1 : 0) + (config.is_client ? 1 : 0) + (key ? 1 : 0);
|
||||
}
|
||||
void packOptionalFields(msgpack::packer<msgpack::sbuffer>& pk, bool key) const;
|
||||
|
||||
void process(std::unique_ptr<ParsedMessage>&&, const SockAddr& from);
|
||||
bool isExpectedReply(const ParsedMessage&, const SockAddr& from);
|
||||
bool tryCompleteMessage(PartialMessage&, const SockAddr& from);
|
||||
|
||||
bool rateLimit(const SockAddr& addr);
|
||||
/* Admits a request, unless `charged` already: Session and Data senders have their own budget.
|
||||
* A plaintext request whose answer takes an Initial envelope also needs crypto budget. */
|
||||
bool limitRequest(const ParsedMessage& msg, const SockAddr& from, bool charged = false);
|
||||
/* Admits a packet needing a key agreement, from a separate budget if we await a reply from there */
|
||||
bool limitCrypto(const transport::Key& sender, const SockAddr& from);
|
||||
bool expectsReply(const transport::Key& sender, const SockAddr& from);
|
||||
|
||||
static bool isMartian(const SockAddr& addr);
|
||||
bool isNodeBlacklisted(const SockAddr& addr) const;
|
||||
|
||||
void requestStep(Sp<Request> req);
|
||||
void transmitRequest(const Sp<Request>& req);
|
||||
void notifyRequestTimeout(Request& req);
|
||||
void completeSession(Node& node);
|
||||
/* Re-establishes the session with a ping in an Initial envelope, unless one is pending */
|
||||
void recoverSession(const Sp<Node>& node);
|
||||
/* Sends the requests withheld during the recovery, under the new session */
|
||||
void resumeRequests(Node& node);
|
||||
|
||||
/**
|
||||
* Sends a request to a node. Request::MAX_ATTEMPT_COUNT attempts will
|
||||
@@ -510,76 +643,95 @@ private:
|
||||
*/
|
||||
void sendRequest(const Sp<Request>& request);
|
||||
|
||||
struct MessageStats {
|
||||
unsigned ping {0};
|
||||
unsigned find {0};
|
||||
unsigned get {0};
|
||||
unsigned put {0};
|
||||
unsigned listen {0};
|
||||
unsigned refresh {0};
|
||||
unsigned updateValue {0};
|
||||
struct MessageStats
|
||||
{
|
||||
unsigned ping {0};
|
||||
unsigned find {0};
|
||||
unsigned get {0};
|
||||
unsigned put {0};
|
||||
unsigned listen {0};
|
||||
unsigned refresh {0};
|
||||
unsigned updateValue {0};
|
||||
};
|
||||
|
||||
|
||||
// basic wrapper for socket sendto function
|
||||
int send(const SockAddr& addr, const char *buf, size_t len, bool confirmed = false);
|
||||
int sendRaw(const SockAddr& addr, const uint8_t* buf, size_t len, bool confirmed = false);
|
||||
// send to a node, encrypted if supported
|
||||
int send(const Node& node, const SockAddr& addr, const char* buf, size_t len, bool confirmed = false);
|
||||
/* Bytes added by the envelope that send() uses for the node at `addr` */
|
||||
size_t envelopeOverhead(const Node& node, const SockAddr& addr);
|
||||
|
||||
void sendValueParts(Tid tid, const std::vector<Blob>& svals, const SockAddr& addr);
|
||||
std::vector<Blob> packValueHeader(msgpack::sbuffer&, const std::vector<Sp<Value>>&);
|
||||
void maintainRxBuffer(Tid tid);
|
||||
void sendValueParts(Tid tid, const std::vector<Blob>& svals, const Node& node, const SockAddr& addr);
|
||||
std::vector<Blob> packValueHeader(msgpack::sbuffer&,
|
||||
std::vector<Sp<Value>>::const_iterator,
|
||||
std::vector<Sp<Value>>::const_iterator) const;
|
||||
std::vector<Blob> packValueHeader(msgpack::sbuffer& buf, const std::vector<Sp<Value>>& values) const
|
||||
{
|
||||
return packValueHeader(buf, values.begin(), values.end());
|
||||
}
|
||||
using PartialMessageKey = std::tuple<SockAddr, Tid, transport::Key>;
|
||||
void maintainRxBuffer(const PartialMessageKey& key);
|
||||
|
||||
/*************
|
||||
* Answers *
|
||||
*************/
|
||||
/* answer to a ping request */
|
||||
void sendPong(const SockAddr& addr, Tid tid);
|
||||
void sendPong(const Node& node, const SockAddr& addr, Tid tid);
|
||||
struct BufferedNodes
|
||||
{
|
||||
Blob nodes4, nodes6;
|
||||
/* transport keys, aligned with nodes, zeros if unknown. Empty if none is known. */
|
||||
Blob keys4, keys6;
|
||||
};
|
||||
/* answer to findnodes/getvalues request */
|
||||
void sendNodesValues(const SockAddr& addr,
|
||||
Tid tid,
|
||||
const Blob& nodes,
|
||||
const Blob& nodes6,
|
||||
const std::vector<Sp<Value>>& st,
|
||||
const Query& query,
|
||||
const Blob& token);
|
||||
Blob bufferNodes(sa_family_t af, const InfoHash& id, std::vector<Sp<Node>>& nodes);
|
||||
void sendNodesValues(const Node& node,
|
||||
const SockAddr& addr,
|
||||
Tid tid,
|
||||
const BufferedNodes& nodes,
|
||||
const std::vector<Sp<Value>>& st,
|
||||
const Query& query,
|
||||
const Blob& token);
|
||||
std::pair<Blob, Blob> bufferNodes(sa_family_t af, const InfoHash& id, std::vector<Sp<Node>>& nodes);
|
||||
|
||||
std::pair<Blob, Blob> bufferNodes(sa_family_t af,
|
||||
const InfoHash& id,
|
||||
want_t want,
|
||||
std::vector<Sp<Node>>& nodes,
|
||||
std::vector<Sp<Node>>& nodes6);
|
||||
BufferedNodes bufferNodes(
|
||||
sa_family_t af, const InfoHash& id, want_t want, std::vector<Sp<Node>>& nodes, std::vector<Sp<Node>>& nodes6);
|
||||
/* answer to a listen request */
|
||||
void sendListenConfirmation(const SockAddr& addr, Tid tid);
|
||||
void sendListenConfirmation(const Node& node, const SockAddr& addr, Tid tid, const Blob& token = {});
|
||||
/* answer to put request */
|
||||
void sendValueAnnounced(const SockAddr& addr, Tid, Value::Id);
|
||||
void sendValueAnnounced(const Node& node, const SockAddr& addr, Tid, Value::Id);
|
||||
/* answer in case of error */
|
||||
void sendError(const SockAddr& addr,
|
||||
Tid tid,
|
||||
uint16_t code,
|
||||
const std::string& message,
|
||||
bool include_id=false);
|
||||
void sendError(const Node& node,
|
||||
const SockAddr& addr,
|
||||
Tid tid,
|
||||
uint16_t code,
|
||||
const std::string& message,
|
||||
bool include_id = false);
|
||||
|
||||
void deserializeNodes(ParsedMessage& msg, const SockAddr& from);
|
||||
|
||||
/* DHT info */
|
||||
const InfoHash& myid;
|
||||
const NetworkConfig config {};
|
||||
NetworkConfig config {};
|
||||
const bool transport_ {false};
|
||||
const Blob credential_ {};
|
||||
Epoch epoch_ {};
|
||||
Epoch previousEpoch_ {};
|
||||
Sp<Scheduler::Job> epochRotation_ {};
|
||||
const std::unique_ptr<DatagramSocket> dht_socket;
|
||||
Sp<Logger> logger_;
|
||||
std::mt19937_64& rd;
|
||||
|
||||
NodeCache cache;
|
||||
|
||||
// global limiting should be triggered by at least 8 different IPs
|
||||
using IpLimiter = RateLimiter;
|
||||
using IpLimiterMap = std::map<SockAddr, IpLimiter, SockAddr::ipCmp>;
|
||||
IpLimiterMap address_rate_limiter;
|
||||
RateLimiter rate_limiter;
|
||||
ssize_t limiter_maintenance {0};
|
||||
/* Requests from Session/Data senders, other requests, public-key work for unexpected and expected senders */
|
||||
AddressRateLimiter requestLimiter_;
|
||||
AddressRateLimiter unauthLimiter_;
|
||||
AddressRateLimiter cryptoLimiter_;
|
||||
AddressRateLimiter replyCryptoLimiter_;
|
||||
|
||||
// requests handling
|
||||
std::map<Tid, Sp<Request>> requests {};
|
||||
std::map<Tid, PartialMessage> partial_messages;
|
||||
std::map<PartialMessageKey, PartialMessage> partial_messages;
|
||||
|
||||
MessageStats in_stats {}, out_stats {};
|
||||
std::set<SockAddr> blacklist {};
|
||||
|
||||
@@ -1,27 +1,12 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
|
||||
#include "sockaddr.h"
|
||||
#include "utils.h"
|
||||
#include "log_enable.h"
|
||||
#include "logger.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <ws2tcpip.h>
|
||||
@@ -42,7 +27,7 @@ namespace dht {
|
||||
namespace net {
|
||||
|
||||
static const constexpr in_port_t DHT_DEFAULT_PORT = 4222;
|
||||
static const constexpr size_t RX_QUEUE_MAX_SIZE = 1024 * 16;
|
||||
static const constexpr size_t RX_QUEUE_MAX_SIZE = 1024 * 64;
|
||||
static const constexpr std::chrono::milliseconds RX_QUEUE_MAX_DELAY(650);
|
||||
|
||||
int bindSocket(const SockAddr& addr, SockAddr& bound);
|
||||
@@ -52,14 +37,16 @@ bool setNonblocking(int fd, bool nonblocking = true);
|
||||
#ifdef _WIN32
|
||||
void udpPipe(int fds[2]);
|
||||
#endif
|
||||
struct ReceivedPacket {
|
||||
struct ReceivedPacket
|
||||
{
|
||||
Blob data;
|
||||
SockAddr from;
|
||||
time_point received;
|
||||
};
|
||||
using PacketList = std::list<ReceivedPacket>;
|
||||
|
||||
class OPENDHT_PUBLIC DatagramSocket {
|
||||
class OPENDHT_PUBLIC DatagramSocket
|
||||
{
|
||||
public:
|
||||
/** A function that takes a list of new received packets and
|
||||
* optionally returns consumed packets for recycling.
|
||||
@@ -69,34 +56,39 @@ public:
|
||||
|
||||
virtual int sendTo(const SockAddr& dest, const uint8_t* data, size_t size, bool replied) = 0;
|
||||
|
||||
inline void setOnReceive(OnReceive&& cb) {
|
||||
std::lock_guard<std::mutex> lk(lock);
|
||||
inline void setOnReceive(OnReceive&& cb)
|
||||
{
|
||||
std::lock_guard lk(lock);
|
||||
rx_callback = std::move(cb);
|
||||
}
|
||||
|
||||
virtual bool hasIPv4() const = 0;
|
||||
virtual bool hasIPv6() const = 0;
|
||||
|
||||
SockAddr getBound(sa_family_t family = AF_UNSPEC) const {
|
||||
std::lock_guard<std::mutex> lk(lock);
|
||||
SockAddr getBound(sa_family_t family = AF_UNSPEC) const
|
||||
{
|
||||
std::lock_guard lk(lock);
|
||||
return getBoundRef(family);
|
||||
}
|
||||
in_port_t getPort(sa_family_t family = AF_UNSPEC) const {
|
||||
std::lock_guard<std::mutex> lk(lock);
|
||||
in_port_t getPort(sa_family_t family = AF_UNSPEC) const
|
||||
{
|
||||
std::lock_guard lk(lock);
|
||||
return getBoundRef(family).getPort();
|
||||
}
|
||||
|
||||
virtual const SockAddr& getBoundRef(sa_family_t family = AF_UNSPEC) const = 0;
|
||||
|
||||
/** Virtual resolver mothod allows to implement custom resolver */
|
||||
virtual std::vector<SockAddr> resolve(const std::string& host, const std::string& service = {}) {
|
||||
virtual std::vector<SockAddr> resolve(const std::string& host, const std::string& service = {})
|
||||
{
|
||||
return SockAddr::resolve(host, service);
|
||||
}
|
||||
|
||||
virtual void stop() = 0;
|
||||
protected:
|
||||
|
||||
PacketList getNewPacket() {
|
||||
protected:
|
||||
PacketList getNewPacket()
|
||||
{
|
||||
PacketList pkts;
|
||||
if (toRecycle_.empty()) {
|
||||
pkts.emplace_back();
|
||||
@@ -108,22 +100,26 @@ protected:
|
||||
return pkts;
|
||||
}
|
||||
|
||||
inline void onReceived(PacketList&& packets) {
|
||||
std::lock_guard<std::mutex> lk(lock);
|
||||
inline void onReceived(PacketList&& packets)
|
||||
{
|
||||
std::lock_guard lk(lock);
|
||||
if (rx_callback) {
|
||||
auto r = rx_callback(std::move(packets));
|
||||
if (not r.empty() and toRecycle_.size() < RX_QUEUE_MAX_SIZE)
|
||||
toRecycle_.splice(toRecycle_.end(), std::move(r));
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
mutable std::mutex lock;
|
||||
|
||||
private:
|
||||
OnReceive rx_callback;
|
||||
PacketList toRecycle_;
|
||||
};
|
||||
|
||||
class OPENDHT_PUBLIC UdpSocket : public DatagramSocket {
|
||||
class OPENDHT_PUBLIC UdpSocket : public DatagramSocket
|
||||
{
|
||||
public:
|
||||
UdpSocket(in_port_t port, const std::shared_ptr<Logger>& l = {});
|
||||
UdpSocket(const SockAddr& bind4, const SockAddr& bind6, const std::shared_ptr<Logger>& l = {});
|
||||
@@ -131,20 +127,24 @@ public:
|
||||
|
||||
int sendTo(const SockAddr& dest, const uint8_t* data, size_t size, bool replied) override;
|
||||
|
||||
const SockAddr& getBoundRef(sa_family_t family = AF_UNSPEC) const override {
|
||||
const SockAddr& getBoundRef(sa_family_t family = AF_UNSPEC) const override
|
||||
{
|
||||
return (family == AF_INET6) ? bound6 : bound4;
|
||||
}
|
||||
|
||||
bool hasIPv4() const override {
|
||||
std::lock_guard<std::mutex> lk(lock);
|
||||
bool hasIPv4() const override
|
||||
{
|
||||
std::lock_guard lk(lock);
|
||||
return s4 != -1;
|
||||
}
|
||||
bool hasIPv6() const override {
|
||||
std::lock_guard<std::mutex> lk(lock);
|
||||
bool hasIPv6() const override
|
||||
{
|
||||
std::lock_guard lk(lock);
|
||||
return s6 != -1;
|
||||
}
|
||||
|
||||
void stop() override;
|
||||
|
||||
private:
|
||||
std::shared_ptr<Logger> logger;
|
||||
int s4 {-1};
|
||||
@@ -157,5 +157,5 @@ private:
|
||||
void openSockets(const SockAddr& bind4, const SockAddr& bind6);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
} // namespace net
|
||||
} // namespace dht
|
||||
+44
-49
@@ -1,27 +1,11 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "infohash.h" // includes socket structures
|
||||
#include "utils.h"
|
||||
#include "sockaddr.h"
|
||||
#include "node_export.h"
|
||||
|
||||
#include <list>
|
||||
#include <map>
|
||||
@@ -34,34 +18,41 @@ struct Request;
|
||||
struct Socket;
|
||||
struct RequestAnswer;
|
||||
} /* namespace net */
|
||||
namespace transport {
|
||||
struct Peer;
|
||||
}
|
||||
|
||||
using Tid = uint32_t;
|
||||
using SocketCb = std::function<void(const Sp<Node>&, net::RequestAnswer&&)>;
|
||||
struct Socket {
|
||||
struct Socket
|
||||
{
|
||||
Socket() {}
|
||||
Socket(SocketCb&& on_receive) :
|
||||
on_receive(std::move(on_receive)) {}
|
||||
Socket(SocketCb&& on_receive)
|
||||
: on_receive(std::move(on_receive))
|
||||
{}
|
||||
SocketCb on_receive {};
|
||||
};
|
||||
|
||||
struct Node {
|
||||
struct Node
|
||||
{
|
||||
const InfoHash id;
|
||||
|
||||
Node(const InfoHash& id, const SockAddr& addr, std::mt19937_64& rd, bool client=false);
|
||||
Node(const InfoHash& id, SockAddr&& addr, std::mt19937_64& rd, bool client=false);
|
||||
Node(const InfoHash& id, const SockAddr& addr, std::mt19937_64& rd, bool client = false);
|
||||
Node(const InfoHash& id, SockAddr&& addr, std::mt19937_64& rd, bool client = false);
|
||||
Node(const InfoHash& id, const sockaddr* sa, socklen_t salen, std::mt19937_64& rd)
|
||||
: Node(id, SockAddr(sa, salen), rd) {}
|
||||
: Node(id, SockAddr(sa, salen), rd)
|
||||
{}
|
||||
|
||||
InfoHash getId() const {
|
||||
return id;
|
||||
}
|
||||
const InfoHash& getId() const { return id; }
|
||||
const SockAddr& getAddr() const { return addr; }
|
||||
std::string getAddrStr() const {
|
||||
return addr.toString();
|
||||
}
|
||||
std::string getAddrStr() const { return addr.toString(); }
|
||||
bool isClient() const { return is_client; }
|
||||
bool isIncoming() { return time > reply_time; }
|
||||
|
||||
/** Transport encryption state, if the node is known to support it */
|
||||
const Sp<transport::Peer>& getTransport() const { return transport_; }
|
||||
void setTransport(const Sp<transport::Peer>& peer) { transport_ = peer; }
|
||||
|
||||
const time_point& getTime() const { return time; }
|
||||
const time_point& getReplyTime() const { return reply_time; }
|
||||
void setTime(const time_point& t) { time = t; }
|
||||
@@ -71,7 +62,8 @@ struct Node {
|
||||
* to MAX_AUTH_ERRORS errors are accepted in order to let the node recover.
|
||||
* Upon this limit, the node expires.
|
||||
*/
|
||||
void authError() {
|
||||
void authError()
|
||||
{
|
||||
if (++auth_errors > MAX_AUTH_ERRORS)
|
||||
setExpired();
|
||||
}
|
||||
@@ -82,18 +74,14 @@ struct Node {
|
||||
bool isPendingMessage() const;
|
||||
size_t getPendingMessageCount() const;
|
||||
|
||||
bool isOld(const time_point& now) const {
|
||||
return time + NODE_EXPIRE_TIME < now;
|
||||
}
|
||||
bool isRemovable(const time_point& now) const {
|
||||
return isExpired() and isOld(now);
|
||||
}
|
||||
bool isOld(const time_point& now) const { return time + NODE_EXPIRE_TIME < now; }
|
||||
bool isRemovable(const time_point& now) const { return isExpired() and isOld(now); }
|
||||
|
||||
NodeExport exportNode() const {
|
||||
NodeExport exportNode() const
|
||||
{
|
||||
NodeExport ne;
|
||||
ne.id = id;
|
||||
ne.sslen = addr.getLength();
|
||||
std::memcpy(&ne.ss, addr.get(), ne.sslen);
|
||||
ne.addr = addr;
|
||||
return ne;
|
||||
}
|
||||
sa_family_t getFamily() const { return addr.getFamily(); }
|
||||
@@ -103,6 +91,7 @@ struct Node {
|
||||
void requested(const Sp<net::Request>& req);
|
||||
void received(time_point now, const Sp<net::Request>& req);
|
||||
Sp<net::Request> getRequest(Tid tid);
|
||||
const std::map<Tid, Sp<net::Request>>& getRequests() const { return requests_; }
|
||||
void cancelRequest(const Sp<net::Request>& req);
|
||||
|
||||
void setExpired();
|
||||
@@ -130,21 +119,26 @@ struct Node {
|
||||
/**
|
||||
* Resets the state of the node so it's not expired anymore.
|
||||
*/
|
||||
void reset() { expired_ = false; reply_time = time_point::min(); }
|
||||
void reset()
|
||||
{
|
||||
expired_ = false;
|
||||
reply_time = time_point::min();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a new request id, skipping the invalid id.
|
||||
*
|
||||
* @return the new id.
|
||||
*/
|
||||
Tid getNewTid() {
|
||||
Tid getNewTid()
|
||||
{
|
||||
++transaction_id;
|
||||
return transaction_id ? ++transaction_id : transaction_id;
|
||||
return transaction_id ? transaction_id : ++transaction_id;
|
||||
}
|
||||
|
||||
std::string toString() const;
|
||||
|
||||
OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const Node& h);
|
||||
OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const Node& h);
|
||||
|
||||
static constexpr const std::chrono::minutes NODE_GOOD_TIME {120};
|
||||
|
||||
@@ -160,8 +154,8 @@ private:
|
||||
|
||||
SockAddr addr;
|
||||
bool is_client {false};
|
||||
time_point time {time_point::min()}; /* last time eared about */
|
||||
time_point reply_time {time_point::min()}; /* time of last correct reply received */
|
||||
time_point time {time_point::min()}; /* last time eared about */
|
||||
time_point reply_time {time_point::min()}; /* time of last correct reply received */
|
||||
unsigned auth_errors {0};
|
||||
bool expired_ {false};
|
||||
Tid transaction_id;
|
||||
@@ -169,6 +163,7 @@ private:
|
||||
|
||||
std::map<Tid, Sp<net::Request>> requests_ {};
|
||||
std::map<Tid, Sp<Socket>> sockets_;
|
||||
Sp<transport::Peer> transport_ {};
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
@@ -1,21 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "node.h"
|
||||
@@ -25,16 +9,13 @@
|
||||
|
||||
namespace dht {
|
||||
|
||||
struct NodeCache {
|
||||
size_t size(sa_family_t family) const {
|
||||
return cache(family).count();
|
||||
}
|
||||
size_t size() const {
|
||||
return size(AF_INET) + size(AF_INET6);
|
||||
}
|
||||
struct NodeCache
|
||||
{
|
||||
size_t size(sa_family_t family) const { return cache(family).count(); }
|
||||
size_t size() const { return size(AF_INET) + size(AF_INET6); }
|
||||
|
||||
Sp<Node> getNode(const InfoHash& id, sa_family_t family);
|
||||
Sp<Node> getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client=false);
|
||||
Sp<Node> getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client = false);
|
||||
std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count) const;
|
||||
|
||||
/**
|
||||
@@ -43,20 +24,25 @@ struct NodeCache {
|
||||
* To use in case of connectivity change etc.
|
||||
*/
|
||||
void clearBadNodes(sa_family_t family = 0);
|
||||
void clear();
|
||||
|
||||
NodeCache(std::mt19937_64& r) : rd(r) {};
|
||||
NodeCache(std::mt19937_64& r)
|
||||
: rd(r) {};
|
||||
~NodeCache();
|
||||
|
||||
private:
|
||||
class NodeMap : private std::map<InfoHash, std::weak_ptr<Node>> {
|
||||
class NodeMap : private std::map<InfoHash, std::weak_ptr<Node>>
|
||||
{
|
||||
public:
|
||||
Sp<Node> getNode(const InfoHash& id);
|
||||
Sp<Node> getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client, std::mt19937_64& rd);
|
||||
Sp<Node> getNode(
|
||||
const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client, std::mt19937_64& rd);
|
||||
std::vector<Sp<Node>> getCachedNodes(const InfoHash& id, size_t count) const;
|
||||
void clearBadNodes();
|
||||
void setExpired();
|
||||
void cleanup();
|
||||
size_t count() const { return size(); }
|
||||
|
||||
private:
|
||||
size_t cleanup_counter {0};
|
||||
};
|
||||
@@ -68,4 +54,4 @@ private:
|
||||
std::mt19937_64& rd;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
@@ -0,0 +1,35 @@
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
#include "infohash.h"
|
||||
#include "sockaddr.h"
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace dht {
|
||||
using namespace std::literals;
|
||||
|
||||
struct OPENDHT_PUBLIC NodeExport
|
||||
{
|
||||
InfoHash id;
|
||||
SockAddr addr;
|
||||
|
||||
template<typename Packer>
|
||||
void msgpack_pack(Packer& pk) const
|
||||
{
|
||||
pk.pack_map(2);
|
||||
pk.pack("id"sv);
|
||||
pk.pack(id);
|
||||
pk.pack("addr"sv);
|
||||
pk.pack_bin(addr.getLength());
|
||||
pk.pack_bin_body((const char*) addr.get(), (size_t) addr.getLength());
|
||||
}
|
||||
|
||||
void msgpack_unpack(msgpack::object o);
|
||||
|
||||
OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const NodeExport& h);
|
||||
};
|
||||
|
||||
} // namespace dht
|
||||
@@ -1,29 +1,14 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Mingrui Zhang <mingrui.zhang@savoirfairelinux.com>
|
||||
* Vsevolod Ivanov <vsevolod.ivanov@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
#include "sockaddr.h"
|
||||
#include "infohash.h"
|
||||
#include "log_enable.h"
|
||||
#include "logger.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include <asio/steady_timer.hpp>
|
||||
#include <thread>
|
||||
|
||||
namespace asio {
|
||||
@@ -38,29 +23,32 @@ public:
|
||||
static constexpr in_port_t DEFAULT_PORT = 8888;
|
||||
using ServiceDiscoveredCallback = std::function<void(msgpack::object&&, SockAddr&&)>;
|
||||
|
||||
PeerDiscovery(in_port_t port = DEFAULT_PORT, std::shared_ptr<asio::io_context> ioContext = {}, std::shared_ptr<Logger> logger = {});
|
||||
PeerDiscovery(in_port_t port = DEFAULT_PORT,
|
||||
std::shared_ptr<asio::io_context> ioContext = {},
|
||||
std::shared_ptr<Logger> logger = {});
|
||||
~PeerDiscovery();
|
||||
|
||||
/**
|
||||
* startDiscovery - Keep Listening data from the sender until node is joinned or stop is called
|
||||
*/
|
||||
void startDiscovery(const std::string &type, ServiceDiscoveredCallback callback);
|
||||
* startDiscovery - Keep Listening data from the sender until node is joinned
|
||||
* or stop is called
|
||||
*/
|
||||
void startDiscovery(std::string_view type, ServiceDiscoveredCallback callback);
|
||||
|
||||
template<typename T>
|
||||
void startDiscovery(const std::string &type, std::function<void(T&&, SockAddr&&)> cb) {
|
||||
startDiscovery(type, [cb](msgpack::object&& ob, SockAddr&& addr) {
|
||||
cb(ob.as<T>(), std::move(addr));
|
||||
});
|
||||
void startDiscovery(std::string_view type, std::function<void(T&&, SockAddr&&)> cb)
|
||||
{
|
||||
startDiscovery(type, [cb](msgpack::object&& ob, SockAddr&& addr) { cb(ob.as<T>(), std::move(addr)); });
|
||||
}
|
||||
|
||||
/**
|
||||
* startPublish - Keeping sending data until node is joinned or stop is called
|
||||
*/
|
||||
void startPublish(const std::string &type, const msgpack::sbuffer &pack_buf);
|
||||
void startPublish(sa_family_t domain, const std::string &type, const msgpack::sbuffer &pack_buf);
|
||||
*/
|
||||
void startPublish(std::string_view type, const msgpack::sbuffer& pack_buf);
|
||||
void startPublish(sa_family_t domain, std::string_view type, const msgpack::sbuffer& pack_buf);
|
||||
|
||||
template<typename T>
|
||||
void startPublish(const std::string &type, const T& object) {
|
||||
void startPublish(std::string_view type, const T& object)
|
||||
{
|
||||
msgpack::sbuffer buf;
|
||||
msgpack::pack(buf, object);
|
||||
startPublish(type, buf);
|
||||
@@ -68,22 +56,24 @@ public:
|
||||
|
||||
/**
|
||||
* Thread Stopper
|
||||
*/
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/**
|
||||
* Remove possible callBack to discovery
|
||||
*/
|
||||
bool stopDiscovery(const std::string &type);
|
||||
*/
|
||||
bool stopDiscovery(std::string_view type);
|
||||
|
||||
/**
|
||||
* Remove different serivce message to send
|
||||
*/
|
||||
bool stopPublish(const std::string &type);
|
||||
bool stopPublish(sa_family_t domain, const std::string &type);
|
||||
*/
|
||||
bool stopPublish(std::string_view type);
|
||||
bool stopPublish(sa_family_t domain, std::string_view type);
|
||||
|
||||
void connectivityChanged();
|
||||
|
||||
void stopConnectivityChanged();
|
||||
|
||||
private:
|
||||
class DomainPeerDiscovery;
|
||||
std::unique_ptr<DomainPeerDiscovery> peerDiscovery4_;
|
||||
@@ -92,4 +82,4 @@ private:
|
||||
std::thread ioRunnner_;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+6
-21
@@ -1,20 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
@@ -23,9 +8,9 @@ namespace dht {
|
||||
namespace proxy {
|
||||
|
||||
constexpr const std::chrono::hours OP_TIMEOUT {24}; // one day
|
||||
constexpr const std::chrono::hours OP_MARGIN {2}; // two hours
|
||||
constexpr const char* const HTTP_PROTO {"http://"};
|
||||
constexpr const std::chrono::hours OP_MARGIN {8}; // eight hours
|
||||
|
||||
using ListenToken = uint64_t;
|
||||
|
||||
}
|
||||
}
|
||||
} // namespace proxy
|
||||
} // namespace dht
|
||||
@@ -1,42 +1,39 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "utils.h"
|
||||
#include "sockaddr.h"
|
||||
|
||||
#include <map>
|
||||
#include <queue>
|
||||
|
||||
namespace dht {
|
||||
|
||||
class RateLimiter {
|
||||
class RateLimiter
|
||||
{
|
||||
public:
|
||||
RateLimiter(size_t quota, const duration& period = std::chrono::seconds(1))
|
||||
: quota_(quota), period_(period) {}
|
||||
: quota_(quota)
|
||||
, period_(period)
|
||||
{}
|
||||
|
||||
/** Clear outdated records and return current quota usage */
|
||||
size_t maintain(const time_point& now) {
|
||||
size_t maintain(const time_point& now)
|
||||
{
|
||||
auto limit = now - period_;
|
||||
while (not records.empty() and records.front() < limit)
|
||||
records.pop();
|
||||
return records.size();
|
||||
}
|
||||
/** Whether quota remains, without using it */
|
||||
bool available(const time_point& now)
|
||||
{
|
||||
return quota_ == std::numeric_limits<size_t>::max() or maintain(now) < quota_;
|
||||
}
|
||||
/** Return false if quota is reached, insert record and return true otherwise. */
|
||||
bool limit(const time_point& now) {
|
||||
bool limit(const time_point& now)
|
||||
{
|
||||
if (quota_ == std::numeric_limits<size_t>::max())
|
||||
return true;
|
||||
if (maintain(now) >= quota_)
|
||||
@@ -44,13 +41,60 @@ public:
|
||||
records.emplace(now);
|
||||
return true;
|
||||
}
|
||||
bool empty() const {
|
||||
return records.empty();
|
||||
}
|
||||
bool empty() const { return records.empty(); }
|
||||
|
||||
private:
|
||||
const size_t quota_;
|
||||
const duration period_;
|
||||
std::queue<time_point> records {};
|
||||
};
|
||||
|
||||
}
|
||||
/**
|
||||
* A global quota and a quota per address. IPv6 addresses share the quota of their /64 prefix.
|
||||
* Negative quotas are unlimited.
|
||||
*/
|
||||
class AddressRateLimiter
|
||||
{
|
||||
public:
|
||||
AddressRateLimiter(ssize_t quota, ssize_t peerQuota, const duration& period = std::chrono::seconds(1))
|
||||
: global_(quota, period)
|
||||
, peerQuota_(peerQuota)
|
||||
, period_(period)
|
||||
{}
|
||||
|
||||
bool limit(const SockAddr& addr, const time_point& now)
|
||||
{
|
||||
// Checked first so that dropped packets create no per-address record
|
||||
if (not global_.available(now))
|
||||
return false;
|
||||
if (peerQuota_ >= 0) {
|
||||
maintain(now);
|
||||
auto it = peers_.find(addr);
|
||||
if (it == peers_.end())
|
||||
it = peers_.emplace(addr, RateLimiter(peerQuota_, period_)).first;
|
||||
if (not it->second.limit(now))
|
||||
return false;
|
||||
}
|
||||
return global_.limit(now);
|
||||
}
|
||||
/** Number of addresses with a record */
|
||||
size_t size() const { return peers_.size(); }
|
||||
|
||||
private:
|
||||
void maintain(const time_point& now)
|
||||
{
|
||||
if (now < nextMaintenance_)
|
||||
return;
|
||||
for (auto it = peers_.begin(); it != peers_.end();)
|
||||
it = it->second.maintain(now) ? std::next(it) : peers_.erase(it);
|
||||
nextMaintenance_ = now + period_;
|
||||
}
|
||||
|
||||
RateLimiter global_;
|
||||
const ssize_t peerQuota_;
|
||||
const duration period_;
|
||||
std::map<SockAddr, RateLimiter, SockAddr::ipCmp> peers_ {};
|
||||
time_point nextMaintenance_ {time_point::min()};
|
||||
};
|
||||
|
||||
} // namespace dht
|
||||
+42
-110
@@ -1,21 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include <random>
|
||||
@@ -27,104 +11,52 @@
|
||||
namespace dht {
|
||||
namespace crypto {
|
||||
|
||||
#ifndef _MSC_VER
|
||||
#ifdef _WIN32
|
||||
|
||||
/**
|
||||
* Hardware random number generator using Intel RDRAND/RDSEED,
|
||||
* API-compatible with std::random_device.
|
||||
* Generate a seeded random engine.
|
||||
*/
|
||||
class random_device {
|
||||
public:
|
||||
using result_type = std::random_device::result_type;
|
||||
using pseudo_engine = std::mt19937_64;
|
||||
|
||||
/**
|
||||
* Current implementation assumption : result_type must be of a size
|
||||
* supported by Intel RDRAND/RDSEED.
|
||||
* result_type is unsigned int so this is currently safe.
|
||||
*/
|
||||
static_assert(
|
||||
sizeof(result_type) == 2 ||
|
||||
sizeof(result_type) == 4 ||
|
||||
sizeof(result_type) == 8,
|
||||
"result_type must be 16, 32 or 64 bits");
|
||||
|
||||
random_device();
|
||||
|
||||
result_type operator()();
|
||||
|
||||
static constexpr result_type min() {
|
||||
return std::numeric_limits<result_type>::lowest();
|
||||
}
|
||||
|
||||
static constexpr result_type max() {
|
||||
return std::numeric_limits<result_type>::max();
|
||||
}
|
||||
|
||||
double entropy() const {
|
||||
if (hasRdrand() or hasRdseed())
|
||||
return 1.;
|
||||
return 0.;
|
||||
}
|
||||
|
||||
static bool hasRdrand() {
|
||||
static const bool hasrdrand = _hasRdrand();
|
||||
return hasrdrand;
|
||||
}
|
||||
|
||||
static bool hasRdseed() {
|
||||
static const bool hasrdseed = _hasRdseed();
|
||||
return hasrdseed;
|
||||
}
|
||||
|
||||
private:
|
||||
random_device& operator=(random_device&) = delete;
|
||||
|
||||
pseudo_engine gen;
|
||||
std::uniform_int_distribution<result_type> dis {};
|
||||
|
||||
static bool hasIntelCpu();
|
||||
static bool _hasRdrand();
|
||||
static bool _hasRdseed();
|
||||
|
||||
struct CPUIDinfo {
|
||||
unsigned int EAX;
|
||||
unsigned int EBX;
|
||||
unsigned int ECX;
|
||||
unsigned int EDX;
|
||||
CPUIDinfo(const unsigned int func, const unsigned int subfunc);
|
||||
template<class T = std::mt19937, std::size_t N = T::state_size + 1>
|
||||
auto
|
||||
getSeededRandomEngine() -> typename std::enable_if<!!N, T>::type
|
||||
{
|
||||
std::array<typename T::result_type, N> random_data;
|
||||
constexpr auto gen = [](std::random_device& source) -> typename T::result_type {
|
||||
for (unsigned j = 0; j < 64; j++) {
|
||||
try {
|
||||
return source();
|
||||
} catch (...) {
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(500));
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("Can't generate random number");
|
||||
};
|
||||
bool rdrandStep(result_type* r);
|
||||
bool rdrand(result_type* r);
|
||||
bool rdseedStep(result_type* r);
|
||||
bool rdseed(result_type* r);
|
||||
};
|
||||
|
||||
#else
|
||||
|
||||
using random_device = std::random_device;
|
||||
|
||||
#endif
|
||||
#else
|
||||
using random_device = std::random_device;
|
||||
#endif
|
||||
|
||||
template<class T = std::mt19937, std::size_t N = T::state_size>
|
||||
auto getSeededRandomEngine () -> typename std::enable_if<!!N, T>::type {
|
||||
typename T::result_type random_data[N];
|
||||
for (unsigned i=0; i<256; i++) {
|
||||
for (unsigned i = 0; i < 8; i++) {
|
||||
try {
|
||||
random_device source;
|
||||
std::generate(std::begin(random_data), std::end(random_data), std::ref(source));
|
||||
std::seed_seq seeds(std::begin(random_data), std::end(random_data));
|
||||
T seededEngine (seeds);
|
||||
return seededEngine;
|
||||
std::random_device source;
|
||||
for (auto& r : random_data)
|
||||
r = gen(source);
|
||||
std::seed_seq seed((std::seed_seq::result_type*) random_data.data(),
|
||||
(std::seed_seq::result_type*) (random_data.data() + random_data.size()));
|
||||
return T(seed);
|
||||
} catch (...) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1));
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(500));
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("Can't seed random engine");
|
||||
throw std::runtime_error("Can't seed random seed");
|
||||
}
|
||||
|
||||
}} // dht::crypto
|
||||
/**
|
||||
* Generate a random engine from another source.
|
||||
*/
|
||||
template<class T = std::mt19937, std::size_t N = T::state_size + 1>
|
||||
auto
|
||||
getDerivedRandomEngine(T& source) -> typename std::enable_if<!!N, T>::type
|
||||
{
|
||||
std::array<typename T::result_type, N> random_data;
|
||||
std::generate(random_data.begin(), random_data.end(), std::ref(source));
|
||||
std::seed_seq seed((std::seed_seq::result_type*) random_data.data(),
|
||||
(std::seed_seq::result_type*) (random_data.data() + random_data.size()));
|
||||
return T(seed);
|
||||
}
|
||||
|
||||
} // namespace crypto
|
||||
} // namespace dht
|
||||
@@ -1,22 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "node.h"
|
||||
@@ -28,28 +11,37 @@ namespace net {
|
||||
class NetworkEngine;
|
||||
}
|
||||
|
||||
struct Bucket {
|
||||
Bucket() : cached() {}
|
||||
struct Bucket
|
||||
{
|
||||
Bucket()
|
||||
: cached()
|
||||
{}
|
||||
Bucket(sa_family_t af, const InfoHash& f = {}, time_point t = time_point::min())
|
||||
: af(af), first(f), time(t), cached() {}
|
||||
: af(af)
|
||||
, first(f)
|
||||
, time(t)
|
||||
, cached()
|
||||
{}
|
||||
sa_family_t af {0};
|
||||
InfoHash first {};
|
||||
time_point time {time_point::min()}; /* time of last reply in this bucket */
|
||||
std::list<Sp<Node>> nodes {};
|
||||
Sp<Node> cached; /* the address of a likely candidate */
|
||||
Sp<Node> cached; /* the address of a likely candidate */
|
||||
|
||||
/** Return a random node in a bucket. */
|
||||
Sp<Node> randomNode(std::mt19937_64& rd);
|
||||
|
||||
void sendCachedPing(net::NetworkEngine& ne);
|
||||
void connectivityChanged() {
|
||||
void connectivityChanged()
|
||||
{
|
||||
time = time_point::min();
|
||||
for (auto& node : nodes)
|
||||
node->setTime(time_point::min());
|
||||
}
|
||||
};
|
||||
|
||||
class RoutingTable : public std::list<Bucket> {
|
||||
class RoutingTable : public std::list<Bucket>
|
||||
{
|
||||
public:
|
||||
using std::list<Bucket>::list;
|
||||
|
||||
@@ -66,25 +58,26 @@ public:
|
||||
/**
|
||||
* Return true if the id is in the bucket's range.
|
||||
*/
|
||||
inline bool contains(const RoutingTable::const_iterator& bucket, const InfoHash& id) const {
|
||||
inline bool contains(const RoutingTable::const_iterator& bucket, const InfoHash& id) const
|
||||
{
|
||||
return InfoHash::cmp(bucket->first, id) <= 0
|
||||
&& (std::next(bucket) == end() || InfoHash::cmp(id, std::next(bucket)->first) < 0);
|
||||
&& (std::next(bucket) == end() || InfoHash::cmp(id, std::next(bucket)->first) < 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the table has no bucket ore one empty buket.
|
||||
*/
|
||||
inline bool isEmpty() const {
|
||||
return empty() || (size() == 1 && front().nodes.empty());
|
||||
}
|
||||
inline bool isEmpty() const { return empty() || (size() == 1 && front().nodes.empty()); }
|
||||
|
||||
void connectivityChanged(const time_point& now) {
|
||||
void connectivityChanged(const time_point& now)
|
||||
{
|
||||
grow_time = now;
|
||||
for (auto& b : *this)
|
||||
b.connectivityChanged();
|
||||
}
|
||||
|
||||
bool onNewNode(const Sp<Node>& node, int comfirm, const time_point& now, const InfoHash& myid, net::NetworkEngine& ne);
|
||||
bool onNewNode(
|
||||
const Sp<Node>& node, int comfirm, const time_point& now, const InfoHash& myid, net::NetworkEngine& ne);
|
||||
|
||||
/**
|
||||
* Return a random id in the bucket's range.
|
||||
@@ -99,4 +92,4 @@ public:
|
||||
bool split(const RoutingTable::iterator& b);
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+20
-31
@@ -1,23 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author(s) : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "utils.h"
|
||||
@@ -33,10 +15,15 @@ namespace dht {
|
||||
* @details
|
||||
* Maintains the timings upon which to execute a job.
|
||||
*/
|
||||
class Scheduler {
|
||||
class Scheduler
|
||||
{
|
||||
public:
|
||||
struct Job {
|
||||
Job(std::function<void()>&& f, time_point t) : do_(std::move(f)), t_(t) {}
|
||||
struct Job
|
||||
{
|
||||
Job(std::function<void()>&& f, time_point t)
|
||||
: do_(std::move(f))
|
||||
, t_(t)
|
||||
{}
|
||||
std::function<void()> do_;
|
||||
const time_point t_;
|
||||
void cancel() { do_ = {}; }
|
||||
@@ -50,7 +37,8 @@ public:
|
||||
*
|
||||
* @return pointer to the newly scheduled job.
|
||||
*/
|
||||
Sp<Scheduler::Job> add(time_point t, std::function<void()>&& job_func) {
|
||||
Sp<Scheduler::Job> add(time_point t, std::function<void()>&& job_func)
|
||||
{
|
||||
auto job = std::make_shared<Job>(std::move(job_func), t);
|
||||
if (t != time_point::max())
|
||||
timers.emplace(std::move(t), job);
|
||||
@@ -63,7 +51,8 @@ public:
|
||||
* @param job The job to edit.
|
||||
* @param t The time at which the job shall be rescheduled.
|
||||
*/
|
||||
void edit(Sp<Scheduler::Job>& job, time_point t) {
|
||||
void edit(Sp<Scheduler::Job>& job, time_point t)
|
||||
{
|
||||
if (not job)
|
||||
return;
|
||||
// std::function move doesn't garantee to leave the object empty.
|
||||
@@ -73,7 +62,8 @@ public:
|
||||
job = add(t, std::move(task));
|
||||
}
|
||||
|
||||
bool cancel(Sp<Scheduler::Job>& job) {
|
||||
bool cancel(Sp<Scheduler::Job>& job)
|
||||
{
|
||||
if (job) {
|
||||
job->cancel();
|
||||
for (auto r = timers.equal_range(job->t_); r.first != r.second; ++r.first) {
|
||||
@@ -92,7 +82,8 @@ public:
|
||||
*
|
||||
* @return The time for the next job to run.
|
||||
*/
|
||||
time_point run() {
|
||||
time_point run()
|
||||
{
|
||||
while (not timers.empty()) {
|
||||
auto timer = timers.begin();
|
||||
/*
|
||||
@@ -112,9 +103,7 @@ public:
|
||||
return getNextJobTime();
|
||||
}
|
||||
|
||||
inline time_point getNextJobTime() const {
|
||||
return timers.empty() ? time_point::max() : timers.begin()->first;
|
||||
}
|
||||
inline time_point getNextJobTime() const { return timers.empty() ? time_point::max() : timers.begin()->first; }
|
||||
|
||||
/**
|
||||
* Accessors for the common time reference used for synchronizing
|
||||
@@ -129,4 +118,4 @@ private:
|
||||
std::multimap<time_point, Sp<Job>> timers {}; /* the jobs ordered by time */
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+188
-210
@@ -1,23 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Authors: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
* Simon Désaulniers <simon.desaulniers@savoirfairelinux.com>
|
||||
* Sébastien Blin <sebastien.blin@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "dht.h"
|
||||
@@ -30,9 +12,9 @@
|
||||
|
||||
namespace dht {
|
||||
|
||||
class OPENDHT_PUBLIC SecureDht final : public DhtInterface {
|
||||
class OPENDHT_PUBLIC SecureDht final : public DhtInterface
|
||||
{
|
||||
public:
|
||||
|
||||
typedef std::function<void(bool)> SignatureCheckCallback;
|
||||
|
||||
using Config = SecureDhtConfig;
|
||||
@@ -41,7 +23,7 @@ public:
|
||||
{
|
||||
auto c = conf.node_config;
|
||||
if (not c.node_id and conf.id.second)
|
||||
c.node_id = InfoHash::get("node:"+conf.id.second->getId().toString());
|
||||
c.node_id = InfoHash::get("node:" + conf.id.second->getId().toString());
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -51,53 +33,69 @@ public:
|
||||
* id: the identity to use for the crypto layer and to compute
|
||||
* our own hash on the Dht.
|
||||
*/
|
||||
SecureDht(std::unique_ptr<DhtInterface> dht, Config config, IdentityAnnouncedCb iacb = {}, const std::shared_ptr<Logger>& l = {});
|
||||
SecureDht(std::unique_ptr<DhtInterface> dht,
|
||||
Config config,
|
||||
IdentityAnnouncedCb iacb = {},
|
||||
const std::shared_ptr<Logger>& l = {});
|
||||
|
||||
virtual ~SecureDht();
|
||||
|
||||
InfoHash getId() const {
|
||||
return key_ ? key_->getPublicKey().getId() : InfoHash();
|
||||
}
|
||||
PkId getLongId() const {
|
||||
return key_ ? key_->getPublicKey().getLongId() : PkId();
|
||||
}
|
||||
Sp<crypto::PublicKey> getPublicKey() const {
|
||||
return key_ ? key_->getSharedPublicKey() : Sp<crypto::PublicKey>{};
|
||||
}
|
||||
InfoHash getId() const { return key_ ? key_->getPublicKey().getId() : InfoHash(); }
|
||||
PkId getLongId() const { return key_ ? key_->getPublicKey().getLongId() : PkId(); }
|
||||
Sp<crypto::PublicKey> getPublicKey() const { return key_ ? key_->getSharedPublicKey() : Sp<crypto::PublicKey> {}; }
|
||||
|
||||
ValueType secureType(ValueType&& type);
|
||||
|
||||
ValueType secureType(const ValueType& type) {
|
||||
ValueType secureType(const ValueType& type)
|
||||
{
|
||||
ValueType tmp_type = type;
|
||||
return secureType(std::move(tmp_type));
|
||||
}
|
||||
|
||||
void registerType(const ValueType& type) override {
|
||||
void registerType(const ValueType& type) override
|
||||
{
|
||||
if (dht_)
|
||||
dht_->registerType(secureType(type));
|
||||
}
|
||||
void registerType(ValueType&& type) {
|
||||
void registerType(ValueType&& type)
|
||||
{
|
||||
if (dht_)
|
||||
dht_->registerType(secureType(std::forward<ValueType>(type)));
|
||||
}
|
||||
void registerInsecureType(const ValueType& type) {
|
||||
void registerInsecureType(const ValueType& type)
|
||||
{
|
||||
if (dht_)
|
||||
dht_->registerType(type);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Secure" get(), that will check the signature of signed data, and decrypt encrypted data.
|
||||
* If the signature can't be checked, or if the data can't be decrypted, it is not returned.
|
||||
* If the signature is unable to be checked, or if the data is unable to be decrypted, it is not returned.
|
||||
* Public, non-signed & non-encrypted data is retransmitted as-is.
|
||||
*/
|
||||
void get(const InfoHash& id, GetCallback cb, DoneCallback donecb={}, Value::Filter&& = {}, Where&& w = {}) override;
|
||||
void get(const InfoHash& id, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f = {}, Where&& w = {}) override {
|
||||
void get(const InfoHash& id, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& = {}, Where&& w = {}) override;
|
||||
void get(const InfoHash& id,
|
||||
GetCallback cb,
|
||||
DoneCallbackSimple donecb = {},
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(id, cb, bindDoneCb(donecb), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
void get(const InfoHash& key,
|
||||
GetCallbackSimple cb,
|
||||
DoneCallback donecb = {},
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, bindGetCb(cb), donecb, std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) override {
|
||||
void get(const InfoHash& key,
|
||||
GetCallbackSimple cb,
|
||||
DoneCallbackSimple donecb,
|
||||
Value::Filter&& f = {},
|
||||
Where&& w = {}) override
|
||||
{
|
||||
get(key, bindGetCb(cb), bindDoneCb(donecb), std::forward<Value::Filter>(f), std::forward<Where>(w));
|
||||
}
|
||||
|
||||
@@ -105,7 +103,8 @@ public:
|
||||
* Will take ownership of the value, sign it using our private key and put it in the DHT.
|
||||
*/
|
||||
void putSigned(const InfoHash& hash, Sp<Value> val, DoneCallback callback, bool permanent = false);
|
||||
void putSigned(const InfoHash& hash, Value&& v, DoneCallback callback, bool permanent = false) {
|
||||
void putSigned(const InfoHash& hash, Value&& v, DoneCallback callback, bool permanent = false)
|
||||
{
|
||||
putSigned(hash, std::make_shared<Value>(std::move(v)), callback, permanent);
|
||||
}
|
||||
|
||||
@@ -114,15 +113,21 @@ public:
|
||||
* and put it in the DHT.
|
||||
* The operation will be immediate if the recipient' public key is known (otherwise it will be retrived first).
|
||||
*/
|
||||
void putEncrypted(const InfoHash& hash, const InfoHash& to, Sp<Value> val, DoneCallback callback, bool permanent = false);
|
||||
void putEncrypted(const InfoHash& hash, const InfoHash& to, Value&& v, DoneCallback callback, bool permanent = false) {
|
||||
putEncrypted(hash, to, std::make_shared<Value>(std::move(v)), callback, permanent);
|
||||
}
|
||||
void putEncrypted(const InfoHash& hash, const crypto::PublicKey& to, Sp<Value> val, DoneCallback callback, bool permanent = false);
|
||||
void putEncrypted(const InfoHash& hash, const crypto::PublicKey& to, Value&& v, DoneCallback callback, bool permanent = false) {
|
||||
void putEncrypted(const InfoHash& hash,
|
||||
const crypto::PublicKey& to,
|
||||
Sp<Value> val,
|
||||
DoneCallback callback,
|
||||
bool permanent = false);
|
||||
|
||||
[[deprecated("Use the shared_ptr version instead")]]
|
||||
void putEncrypted(
|
||||
const InfoHash& hash, const crypto::PublicKey& to, Value&& v, DoneCallback callback, bool permanent = false)
|
||||
{
|
||||
putEncrypted(hash, to, std::make_shared<Value>(std::move(v)), callback, permanent);
|
||||
}
|
||||
|
||||
void putEncrypted(const InfoHash& hash, const PkId& to, Sp<Value> val, DoneCallback callback, bool permanent = false);
|
||||
|
||||
/**
|
||||
* Take ownership of the value and sign it using our private key.
|
||||
*/
|
||||
@@ -132,205 +137,170 @@ public:
|
||||
|
||||
Value decrypt(const Value& v);
|
||||
|
||||
void findCertificate(const InfoHash& node, const std::function<void(const Sp<crypto::Certificate>)>& cb);
|
||||
void findPublicKey(const InfoHash& node, const std::function<void(const Sp<crypto::PublicKey>)>& cb);
|
||||
void findCertificate(const PkId& id, const std::function<void(const Sp<crypto::Certificate>)>& cb);
|
||||
void findPublicKey(const PkId& id, const std::function<void(const Sp<crypto::PublicKey>)>& cb);
|
||||
|
||||
Sp<crypto::Certificate> registerCertificate(const InfoHash& node, const Blob& cert);
|
||||
void registerCertificate(Sp<crypto::Certificate>& cert);
|
||||
void registerCertificate(const Sp<crypto::Certificate>& cert);
|
||||
|
||||
Sp<crypto::Certificate> getCertificate(const InfoHash& node) const;
|
||||
Sp<crypto::PublicKey> getPublicKey(const InfoHash& node) const;
|
||||
Sp<crypto::Certificate> getCertificate(const PkId& node) const;
|
||||
Sp<crypto::PublicKey> getPublicKey(const PkId& node) const;
|
||||
|
||||
/**
|
||||
* Allows to set a custom callback called by the library to find a locally-stored certificate.
|
||||
* The search key used is the public key ID, so there may be multiple certificates retured, signed with
|
||||
* the same private key.
|
||||
*/
|
||||
void setLocalCertificateStore(CertificateStoreQuery&& query_method) {
|
||||
localQueryMethod_ = std::move(query_method);
|
||||
}
|
||||
void setLocalCertificateStore(CertificateStoreQuery&& query_method) { localQueryMethod_ = std::move(query_method); }
|
||||
void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { dht_->setOnPublicAddressChanged(cb); }
|
||||
|
||||
/**
|
||||
* SecureDht to Dht proxy
|
||||
*/
|
||||
void shutdown(ShutdownCallback cb, bool stop = false) override {
|
||||
dht_->shutdown(cb, stop);
|
||||
}
|
||||
void dumpTables() const override {
|
||||
dht_->dumpTables();
|
||||
}
|
||||
void shutdown(ShutdownCallback cb, bool stop = false) override { dht_->shutdown(cb, stop); }
|
||||
void dumpTables() const override { dht_->dumpTables(); }
|
||||
inline const InfoHash& getNodeId() const override { return dht_->getNodeId(); }
|
||||
|
||||
std::pair<size_t, size_t> getStoreSize() const override {
|
||||
return dht_->getStoreSize();
|
||||
std::pair<size_t, size_t> getStoreSize() const override { return dht_->getStoreSize(); }
|
||||
std::pair<size_t, size_t> getLocalStoreSize() const override { return dht_->getLocalStoreSize(); }
|
||||
std::string getStorageLog() const override { return dht_->getStorageLog(); }
|
||||
std::string getStorageLog(const InfoHash& h) const override { return dht_->getStorageLog(h); }
|
||||
void setStorageLimit(size_t limit = 0) override { dht_->setStorageLimit(limit); }
|
||||
size_t getStorageLimit() const override { return dht_->getStorageLimit(); }
|
||||
void setLocalStorageLimit(size_t limit = 0) override { dht_->setLocalStorageLimit(limit); }
|
||||
size_t getLocalStorageLimit() const override { return dht_->getLocalStorageLimit(); }
|
||||
|
||||
std::vector<NodeExport> exportNodes() const override { return dht_->exportNodes(); }
|
||||
std::vector<ValuesExport> exportValues() const override { return dht_->exportValues(); }
|
||||
void importValues(const std::vector<ValuesExport>& v) override { dht_->importValues(v); }
|
||||
NodeStats getNodesStats(sa_family_t af) const override { return dht_->getNodesStats(af); }
|
||||
|
||||
NodeInfo getNodeInfo()
|
||||
{
|
||||
NodeInfo info;
|
||||
info.id = getId();
|
||||
info.node_id = getNodeId();
|
||||
info.ipv4 = getNodesStats(AF_INET);
|
||||
info.ipv6 = getNodesStats(AF_INET6);
|
||||
std::tie(info.storage_size, info.storage_values) = getStoreSize();
|
||||
std::tie(info.local_storage_size, info.local_storage_values) = getLocalStoreSize();
|
||||
if (auto sock = getSocket()) {
|
||||
info.bound4 = sock->getBoundRef(AF_INET).getPort();
|
||||
info.bound6 = sock->getBoundRef(AF_INET6).getPort();
|
||||
}
|
||||
return info;
|
||||
}
|
||||
std::string getStorageLog() const override {
|
||||
return dht_->getStorageLog();
|
||||
}
|
||||
std::string getStorageLog(const InfoHash& h) const override {
|
||||
return dht_->getStorageLog(h);
|
||||
}
|
||||
void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override {
|
||||
dht_->setStorageLimit(limit);
|
||||
}
|
||||
std::vector<NodeExport> exportNodes() const override {
|
||||
return dht_->exportNodes();
|
||||
}
|
||||
std::vector<ValuesExport> exportValues() const override {
|
||||
return dht_->exportValues();
|
||||
}
|
||||
void importValues(const std::vector<ValuesExport>& v) override {
|
||||
dht_->importValues(v);
|
||||
}
|
||||
NodeStats getNodesStats(sa_family_t af) const override {
|
||||
return dht_->getNodesStats(af);
|
||||
}
|
||||
std::vector<unsigned> getNodeMessageStats(bool in = false) override {
|
||||
return dht_->getNodeMessageStats(in);
|
||||
}
|
||||
std::string getRoutingTablesLog(sa_family_t af) const override {
|
||||
return dht_->getRoutingTablesLog(af);
|
||||
}
|
||||
std::string getSearchesLog(sa_family_t af) const override {
|
||||
return dht_->getSearchesLog(af);
|
||||
}
|
||||
std::string getSearchLog(const InfoHash& h, sa_family_t af = AF_UNSPEC) const override {
|
||||
|
||||
std::vector<unsigned> getNodeMessageStats(bool in = false) override { return dht_->getNodeMessageStats(in); }
|
||||
std::string getRoutingTablesLog(sa_family_t af) const override { return dht_->getRoutingTablesLog(af); }
|
||||
std::string getSearchesLog(sa_family_t af) const override { return dht_->getSearchesLog(af); }
|
||||
std::string getSearchLog(const InfoHash& h, sa_family_t af = AF_UNSPEC) const override
|
||||
{
|
||||
return dht_->getSearchLog(h, af);
|
||||
}
|
||||
std::vector<SockAddr> getPublicAddress(sa_family_t family = 0) override {
|
||||
return dht_->getPublicAddress(family);
|
||||
}
|
||||
time_point periodic(const uint8_t *buf, size_t buflen, SockAddr sa, const time_point& now) override {
|
||||
std::vector<SockAddr> getPublicAddress(sa_family_t family = 0) override { return dht_->getPublicAddress(family); }
|
||||
time_point periodic(const uint8_t* buf, size_t buflen, SockAddr sa, const time_point& now) override
|
||||
{
|
||||
return dht_->periodic(buf, buflen, std::move(sa), now);
|
||||
}
|
||||
time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override {
|
||||
time_point periodic(
|
||||
const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override
|
||||
{
|
||||
return dht_->periodic(buf, buflen, from, fromlen, now);
|
||||
}
|
||||
NodeStatus updateStatus(sa_family_t af) override {
|
||||
return dht_->updateStatus(af);
|
||||
}
|
||||
NodeStatus getStatus(sa_family_t af) const override {
|
||||
return dht_->getStatus(af);
|
||||
}
|
||||
NodeStatus getStatus() const override {
|
||||
return dht_->getStatus();
|
||||
}
|
||||
net::DatagramSocket* getSocket() const override {
|
||||
return dht_->getSocket();
|
||||
};
|
||||
bool isRunning(sa_family_t af = 0) const override {
|
||||
return dht_->isRunning(af);
|
||||
}
|
||||
const ValueType& getType(ValueType::Id type_id) const override {
|
||||
return dht_->getType(type_id);
|
||||
}
|
||||
void addBootstrap(const std::string& host, const std::string& service) override {
|
||||
NodeStatus updateStatus(sa_family_t af) override { return dht_->updateStatus(af); }
|
||||
NodeStatus getStatus(sa_family_t af) const override { return dht_->getStatus(af); }
|
||||
NodeStatus getStatus() const override { return dht_->getStatus(); }
|
||||
net::DatagramSocket* getSocket() const override { return dht_->getSocket(); };
|
||||
bool isRunning(sa_family_t af = 0) const override { return dht_->isRunning(af); }
|
||||
const ValueType& getType(ValueType::Id type_id) const override { return dht_->getType(type_id); }
|
||||
void addBootstrap(const std::string& host, const std::string& service) override
|
||||
{
|
||||
dht_->addBootstrap(host, service);
|
||||
}
|
||||
void clearBootstrap() override {
|
||||
dht_->clearBootstrap();
|
||||
}
|
||||
void insertNode(const InfoHash& id, const SockAddr& sa) override {
|
||||
dht_->insertNode(id, sa);
|
||||
}
|
||||
void insertNode(const NodeExport& n) override {
|
||||
dht_->insertNode(n);
|
||||
}
|
||||
void pingNode(SockAddr sa, DoneCallbackSimple&& cb={}) override {
|
||||
dht_->pingNode(std::move(sa), std::move(cb));
|
||||
}
|
||||
void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override {
|
||||
void clearBootstrap() override { dht_->clearBootstrap(); }
|
||||
void insertNode(const InfoHash& id, const SockAddr& sa) override { dht_->insertNode(id, sa); }
|
||||
void insertNode(const NodeExport& n) override { dht_->insertNode(n); }
|
||||
void pingNode(SockAddr sa, DoneCallbackSimple&& cb = {}) override { dht_->pingNode(std::move(sa), std::move(cb)); }
|
||||
void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override
|
||||
{
|
||||
dht_->query(key, cb, done_cb, std::move(q));
|
||||
}
|
||||
void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override {
|
||||
void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override
|
||||
{
|
||||
dht_->query(key, cb, done_cb, std::move(q));
|
||||
}
|
||||
std::vector<Sp<Value>> getLocal(const InfoHash& key, const Value::Filter& f = {}) const override {
|
||||
std::vector<Sp<Value>> getLocal(const InfoHash& key, const Value::Filter& f = {}) const override
|
||||
{
|
||||
return dht_->getLocal(key, f);
|
||||
}
|
||||
Sp<Value> getLocalById(const InfoHash& key, Value::Id vid) const override {
|
||||
return dht_->getLocalById(key, vid);
|
||||
}
|
||||
Sp<Value> getLocalById(const InfoHash& key, Value::Id vid) const override { return dht_->getLocalById(key, vid); }
|
||||
void put(const InfoHash& key,
|
||||
Sp<Value> v,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
Sp<Value> v,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
dht_->put(key, v, cb, created, permanent);
|
||||
}
|
||||
void put(const InfoHash& key,
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
const Sp<Value>& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
dht_->put(key, v, cb, created, permanent);
|
||||
}
|
||||
|
||||
void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallback cb=nullptr,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
Value&& v,
|
||||
DoneCallback cb = nullptr,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
dht_->put(key, std::move(v), cb, created, permanent);
|
||||
}
|
||||
void put(const InfoHash& key,
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created=time_point::max(),
|
||||
bool permanent = false) override
|
||||
Value&& v,
|
||||
DoneCallbackSimple cb,
|
||||
time_point created = time_point::max(),
|
||||
bool permanent = false) override
|
||||
{
|
||||
dht_->put(key, std::move(v), cb, created, permanent);
|
||||
}
|
||||
std::vector<Sp<Value>> getPut(const InfoHash& h) const override {
|
||||
return dht_->getPut(h);
|
||||
}
|
||||
Sp<Value> getPut(const InfoHash& h, const Value::Id& vid) const override {
|
||||
return dht_->getPut(h, vid);
|
||||
}
|
||||
bool cancelPut(const InfoHash& h, const Value::Id& vid) override {
|
||||
return dht_->cancelPut(h, vid);
|
||||
}
|
||||
std::vector<Sp<Value>> getPut(const InfoHash& h) const override { return dht_->getPut(h); }
|
||||
Sp<Value> getPut(const InfoHash& h, const Value::Id& vid) const override { return dht_->getPut(h, vid); }
|
||||
bool cancelPut(const InfoHash& h, const Value::Id& vid) override { return dht_->cancelPut(h, vid); }
|
||||
|
||||
size_t listen(const InfoHash& key, ValueCallback, Value::Filter={}, Where={}) override;
|
||||
size_t listen(const InfoHash& key, ValueCallback, Value::Filter = {}, Where = {}) override;
|
||||
size_t listen(const InfoHash& key, GetCallback cb, Value::Filter = {}, Where w = {}) override;
|
||||
size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w = {}) override {
|
||||
size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override
|
||||
{
|
||||
return listen(key, bindGetCb(cb), f, w);
|
||||
}
|
||||
bool cancelListen(const InfoHash& h, size_t token) override {
|
||||
return dht_->cancelListen(h, token);
|
||||
}
|
||||
void connectivityChanged(sa_family_t af) override {
|
||||
dht_->connectivityChanged(af);
|
||||
}
|
||||
void connectivityChanged() override {
|
||||
dht_->connectivityChanged();
|
||||
}
|
||||
bool cancelListen(const InfoHash& h, size_t token) override { return dht_->cancelListen(h, token); }
|
||||
void connectivityChanged(sa_family_t af) override { dht_->connectivityChanged(af); }
|
||||
void connectivityChanged() override { dht_->connectivityChanged(); }
|
||||
|
||||
void forwardAllMessages(bool forward) {
|
||||
forward_all_ = forward;
|
||||
}
|
||||
void forwardAllMessages(bool forward) { forward_all_ = forward; }
|
||||
|
||||
void setPushNotificationToken(const std::string& token = "") override {
|
||||
dht_->setPushNotificationToken(token);
|
||||
void setPushNotificationToken(const std::string& token = "") override { dht_->setPushNotificationToken(token); }
|
||||
void setPushNotificationTopic(const std::string& topic) override { dht_->setPushNotificationTopic(topic); }
|
||||
void setPushNotificationPlatform(const std::string& platform) override
|
||||
{
|
||||
dht_->setPushNotificationPlatform(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call linked callback with push_notification
|
||||
* @param notification to process
|
||||
*/
|
||||
void pushNotificationReceived(const std::map<std::string, std::string>& notification) override {
|
||||
dht_->pushNotificationReceived(notification);
|
||||
PushNotificationResult pushNotificationReceived(const std::map<std::string, std::string>& notification) override
|
||||
{
|
||||
return dht_->pushNotificationReceived(notification);
|
||||
}
|
||||
|
||||
void setLogger(const Logger& logger) override {
|
||||
DhtInterface::setLogger(logger);
|
||||
dht_->setLogger(logger);
|
||||
}
|
||||
|
||||
void setLogger(const std::shared_ptr<Logger>& logger) override {
|
||||
void setLogger(const std::shared_ptr<Logger>& logger) override
|
||||
{
|
||||
DhtInterface::setLogger(logger);
|
||||
dht_->setLogger(logger);
|
||||
}
|
||||
@@ -338,7 +308,8 @@ public:
|
||||
/**
|
||||
* Only print logs related to the given InfoHash (if given), or disable filter (if zeroes).
|
||||
*/
|
||||
void setLogFilter(const InfoHash& f) override {
|
||||
void setLogFilter(const InfoHash& f) override
|
||||
{
|
||||
DhtInterface::setLogFilter(f);
|
||||
dht_->setLogFilter(f);
|
||||
}
|
||||
@@ -353,6 +324,9 @@ private:
|
||||
ValueCallback getCallbackFilter(const ValueCallback&, Value::Filter&&);
|
||||
GetCallback getCallbackFilter(const GetCallback&, Value::Filter&&);
|
||||
|
||||
Sp<crypto::Certificate> registerCertificate(const InfoHash& node, const Blob& cert);
|
||||
Sp<crypto::Certificate> registerCertificate(const PkId& node, const Blob& cert);
|
||||
|
||||
Sp<crypto::PrivateKey> key_ {};
|
||||
Sp<crypto::Certificate> certificate_ {};
|
||||
|
||||
@@ -360,30 +334,34 @@ private:
|
||||
CertificateStoreQuery localQueryMethod_ {};
|
||||
|
||||
// our certificate cache
|
||||
std::map<InfoHash, Sp<crypto::Certificate>> nodesCertificates_ {};
|
||||
std::map<InfoHash, Sp<crypto::PublicKey>> nodesPubKeys_ {};
|
||||
std::map<PkId, Sp<crypto::Certificate>> nodesCertificates_ {};
|
||||
std::map<PkId, Sp<crypto::PublicKey>> nodesPubKeys_ {};
|
||||
|
||||
std::atomic_bool forward_all_ {false};
|
||||
bool enableCache_ {false};
|
||||
};
|
||||
|
||||
const ValueType CERTIFICATE_TYPE = {
|
||||
8, "Certificate", std::chrono::hours(24 * 7),
|
||||
// A certificate can only be stored at its public key ID.
|
||||
[](InfoHash id, Sp<Value>& v, const InfoHash&, const SockAddr&) {
|
||||
try {
|
||||
crypto::Certificate crt(v->data);
|
||||
// TODO check certificate signature
|
||||
return crt.getPublicKey().getId() == id;
|
||||
} catch (const std::exception& e) {}
|
||||
return false;
|
||||
},
|
||||
[](InfoHash, const Sp<Value>& o, Sp<Value>& n, const InfoHash&, const SockAddr&) {
|
||||
try {
|
||||
return crypto::Certificate(o->data).getPublicKey().getId() == crypto::Certificate(n->data).getPublicKey().getId();
|
||||
} catch (const std::exception& e) {}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
const ValueType CERTIFICATE_TYPE = {8,
|
||||
"Certificate",
|
||||
std::chrono::hours(24 * 7),
|
||||
// A certificate can only be stored at its public key ID.
|
||||
[](InfoHash id, Sp<Value>& v, const InfoHash&, const SockAddr&) {
|
||||
try {
|
||||
crypto::Certificate crt(v->data);
|
||||
// TODO check certificate signature
|
||||
return crt.getPublicKey().getId() == id
|
||||
|| InfoHash::get(crt.getPublicKey().getLongId()) == id;
|
||||
} catch (const std::exception& e) {
|
||||
}
|
||||
return false;
|
||||
},
|
||||
[](InfoHash, const Sp<Value>& o, Sp<Value>& n, const InfoHash&, const SockAddr&) {
|
||||
try {
|
||||
return crypto::Certificate(o->data).getPublicKey().getLongId()
|
||||
== crypto::Certificate(n->data).getPublicKey().getLongId();
|
||||
} catch (const std::exception& e) {
|
||||
}
|
||||
return false;
|
||||
}};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
+125
-88
@@ -1,25 +1,13 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
|
||||
#include <fmt/core.h>
|
||||
#include <fmt/format.h>
|
||||
#include <fmt/ostream.h>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
@@ -48,36 +36,41 @@ typedef uint16_t in_port_t;
|
||||
|
||||
namespace dht {
|
||||
|
||||
OPENDHT_PUBLIC void print_addr(std::ostream& os, const sockaddr* sa, socklen_t slen);
|
||||
OPENDHT_PUBLIC std::string print_addr(const sockaddr* sa, socklen_t slen);
|
||||
OPENDHT_PUBLIC std::string print_addr(const sockaddr_storage& ss, socklen_t sslen);
|
||||
|
||||
/**
|
||||
* A Socket Address (sockaddr*), with abstraction for IPv4, IPv6 address families.
|
||||
*/
|
||||
class OPENDHT_PUBLIC SockAddr {
|
||||
class OPENDHT_PUBLIC SockAddr
|
||||
{
|
||||
public:
|
||||
SockAddr() {}
|
||||
SockAddr(const SockAddr& o) {
|
||||
set(o.get(), o.getLength());
|
||||
}
|
||||
SockAddr(SockAddr&& o) noexcept : addr(std::move(o.addr)), len(o.len) {
|
||||
SockAddr(const SockAddr& o) { set(o.get(), o.getLength()); }
|
||||
SockAddr(SockAddr&& o) noexcept
|
||||
: addr(std::move(o.addr))
|
||||
, len(o.len)
|
||||
{
|
||||
o.len = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build from existing address.
|
||||
*/
|
||||
SockAddr(const sockaddr* sa, socklen_t length) {
|
||||
SockAddr(const sockaddr* sa, socklen_t length)
|
||||
{
|
||||
if (length > static_cast<socklen_t>(sizeof(sockaddr_storage)))
|
||||
throw std::runtime_error("Socket address length is too large");
|
||||
set(sa, length);
|
||||
}
|
||||
SockAddr(const sockaddr* sa) {
|
||||
SockAddr(const sockaddr* sa)
|
||||
{
|
||||
socklen_t len = 0;
|
||||
if (sa) {
|
||||
if (sa->sa_family == AF_INET)
|
||||
len = sizeof(sockaddr_in);
|
||||
else if(sa->sa_family == AF_INET6)
|
||||
else if (sa->sa_family == AF_INET6)
|
||||
len = sizeof(sockaddr_in6);
|
||||
else
|
||||
throw std::runtime_error("Unknown address family");
|
||||
@@ -88,34 +81,40 @@ public:
|
||||
/**
|
||||
* Build from an existing sockaddr_storage structure.
|
||||
*/
|
||||
SockAddr(const sockaddr_storage& ss, socklen_t len) : SockAddr((const sockaddr*)&ss, len) {}
|
||||
SockAddr(const sockaddr_storage& ss, socklen_t len)
|
||||
: SockAddr((const sockaddr*) &ss, len)
|
||||
{}
|
||||
|
||||
static std::vector<SockAddr> resolve(const std::string& host, const std::string& service = {});
|
||||
|
||||
bool operator<(const SockAddr& o) const {
|
||||
bool operator<(const SockAddr& o) const
|
||||
{
|
||||
if (len != o.len)
|
||||
return len < o.len;
|
||||
return std::memcmp((const uint8_t*)get(), (const uint8_t*)o.get(), len) < 0;
|
||||
return std::memcmp((const uint8_t*) get(), (const uint8_t*) o.get(), len) < 0;
|
||||
}
|
||||
|
||||
bool equals(const SockAddr& o) const {
|
||||
return len == o.len
|
||||
&& std::memcmp((const uint8_t*)get(), (const uint8_t*)o.get(), len) == 0;
|
||||
bool equals(const SockAddr& o) const
|
||||
{
|
||||
return len == o.len && std::memcmp((const uint8_t*) get(), (const uint8_t*) o.get(), len) == 0;
|
||||
}
|
||||
SockAddr& operator=(const SockAddr& o) {
|
||||
bool operator==(const SockAddr& o) const { return equals(o); }
|
||||
bool operator!=(const SockAddr& o) const { return !equals(o); }
|
||||
|
||||
SockAddr& operator=(const SockAddr& o)
|
||||
{
|
||||
set(o.get(), o.getLength());
|
||||
return *this;
|
||||
}
|
||||
SockAddr& operator=(SockAddr&& o) {
|
||||
SockAddr& operator=(SockAddr&& o)
|
||||
{
|
||||
len = o.len;
|
||||
o.len = 0;
|
||||
addr = std::move(o.addr);
|
||||
return *this;
|
||||
}
|
||||
|
||||
std::string toString() const {
|
||||
return print_addr(get(), getLength());
|
||||
}
|
||||
std::string toString() const { return print_addr(get(), getLength()); }
|
||||
|
||||
/**
|
||||
* Returns the address family or AF_UNSPEC if the address is not set.
|
||||
@@ -127,9 +126,10 @@ public:
|
||||
* in which case the sockaddr structure is cleared to zero,
|
||||
* and set the address family field (sa_family).
|
||||
*/
|
||||
void setFamily(sa_family_t af) {
|
||||
void setFamily(sa_family_t af)
|
||||
{
|
||||
socklen_t new_length;
|
||||
switch(af) {
|
||||
switch (af) {
|
||||
case AF_INET:
|
||||
new_length = sizeof(sockaddr_in);
|
||||
break;
|
||||
@@ -141,19 +141,22 @@ public:
|
||||
}
|
||||
if (new_length != len) {
|
||||
len = new_length;
|
||||
if (len) addr.reset((sockaddr*)::calloc(len, 1));
|
||||
else addr.reset();
|
||||
if (len)
|
||||
addr.reset((sockaddr*) ::calloc(len, 1));
|
||||
else
|
||||
addr.reset();
|
||||
}
|
||||
if (len)
|
||||
addr->sa_family = af;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Network Interface to any
|
||||
* Set address to any
|
||||
*/
|
||||
void setAny() {
|
||||
void setAny()
|
||||
{
|
||||
auto family = getFamily();
|
||||
switch(family) {
|
||||
switch (family) {
|
||||
case AF_INET:
|
||||
getIPv4().sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
break;
|
||||
@@ -163,12 +166,29 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set address to loopback.
|
||||
*/
|
||||
void setLoopback()
|
||||
{
|
||||
auto family = getFamily();
|
||||
switch (family) {
|
||||
case AF_INET:
|
||||
getIPv4().sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
break;
|
||||
case AF_INET6:
|
||||
getIPv6().sin6_addr = in6addr_loopback;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retreive the port (in host byte order) or 0 if the address is not
|
||||
* of a supported family.
|
||||
*/
|
||||
in_port_t getPort() const {
|
||||
switch(getFamily()) {
|
||||
in_port_t getPort() const
|
||||
{
|
||||
switch (getFamily()) {
|
||||
case AF_INET:
|
||||
return ntohs(getIPv4().sin_port);
|
||||
case AF_INET6:
|
||||
@@ -181,8 +201,9 @@ public:
|
||||
* Set the port. The address must be of a supported family.
|
||||
* @param p The port in host byte order.
|
||||
*/
|
||||
void setPort(in_port_t p) {
|
||||
switch(getFamily()) {
|
||||
void setPort(in_port_t p)
|
||||
{
|
||||
switch (getFamily()) {
|
||||
case AF_INET:
|
||||
getIPv4().sin_port = htons(p);
|
||||
break;
|
||||
@@ -207,9 +228,7 @@ public:
|
||||
/**
|
||||
* An address is defined to be true if its length is not zero.
|
||||
*/
|
||||
explicit operator bool() const noexcept {
|
||||
return len;
|
||||
}
|
||||
explicit operator bool() const noexcept { return len; }
|
||||
|
||||
/**
|
||||
* Returns the address to the managed sockaddr structure.
|
||||
@@ -223,17 +242,19 @@ public:
|
||||
*/
|
||||
sockaddr* get() { return addr.get(); }
|
||||
|
||||
inline const sockaddr_in& getIPv4() const {
|
||||
return *reinterpret_cast<const sockaddr_in*>(get());
|
||||
}
|
||||
inline const sockaddr_in6& getIPv6() const {
|
||||
return *reinterpret_cast<const sockaddr_in6*>(get());
|
||||
}
|
||||
inline sockaddr_in& getIPv4() {
|
||||
return *reinterpret_cast<sockaddr_in*>(get());
|
||||
}
|
||||
inline sockaddr_in6& getIPv6() {
|
||||
return *reinterpret_cast<sockaddr_in6*>(get());
|
||||
inline const sockaddr_in& getIPv4() const { return *reinterpret_cast<const sockaddr_in*>(get()); }
|
||||
inline const sockaddr_in6& getIPv6() const { return *reinterpret_cast<const sockaddr_in6*>(get()); }
|
||||
inline sockaddr_in& getIPv4() { return *reinterpret_cast<sockaddr_in*>(get()); }
|
||||
inline sockaddr_in6& getIPv6() { return *reinterpret_cast<sockaddr_in6*>(get()); }
|
||||
|
||||
/**
|
||||
* Releases the ownership of the managed object, if any.
|
||||
* The caller is responsible for deleting the object with free().
|
||||
*/
|
||||
inline sockaddr* release()
|
||||
{
|
||||
len = 0;
|
||||
return addr.release();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -256,47 +277,63 @@ public:
|
||||
* A comparator to classify IP addresses, only considering the
|
||||
* first 64 bits in IPv6.
|
||||
*/
|
||||
struct ipCmp {
|
||||
bool operator()(const SockAddr& a, const SockAddr& b) const {
|
||||
struct ipCmp
|
||||
{
|
||||
bool operator()(const SockAddr& a, const SockAddr& b) const
|
||||
{
|
||||
if (a.len != b.len)
|
||||
return a.len < b.len;
|
||||
socklen_t start, len;
|
||||
switch(a.getFamily()) {
|
||||
case AF_INET:
|
||||
start = offsetof(sockaddr_in, sin_addr);
|
||||
len = sizeof(in_addr);
|
||||
break;
|
||||
case AF_INET6:
|
||||
start = offsetof(sockaddr_in6, sin6_addr);
|
||||
// don't consider more than 64 bits (IPv6)
|
||||
len = 8;
|
||||
break;
|
||||
default:
|
||||
start = 0;
|
||||
len = a.len;
|
||||
break;
|
||||
switch (a.getFamily()) {
|
||||
case AF_INET:
|
||||
start = offsetof(sockaddr_in, sin_addr);
|
||||
len = sizeof(in_addr);
|
||||
break;
|
||||
case AF_INET6:
|
||||
start = offsetof(sockaddr_in6, sin6_addr);
|
||||
// don't consider more than 64 bits (IPv6)
|
||||
len = 8;
|
||||
break;
|
||||
default:
|
||||
start = 0;
|
||||
len = a.len;
|
||||
break;
|
||||
}
|
||||
return std::memcmp((uint8_t*)a.get()+start,
|
||||
(uint8_t*)b.get()+start, len) < 0;
|
||||
return std::memcmp((uint8_t*) a.get() + start, (uint8_t*) b.get() + start, len) < 0;
|
||||
}
|
||||
};
|
||||
friend std::ostream& operator<<(std::ostream& s, const SockAddr& h)
|
||||
{
|
||||
print_addr(s, h.get(), h.getLength());
|
||||
return s;
|
||||
}
|
||||
|
||||
private:
|
||||
struct free_delete { void operator()(void* p) { ::free(p); } };
|
||||
struct free_delete
|
||||
{
|
||||
void operator()(void* p) { ::free(p); }
|
||||
};
|
||||
std::unique_ptr<sockaddr, free_delete> addr {};
|
||||
socklen_t len {0};
|
||||
|
||||
void set(const sockaddr* sa, socklen_t length) {
|
||||
void set(const sockaddr* sa, socklen_t length)
|
||||
{
|
||||
if (len != length) {
|
||||
len = length;
|
||||
if (len) addr.reset((sockaddr*)::malloc(len));
|
||||
else addr.reset();
|
||||
if (len)
|
||||
addr.reset((sockaddr*) ::malloc(len));
|
||||
else
|
||||
addr.reset();
|
||||
}
|
||||
if (len)
|
||||
std::memcpy((uint8_t*)get(), (const uint8_t*)sa, len);
|
||||
std::memcpy((uint8_t*) get(), (const uint8_t*) sa, len);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
OPENDHT_PUBLIC bool operator==(const SockAddr& a, const SockAddr& b);
|
||||
} // namespace dht
|
||||
|
||||
}
|
||||
#if FMT_VERSION >= 90000
|
||||
template<>
|
||||
struct fmt::formatter<dht::SockAddr> : ostream_formatter
|
||||
{};
|
||||
#endif
|
||||
@@ -1,22 +1,5 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
*
|
||||
* Author: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
@@ -27,23 +10,27 @@
|
||||
#include <future>
|
||||
#include <functional>
|
||||
|
||||
#include <ciso646> // fix windows compiler bug
|
||||
#if __cplusplus < 202002L
|
||||
#include <ciso646>
|
||||
#endif
|
||||
|
||||
namespace dht {
|
||||
|
||||
class OPENDHT_PUBLIC ThreadPool {
|
||||
class OPENDHT_PUBLIC ThreadPool
|
||||
{
|
||||
public:
|
||||
static ThreadPool& computation();
|
||||
static ThreadPool& io();
|
||||
|
||||
ThreadPool();
|
||||
ThreadPool(size_t maxThreads);
|
||||
ThreadPool(unsigned minThreads, unsigned maxThreads = 0);
|
||||
~ThreadPool();
|
||||
|
||||
void run(std::function<void()>&& cb);
|
||||
|
||||
template<class T>
|
||||
std::future<T> get(std::function<T()>&& cb) {
|
||||
std::future<T> get(std::function<T()>&& cb)
|
||||
{
|
||||
auto ret = std::make_shared<std::promise<T>>();
|
||||
run([cb = std::move(cb), ret]() mutable {
|
||||
try {
|
||||
@@ -51,34 +38,46 @@ public:
|
||||
} catch (...) {
|
||||
try {
|
||||
ret->set_exception(std::current_exception());
|
||||
} catch(...) {}
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
});
|
||||
return ret->get_future();
|
||||
}
|
||||
template<class T>
|
||||
std::shared_future<T> getShared(std::function<T()>&& cb) {
|
||||
std::shared_future<T> getShared(std::function<T()>&& cb)
|
||||
{
|
||||
return get(std::move(cb));
|
||||
}
|
||||
|
||||
void stop();
|
||||
void stop(bool wait = true);
|
||||
void join();
|
||||
void detach();
|
||||
|
||||
private:
|
||||
std::mutex lock_ {};
|
||||
std::mutex lock_;
|
||||
std::condition_variable cv_ {};
|
||||
std::condition_variable stopCv_ {};
|
||||
std::queue<std::function<void()>> tasks_ {};
|
||||
std::vector<std::unique_ptr<std::thread>> threads_;
|
||||
unsigned readyThreads_ {0};
|
||||
bool running_ {true};
|
||||
bool stopping_ {false};
|
||||
|
||||
unsigned minThreads_;
|
||||
const unsigned maxThreads_;
|
||||
std::chrono::steady_clock::duration threadExpirationDelay {std::chrono::minutes(5)};
|
||||
double threadDelayRatio_ {2};
|
||||
|
||||
void threadEnded(std::thread&);
|
||||
};
|
||||
|
||||
class OPENDHT_PUBLIC Executor : public std::enable_shared_from_this<Executor> {
|
||||
class OPENDHT_PUBLIC Executor : public std::enable_shared_from_this<Executor>
|
||||
{
|
||||
public:
|
||||
Executor(ThreadPool& pool, unsigned maxConcurrent = 1)
|
||||
: threadPool_(pool), maxConcurrent_(maxConcurrent)
|
||||
: threadPool_(pool)
|
||||
, maxConcurrent_(maxConcurrent)
|
||||
{}
|
||||
|
||||
void run(std::function<void()>&& task);
|
||||
@@ -86,7 +85,7 @@ public:
|
||||
private:
|
||||
std::reference_wrapper<ThreadPool> threadPool_;
|
||||
const unsigned maxConcurrent_ {1};
|
||||
std::mutex lock_ {};
|
||||
std::mutex lock_;
|
||||
unsigned current_ {0};
|
||||
std::queue<std::function<void()>> tasks_ {};
|
||||
|
||||
@@ -94,33 +93,32 @@ private:
|
||||
void schedule();
|
||||
};
|
||||
|
||||
class OPENDHT_PUBLIC ExecutionContext {
|
||||
class OPENDHT_PUBLIC ExecutionContext
|
||||
{
|
||||
public:
|
||||
ExecutionContext(ThreadPool& pool)
|
||||
: threadPool_(pool), state_(std::make_shared<SharedState>())
|
||||
: threadPool_(pool)
|
||||
, state_(std::make_shared<SharedState>())
|
||||
{}
|
||||
|
||||
~ExecutionContext() {
|
||||
state_->destroy();
|
||||
}
|
||||
~ExecutionContext() { state_->destroy(); }
|
||||
|
||||
/** Wait for ongoing tasks to complete execution and drop other pending tasks */
|
||||
void stop() {
|
||||
state_->destroy(false);
|
||||
}
|
||||
void stop() { state_->destroy(false); }
|
||||
|
||||
void run(std::function<void()>&& task) {
|
||||
std::lock_guard<std::mutex> lock(state_->mtx);
|
||||
if (state_->shutdown_) return;
|
||||
void run(std::function<void()>&& task)
|
||||
{
|
||||
std::lock_guard lock(state_->mtx);
|
||||
if (state_->shutdown_)
|
||||
return;
|
||||
state_->pendingTasks++;
|
||||
threadPool_.get().run([task = std::move(task), state = state_] {
|
||||
state->run(task);
|
||||
});
|
||||
threadPool_.get().run([task = std::move(task), state = state_] { state->run(task); });
|
||||
}
|
||||
|
||||
private:
|
||||
struct SharedState {
|
||||
std::mutex mtx {};
|
||||
struct SharedState
|
||||
{
|
||||
std::mutex mtx;
|
||||
std::condition_variable cv {};
|
||||
unsigned pendingTasks {0};
|
||||
unsigned ongoingTasks {0};
|
||||
@@ -129,9 +127,11 @@ private:
|
||||
/** When true, prevents scheduled tasks to be executed */
|
||||
std::atomic_bool destroyed {false};
|
||||
|
||||
void destroy(bool wait = true) {
|
||||
std::unique_lock<std::mutex> lock(mtx);
|
||||
if (destroyed) return;
|
||||
void destroy(bool wait = true)
|
||||
{
|
||||
std::unique_lock lock(mtx);
|
||||
if (destroyed)
|
||||
return;
|
||||
if (wait) {
|
||||
cv.wait(lock, [this] { return pendingTasks == 0 && ongoingTasks == 0; });
|
||||
}
|
||||
@@ -142,16 +142,18 @@ private:
|
||||
destroyed = true;
|
||||
}
|
||||
|
||||
void run(const std::function<void()>& task) {
|
||||
void run(const std::function<void()>& task)
|
||||
{
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
std::lock_guard lock(mtx);
|
||||
pendingTasks--;
|
||||
ongoingTasks++;
|
||||
}
|
||||
if (destroyed) return;
|
||||
task();
|
||||
if (destroyed)
|
||||
return;
|
||||
task();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
std::lock_guard lock(mtx);
|
||||
ongoingTasks--;
|
||||
cv.notify_all();
|
||||
}
|
||||
@@ -161,4 +163,4 @@ private:
|
||||
std::shared_ptr<SharedState> state_;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace dht
|
||||
@@ -0,0 +1,219 @@
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
#include "infohash.h"
|
||||
#include "sockaddr.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include <array>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
|
||||
namespace dht {
|
||||
namespace transport {
|
||||
|
||||
constexpr size_t KEY_SIZE {32};
|
||||
constexpr size_t SIGNATURE_SIZE {64};
|
||||
using Key = std::array<uint8_t, KEY_SIZE>;
|
||||
using Signature = std::array<uint8_t, SIGNATURE_SIZE>;
|
||||
|
||||
/** Erases secret key material. */
|
||||
OPENDHT_PUBLIC void wipe(Key& key);
|
||||
|
||||
/**
|
||||
* X25519 key pair used to encrypt the DHT protocol: the static key of a node, from which its node ID derives,
|
||||
* or a periodically rotated ephemeral key.
|
||||
*/
|
||||
struct OPENDHT_PUBLIC KeyPair
|
||||
{
|
||||
Key secret {};
|
||||
Key pub {};
|
||||
|
||||
static KeyPair generate();
|
||||
static KeyPair fromSecret(const Key& secret);
|
||||
explicit operator bool() const { return pub != Key {}; }
|
||||
};
|
||||
|
||||
/** Node ID of a node using the transport public key `pub`. */
|
||||
OPENDHT_PUBLIC InfoHash nodeId(const Key& pub);
|
||||
|
||||
/** Secret from the system CSPRNG. */
|
||||
OPENDHT_PUBLIC Key randomSecret();
|
||||
|
||||
/** Ephemeral key pair used with the peer at `address` (IP and port), derived from an epoch secret. */
|
||||
OPENDHT_PUBLIC KeyPair addressKey(const Key& epochSecret, const uint8_t* address, size_t size);
|
||||
|
||||
/** Write token of the plaintext peer at `address` (IP and port), derived from an epoch secret. */
|
||||
OPENDHT_PUBLIC Key addressToken(const Key& epochSecret, const uint8_t* address, size_t size);
|
||||
|
||||
/** Non-expiring authority-signed grant binding a transport public key to a private network. */
|
||||
struct OPENDHT_PUBLIC Credential
|
||||
{
|
||||
static constexpr size_t PACKED_SIZE {1 + KEY_SIZE + SIGNATURE_SIZE};
|
||||
|
||||
Key key {};
|
||||
Signature signature {};
|
||||
|
||||
Blob pack() const;
|
||||
/** @throws std::invalid_argument if the data is not a packed credential */
|
||||
static Credential unpack(const uint8_t* data, size_t size);
|
||||
static Credential unpack(const Blob& b) { return unpack(b.data(), b.size()); }
|
||||
|
||||
/** True if signed by one of the trusted authorities. */
|
||||
bool verify(const std::vector<Key>& authorities) const;
|
||||
explicit operator bool() const { return key != Key {}; }
|
||||
};
|
||||
|
||||
/** Ed25519 key of a private network authority, issuing node credentials. */
|
||||
struct OPENDHT_PUBLIC Authority
|
||||
{
|
||||
Key secret {};
|
||||
Key pub {};
|
||||
|
||||
static Authority generate();
|
||||
static Authority fromSecret(const Key& secret);
|
||||
Credential issue(const Key& transportKey) const;
|
||||
};
|
||||
|
||||
/** Transport state of a remote node, attached to its Node. */
|
||||
struct Peer
|
||||
{
|
||||
explicit Peer(const Key& k)
|
||||
: key(k)
|
||||
{}
|
||||
const Key key;
|
||||
/** Last authenticated ephemeral key of the peer */
|
||||
std::optional<Key> ephemeral {};
|
||||
/** Address proven by the Session or Data envelope carrying the ephemeral key */
|
||||
SockAddr validatedAddress {};
|
||||
/** Private networks: the peer presented a grant from a trusted authority */
|
||||
bool authorized {false};
|
||||
/** Our session was lost: requests other than pings wait for a new ephemeral key */
|
||||
bool recovering {false};
|
||||
|
||||
void setEphemeral(const Key& k, const SockAddr& address = {})
|
||||
{
|
||||
ephemeral = k;
|
||||
validatedAddress = address;
|
||||
}
|
||||
void resetEphemeral()
|
||||
{
|
||||
ephemeral.reset();
|
||||
validatedAddress = {};
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* Envelope: marker | type | sender static key | sender ephemeral key | nonce | ChaCha20-Poly1305(payload) | tag
|
||||
* Data envelope: marker | type | nonce | ChaCha20-Poly1305(payload) | tag, keys found from the source address.
|
||||
* The marker is never a valid msgpack first byte, so legacy nodes drop envelopes.
|
||||
* Hello (private networks only, plaintext): marker | type | sender static key | sender ephemeral key | credential | message
|
||||
*/
|
||||
constexpr uint8_t ENVELOPE_MARKER {0xC1};
|
||||
/** Initial: the sender doesn't know the receiver ephemeral key. Session: it does. Data: the receiver has the session. */
|
||||
enum class EnvelopeType : uint8_t { Initial = 1, Session = 2, Hello = 3, Data = 4 };
|
||||
/** Type flag: the payload starts with the sender credential */
|
||||
constexpr uint8_t CREDENTIAL_FLAG {0x80};
|
||||
constexpr size_t NONCE_SIZE {12};
|
||||
constexpr size_t TAG_SIZE {16};
|
||||
constexpr size_t HEADER_SIZE {2 + 2 * KEY_SIZE};
|
||||
constexpr size_t DATA_HEADER_SIZE {2};
|
||||
constexpr size_t ENVELOPE_OVERHEAD {HEADER_SIZE + NONCE_SIZE + TAG_SIZE};
|
||||
constexpr size_t DATA_ENVELOPE_OVERHEAD {DATA_HEADER_SIZE + NONCE_SIZE + TAG_SIZE};
|
||||
constexpr size_t MAX_ENVELOPE_OVERHEAD {ENVELOPE_OVERHEAD + Credential::PACKED_SIZE};
|
||||
|
||||
inline bool
|
||||
isEnvelope(const uint8_t* data, size_t size)
|
||||
{
|
||||
return size >= DATA_HEADER_SIZE and data[0] == ENVELOPE_MARKER;
|
||||
}
|
||||
|
||||
struct Header
|
||||
{
|
||||
EnvelopeType type;
|
||||
bool credential;
|
||||
/* not in Data envelopes */
|
||||
Key sender;
|
||||
Key ephemeral;
|
||||
};
|
||||
|
||||
/** Envelope header, or nullopt if not an envelope of a known type. */
|
||||
OPENDHT_PUBLIC std::optional<Header> parseHeader(const uint8_t* data, size_t size);
|
||||
|
||||
/** Keys to send to and receive from a peer. */
|
||||
struct SessionKeys
|
||||
{
|
||||
Key tx;
|
||||
Key rx;
|
||||
|
||||
/** Erases secret key material. */
|
||||
void wipe()
|
||||
{
|
||||
transport::wipe(tx);
|
||||
transport::wipe(rx);
|
||||
}
|
||||
|
||||
/** Destructor that wipes secret key material. */
|
||||
~SessionKeys()
|
||||
{
|
||||
wipe();
|
||||
}
|
||||
};
|
||||
|
||||
/** Session keys with a peer whose ephemeral key is known, or nullopt for an invalid peer key. */
|
||||
OPENDHT_PUBLIC std::optional<SessionKeys> sessionKeys(
|
||||
const KeyPair& own, const KeyPair& ephemeral, const Key& peer, const Key& peerEphemeral, NetId network);
|
||||
|
||||
/** Key of an Initial envelope to `peer`, or nullopt for an invalid peer key. */
|
||||
OPENDHT_PUBLIC std::optional<Key> initialSendKey(const KeyPair& own,
|
||||
const KeyPair& ephemeral,
|
||||
const Key& peer,
|
||||
NetId network);
|
||||
|
||||
/** Key of an Initial envelope from `peer`, or nullopt for an invalid peer key. */
|
||||
OPENDHT_PUBLIC std::optional<Key> initialReceiveKey(const KeyPair& own,
|
||||
const Key& peer,
|
||||
const Key& peerEphemeral,
|
||||
NetId network);
|
||||
|
||||
/** Encrypts `credential || data`, authenticating the envelope header. */
|
||||
OPENDHT_PUBLIC Blob seal(const Key& key,
|
||||
EnvelopeType type,
|
||||
const Key& sender,
|
||||
const Key& ephemeral,
|
||||
const uint8_t* data,
|
||||
size_t size,
|
||||
const Blob& credential = {});
|
||||
|
||||
/** Encrypts `data` in a Data envelope. */
|
||||
OPENDHT_PUBLIC Blob sealData(const Key& key, const uint8_t* data, size_t size);
|
||||
|
||||
/** Decrypted payload, or nullopt if the envelope is not authentic. */
|
||||
OPENDHT_PUBLIC std::optional<Blob> open(const Key& key, const uint8_t* data, size_t size);
|
||||
|
||||
OPENDHT_PUBLIC Blob
|
||||
hello(const Key& sender, const Key& ephemeral, const Blob& credential, const uint8_t* data, size_t size);
|
||||
|
||||
} // namespace transport
|
||||
|
||||
/**
|
||||
* Encryption of the DHT protocol. Peers that don't support it keep talking in plaintext,
|
||||
* unless the node is part of a private network.
|
||||
*/
|
||||
struct TransportConfig
|
||||
{
|
||||
/** Advertise our key and encrypt traffic with nodes supporting it. Disabling uses a legacy random node ID. */
|
||||
bool enabled {true};
|
||||
/** Transport key. If empty, generated on start, and kept in the persisted state if Config::persist_path is set. */
|
||||
transport::KeyPair key {};
|
||||
/** Network authorities. If set, only nodes with a credential issued by one of them are accepted. */
|
||||
std::vector<transport::Key> authorities {};
|
||||
/** Credential of `key`, required for private networks. */
|
||||
transport::Credential credential {};
|
||||
|
||||
bool isPrivate() const { return not authorities.empty(); }
|
||||
};
|
||||
|
||||
} // namespace dht
|
||||
+103
-78
@@ -1,31 +1,18 @@
|
||||
/*
|
||||
* Copyright (C) 2014-2022 Savoir-faire Linux Inc.
|
||||
* Author : Adrien Béraud <adrien.beraud@savoirfairelinux.com>
|
||||
*
|
||||
* This program is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation; either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
|
||||
// SPDX-License-Identifier: MIT
|
||||
#pragma once
|
||||
|
||||
#include "def.h"
|
||||
|
||||
#include <type_traits>
|
||||
#include <msgpack.hpp>
|
||||
#include <fmt/format.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <random>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <string_view>
|
||||
|
||||
#include <cstdarg>
|
||||
|
||||
@@ -46,32 +33,49 @@ OPENDHT_PUBLIC const char* version();
|
||||
template<class T>
|
||||
using Sp = std::shared_ptr<T>;
|
||||
|
||||
template <typename Key, typename Item, typename Condition>
|
||||
void erase_if(std::map<Key, Item>& map, const Condition& condition)
|
||||
template<typename Key, typename Item, typename Condition>
|
||||
void
|
||||
erase_if(std::map<Key, Item>& map, const Condition& condition)
|
||||
{
|
||||
for (auto it = map.begin(); it != map.end(); ) {
|
||||
for (auto it = map.begin(); it != map.end();) {
|
||||
if (condition(*it)) {
|
||||
it = map.erase(it);
|
||||
} else { ++it; }
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template<typename... Args>
|
||||
std::string
|
||||
concat(Args&&... args)
|
||||
{
|
||||
static_assert((std::is_constructible_v<std::string_view, Args&&> && ...));
|
||||
std::string s;
|
||||
s.reserve((std::string_view {args}.size() + ...));
|
||||
(s.append(std::forward<Args>(args)), ...);
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Split "[host]:port" or "host:port" to pair<"host", "port">.
|
||||
*/
|
||||
OPENDHT_PUBLIC std::pair<std::string, std::string>
|
||||
splitPort(const std::string& s);
|
||||
OPENDHT_PUBLIC std::pair<std::string_view, std::string_view> splitPort(std::string_view s);
|
||||
|
||||
class OPENDHT_PUBLIC DhtException : public std::runtime_error {
|
||||
class OPENDHT_PUBLIC DhtException : public std::runtime_error
|
||||
{
|
||||
public:
|
||||
DhtException(const std::string &str = "") :
|
||||
std::runtime_error("DhtException occurred: " + str) {}
|
||||
DhtException(const std::string& str = "")
|
||||
: std::runtime_error("DhtException occurred: " + str)
|
||||
{}
|
||||
};
|
||||
|
||||
class OPENDHT_PUBLIC SocketException : public DhtException {
|
||||
class OPENDHT_PUBLIC SocketException : public DhtException
|
||||
{
|
||||
public:
|
||||
SocketException(int err) :
|
||||
DhtException(strerror(err)) {}
|
||||
SocketException(int err)
|
||||
: DhtException(strerror(err))
|
||||
{}
|
||||
};
|
||||
|
||||
// Time related definitions and utility functions
|
||||
@@ -81,64 +85,75 @@ using system_clock = std::chrono::system_clock;
|
||||
using time_point = clock::time_point;
|
||||
using duration = clock::duration;
|
||||
|
||||
time_point from_time_t(std::time_t t);
|
||||
std::time_t to_time_t(time_point t);
|
||||
OPENDHT_PUBLIC time_point from_system_time(system_clock::time_point t,
|
||||
time_point steady_now,
|
||||
system_clock::time_point system_now);
|
||||
OPENDHT_PUBLIC time_point from_system_time(system_clock::time_point t);
|
||||
OPENDHT_PUBLIC system_clock::time_point to_system_time(time_point t,
|
||||
time_point steady_now,
|
||||
system_clock::time_point system_now);
|
||||
OPENDHT_PUBLIC system_clock::time_point to_system_time(time_point t);
|
||||
OPENDHT_PUBLIC time_point from_time_t(std::time_t t);
|
||||
OPENDHT_PUBLIC std::time_t to_time_t(time_point t);
|
||||
|
||||
inline std::string
|
||||
to_str(double d) {
|
||||
char buf[16];
|
||||
auto ret = snprintf(buf, sizeof(buf), "%.3g", d);
|
||||
return (ret < 0) ? std::to_string(d) : std::string(buf, ret);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts std::chrono::duration to floating-point seconds.
|
||||
*/
|
||||
template <class DT>
|
||||
static double
|
||||
print_dt(DT d) {
|
||||
return std::chrono::duration_cast<std::chrono::duration<double>>(d).count();
|
||||
}
|
||||
|
||||
template <class DT>
|
||||
template<class DT>
|
||||
static std::string
|
||||
print_duration(DT d) {
|
||||
print_duration(DT d)
|
||||
{
|
||||
if (d < std::chrono::seconds(0)) {
|
||||
return "-" + print_duration(-d);
|
||||
} else if (d < std::chrono::milliseconds(1)) {
|
||||
return to_str(std::chrono::duration_cast<std::chrono::duration<double, std::micro>>(d).count()) + " us";
|
||||
return fmt::format("{:.3g} us",
|
||||
std::chrono::duration_cast<std::chrono::duration<double, std::micro>>(d).count());
|
||||
} else if (d < std::chrono::seconds(1)) {
|
||||
return to_str(std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(d).count()) + " ms";
|
||||
return fmt::format("{:.3g} ms",
|
||||
std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(d).count());
|
||||
} else if (d < std::chrono::minutes(1)) {
|
||||
return to_str(std::chrono::duration_cast<std::chrono::duration<double>>(d).count()) + " s";
|
||||
return fmt::format("{:.3g} s", std::chrono::duration_cast<std::chrono::duration<double>>(d).count());
|
||||
} else if (d < std::chrono::hours(1)) {
|
||||
return to_str(std::chrono::duration_cast<std::chrono::duration<double, std::ratio<60>>>(d).count()) + " min";
|
||||
return fmt::format("{:.3g} min",
|
||||
std::chrono::duration_cast<std::chrono::duration<double, std::ratio<60>>>(d).count());
|
||||
} else if (d < std::chrono::hours(72)) {
|
||||
return fmt::format("{:.3g} h",
|
||||
std::chrono::duration_cast<std::chrono::duration<double, std::ratio<3600>>>(d).count());
|
||||
} else {
|
||||
return to_str(std::chrono::duration_cast<std::chrono::duration<double, std::ratio<3600>>>(d).count()) + " h";
|
||||
return fmt::format("{:.3g} days",
|
||||
std::chrono::duration_cast<std::chrono::duration<double, std::ratio<86400>>>(d).count());
|
||||
}
|
||||
}
|
||||
|
||||
template <class TimePoint>
|
||||
template<class TimePoint>
|
||||
static std::string
|
||||
print_time_relative(TimePoint now, TimePoint d) {
|
||||
if (d == TimePoint::min()) return "never";
|
||||
if (d == now) return "now";
|
||||
return (d > now) ? std::string("in ") + print_duration(d - now)
|
||||
: print_duration(now - d) + std::string(" ago");
|
||||
print_time_relative(TimePoint now, TimePoint d)
|
||||
{
|
||||
using namespace std::literals;
|
||||
if (d == TimePoint::min())
|
||||
return "never"s;
|
||||
if (d == now)
|
||||
return "now"s;
|
||||
return (d > now) ? concat("in "sv, print_duration(d - now)) : concat(print_duration(now - d), " ago"sv);
|
||||
}
|
||||
|
||||
template <typename Duration = duration>
|
||||
class uniform_duration_distribution : public std::uniform_int_distribution<typename Duration::rep> {
|
||||
OPENDHT_PUBLIC std::string printByteCount(size_t bytes);
|
||||
|
||||
template<typename Duration = duration>
|
||||
class uniform_duration_distribution : public std::uniform_int_distribution<typename Duration::rep>
|
||||
{
|
||||
using Base = std::uniform_int_distribution<typename Duration::rep>;
|
||||
using param_type = typename Base::param_type;
|
||||
|
||||
public:
|
||||
uniform_duration_distribution(Duration min, Duration max) : Base(min.count(), max.count()) {}
|
||||
template <class Generator>
|
||||
Duration operator()(Generator && g) {
|
||||
uniform_duration_distribution(Duration min, Duration max)
|
||||
: Base(min.count(), max.count())
|
||||
{}
|
||||
template<class Generator>
|
||||
Duration operator()(Generator&& g)
|
||||
{
|
||||
return Duration(Base::operator()(g));
|
||||
}
|
||||
template< class Generator >
|
||||
Duration operator()( Generator && g, const param_type& params ) {
|
||||
template<class Generator>
|
||||
Duration operator()(Generator&& g, const param_type& params)
|
||||
{
|
||||
return Duration(Base::operator()(g, params));
|
||||
}
|
||||
};
|
||||
@@ -155,30 +170,40 @@ using Blob = std::vector<uint8_t>;
|
||||
*/
|
||||
OPENDHT_PUBLIC Blob unpackBlob(const msgpack::object& o);
|
||||
|
||||
template <typename Type>
|
||||
template<typename Type>
|
||||
Blob
|
||||
packMsg(const Type& t) {
|
||||
packMsg(const Type& t)
|
||||
{
|
||||
msgpack::sbuffer buffer;
|
||||
msgpack::packer<msgpack::sbuffer> pk(&buffer);
|
||||
pk.pack(t);
|
||||
return {buffer.data(), buffer.data()+buffer.size()};
|
||||
return {buffer.data(), buffer.data() + buffer.size()};
|
||||
}
|
||||
|
||||
template <typename Type>
|
||||
template<typename Type>
|
||||
Type
|
||||
unpackMsg(Blob b) {
|
||||
msgpack::unpacked msg_res = msgpack::unpack((const char*)b.data(), b.size());
|
||||
unpackMsg(const Blob& b)
|
||||
{
|
||||
msgpack::unpacked msg_res = msgpack::unpack((const char*) b.data(), b.size());
|
||||
return msg_res.get().as<Type>();
|
||||
}
|
||||
|
||||
msgpack::unpacked unpackMsg(Blob b);
|
||||
inline msgpack::unpacked
|
||||
unpackMsg(const Blob& b)
|
||||
{
|
||||
return msgpack::unpack((const char*) b.data(), b.size());
|
||||
}
|
||||
|
||||
msgpack::object* findMapValue(const msgpack::object& map, const char* key, size_t length);
|
||||
OPENDHT_PUBLIC msgpack::object* findMapValue(const msgpack::object& map, const char* key, size_t length);
|
||||
|
||||
inline msgpack::object* findMapValue(const msgpack::object& map, const char* key) {
|
||||
inline msgpack::object*
|
||||
findMapValue(const msgpack::object& map, const char* key)
|
||||
{
|
||||
return findMapValue(map, key, strlen(key));
|
||||
}
|
||||
inline msgpack::object* findMapValue(const msgpack::object& map, std::string_view key) {
|
||||
inline msgpack::object*
|
||||
findMapValue(const msgpack::object& map, std::string_view key)
|
||||
{
|
||||
return findMapValue(map, key.data(), key.size());
|
||||
}
|
||||
|
||||
|
||||
+405
-311
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+446
@@ -0,0 +1,446 @@
|
||||
project(
|
||||
'opendht',
|
||||
'c',
|
||||
'cpp',
|
||||
'cython',
|
||||
license: 'MIT',
|
||||
license_files: 'LICENSE',
|
||||
version: '4.4.99',
|
||||
meson_version: '>=1.1.0',
|
||||
default_options: ['cpp_std=c++20', 'warning_level=3'],
|
||||
)
|
||||
|
||||
gnutls = dependency('gnutls')
|
||||
nettle = dependency('nettle')
|
||||
hogweed = dependency('hogweed', version: '>=3.1')
|
||||
msgpack = dependency('msgpack-cxx', required: false)
|
||||
argon2 = dependency('libargon2')
|
||||
fmt = dependency('fmt')
|
||||
|
||||
proxy_enabled = get_option('proxy_client').enabled() or get_option('proxy_server').enabled()
|
||||
|
||||
openssl = dependency('openssl', required: proxy_enabled)
|
||||
jsoncpp = dependency('jsoncpp', required: proxy_enabled)
|
||||
llhttp = dependency('llhttp', 'libllhttp', required: proxy_enabled)
|
||||
simdutf = dependency('simdutf', required: proxy_enabled)
|
||||
|
||||
# restinio is a header-only library that may not ship a pkg-config file
|
||||
restinio_dep = dependency('restinio', required: false)
|
||||
if not restinio_dep.found()
|
||||
cpp = meson.get_compiler('cpp')
|
||||
if cpp.has_header('restinio/all.hpp', required: proxy_enabled)
|
||||
restinio_dep = declare_dependency()
|
||||
endif
|
||||
endif
|
||||
|
||||
io_uring = host_machine.system() == 'linux' ? dependency('liburing', required: false) : disabler()
|
||||
|
||||
deps = [
|
||||
fmt,
|
||||
gnutls,
|
||||
nettle,
|
||||
hogweed,
|
||||
msgpack,
|
||||
argon2,
|
||||
openssl,
|
||||
jsoncpp,
|
||||
simdutf,
|
||||
llhttp,
|
||||
]
|
||||
|
||||
if restinio_dep.found()
|
||||
deps += restinio_dep
|
||||
endif
|
||||
|
||||
if host_machine.system() == 'linux' and io_uring.found()
|
||||
deps += io_uring
|
||||
endif
|
||||
conf_data = configuration_data()
|
||||
|
||||
add_project_arguments('-DMSGPACK_NO_BOOST', '-DASIO_STANDALONE', language: 'cpp')
|
||||
if io_uring.found()
|
||||
add_project_arguments('-DASIO_HAS_IO_URING', '-DASIO_DISABLE_EPOLL', language: 'cpp')
|
||||
conf_data.set('iouring_lib', ', liburing')
|
||||
endif
|
||||
add_project_arguments(
|
||||
[
|
||||
'-Wno-return-type',
|
||||
'-Wno-deprecated',
|
||||
'-Wnon-virtual-dtor',
|
||||
'-pedantic-errors',
|
||||
'-fvisibility=hidden',
|
||||
],
|
||||
language: 'cpp',
|
||||
)
|
||||
|
||||
opendht_inc = include_directories('include/opendht')
|
||||
opendht_interface_inc = include_directories('include', is_system: true)
|
||||
opendht_src = [
|
||||
'src/utils.cpp',
|
||||
'src/crypto.cpp',
|
||||
'src/default_types.cpp',
|
||||
'src/node.cpp',
|
||||
'src/value.cpp',
|
||||
'src/dht.cpp',
|
||||
'src/callbacks.cpp',
|
||||
'src/routing_table.cpp',
|
||||
'src/node_cache.cpp',
|
||||
'src/network_engine.cpp',
|
||||
'src/transport.cpp',
|
||||
'src/securedht.cpp',
|
||||
'src/dhtrunner.cpp',
|
||||
'src/log.cpp',
|
||||
'src/op_cache.cpp',
|
||||
'src/network_utils.cpp',
|
||||
'src/thread_pool.cpp',
|
||||
]
|
||||
|
||||
if get_option('indexation').enabled()
|
||||
opendht_src += 'src/indexation/pht.cpp'
|
||||
add_project_arguments('-DOPENDHT_INDEXATION', language: 'cpp')
|
||||
endif
|
||||
if jsoncpp.found() and simdutf.found()
|
||||
opendht_src += ['src/base64.cpp']
|
||||
add_project_arguments('-DOPENDHT_JSONCPP', language: 'cpp')
|
||||
conf_data.set('jsoncpp_lib', ', jsoncpp')
|
||||
endif
|
||||
if llhttp.found()
|
||||
opendht_src += ['src/http.cpp', 'src/compat/os_cert.cpp']
|
||||
if host_machine.system() == 'darwin'
|
||||
deps += dependency('appleframeworks', modules: ['CoreFoundation', 'Security'])
|
||||
endif
|
||||
conf_data.set('http_lib', '-lllhttp')
|
||||
endif
|
||||
if openssl.found()
|
||||
conf_data.set('openssl_lib', ', openssl')
|
||||
endif
|
||||
if get_option('proxy_client').enabled()
|
||||
opendht_src += ['src/dht_proxy_client.cpp']
|
||||
add_project_arguments('-DOPENDHT_PROXY_CLIENT', language: 'cpp')
|
||||
endif
|
||||
if get_option('proxy_server').enabled()
|
||||
opendht_src += 'src/dht_proxy_server.cpp'
|
||||
add_project_arguments('-DOPENDHT_PROXY_SERVER', language: 'cpp')
|
||||
endif
|
||||
if get_option('push_notifications').enabled()
|
||||
add_project_arguments('-DOPENDHT_PUSH_NOTIFICATIONS', language: 'cpp')
|
||||
endif
|
||||
if get_option('peer_discovery').enabled()
|
||||
opendht_src += 'src/peer_discovery.cpp'
|
||||
add_project_arguments('-DOPENDHT_PEER_DISCOVERY', language: 'cpp')
|
||||
endif
|
||||
opendht = library(
|
||||
'opendht',
|
||||
opendht_src,
|
||||
include_directories: opendht_inc,
|
||||
dependencies: deps,
|
||||
cpp_args: ['-DOPENDHT_BUILD', '-Dopendht_EXPORTS'],
|
||||
install: true,
|
||||
)
|
||||
|
||||
opendht_dep_args = []
|
||||
if get_option('default_library') != 'static'
|
||||
opendht_dep_args += '-Dopendht_EXPORTS'
|
||||
endif
|
||||
|
||||
opendht_dep = declare_dependency(
|
||||
link_with: opendht,
|
||||
include_directories: opendht_interface_inc,
|
||||
compile_args: opendht_dep_args,
|
||||
)
|
||||
|
||||
# Install library headers.
|
||||
install_subdir('include', install_dir: get_option('includedir'), strip_directory: true)
|
||||
|
||||
conf_data.set('VERSION', meson.project_version())
|
||||
conf_data.set('prefix', get_option('prefix'))
|
||||
conf_data.set('exec_prefix', get_option('prefix'))
|
||||
conf_data.set('libdir', join_paths(get_option('prefix'), get_option('libdir')))
|
||||
conf_data.set('includedir', join_paths(get_option('prefix'), get_option('includedir')))
|
||||
conf_data.set('argon2_lib', ', libargon2')
|
||||
conf_data.set('simdutf_lib', ', simdutf')
|
||||
conf_data.set('opendht_public_cflags', '')
|
||||
conf_data.set('opendht_c_public_cflags', '')
|
||||
|
||||
if get_option('default_library') != 'static'
|
||||
conf_data.set('opendht_public_cflags', ' -Dopendht_EXPORTS')
|
||||
conf_data.set('opendht_c_public_cflags', ' -Dopendht_c_EXPORTS')
|
||||
endif
|
||||
|
||||
configure_file(
|
||||
input: 'opendht.pc.in',
|
||||
output: 'opendht.pc',
|
||||
configuration: conf_data,
|
||||
install: true,
|
||||
install_dir: join_paths(get_option('prefix'), get_option('libdir'), 'pkgconfig'),
|
||||
)
|
||||
|
||||
readline = meson.get_compiler('c').find_library('readline', required: get_option('tools'))
|
||||
|
||||
if get_option('c').enabled()
|
||||
opendht_c = library(
|
||||
'opendht-c',
|
||||
['c/opendht.cpp', 'c/opendht_c.h'],
|
||||
dependencies: [opendht_dep, msgpack, jsoncpp, fmt],
|
||||
cpp_args: ['-DOPENDHT_C_BUILD', '-Dopendht_c_EXPORTS'],
|
||||
install: true,
|
||||
)
|
||||
|
||||
install_headers('c/opendht_c.h', subdir: 'opendht')
|
||||
|
||||
configure_file(
|
||||
input: 'opendht-c.pc.in',
|
||||
output: 'opendht-c.pc',
|
||||
configuration: conf_data,
|
||||
install: true,
|
||||
install_dir: join_paths(get_option('prefix'), get_option('libdir'), 'pkgconfig'),
|
||||
)
|
||||
|
||||
if get_option('tools').enabled()
|
||||
dhtcnode = executable(
|
||||
'dhtcnode',
|
||||
'tools/dhtcnode.c',
|
||||
include_directories: ['c', opendht_interface_inc],
|
||||
link_with: opendht_c,
|
||||
dependencies: [readline],
|
||||
install: true,
|
||||
)
|
||||
endif
|
||||
endif
|
||||
|
||||
rust_option = get_option('rust').require(
|
||||
get_option('c').enabled(),
|
||||
error_message: 'rust requires c',
|
||||
).require(
|
||||
get_option('default_library') != 'static',
|
||||
error_message: 'rust requires shared libraries',
|
||||
)
|
||||
if rust_option.allowed()
|
||||
cargo = find_program('cargo', required: rust_option)
|
||||
if cargo.found()
|
||||
rust_env = environment()
|
||||
rust_env.prepend('LIBRARY_PATH', meson.current_build_dir())
|
||||
rust_env.prepend('LD_LIBRARY_PATH', meson.current_build_dir())
|
||||
rust_env.prepend('DYLD_LIBRARY_PATH', meson.current_build_dir())
|
||||
rust_env.prepend('PATH', meson.current_build_dir())
|
||||
cargo_args = [
|
||||
'--manifest-path', meson.current_source_dir() / 'rust/Cargo.toml',
|
||||
'--target-dir', meson.current_build_dir() / 'rust',
|
||||
]
|
||||
rust_build = custom_target(
|
||||
'rust-bindings',
|
||||
output: 'rust-build.json',
|
||||
command: [cargo, 'build', '--lib', '--examples', '--message-format=json-render-diagnostics'] + cargo_args,
|
||||
env: rust_env,
|
||||
depends: opendht_c,
|
||||
capture: true,
|
||||
build_by_default: true,
|
||||
build_always_stale: true,
|
||||
)
|
||||
if get_option('tests').enabled()
|
||||
test(
|
||||
'Rust',
|
||||
cargo,
|
||||
args: ['test'] + cargo_args,
|
||||
env: rust_env,
|
||||
depends: rust_build,
|
||||
timeout: 120,
|
||||
)
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
if get_option('python').require(
|
||||
get_option('indexation').enabled(),
|
||||
error_message: 'python requires indexation',
|
||||
).allowed()
|
||||
py = import('python').find_installation(pure: false)
|
||||
dep_py = py.dependency()
|
||||
py.extension_module(
|
||||
'_core',
|
||||
'python/opendht.pyx',
|
||||
subdir: 'opendht',
|
||||
cython_args: ['--module-name', 'opendht._core'],
|
||||
override_options: ['cython_language=cpp'],
|
||||
dependencies: [opendht_dep, msgpack, jsoncpp, fmt, dep_py],
|
||||
install: true,
|
||||
)
|
||||
py.install_sources(
|
||||
'python/opendht/__init__.py',
|
||||
'python/opendht/aio.py',
|
||||
subdir: 'opendht',
|
||||
)
|
||||
endif
|
||||
|
||||
if get_option('tools').enabled()
|
||||
dhtnode = executable(
|
||||
'dhtnode',
|
||||
'tools/dhtnode.cpp',
|
||||
dependencies: [opendht_dep, readline, jsoncpp, msgpack, fmt, openssl],
|
||||
install: true,
|
||||
)
|
||||
dhtchat = executable(
|
||||
'dhtchat',
|
||||
'tools/dhtchat.cpp',
|
||||
dependencies: [opendht_dep, readline, jsoncpp, msgpack, fmt, openssl],
|
||||
install: true,
|
||||
)
|
||||
dhtscanner = executable(
|
||||
'dhtscanner',
|
||||
'tools/dhtscanner.cpp',
|
||||
dependencies: [opendht_dep, readline, jsoncpp, msgpack, fmt, openssl],
|
||||
install: true,
|
||||
)
|
||||
if llhttp.found()
|
||||
durl_deps = [msgpack, openssl]
|
||||
|
||||
if io_uring.found()
|
||||
durl_deps += io_uring
|
||||
endif
|
||||
|
||||
durl = executable(
|
||||
'durl',
|
||||
'tools/durl.cpp',
|
||||
dependencies: [opendht_dep] + durl_deps,
|
||||
)
|
||||
endif
|
||||
endif
|
||||
|
||||
# Unit tests
|
||||
if get_option('tests').enabled()
|
||||
if get_option('c').enabled()
|
||||
test_c = executable(
|
||||
'test_c',
|
||||
'tests/test_c.c',
|
||||
include_directories: ['c', opendht_interface_inc],
|
||||
dependencies: [gnutls],
|
||||
link_with: opendht_c,
|
||||
)
|
||||
test('CBindings', test_c)
|
||||
endif
|
||||
cppunit = dependency('cppunit')
|
||||
|
||||
test_infohash = executable(
|
||||
'test_infohash',
|
||||
'tests/test_infohash.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('Infohash', test_infohash)
|
||||
|
||||
test_value = executable(
|
||||
'test_value',
|
||||
'tests/test_value.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('Value', test_value)
|
||||
|
||||
test_parsedmessage = executable(
|
||||
'test_parsedmessage',
|
||||
'tests/test_parsedmessage.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
include_directories: opendht_inc,
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('ParsedMessage', test_parsedmessage)
|
||||
|
||||
test_networkengine = executable(
|
||||
'test_networkengine',
|
||||
'tests/test_networkengine.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
include_directories: opendht_inc,
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('NetworkEngine', test_networkengine)
|
||||
|
||||
test_opcache = executable(
|
||||
'test_opcache',
|
||||
'tests/test_opcache.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
include_directories: opendht_inc,
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('OpCache', test_opcache)
|
||||
|
||||
test_valuecache = executable(
|
||||
'test_valuecache',
|
||||
'tests/test_valuecache.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
include_directories: opendht_inc,
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('ValueCache', test_valuecache)
|
||||
|
||||
test_crypto = executable(
|
||||
'test_crypto',
|
||||
'tests/test_crypto.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack, gnutls],
|
||||
)
|
||||
test('Crypto', test_crypto, timeout: 60)
|
||||
|
||||
test_transport = executable(
|
||||
'test_transport',
|
||||
'tests/test_transport.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('Transport', test_transport)
|
||||
|
||||
test_dhtrunner = executable(
|
||||
'test_dhtrunner',
|
||||
'tests/test_dhtrunner.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('DhtRunner', test_dhtrunner, timeout: 60)
|
||||
|
||||
test_threadpool = executable(
|
||||
'test_threadpool',
|
||||
'tests/test_threadpool.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('ThreadPool', test_threadpool)
|
||||
|
||||
if get_option('proxy_client').enabled() or get_option('proxy_server').enabled()
|
||||
test_http = executable(
|
||||
'test_http',
|
||||
'tests/test_http.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('Http', test_http)
|
||||
endif
|
||||
|
||||
if get_option('peer_discovery').enabled()
|
||||
test_peerdiscovery = executable(
|
||||
'test_peerdiscovery',
|
||||
'tests/test_peerdiscovery.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('PeerDiscovery', test_peerdiscovery)
|
||||
endif
|
||||
|
||||
if get_option('proxy_server').enabled()
|
||||
test_proxy = executable(
|
||||
'test_dhtproxy',
|
||||
'tests/test_dhtproxy.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('DhtProxy', test_proxy)
|
||||
|
||||
if get_option('long_tests').enabled()
|
||||
test_proxystress = executable(
|
||||
'test_dhtproxystress',
|
||||
'tests/dhtproxy_stress_tester.cpp',
|
||||
'tests/tests_runner.cpp',
|
||||
dependencies: [opendht_dep, cppunit, jsoncpp, fmt, openssl, msgpack],
|
||||
)
|
||||
test('DhtProxy Stress', test_proxystress)
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
@@ -0,0 +1,11 @@
|
||||
option('proxy_client', type : 'feature', value : 'disabled')
|
||||
option('proxy_server', type : 'feature', value : 'disabled')
|
||||
option('push_notifications', type : 'feature', value : 'disabled')
|
||||
option('peer_discovery', type : 'feature', value : 'enabled')
|
||||
option('tools', type : 'feature', value : 'enabled')
|
||||
option('c', type : 'feature', value : 'enabled')
|
||||
option('rust', type : 'feature', value : 'disabled')
|
||||
option('indexation', type : 'feature', value : 'enabled')
|
||||
option('python', type : 'feature', value : 'enabled')
|
||||
option('tests', type : 'feature', value : 'enabled')
|
||||
option('long_tests', type : 'feature', value : 'disabled')
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
build*/
|
||||
prebuilds/
|
||||
dist/
|
||||
examples/dhtnode.js
|
||||
@@ -0,0 +1,64 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(opendht_node LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
set(OPENDHT_TOOLS OFF CACHE BOOL "Build DHT tools")
|
||||
set(OPENDHT_PYTHON OFF CACHE BOOL "Build Python bindings")
|
||||
set(OPENDHT_PROXY_CLIENT ON CACHE BOOL "Enable DHT proxy client")
|
||||
set(OPENDHT_PEER_DISCOVERY OFF CACHE BOOL "Enable multicast peer discovery")
|
||||
set(OPENDHT_DOCUMENTATION OFF CACHE BOOL "Build documentation")
|
||||
set(BUILD_TESTING OFF CACHE BOOL "Build native tests")
|
||||
add_subdirectory(.. native EXCLUDE_FROM_ALL)
|
||||
|
||||
find_program(NODE_EXECUTABLE node REQUIRED)
|
||||
execute_process(
|
||||
COMMAND "${NODE_EXECUTABLE}" --input-type=module -e "import addon from 'node-addon-api'; process.stdout.write(addon.include_dir)"
|
||||
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
OUTPUT_VARIABLE NODE_ADDON_API_DIR
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE
|
||||
COMMAND_ERROR_IS_FATAL ANY
|
||||
)
|
||||
|
||||
add_library(opendht_node MODULE addon.cpp crypto.cpp ${CMAKE_JS_SRC})
|
||||
target_compile_definitions(opendht_node PRIVATE NAPI_VERSION=8 NAPI_CPP_EXCEPTIONS)
|
||||
target_include_directories(opendht_node PRIVATE
|
||||
${CMAKE_JS_INC}
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/${NODE_ADDON_API_DIR}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../include"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/native/include"
|
||||
)
|
||||
target_link_libraries(opendht_node PRIVATE opendht ${CMAKE_JS_LIB})
|
||||
if(OPENDHT_SANITIZE AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
target_compile_options(opendht_node PRIVATE -fsanitize=address -fstack-protector-strong)
|
||||
target_link_options(opendht_node PRIVATE -fsanitize=address)
|
||||
endif()
|
||||
set_target_properties(opendht_node PROPERTIES
|
||||
PREFIX ""
|
||||
SUFFIX ".node"
|
||||
OUTPUT_NAME "opendht"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/$<CONFIG>"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/$<CONFIG>"
|
||||
)
|
||||
if(APPLE)
|
||||
target_link_options(opendht_node PRIVATE "-undefined" "dynamic_lookup")
|
||||
endif()
|
||||
if(WIN32)
|
||||
add_custom_command(TARGET opendht_node POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different
|
||||
$<TARGET_RUNTIME_DLLS:opendht_node> $<TARGET_FILE_DIR:opendht_node>
|
||||
COMMAND_EXPAND_LISTS
|
||||
)
|
||||
endif()
|
||||
if(MSVC)
|
||||
target_compile_options(opendht_node PRIVATE /EHsc)
|
||||
target_include_directories(opendht_node PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../src/compat/msvc"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../src/compat/win32"
|
||||
)
|
||||
if(CMAKE_JS_NODELIB_DEF AND CMAKE_JS_NODELIB_TARGET)
|
||||
execute_process(COMMAND ${CMAKE_AR} /def:${CMAKE_JS_NODELIB_DEF}
|
||||
/out:${CMAKE_JS_NODELIB_TARGET} ${CMAKE_STATIC_LINKER_FLAGS})
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,243 @@
|
||||
# OpenDHT Node.js Bindings
|
||||
|
||||
Initial Node-API bindings using `node-addon-api` directly over the C++ library.
|
||||
Node.js 22.9 or later is required; the addon targets Node-API version 8.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
npm install opendht
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
Install the native dependencies described in [BUILD.md](../BUILD.md), plus Node.js,
|
||||
a C++17 compiler, and CMake 3.21 or later. Ninja is optional. Proxy-client support
|
||||
defaults to enabled and requires ASIO, llhttp, RESTinio, and expected-lite headers.
|
||||
|
||||
```sh
|
||||
cd nodejs
|
||||
npm ci
|
||||
npm run build
|
||||
npm test
|
||||
npm run typecheck
|
||||
```
|
||||
|
||||
CMake.js builds OpenDHT from the parent source directory in `nodejs/build/native`.
|
||||
It does not change the repository's existing build directory. Tools, Python,
|
||||
peer discovery, documentation, and native tests default to disabled in this build.
|
||||
Native CMake options can be passed through, for example:
|
||||
|
||||
```sh
|
||||
npm run build -- --CDOPENDHT_PEER_DISCOVERY=ON
|
||||
```
|
||||
|
||||
For an existing build, change cached options directly with CMake, for example
|
||||
`cmake -S . -B build -DOPENDHT_PROXY_CLIENT=ON`, then rebuild. A custom build can
|
||||
disable proxy support with `-DOPENDHT_PROXY_CLIENT=OFF`; requesting a proxy then
|
||||
throws an explicit unsupported-build error.
|
||||
|
||||
The loader checks local builds, then compatible Node-API binaries under `prebuilds/`.
|
||||
Set `OPENDHT_NODE_BINDING` to an absolute addon path to select an explicit build.
|
||||
Packaged binaries include OpenDHT and non-system native dependencies, so archive
|
||||
installation does not require a compiler or a system OpenDHT installation.
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
import { DhtRunner, hash } from 'opendht';
|
||||
|
||||
async function main() {
|
||||
const writer = new DhtRunner();
|
||||
const reader = new DhtRunner();
|
||||
try {
|
||||
writer.run({ port: 0, ipv4: '127.0.0.1', ipv6: '::1' });
|
||||
reader.run({ port: 0, ipv4: '127.0.0.1', ipv6: '::1' });
|
||||
writer.bootstrap('127.0.0.1', reader.getBoundPort());
|
||||
reader.bootstrap('127.0.0.1', writer.getBoundPort());
|
||||
const key = hash('example');
|
||||
const stored = await writer.put(key, Buffer.from('hello'), { id: 42n });
|
||||
if (!stored) throw new Error('DHT put failed');
|
||||
for await (const value of reader.get(key)) {
|
||||
console.log(value.id, value.data.toString());
|
||||
}
|
||||
} finally {
|
||||
await Promise.all([writer.close(), reader.close()]);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
- `hash(string | Uint8Array)` returns a SHA-1 hash as a 40-character hex string.
|
||||
All get/put/listen keys must be hex hashes, not unhashed application keys.
|
||||
- `version` is the underlying OpenDHT version.
|
||||
- `run({port, ipv4, ipv6, network, persistPath, identity})` starts a threaded node. Port 0
|
||||
selects a free port. The defaults bind both IP families on all interfaces.
|
||||
`persistPath` is optional; use an empty string to disable persistence.
|
||||
`proxyServer` and `proxyUserAgent` configure proxy mode (see below).
|
||||
- `getBoundPort(4 | 6)` defaults to IPv4; `getNodeId()` returns the node's hex ID.
|
||||
- `getStatus()` returns the latest JS-dispatched `{ipv4, ipv6}` connectivity
|
||||
snapshot. Each family is `'disconnected'`, `'connecting'`, or `'connected'`.
|
||||
`runner.on('statusChanged', status => {})` receives changes on the JS thread.
|
||||
New and closing/closed runners report both families as disconnected. No status
|
||||
events are delivered after close begins; close does not emit a final event.
|
||||
- `bootstrap(host, port)` queues bootstrap discovery. Returning does not mean the
|
||||
peer is connected; subsequent DHT operations report their own completion.
|
||||
- `put(key, Uint8Array, {id, type, userType, permanent})` copies the input and
|
||||
resolves to the native success boolean. IDs are unsigned 64-bit `bigint` values.
|
||||
- `get(key)` returns an async iterator of values as they arrive. The iterator
|
||||
ends when the lookup completes, or rejects with `ERR_DHT_GET_FAILED` on failure.
|
||||
`getAll(key)` returns a single promise resolving to the complete value array.
|
||||
Values contain `id`, `type`, `seq`, `userType`, copied `Buffer` data, `isSigned`,
|
||||
`isEncrypted`, and an `owner` long fingerprint (or null for unsigned values).
|
||||
- `listen(key, (value, expired) => {})` returns a listener with idempotent
|
||||
`cancel()`. Queued deliveries are suppressed after cancellation. Callback
|
||||
return values are ignored; callbacks may cancel or close the runner.
|
||||
- `listen(key)` without a callback returns an async iterator of `{value, expired}`
|
||||
events. It continues until cancelled or the runner closes.
|
||||
- `close()` is idempotent and returns the same promise on repeated calls. It
|
||||
waits off the JS thread for graceful shutdown, then joins the native threads.
|
||||
After two seconds it forces the join if graceful shutdown has not completed.
|
||||
Pending operations reject with `ERR_DHT_CLOSED`. A closed runner cannot restart.
|
||||
- `ref()` and `unref()` control whether the runner keeps Node's event loop alive.
|
||||
Running nodes are referenced by default. `Symbol.asyncDispose` calls `close()`.
|
||||
|
||||
Callbacks run only on their owning JS thread. There is no polling timer or worker
|
||||
thread waiting on each get/put. Explicitly close runners; GC cleanup and Node
|
||||
environment cleanup hooks are fallbacks, including forced worker termination.
|
||||
Pending operations, active listeners, and registered status handlers keep their
|
||||
runner alive until completion, cancellation, handler removal, or explicit close.
|
||||
Graceful persistence cannot be guaranteed if the process is killed.
|
||||
|
||||
The binding does not cap the callback queue, accumulated `getAll()` results, or
|
||||
iterator buffers. Slow iterator consumers can accumulate values without
|
||||
backpressure. Queued callbacks retain their native values until delivery or cleanup.
|
||||
|
||||
## Async Iteration
|
||||
|
||||
`get()` and callback-free `listen()` start immediately and return iterators with
|
||||
`next()`, `return()`, `throw()`, `cancel()`, and `Symbol.asyncDispose`.
|
||||
Leaving a `for await` loop with `break` or an exception cancels the subscription.
|
||||
Explicit cancellation discards buffered values and settles pending reads as done.
|
||||
Closing the runner rejects active get iterators with `ERR_DHT_CLOSED`; listener
|
||||
iterators end normally. Successful get completion preserves unread buffered values.
|
||||
|
||||
```js
|
||||
for await (const value of runner.get(hash('example'))) {
|
||||
console.log(value.id, value.data);
|
||||
}
|
||||
const snapshots = await runner.getAll(hash('example'));
|
||||
|
||||
for await (const { value, expired } of runner.listen(hash('updates'))) {
|
||||
console.log(value.id, expired);
|
||||
if (expired) break;
|
||||
}
|
||||
```
|
||||
|
||||
## Proxy Configuration
|
||||
|
||||
Pass the URL of an OpenDHT HTTP(S) proxy at startup:
|
||||
|
||||
```js
|
||||
runner.run({
|
||||
proxyServer: 'https://proxy.example.com',
|
||||
proxyUserAgent: 'my-app/1.0',
|
||||
});
|
||||
```
|
||||
|
||||
This selects the native OpenDHT proxy client, not an HTTP CONNECT or SOCKS proxy.
|
||||
The node does not bind UDP sockets in this mode; `port`, `ipv4`, `ipv6`, and
|
||||
`bootstrap()` are for direct DHT nodes. Omit `proxyServer` or use an empty string
|
||||
for direct networking. Proxy settings are startup-only; create a new runner to
|
||||
change transports or servers. Packaged binaries include proxy-client support.
|
||||
|
||||
## Crypto
|
||||
|
||||
`PrivateKey.generate(options)` and `Identity.generate(name, options)` return
|
||||
promises and generate keys off the JS thread. Options accept `algorithm: 'ec'`
|
||||
(the default, using OpenDHT's default EC curve) or `'rsa'`. RSA `bits` must be an
|
||||
integer between 2048 and 8192; the default is 2048.
|
||||
|
||||
- `new PrivateKey(bytes, password?)` imports PEM/DER; `serialize(password?)`
|
||||
exports PKCS#8 PEM. A nonempty password encrypts the exported key.
|
||||
- `privateKey.getPublicKey()` returns an owned public key. `sign(bytes)` and
|
||||
`decrypt(bytes)` return copied Buffers.
|
||||
- `new PublicKey(bytes)` imports a public key; `serialize()` exports DER.
|
||||
`checkSignature(data, signature)` returns a boolean. `encrypt(bytes)` requires
|
||||
an RSA key; EC keys support signatures, not this encryption scheme.
|
||||
- `new Certificate(bytes)` imports PEM/DER or a PEM certificate chain;
|
||||
`serialize()` exports a PEM chain. Import does not establish trust or validate
|
||||
the chain against a trust store. `getPublicKey()` returns its public key.
|
||||
- Public keys and certificates expose `getId()` (40 hex characters) and
|
||||
`getLongId()` (64 hex characters).
|
||||
- `new Identity(privateKey, certificate)` requires matching fingerprints.
|
||||
Its read-only `privateKey` and `certificate` properties return owned wrappers.
|
||||
- Pass `identity` to `run()` to enable `putSigned(key, data, options?)` and
|
||||
`putEncrypted(key, data, recipientPublicKey, options?)`. Both return the same
|
||||
success boolean as `put()`. Encrypted values are signed by the sender and
|
||||
transparently decrypted for the recipient by OpenDHT's get/listen layer.
|
||||
|
||||
```js
|
||||
import { Identity, DhtRunner } from 'opendht';
|
||||
|
||||
async function createAuthenticatedNode() {
|
||||
const identity = await Identity.generate('example', { algorithm: 'rsa', bits: 2048 });
|
||||
const runner = new DhtRunner();
|
||||
runner.run({ port: 0, identity });
|
||||
return { runner, identity };
|
||||
}
|
||||
```
|
||||
|
||||
Crypto methods take Uint8Array/Buffer inputs, not implicit text encodings. Imports
|
||||
must be nonempty. Malformed handles/data,
|
||||
mismatched identities, and unsupported encryption keys raise JS exceptions.
|
||||
Only generation is asynchronous; import/export/sign/encrypt/decrypt are
|
||||
synchronous and should be used from worker threads for large workloads.
|
||||
|
||||
## Packaging And CI
|
||||
|
||||
From a successful Release build:
|
||||
|
||||
```sh
|
||||
npm run package
|
||||
npm run test:package
|
||||
```
|
||||
|
||||
`bundle` copies the addon into `prebuilds/<platform>-<arch>/`, gathers its runtime
|
||||
dependencies, rewrites native loader paths, and copies dependency license
|
||||
notices. macOS needs `dylibbundler` and Apple developer tools; Linux needs
|
||||
`patchelf` and Debian/Ubuntu dependency copyright files. Windows uses the vcpkg
|
||||
installed tree (`VCPKG_INSTALLED_DIR`, `VCPKG_DEFAULT_TRIPLET`) and MSVC tools.
|
||||
`OPENDHT_LIBRARY_PATH` adds native library search directories when bundling.
|
||||
An explicit addon path may be passed to `npm run bundle -- /absolute/addon.node`.
|
||||
Bundling replaces only the current platform's generated prebuild directory.
|
||||
|
||||
`test:package` creates an npm archive, installs it in a temporary consumer with
|
||||
install scripts disabled and no dev dependencies, forces prebuild-only loading,
|
||||
and runs the full runtime suite. Pass an archive file or a directory containing
|
||||
one archive to test it directly, for example `npm run test:package -- dist`.
|
||||
Only runtime JS, declarations, the example's TypeScript source, documentation,
|
||||
and prebuilds are included in the archive. `prepack` compiles the example, so
|
||||
archive creation needs the development dependencies; archive installation does not.
|
||||
|
||||
The [Node.js package workflow](../.github/workflows/nodejs-package.yml) builds:
|
||||
|
||||
| Target | Build Baseline |
|
||||
| --- | --- |
|
||||
| Linux x64 | Ubuntu 24.04 / glibc 2.39 (Noble dependency image) |
|
||||
| macOS ARM64 and x64 | macOS 15 |
|
||||
| Windows x64 | Windows Server 2022 / MSVC |
|
||||
|
||||
CI combines platform prebuilds into one npm archive and verifies that archive on
|
||||
Node 22, 24, and 26 on each platform, including Ubuntu 24.04 and 26.04. Branch
|
||||
pushes, pull requests, and manual runs build and test without publishing.
|
||||
musl/Alpine and other architectures are not currently built. Node-API stability
|
||||
does not remove OS/libc or native dependency compatibility requirements. Review
|
||||
the included dependency licenses and source-distribution obligations before
|
||||
redistributing binaries.
|
||||
|
||||
Query filters, AbortSignal support, certificate trust-store validation, CA
|
||||
issuance controls, and runtime proxy switching remain future work.
|
||||
@@ -0,0 +1,734 @@
|
||||
#include <napi.h>
|
||||
#include <opendht.h>
|
||||
#include <gnutls/gnutls.h>
|
||||
#include "crypto.h"
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <condition_variable>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace {
|
||||
|
||||
struct GnuTlsContext
|
||||
{
|
||||
const int result = gnutls_global_init();
|
||||
|
||||
~GnuTlsContext()
|
||||
{
|
||||
if (result == GNUTLS_E_SUCCESS)
|
||||
gnutls_global_deinit();
|
||||
}
|
||||
};
|
||||
|
||||
using opendht_node::guarded;
|
||||
|
||||
uint32_t
|
||||
unsignedNumber(Napi::Value value, uint32_t maximum, const char* name)
|
||||
{
|
||||
if (!value.IsNumber())
|
||||
throw Napi::TypeError::New(value.Env(), std::string(name) + " must be a number");
|
||||
const auto number = value.As<Napi::Number>().DoubleValue();
|
||||
if (!std::isfinite(number) || number < 0 || number > maximum || std::floor(number) != number)
|
||||
throw Napi::RangeError::New(value.Env(), std::string(name) + " is out of range");
|
||||
return static_cast<uint32_t>(number);
|
||||
}
|
||||
|
||||
uint64_t
|
||||
unsignedBigInt(Napi::Value value)
|
||||
{
|
||||
if (!value.IsBigInt())
|
||||
throw Napi::TypeError::New(value.Env(), "id must be a bigint");
|
||||
int sign = 0;
|
||||
size_t count = 1;
|
||||
uint64_t word = 0;
|
||||
value.As<Napi::BigInt>().ToWords(&sign, &count, &word);
|
||||
if (sign || count > 1)
|
||||
throw Napi::RangeError::New(value.Env(), "id must fit in an unsigned 64-bit integer");
|
||||
return word;
|
||||
}
|
||||
|
||||
std::string
|
||||
text(Napi::Value value, const char* name)
|
||||
{
|
||||
if (!value.IsString())
|
||||
throw Napi::TypeError::New(value.Env(), std::string(name) + " must be a string");
|
||||
auto result = value.As<Napi::String>().Utf8Value();
|
||||
if (result.find('\0') != std::string::npos)
|
||||
throw Napi::TypeError::New(value.Env(), std::string(name) + " must not contain NUL bytes");
|
||||
return result;
|
||||
}
|
||||
|
||||
dht::InfoHash
|
||||
infoHash(Napi::Value value)
|
||||
{
|
||||
const auto result = text(value, "hash");
|
||||
if (result.size() != 40 || result.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos)
|
||||
throw Napi::TypeError::New(value.Env(), "Expected a 40-character hexadecimal hash");
|
||||
return dht::InfoHash(result);
|
||||
}
|
||||
|
||||
Napi::Object
|
||||
optionsObject(Napi::Value value)
|
||||
{
|
||||
if (!value.IsObject() || value.IsArray() || value.IsNull())
|
||||
throw Napi::TypeError::New(value.Env(), "options must be an object");
|
||||
return value.As<Napi::Object>();
|
||||
}
|
||||
|
||||
Napi::Object
|
||||
valueToJS(Napi::Env env, const dht::Value& value)
|
||||
{
|
||||
auto result = Napi::Object::New(env);
|
||||
result.Set("id", Napi::BigInt::New(env, value.id));
|
||||
result.Set("type", Napi::Number::New(env, value.type));
|
||||
result.Set("seq", Napi::Number::New(env, value.seq));
|
||||
result.Set("data", Napi::Buffer<uint8_t>::Copy(env, value.data.data(), value.data.size()));
|
||||
result.Set("userType", Napi::String::New(env, value.user_type));
|
||||
result.Set("owner",
|
||||
value.owner ? Napi::Value(Napi::String::New(env, value.owner->getLongId().to_view()))
|
||||
: Napi::Value(env.Null()));
|
||||
result.Set("isSigned", Napi::Boolean::New(env, value.isSigned()));
|
||||
result.Set("isEncrypted", Napi::Boolean::New(env, value.isEncrypted()));
|
||||
return result;
|
||||
}
|
||||
|
||||
struct PendingOperation
|
||||
{
|
||||
Napi::Promise::Deferred deferred;
|
||||
bool get;
|
||||
std::vector<std::shared_ptr<const dht::Value>> values;
|
||||
Napi::FunctionReference onValue;
|
||||
std::shared_ptr<std::atomic_bool> cancelled;
|
||||
};
|
||||
|
||||
struct Subscription
|
||||
{
|
||||
dht::InfoHash key;
|
||||
std::shared_future<size_t> token;
|
||||
Napi::FunctionReference callback;
|
||||
};
|
||||
|
||||
struct RunnerState
|
||||
{
|
||||
using Callback = std::function<void(RunnerState&)>;
|
||||
|
||||
explicit RunnerState(Napi::Env environment)
|
||||
: env(environment)
|
||||
{}
|
||||
|
||||
static std::shared_ptr<RunnerState> create(Napi::Env env)
|
||||
{
|
||||
auto state = std::make_shared<RunnerState>(env);
|
||||
auto dispatchOwner = std::make_unique<std::shared_ptr<RunnerState>>(state);
|
||||
napi_threadsafe_function function;
|
||||
if (napi_create_threadsafe_function(env,
|
||||
nullptr,
|
||||
nullptr,
|
||||
Napi::String::New(env, "OpenDHT callbacks"),
|
||||
0,
|
||||
1,
|
||||
dispatchOwner.get(),
|
||||
finalizeDispatcher,
|
||||
state.get(),
|
||||
dispatch,
|
||||
&function)
|
||||
!= napi_ok)
|
||||
throw Napi::Error::New(env, "Could not create OpenDHT callback dispatcher");
|
||||
dispatchOwner.release();
|
||||
state->dispatcher = Napi::ThreadSafeFunction(function);
|
||||
state->dispatcher.Unref(env);
|
||||
auto closeOwner = std::make_unique<std::shared_ptr<RunnerState>>(state);
|
||||
if (napi_create_async_work(env,
|
||||
nullptr,
|
||||
Napi::String::New(env, "OpenDHT close"),
|
||||
executeClose,
|
||||
completeClose,
|
||||
closeOwner.get(),
|
||||
&state->closeWork)
|
||||
!= napi_ok) {
|
||||
state->dispatcher.Release();
|
||||
throw Napi::Error::New(env, "Could not create OpenDHT cleanup work");
|
||||
}
|
||||
if (napi_add_async_cleanup_hook(env, cleanup, state.get(), &state->cleanupHook) != napi_ok) {
|
||||
napi_delete_async_work(env, state->closeWork);
|
||||
state->dispatcher.Release();
|
||||
throw Napi::Error::New(env, "Could not register OpenDHT cleanup hook");
|
||||
}
|
||||
state->closeOwner = closeOwner.release();
|
||||
return state;
|
||||
}
|
||||
|
||||
void requireRunning() const
|
||||
{
|
||||
if (closing)
|
||||
throw Napi::Error::New(env, "DHT runner is closed");
|
||||
if (!started)
|
||||
throw Napi::Error::New(env, "DHT runner is not running");
|
||||
}
|
||||
|
||||
void startClose()
|
||||
{
|
||||
if (closing.exchange(true))
|
||||
return;
|
||||
if (napi_queue_async_work(env, closeWork) != napi_ok) {
|
||||
executeClose(env, closeOwner);
|
||||
completeClose(env, napi_ok, closeOwner);
|
||||
}
|
||||
}
|
||||
|
||||
void send(Callback callback)
|
||||
{
|
||||
if (closing)
|
||||
return;
|
||||
auto task = std::make_unique<Callback>(std::move(callback));
|
||||
if (dispatcher.NonBlockingCall(static_cast<void*>(task.get())) == napi_ok)
|
||||
task.release();
|
||||
}
|
||||
|
||||
void sendValue(uint64_t operation, std::shared_ptr<const dht::Value> value, bool expired = false)
|
||||
{
|
||||
send([operation, value = std::move(value), expired](RunnerState& state) mutable {
|
||||
const auto listener = state.listeners.find(operation);
|
||||
if (listener != state.listeners.end()) {
|
||||
listener->second.callback.Call({valueToJS(state.env, *value), Napi::Boolean::New(state.env, expired)});
|
||||
} else if (const auto pending = state.operations.find(operation); pending != state.operations.end()) {
|
||||
if (!pending->second.onValue.IsEmpty())
|
||||
pending->second.onValue.Call({valueToJS(state.env, *value)});
|
||||
else
|
||||
pending->second.values.emplace_back(std::move(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void completeOperation(uint64_t identifier, bool ok)
|
||||
{
|
||||
const auto pending = operations.find(identifier);
|
||||
if (pending == operations.end())
|
||||
return;
|
||||
auto operation = std::move(pending->second);
|
||||
operations.erase(pending);
|
||||
if (!operation.get) {
|
||||
operation.deferred.Resolve(Napi::Boolean::New(env, ok));
|
||||
} else if (!ok) {
|
||||
auto error = Napi::Error::New(env, "DHT get failed");
|
||||
error.Set("code", "ERR_DHT_GET_FAILED");
|
||||
operation.deferred.Reject(error.Value());
|
||||
} else if (!operation.onValue.IsEmpty()) {
|
||||
operation.deferred.Resolve(env.Undefined());
|
||||
} else {
|
||||
auto values = Napi::Array::New(env, operation.values.size());
|
||||
for (size_t index = 0; index < operation.values.size(); ++index)
|
||||
values.Set(static_cast<uint32_t>(index), valueToJS(env, *operation.values[index]));
|
||||
operation.deferred.Resolve(values);
|
||||
}
|
||||
}
|
||||
|
||||
Napi::Object status() const
|
||||
{
|
||||
auto result = Napi::Object::New(env);
|
||||
result.Set("ipv4", Napi::String::New(env, dht::statusToStr(closing ? dht::NodeStatus::Disconnected : status4)));
|
||||
result.Set("ipv6", Napi::String::New(env, dht::statusToStr(closing ? dht::NodeStatus::Disconnected : status6)));
|
||||
return result;
|
||||
}
|
||||
|
||||
static void dispatch(napi_env environment, napi_value, void* context, void* data)
|
||||
{
|
||||
auto state = static_cast<RunnerState*>(context);
|
||||
std::unique_ptr<Callback> callback(static_cast<Callback*>(data));
|
||||
if (!environment || state->envClosing || state->closing)
|
||||
return;
|
||||
try {
|
||||
(*callback)(*state);
|
||||
} catch (const Napi::Error& error) {
|
||||
napi_fatal_exception(environment, error.Value());
|
||||
} catch (const std::exception& error) {
|
||||
napi_fatal_exception(environment, Napi::Error::New(environment, error.what()).Value());
|
||||
}
|
||||
}
|
||||
|
||||
static void finalizeDispatcher(napi_env, void* data, void*)
|
||||
{
|
||||
delete static_cast<std::shared_ptr<RunnerState>*>(data);
|
||||
}
|
||||
|
||||
static void cleanup(napi_async_cleanup_hook_handle, void* data)
|
||||
{
|
||||
auto state = static_cast<RunnerState*>(data);
|
||||
state->envClosing = true;
|
||||
state->startClose();
|
||||
}
|
||||
|
||||
static void executeClose(napi_env, void* data)
|
||||
{
|
||||
auto state = *static_cast<std::shared_ptr<RunnerState>*>(data);
|
||||
struct ShutdownSignal
|
||||
{
|
||||
std::mutex mutex;
|
||||
std::condition_variable condition;
|
||||
bool done = false;
|
||||
};
|
||||
try {
|
||||
auto signal = std::make_shared<ShutdownSignal>();
|
||||
state->runner.shutdown(
|
||||
[signal] {
|
||||
std::lock_guard lock(signal->mutex);
|
||||
signal->done = true;
|
||||
signal->condition.notify_one();
|
||||
},
|
||||
true);
|
||||
std::unique_lock lock(signal->mutex);
|
||||
signal->condition.wait_for(lock, std::chrono::seconds(2), [&] { return signal->done; });
|
||||
} catch (const std::exception& error) {
|
||||
state->closeError = error.what();
|
||||
}
|
||||
state->runner.join();
|
||||
}
|
||||
|
||||
Napi::Error makeCloseError() const
|
||||
{
|
||||
auto error = Napi::Error::New(env, closeError.empty() ? "DHT runner is closed" : closeError);
|
||||
error.Set("code", "ERR_DHT_CLOSED");
|
||||
return error;
|
||||
}
|
||||
|
||||
static void completeClose(napi_env environment, napi_status, void* data)
|
||||
{
|
||||
std::unique_ptr<std::shared_ptr<RunnerState>> owner(static_cast<std::shared_ptr<RunnerState>*>(data));
|
||||
auto state = *owner;
|
||||
state->finished = true;
|
||||
if (!state->envClosing) {
|
||||
state->dispatcher.Release();
|
||||
auto error = state->makeCloseError();
|
||||
for (auto& pending : state->operations)
|
||||
pending.second.deferred.Reject(error.Value());
|
||||
if (state->closeDeferred) {
|
||||
if (state->closeError.empty())
|
||||
state->closeDeferred->Resolve(Napi::Env(environment).Undefined());
|
||||
else
|
||||
state->closeDeferred->Reject(error.Value());
|
||||
}
|
||||
}
|
||||
state->operations.clear();
|
||||
state->listeners.clear();
|
||||
state->closeDeferred.reset();
|
||||
state->closePromise.Reset();
|
||||
state->onStatus.Reset();
|
||||
state->owner.Reset();
|
||||
napi_delete_async_work(environment, state->closeWork);
|
||||
napi_remove_async_cleanup_hook(state->cleanupHook);
|
||||
state->closeOwner = nullptr;
|
||||
}
|
||||
|
||||
Napi::Env env;
|
||||
dht::DhtRunner runner;
|
||||
Napi::ThreadSafeFunction dispatcher;
|
||||
napi_async_work closeWork {};
|
||||
napi_async_cleanup_hook_handle cleanupHook {};
|
||||
std::shared_ptr<RunnerState>* closeOwner {};
|
||||
std::atomic_bool closing {false};
|
||||
bool envClosing = false;
|
||||
bool started = false;
|
||||
bool hasIdentity = false;
|
||||
bool finished = false;
|
||||
uint64_t nextOperation = 1;
|
||||
std::string closeError;
|
||||
std::unordered_map<uint64_t, PendingOperation> operations;
|
||||
std::unordered_map<uint64_t, Subscription> listeners;
|
||||
std::optional<Napi::Promise::Deferred> closeDeferred;
|
||||
Napi::Reference<Napi::Promise> closePromise;
|
||||
Napi::FunctionReference onStatus;
|
||||
Napi::ObjectReference owner;
|
||||
dht::NodeStatus status4 = dht::NodeStatus::Disconnected;
|
||||
dht::NodeStatus status6 = dht::NodeStatus::Disconnected;
|
||||
};
|
||||
|
||||
class Runner : public Napi::ObjectWrap<Runner>
|
||||
{
|
||||
public:
|
||||
explicit Runner(const Napi::CallbackInfo& info)
|
||||
: Napi::ObjectWrap<Runner>(info)
|
||||
, state_(RunnerState::create(info.Env()))
|
||||
{
|
||||
if (info.Length() && info[0].IsFunction())
|
||||
state_->onStatus = Napi::Persistent(info[0].As<Napi::Function>());
|
||||
}
|
||||
|
||||
~Runner() override { state_->startClose(); }
|
||||
|
||||
static Napi::Function define(Napi::Env env)
|
||||
{
|
||||
return DefineClass(env,
|
||||
"NativeRunner",
|
||||
{
|
||||
InstanceMethod("run", &Runner::run),
|
||||
InstanceMethod("close", &Runner::close),
|
||||
InstanceMethod("isRunning", &Runner::isRunning),
|
||||
InstanceMethod("getBoundPort", &Runner::getBoundPort),
|
||||
InstanceMethod("getNodeId", &Runner::getNodeId),
|
||||
InstanceMethod("getStatus", &Runner::getStatus),
|
||||
InstanceMethod("bootstrap", &Runner::bootstrap),
|
||||
InstanceMethod("get", &Runner::get),
|
||||
InstanceMethod("getAll", &Runner::getAll),
|
||||
InstanceMethod("cancelGet", &Runner::cancelGet),
|
||||
InstanceMethod("put", &Runner::put),
|
||||
InstanceMethod("putSigned", &Runner::putSigned),
|
||||
InstanceMethod("putEncrypted", &Runner::putEncrypted),
|
||||
InstanceMethod("listen", &Runner::listen),
|
||||
InstanceMethod("cancelListen", &Runner::cancelListen),
|
||||
InstanceMethod("ref", &Runner::ref),
|
||||
InstanceMethod("unref", &Runner::unref),
|
||||
InstanceMethod("setOwner", &Runner::setOwner),
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
Napi::Value run(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
if (state_->closing)
|
||||
throw Napi::Error::New(info.Env(), "DHT runner is closed");
|
||||
if (state_->started)
|
||||
throw Napi::Error::New(info.Env(), "DHT runner is already running");
|
||||
auto options = info.Length() && !info[0].IsUndefined() ? optionsObject(info[0])
|
||||
: Napi::Object::New(info.Env());
|
||||
const auto port = options.Has("port") ? unsignedNumber(options.Get("port"), 65535, "port") : 0;
|
||||
const auto ipv4 = options.Has("ipv4") ? text(options.Get("ipv4"), "ipv4") : "0.0.0.0";
|
||||
const auto ipv6 = options.Has("ipv6") ? text(options.Get("ipv6"), "ipv6") : "::";
|
||||
dht::DhtRunner::Config config;
|
||||
if (options.Has("network"))
|
||||
config.dht_config.node_config.network = unsignedNumber(options.Get("network"), UINT32_MAX, "network");
|
||||
if (options.Has("persistPath"))
|
||||
config.dht_config.node_config.persist_path = text(options.Get("persistPath"), "persistPath");
|
||||
if (options.Has("identity"))
|
||||
config.dht_config.id = opendht_node::readIdentity(options.Get("identity"));
|
||||
if (options.Has("proxyServer"))
|
||||
config.proxy_server = text(options.Get("proxyServer"), "proxyServer");
|
||||
if (options.Has("proxyUserAgent")) {
|
||||
config.proxy_user_agent = text(options.Get("proxyUserAgent"), "proxyUserAgent");
|
||||
if (config.proxy_user_agent.find_first_of("\r\n") != std::string::npos)
|
||||
throw Napi::TypeError::New(info.Env(), "proxyUserAgent must not contain line breaks");
|
||||
}
|
||||
dht::DhtRunner::Context context;
|
||||
const std::weak_ptr<RunnerState> state = state_;
|
||||
context.statusChangedCallback = [state](dht::NodeStatus ipv4, dht::NodeStatus ipv6) {
|
||||
if (auto owner = state.lock())
|
||||
owner->send([ipv4, ipv6](RunnerState& state) {
|
||||
state.status4 = ipv4;
|
||||
state.status6 = ipv6;
|
||||
if (!state.onStatus.IsEmpty())
|
||||
state.onStatus.Call({state.status()});
|
||||
});
|
||||
};
|
||||
const auto service = std::to_string(port);
|
||||
state_->runner.run(ipv4.c_str(), ipv6.c_str(), service.c_str(), config, std::move(context));
|
||||
state_->started = true;
|
||||
state_->hasIdentity = bool(config.dht_config.id.first);
|
||||
state_->dispatcher.Ref(info.Env());
|
||||
return info.Env().Undefined();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value close(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
if (!state_->closePromise.IsEmpty())
|
||||
return state_->closePromise.Value();
|
||||
auto deferred = Napi::Promise::Deferred::New(info.Env());
|
||||
if (state_->finished) {
|
||||
if (!state_->closeError.empty())
|
||||
deferred.Reject(state_->makeCloseError().Value());
|
||||
else
|
||||
deferred.Resolve(info.Env().Undefined());
|
||||
} else {
|
||||
state_->closeDeferred = deferred;
|
||||
state_->closePromise = Napi::Persistent(deferred.Promise());
|
||||
state_->startClose();
|
||||
}
|
||||
return deferred.Promise();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value isRunning(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return Napi::Boolean::New(info.Env(), !state_->closing && state_->runner.isRunning());
|
||||
}
|
||||
|
||||
Napi::Value getStatus(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value { return state_->status(); });
|
||||
}
|
||||
|
||||
Napi::Value getBoundPort(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
const auto family = info.Length() ? unsignedNumber(info[0], 6, "family") : 4;
|
||||
if (family != 4 && family != 6)
|
||||
throw Napi::RangeError::New(info.Env(), "family must be 4 or 6");
|
||||
return Napi::Number::New(info.Env(), state_->runner.getBoundPort(family == 4 ? AF_INET : AF_INET6));
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value getNodeId(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
return Napi::String::New(info.Env(), state_->runner.getNodeId().to_view());
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value bootstrap(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
const auto host = text(info[0], "host");
|
||||
const auto port = unsignedNumber(info[1], 65535, "port");
|
||||
if (host.empty() || !port)
|
||||
throw Napi::RangeError::New(info.Env(), "bootstrap requires a host and nonzero port");
|
||||
state_->runner.bootstrap(host, std::to_string(port));
|
||||
return info.Env().Undefined();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value get(const Napi::CallbackInfo& info) { return getValues(info, true); }
|
||||
|
||||
Napi::Value getAll(const Napi::CallbackInfo& info) { return getValues(info, false); }
|
||||
|
||||
Napi::Value getValues(const Napi::CallbackInfo& info, bool stream)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
const auto key = infoHash(info[0]);
|
||||
if (stream && !info[1].IsFunction())
|
||||
throw Napi::TypeError::New(info.Env(), "callback must be a function");
|
||||
const auto operation = state_->nextOperation++;
|
||||
auto deferred = Napi::Promise::Deferred::New(info.Env());
|
||||
auto cancelled = std::make_shared<std::atomic_bool>(false);
|
||||
PendingOperation pending {deferred, true, {}, {}, cancelled};
|
||||
if (stream)
|
||||
pending.onValue = Napi::Persistent(info[1].As<Napi::Function>());
|
||||
state_->operations.emplace(operation, std::move(pending));
|
||||
const std::weak_ptr<RunnerState> state = state_;
|
||||
try {
|
||||
state_->runner.get(key,
|
||||
dht::GetCallback([state, operation, cancelled](
|
||||
const std::vector<std::shared_ptr<dht::Value>>& values) {
|
||||
const auto owner = state.lock();
|
||||
if (!owner || owner->closing || *cancelled)
|
||||
return false;
|
||||
for (const auto& value : values)
|
||||
owner->sendValue(operation, value);
|
||||
return !owner->closing && !*cancelled;
|
||||
}),
|
||||
dht::DoneCallbackSimple([state, operation](bool ok) {
|
||||
if (const auto owner = state.lock())
|
||||
owner->send([operation, ok](RunnerState& state) {
|
||||
state.completeOperation(operation, ok);
|
||||
});
|
||||
}));
|
||||
} catch (...) {
|
||||
state_->operations.erase(operation);
|
||||
throw;
|
||||
}
|
||||
if (stream) {
|
||||
auto result = Napi::Object::New(info.Env());
|
||||
result.Set("token", Napi::BigInt::New(info.Env(), operation));
|
||||
result.Set("done", deferred.Promise());
|
||||
return result;
|
||||
}
|
||||
return deferred.Promise();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value cancelGet(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
const auto operation = state_->operations.find(unsignedBigInt(info[0]));
|
||||
if (operation != state_->operations.end() && !operation->second.onValue.IsEmpty()) {
|
||||
*operation->second.cancelled = true;
|
||||
operation->second.deferred.Resolve(info.Env().Undefined());
|
||||
state_->operations.erase(operation);
|
||||
}
|
||||
return info.Env().Undefined();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value put(const Napi::CallbackInfo& info) { return putValue(info, PutMode::Plain); }
|
||||
|
||||
Napi::Value putSigned(const Napi::CallbackInfo& info) { return putValue(info, PutMode::Signed); }
|
||||
|
||||
Napi::Value putEncrypted(const Napi::CallbackInfo& info) { return putValue(info, PutMode::Encrypted); }
|
||||
|
||||
enum class PutMode { Plain, Signed, Encrypted };
|
||||
|
||||
Napi::Value putValue(const Napi::CallbackInfo& info, PutMode mode)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
if (mode != PutMode::Plain && !state_->hasIdentity)
|
||||
throw Napi::Error::New(info.Env(), "Signed and encrypted puts require an identity");
|
||||
std::shared_ptr<dht::crypto::PublicKey> recipient;
|
||||
if (mode == PutMode::Encrypted) {
|
||||
recipient = opendht_node::readEncryptionKey(info[3]);
|
||||
}
|
||||
const auto key = infoHash(info[0]);
|
||||
if (!info[1].IsTypedArray() || info[1].As<Napi::TypedArray>().TypedArrayType() != napi_uint8_array)
|
||||
throw Napi::TypeError::New(info.Env(), "data must be a Uint8Array");
|
||||
const auto data = info[1].As<Napi::Uint8Array>();
|
||||
dht::Blob bytes(data.ElementLength());
|
||||
if (!bytes.empty())
|
||||
std::copy_n(data.Data(), bytes.size(), bytes.data());
|
||||
auto value = std::make_shared<dht::Value>(std::move(bytes));
|
||||
auto options = info.Length() > 2 && !info[2].IsUndefined() ? optionsObject(info[2])
|
||||
: Napi::Object::New(info.Env());
|
||||
if (options.Has("id"))
|
||||
value->id = unsignedBigInt(options.Get("id"));
|
||||
if (options.Has("type"))
|
||||
value->type = unsignedNumber(options.Get("type"), 65535, "type");
|
||||
if (options.Has("userType")) {
|
||||
if (!options.Get("userType").IsString())
|
||||
throw Napi::TypeError::New(info.Env(), "userType must be a string");
|
||||
value->user_type = options.Get("userType").As<Napi::String>().Utf8Value();
|
||||
}
|
||||
bool permanent = false;
|
||||
if (options.Has("permanent")) {
|
||||
if (!options.Get("permanent").IsBoolean())
|
||||
throw Napi::TypeError::New(info.Env(), "permanent must be a boolean");
|
||||
permanent = options.Get("permanent").As<Napi::Boolean>().Value();
|
||||
}
|
||||
const auto operation = state_->nextOperation++;
|
||||
auto deferred = Napi::Promise::Deferred::New(info.Env());
|
||||
state_->operations.emplace(operation, PendingOperation {deferred, false, {}, {}, {}});
|
||||
const std::weak_ptr<RunnerState> state = state_;
|
||||
try {
|
||||
dht::DoneCallbackSimple done = [state, operation](bool ok) {
|
||||
if (const auto owner = state.lock())
|
||||
owner->send([operation, ok](RunnerState& state) { state.completeOperation(operation, ok); });
|
||||
};
|
||||
if (mode == PutMode::Signed)
|
||||
state_->runner.putSigned(key, value, std::move(done), permanent);
|
||||
else if (mode == PutMode::Encrypted)
|
||||
state_->runner.putEncrypted(key, recipient, value, std::move(done), permanent);
|
||||
else
|
||||
state_->runner.put(key, value, std::move(done), dht::time_point::max(), permanent);
|
||||
} catch (...) {
|
||||
state_->operations.erase(operation);
|
||||
throw;
|
||||
}
|
||||
return deferred.Promise();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value listen(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
const auto key = infoHash(info[0]);
|
||||
if (!info[1].IsFunction())
|
||||
throw Napi::TypeError::New(info.Env(), "callback must be a function");
|
||||
const auto operation = state_->nextOperation++;
|
||||
const std::weak_ptr<RunnerState> state = state_;
|
||||
auto token = state_->runner
|
||||
.listen(key,
|
||||
dht::ValueCallback(
|
||||
[state, operation](const std::vector<std::shared_ptr<dht::Value>>& values,
|
||||
bool expired) {
|
||||
const auto owner = state.lock();
|
||||
if (!owner || owner->closing)
|
||||
return false;
|
||||
for (const auto& value : values)
|
||||
owner->sendValue(operation, value, expired);
|
||||
return !owner->closing;
|
||||
}))
|
||||
.share();
|
||||
state_->listeners.emplace(operation,
|
||||
Subscription {key,
|
||||
std::move(token),
|
||||
Napi::Persistent(info[1].As<Napi::Function>())});
|
||||
return Napi::BigInt::New(info.Env(), operation);
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value cancelListen(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
if (state_->closing)
|
||||
return info.Env().Undefined();
|
||||
const auto listener = state_->listeners.find(unsignedBigInt(info[0]));
|
||||
if (listener != state_->listeners.end()) {
|
||||
state_->runner.cancelListen(listener->second.key, listener->second.token);
|
||||
state_->listeners.erase(listener);
|
||||
}
|
||||
return info.Env().Undefined();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value ref(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
state_->dispatcher.Ref(info.Env());
|
||||
return info.This();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value unref(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
state_->requireRunning();
|
||||
state_->dispatcher.Unref(info.Env());
|
||||
return info.This();
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value setOwner(const Napi::CallbackInfo& info)
|
||||
{
|
||||
if (!state_->closing) {
|
||||
state_->owner.Reset();
|
||||
if (info[0].IsObject())
|
||||
state_->owner = Napi::Persistent(info[0].As<Napi::Object>());
|
||||
}
|
||||
return info.Env().Undefined();
|
||||
}
|
||||
|
||||
std::shared_ptr<RunnerState> state_;
|
||||
};
|
||||
|
||||
Napi::Value
|
||||
hash(const Napi::CallbackInfo& info)
|
||||
{
|
||||
const auto env = info.Env();
|
||||
dht::InfoHash result;
|
||||
if (info.Length() == 1 && info[0].IsString()) {
|
||||
result = dht::InfoHash::get(info[0].As<Napi::String>().Utf8Value());
|
||||
} else if (info.Length() == 1 && info[0].IsTypedArray()
|
||||
&& info[0].As<Napi::TypedArray>().TypedArrayType() == napi_uint8_array) {
|
||||
const auto data = info[0].As<Napi::Uint8Array>();
|
||||
result = dht::InfoHash::get(data.Data(), data.ElementLength());
|
||||
} else {
|
||||
throw Napi::TypeError::New(env, "Expected a string or Uint8Array");
|
||||
}
|
||||
return Napi::String::New(env, result.to_view());
|
||||
}
|
||||
|
||||
Napi::Object
|
||||
initialize(Napi::Env env, Napi::Object exports)
|
||||
{
|
||||
static const GnuTlsContext crypto;
|
||||
if (crypto.result != GNUTLS_E_SUCCESS)
|
||||
throw Napi::Error::New(env, std::string("Unable to initialize GnuTLS: ") + gnutls_strerror(crypto.result));
|
||||
opendht_node::initializeCrypto(env, exports);
|
||||
exports.Set("NativeRunner", Runner::define(env));
|
||||
exports.Set("hash", Napi::Function::New(env, hash));
|
||||
exports.Set("version", Napi::String::New(env, dht::version()));
|
||||
return exports;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NODE_API_MODULE(opendht, initialize)
|
||||
@@ -0,0 +1,304 @@
|
||||
#include "crypto.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <variant>
|
||||
|
||||
namespace opendht_node {
|
||||
namespace {
|
||||
|
||||
using PublicKey = std::shared_ptr<dht::crypto::PublicKey>;
|
||||
using PrivateKey = std::shared_ptr<dht::crypto::PrivateKey>;
|
||||
using Certificate = std::shared_ptr<dht::crypto::Certificate>;
|
||||
using Identity = dht::crypto::Identity;
|
||||
using Handle = std::variant<PublicKey, PrivateKey, Certificate, Identity>;
|
||||
|
||||
constexpr napi_type_tag cryptoTag {0x37cdf3e4648e4cb5ULL, 0x964fb031062c245aULL};
|
||||
|
||||
Handle&
|
||||
handle(Napi::Value value)
|
||||
{
|
||||
bool matches = false;
|
||||
if (!value.IsExternal() || napi_check_object_type_tag(value.Env(), value, &cryptoTag, &matches) != napi_ok
|
||||
|| !matches)
|
||||
throw Napi::TypeError::New(value.Env(), "Invalid OpenDHT crypto handle");
|
||||
return *value.As<Napi::External<Handle>>().Data();
|
||||
}
|
||||
|
||||
template<typename Type>
|
||||
Type
|
||||
read(Napi::Value value)
|
||||
{
|
||||
if (auto result = std::get_if<Type>(&handle(value)))
|
||||
return *result;
|
||||
throw Napi::TypeError::New(value.Env(), "Wrong OpenDHT crypto handle type");
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
wrap(Napi::Env env, Handle value)
|
||||
{
|
||||
auto owner = std::make_unique<Handle>(std::move(value));
|
||||
auto result = Napi::External<Handle>::New(env, owner.get(), [](Napi::Env, Handle* data) { delete data; });
|
||||
owner.release();
|
||||
if (napi_type_tag_object(env, result, &cryptoTag) != napi_ok)
|
||||
throw Napi::Error::New(env, "Could not tag OpenDHT crypto handle");
|
||||
return result;
|
||||
}
|
||||
|
||||
dht::Blob
|
||||
bytes(Napi::Value value)
|
||||
{
|
||||
if (!value.IsTypedArray() || value.As<Napi::TypedArray>().TypedArrayType() != napi_uint8_array)
|
||||
throw Napi::TypeError::New(value.Env(), "Expected a Uint8Array");
|
||||
auto array = value.As<Napi::Uint8Array>();
|
||||
dht::Blob result(array.ElementLength());
|
||||
if (!result.empty())
|
||||
std::copy_n(array.Data(), result.size(), result.data());
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string
|
||||
string(Napi::Value value)
|
||||
{
|
||||
if (!value.IsString())
|
||||
throw Napi::TypeError::New(value.Env(), "Expected a string");
|
||||
auto result = value.As<Napi::String>().Utf8Value();
|
||||
if (result.find('\0') != std::string::npos)
|
||||
throw Napi::TypeError::New(value.Env(), "Crypto strings must not contain NUL bytes");
|
||||
return result;
|
||||
}
|
||||
|
||||
Napi::Buffer<uint8_t>
|
||||
buffer(Napi::Env env, const dht::Blob& value)
|
||||
{
|
||||
return Napi::Buffer<uint8_t>::Copy(env, value.data(), value.size());
|
||||
}
|
||||
|
||||
PublicKey
|
||||
publicKey(const Handle& value)
|
||||
{
|
||||
if (auto key = std::get_if<PublicKey>(&value))
|
||||
return *key;
|
||||
if (auto key = std::get_if<PrivateKey>(&value))
|
||||
return (*key)->getSharedPublicKey();
|
||||
if (auto certificate = std::get_if<Certificate>(&value))
|
||||
return (*certificate)->getSharedPublicKey();
|
||||
return std::get<Identity>(value).second->getSharedPublicKey();
|
||||
}
|
||||
|
||||
class GenerateWorker : public Napi::AsyncWorker
|
||||
{
|
||||
public:
|
||||
GenerateWorker(Napi::Env env, bool identity, std::string name, bool rsa, unsigned bits)
|
||||
: Napi::AsyncWorker(env, "OpenDHT crypto generation")
|
||||
, deferred_(Napi::Promise::Deferred::New(env))
|
||||
, identity_(identity)
|
||||
, name_(std::move(name))
|
||||
, rsa_(rsa)
|
||||
, bits_(bits)
|
||||
{}
|
||||
|
||||
Napi::Promise promise() const { return deferred_.Promise(); }
|
||||
|
||||
void Execute() override
|
||||
{
|
||||
try {
|
||||
if (identity_)
|
||||
result_ = rsa_ ? dht::crypto::generateIdentity(name_, {}, bits_)
|
||||
: dht::crypto::generateEcIdentity(name_);
|
||||
else
|
||||
result_ = std::make_shared<dht::crypto::PrivateKey>(rsa_ ? dht::crypto::PrivateKey::generate(bits_)
|
||||
: dht::crypto::PrivateKey::generateEC());
|
||||
} catch (const std::exception& error) {
|
||||
SetError(error.what());
|
||||
}
|
||||
}
|
||||
|
||||
void OnOK() override { deferred_.Resolve(wrap(Env(), std::move(result_))); }
|
||||
void OnError(const Napi::Error& error) override { deferred_.Reject(error.Value()); }
|
||||
|
||||
private:
|
||||
Napi::Promise::Deferred deferred_;
|
||||
bool identity_;
|
||||
std::string name_;
|
||||
bool rsa_;
|
||||
unsigned bits_;
|
||||
Handle result_;
|
||||
};
|
||||
|
||||
Napi::Value
|
||||
generate(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
const auto kind = string(info[0]);
|
||||
const auto name = string(info[1]);
|
||||
const auto algorithm = string(info[2]);
|
||||
if (algorithm != "rsa" && algorithm != "ec")
|
||||
throw Napi::TypeError::New(info.Env(), "algorithm must be rsa or ec");
|
||||
if (!info[3].IsNumber())
|
||||
throw Napi::TypeError::New(info.Env(), "bits must be a number");
|
||||
const auto bits = info[3].As<Napi::Number>().DoubleValue();
|
||||
if (!std::isfinite(bits) || std::floor(bits) != bits || bits < 2048 || bits > 8192)
|
||||
throw Napi::RangeError::New(info.Env(), "RSA bits must be an integer between 2048 and 8192");
|
||||
if (kind != "private" && kind != "identity")
|
||||
throw Napi::TypeError::New(info.Env(), "Invalid crypto generation type");
|
||||
auto worker = std::make_unique<GenerateWorker>(info.Env(), kind == "identity", name, algorithm == "rsa", bits);
|
||||
auto promise = worker->promise();
|
||||
worker->Queue();
|
||||
worker.release();
|
||||
return promise;
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
import(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
const auto kind = string(info[0]);
|
||||
auto data = bytes(info[1]);
|
||||
if (data.empty())
|
||||
throw Napi::TypeError::New(info.Env(), "Crypto imports must not be empty");
|
||||
if (kind == "private")
|
||||
return wrap(info.Env(), std::make_shared<dht::crypto::PrivateKey>(data, string(info[2])));
|
||||
if (kind == "public")
|
||||
return wrap(info.Env(), std::make_shared<dht::crypto::PublicKey>(data));
|
||||
if (kind == "certificate")
|
||||
return wrap(info.Env(), std::make_shared<dht::crypto::Certificate>(data));
|
||||
throw Napi::TypeError::New(info.Env(), "Invalid crypto import type");
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
serialize(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
auto& value = handle(info[0]);
|
||||
if (auto key = std::get_if<PrivateKey>(&value))
|
||||
return buffer(info.Env(), (*key)->serialize(string(info[1])));
|
||||
if (auto certificate = std::get_if<Certificate>(&value))
|
||||
return buffer(info.Env(), (*certificate)->getPacked());
|
||||
dht::Blob result;
|
||||
readPublicKey(info[0])->pack(result);
|
||||
return buffer(info.Env(), result);
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
getPublicKey(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&] { return wrap(info.Env(), publicKey(handle(info[0]))); });
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
getId(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
const auto key = publicKey(handle(info[0]));
|
||||
if (!info[1].IsBoolean())
|
||||
throw Napi::TypeError::New(info.Env(), "Expected a boolean");
|
||||
return Napi::String::New(info.Env(),
|
||||
info[1].As<Napi::Boolean>().Value() ? key->getLongId().toString()
|
||||
: key->getId().toString());
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
sign(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
return buffer(info.Env(), read<PrivateKey>(info[0])->sign(bytes(info[1])));
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
verify(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
return Napi::Boolean::New(info.Env(), readPublicKey(info[0])->checkSignature(bytes(info[1]), bytes(info[2])));
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
encrypt(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
const auto key = readEncryptionKey(info[0]);
|
||||
return buffer(info.Env(), key->encrypt(bytes(info[1])));
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
decrypt(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
return buffer(info.Env(), read<PrivateKey>(info[0])->decrypt(bytes(info[1])));
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
identity(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
auto key = read<PrivateKey>(info[0]);
|
||||
auto certificate = read<Certificate>(info[1]);
|
||||
if (key->getPublicKey().getLongId() != certificate->getLongId())
|
||||
throw Napi::TypeError::New(info.Env(), "Identity key and certificate do not match");
|
||||
return wrap(info.Env(), Identity {std::move(key), std::move(certificate)});
|
||||
});
|
||||
}
|
||||
|
||||
Napi::Value
|
||||
identityPart(const Napi::CallbackInfo& info)
|
||||
{
|
||||
return guarded(info, [&]() -> Napi::Value {
|
||||
const auto value = readIdentity(info[0]);
|
||||
if (!info[1].IsBoolean())
|
||||
throw Napi::TypeError::New(info.Env(), "Expected a boolean");
|
||||
return info[1].As<Napi::Boolean>().Value() ? wrap(info.Env(), value.first) : wrap(info.Env(), value.second);
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
dht::crypto::Identity
|
||||
readIdentity(Napi::Value value)
|
||||
{
|
||||
return read<Identity>(value);
|
||||
}
|
||||
std::shared_ptr<dht::crypto::PublicKey>
|
||||
readPublicKey(Napi::Value value)
|
||||
{
|
||||
return read<PublicKey>(value);
|
||||
}
|
||||
|
||||
std::shared_ptr<dht::crypto::PublicKey>
|
||||
readEncryptionKey(Napi::Value value)
|
||||
{
|
||||
const auto key = readPublicKey(value);
|
||||
const auto algorithm = gnutls_pubkey_get_pk_algorithm(key->pk, nullptr);
|
||||
if (algorithm != GNUTLS_PK_RSA
|
||||
#if GNUTLS_VERSION_NUMBER >= 0x030804
|
||||
&& algorithm != GNUTLS_PK_RSA_OAEP
|
||||
#endif
|
||||
)
|
||||
throw Napi::TypeError::New(value.Env(), "Encryption requires an RSA public key");
|
||||
return key;
|
||||
}
|
||||
|
||||
void
|
||||
initializeCrypto(Napi::Env env, Napi::Object exports)
|
||||
{
|
||||
exports.Set("cryptoGenerate", Napi::Function::New(env, generate));
|
||||
exports.Set("cryptoImport", Napi::Function::New(env, import));
|
||||
exports.Set("cryptoSerialize", Napi::Function::New(env, serialize));
|
||||
exports.Set("cryptoPublicKey", Napi::Function::New(env, getPublicKey));
|
||||
exports.Set("cryptoId", Napi::Function::New(env, getId));
|
||||
exports.Set("cryptoSign", Napi::Function::New(env, sign));
|
||||
exports.Set("cryptoVerify", Napi::Function::New(env, verify));
|
||||
exports.Set("cryptoEncrypt", Napi::Function::New(env, encrypt));
|
||||
exports.Set("cryptoDecrypt", Napi::Function::New(env, decrypt));
|
||||
exports.Set("cryptoIdentity", Napi::Function::New(env, identity));
|
||||
exports.Set("cryptoIdentityPart", Napi::Function::New(env, identityPart));
|
||||
}
|
||||
|
||||
} // namespace opendht_node
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <napi.h>
|
||||
#include <opendht/crypto.h>
|
||||
|
||||
namespace opendht_node {
|
||||
|
||||
template<typename Callback>
|
||||
Napi::Value
|
||||
guarded(const Napi::CallbackInfo& info, Callback&& callback)
|
||||
{
|
||||
try {
|
||||
return callback();
|
||||
} catch (const Napi::Error&) {
|
||||
throw;
|
||||
} catch (const std::exception& error) {
|
||||
throw Napi::Error::New(info.Env(), error.what());
|
||||
}
|
||||
}
|
||||
|
||||
dht::crypto::Identity readIdentity(Napi::Value value);
|
||||
std::shared_ptr<dht::crypto::PublicKey> readPublicKey(Napi::Value value);
|
||||
std::shared_ptr<dht::crypto::PublicKey> readEncryptionKey(Napi::Value value);
|
||||
void initializeCrypto(Napi::Env env, Napi::Object exports);
|
||||
|
||||
} // namespace opendht_node
|
||||
@@ -0,0 +1,56 @@
|
||||
export default function createCrypto(native) {
|
||||
const handles = new WeakMap();
|
||||
|
||||
function handle(value, Type) {
|
||||
if (!(value instanceof Type) || !handles.has(value)) throw new TypeError(`Expected ${Type.name}`);
|
||||
return handles.get(value);
|
||||
}
|
||||
|
||||
function wrap(Type, nativeHandle) {
|
||||
const result = Object.create(Type.prototype);
|
||||
handles.set(result, nativeHandle);
|
||||
return result;
|
||||
}
|
||||
|
||||
function generate(kind, name, options = {}) {
|
||||
if (!options || typeof options !== 'object' || Array.isArray(options)) throw new TypeError('Invalid crypto options');
|
||||
return native.cryptoGenerate(kind, name, options.algorithm ?? 'ec', options.bits ?? 2048);
|
||||
}
|
||||
|
||||
class PublicKey {
|
||||
constructor(data) { handles.set(this, native.cryptoImport('public', data)); }
|
||||
serialize() { return native.cryptoSerialize(handle(this, PublicKey)); }
|
||||
getId() { return native.cryptoId(handle(this, PublicKey), false); }
|
||||
getLongId() { return native.cryptoId(handle(this, PublicKey), true); }
|
||||
checkSignature(data, signature) { return native.cryptoVerify(handle(this, PublicKey), data, signature); }
|
||||
encrypt(data) { return native.cryptoEncrypt(handle(this, PublicKey), data); }
|
||||
}
|
||||
|
||||
class PrivateKey {
|
||||
constructor(data, password = '') { handles.set(this, native.cryptoImport('private', data, password)); }
|
||||
static generate(options) { return generate('private', '', options).then(value => wrap(PrivateKey, value)); }
|
||||
serialize(password = '') { return native.cryptoSerialize(handle(this, PrivateKey), password); }
|
||||
getPublicKey() { return wrap(PublicKey, native.cryptoPublicKey(handle(this, PrivateKey))); }
|
||||
sign(data) { return native.cryptoSign(handle(this, PrivateKey), data); }
|
||||
decrypt(data) { return native.cryptoDecrypt(handle(this, PrivateKey), data); }
|
||||
}
|
||||
|
||||
class Certificate {
|
||||
constructor(data) { handles.set(this, native.cryptoImport('certificate', data)); }
|
||||
serialize() { return native.cryptoSerialize(handle(this, Certificate)); }
|
||||
getPublicKey() { return wrap(PublicKey, native.cryptoPublicKey(handle(this, Certificate))); }
|
||||
getId() { return native.cryptoId(handle(this, Certificate), false); }
|
||||
getLongId() { return native.cryptoId(handle(this, Certificate), true); }
|
||||
}
|
||||
|
||||
class Identity {
|
||||
constructor(privateKey, certificate) {
|
||||
handles.set(this, native.cryptoIdentity(handle(privateKey, PrivateKey), handle(certificate, Certificate)));
|
||||
}
|
||||
static generate(name = 'dhtnode', options) { return generate('identity', name, options).then(value => wrap(Identity, value)); }
|
||||
get privateKey() { return wrap(PrivateKey, native.cryptoIdentityPart(handle(this, Identity), true)); }
|
||||
get certificate() { return wrap(Certificate, native.cryptoIdentityPart(handle(this, Identity), false)); }
|
||||
}
|
||||
|
||||
return { PublicKey, PrivateKey, Certificate, Identity, handle };
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { clearLine, createInterface, cursorTo, type Interface } from 'node:readline';
|
||||
import { parseArgs } from 'node:util';
|
||||
import type { ConnectivityStatus, Listener, Value } from '../index.js';
|
||||
|
||||
const commands = 'get KEY | put KEY TEXT | sign KEY TEXT | listen KEY | cancel KEY | help | quit';
|
||||
|
||||
function portNumber(value: string, name: string, minimum = 0): number {
|
||||
const port = Number(value);
|
||||
if (!Number.isInteger(port) || port < minimum || port > 65535) {
|
||||
throw new Error(`${name} must be an integer between ${minimum} and 65535`);
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function report(error: unknown): void {
|
||||
console.error(errorMessage(error));
|
||||
process.exitCode = 1;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
help: { type: 'boolean', short: 'h' },
|
||||
port: { type: 'string', short: 'p', default: '4222' },
|
||||
ipv4: { type: 'string', default: '0.0.0.0' },
|
||||
ipv6: { type: 'string', default: '::' },
|
||||
bootstrap: { type: 'string', short: 'b' },
|
||||
'bootstrap-port': { type: 'string', default: '4222' },
|
||||
},
|
||||
});
|
||||
if (values.help) {
|
||||
console.log(`Usage: npm run dhtnode -- [options]
|
||||
|
||||
-p, --port PORT Local UDP port (default: 4222; 0 selects a free port)
|
||||
-b, --bootstrap HOST Optional bootstrap hostname or IP address
|
||||
--bootstrap-port PORT Bootstrap UDP port (default: 4222)
|
||||
--ipv4 ADDRESS IPv4 bind address (default: 0.0.0.0)
|
||||
--ipv6 ADDRESS IPv6 bind address (default: ::)
|
||||
-h, --help Show help
|
||||
|
||||
Commands: ${commands}
|
||||
Keys are text labels hashed with SHA-1. Values are UTF-8 text.`);
|
||||
return;
|
||||
}
|
||||
const port = portNumber(values.port, 'port');
|
||||
const bootstrapPort = portNumber(values['bootstrap-port'], 'bootstrap-port', 1);
|
||||
const { DhtRunner, Identity, hash } = await import('../index.js');
|
||||
const identity = await Identity.generate('dhtnode.ts');
|
||||
const runner = new DhtRunner();
|
||||
const listeners = new Map<string, Listener>();
|
||||
const pending = new Set<Promise<void>>();
|
||||
let lines: Interface | undefined;
|
||||
let closing: Promise<void> | undefined;
|
||||
|
||||
function close(): Promise<void> {
|
||||
if (!closing) {
|
||||
for (const listener of listeners.values()) listener.cancel();
|
||||
listeners.clear();
|
||||
lines?.close();
|
||||
closing = runner.close();
|
||||
}
|
||||
return closing;
|
||||
}
|
||||
|
||||
function print(message: string): void {
|
||||
if (process.stdout.isTTY && lines) {
|
||||
clearLine(process.stdout, 0);
|
||||
cursorTo(process.stdout, 0);
|
||||
}
|
||||
console.log(message);
|
||||
if (!closing && process.stdin.isTTY) lines?.prompt(true);
|
||||
}
|
||||
|
||||
const stop = (): void => { close().catch(report); };
|
||||
const printValue = (label: string, value: Value): void => {
|
||||
print(`${label} ${value.id}: ${JSON.stringify(value.data.toString('utf8'))}${value.isSigned ? ' [signed]' : ''}`);
|
||||
};
|
||||
const printStatus = (status: ConnectivityStatus): void => {
|
||||
print(`Connectivity: IPv4 ${status.ipv4}, IPv6 ${status.ipv6}`);
|
||||
};
|
||||
|
||||
async function execute(line: string): Promise<void> {
|
||||
const [, command, key, data] = line.trim().match(/^(\S+)(?:\s+(\S+))?(?:\s+(.+))?$/) || [];
|
||||
if (!command) return;
|
||||
if (command === 'help') {
|
||||
print(commands);
|
||||
return;
|
||||
}
|
||||
if (!key) throw new Error('Expected a key. Type help for commands.');
|
||||
const location = hash(key);
|
||||
switch (command) {
|
||||
case 'get': {
|
||||
const found = await runner.getAll(location);
|
||||
if (closing) return;
|
||||
for (const value of found) printValue(key, value);
|
||||
if (!found.length) print(`No values for ${key}`);
|
||||
break;
|
||||
}
|
||||
case 'put':
|
||||
case 'sign': {
|
||||
if (data === undefined) throw new Error(`Usage: ${command} KEY TEXT`);
|
||||
const payload = Buffer.from(data, 'utf8');
|
||||
const ok = command === 'sign' ? await runner.putSigned(location, payload)
|
||||
: await runner.put(location, payload);
|
||||
if (closing) return;
|
||||
if (!ok) throw new Error(`Put failed for ${key}`);
|
||||
print(`Stored ${key}`);
|
||||
break;
|
||||
}
|
||||
case 'listen':
|
||||
if (!listeners.has(key)) {
|
||||
listeners.set(key, runner.listen(location, (value, expired) => {
|
||||
printValue(`${expired ? 'Expired' : 'Value'} ${key}`, value);
|
||||
}));
|
||||
}
|
||||
print(`Listening ${key}`);
|
||||
break;
|
||||
case 'cancel':
|
||||
listeners.get(key)?.cancel();
|
||||
listeners.delete(key);
|
||||
print(`Cancelled ${key}`);
|
||||
break;
|
||||
default:
|
||||
throw new Error('Unknown command. Type help for commands.');
|
||||
}
|
||||
}
|
||||
|
||||
runner.on('error', error => { report(error); stop(); });
|
||||
runner.on('statusChanged', printStatus);
|
||||
process.on('SIGINT', stop);
|
||||
process.on('SIGTERM', stop);
|
||||
try {
|
||||
runner.run({ port, ipv4: values.ipv4, ipv6: values.ipv6, identity });
|
||||
if (values.bootstrap) runner.bootstrap(values.bootstrap, bootstrapPort);
|
||||
lines = createInterface({ input: process.stdin, output: process.stdout });
|
||||
lines.on('SIGINT', stop);
|
||||
lines.setPrompt('dht> ');
|
||||
print(`Node ${runner.getNodeId()} listening on UDP ${runner.getBoundPort()}`);
|
||||
printStatus(runner.getStatus());
|
||||
if (process.stdin.isTTY) print(commands);
|
||||
for await (const line of lines) {
|
||||
if (closing) break;
|
||||
if (/^(quit|exit)(?:\s|$)/.test(line.trim())) {
|
||||
stop();
|
||||
break;
|
||||
}
|
||||
const operation = execute(line).catch(error => {
|
||||
if (!closing) console.error(errorMessage(error));
|
||||
}).finally(() => { pending.delete(operation); });
|
||||
pending.add(operation);
|
||||
if (process.stdin.isTTY) lines.prompt();
|
||||
}
|
||||
if (!closing) await Promise.all(pending);
|
||||
} finally {
|
||||
try {
|
||||
await close();
|
||||
await Promise.all(pending);
|
||||
} finally {
|
||||
process.removeListener('SIGINT', stop);
|
||||
process.removeListener('SIGTERM', stop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(report);
|
||||
Vendored
+120
@@ -0,0 +1,120 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
import { EventEmitter } from 'node:events';
|
||||
|
||||
export const version: string;
|
||||
export function hash(data: string | Uint8Array): string;
|
||||
|
||||
export interface KeyOptions {
|
||||
algorithm?: 'ec' | 'rsa';
|
||||
bits?: number;
|
||||
}
|
||||
|
||||
export class PublicKey {
|
||||
constructor(data: Uint8Array);
|
||||
serialize(): Buffer;
|
||||
getId(): string;
|
||||
getLongId(): string;
|
||||
checkSignature(data: Uint8Array, signature: Uint8Array): boolean;
|
||||
encrypt(data: Uint8Array): Buffer;
|
||||
}
|
||||
|
||||
export class PrivateKey {
|
||||
constructor(data: Uint8Array, password?: string);
|
||||
static generate(options?: KeyOptions): Promise<PrivateKey>;
|
||||
serialize(password?: string): Buffer;
|
||||
getPublicKey(): PublicKey;
|
||||
sign(data: Uint8Array): Buffer;
|
||||
decrypt(data: Uint8Array): Buffer;
|
||||
}
|
||||
|
||||
export class Certificate {
|
||||
constructor(data: Uint8Array);
|
||||
serialize(): Buffer;
|
||||
getPublicKey(): PublicKey;
|
||||
getId(): string;
|
||||
getLongId(): string;
|
||||
}
|
||||
|
||||
export class Identity {
|
||||
constructor(privateKey: PrivateKey, certificate: Certificate);
|
||||
static generate(name?: string, options?: KeyOptions): Promise<Identity>;
|
||||
readonly privateKey: PrivateKey;
|
||||
readonly certificate: Certificate;
|
||||
}
|
||||
|
||||
export interface RunOptions {
|
||||
port?: number;
|
||||
ipv4?: string;
|
||||
ipv6?: string;
|
||||
network?: number;
|
||||
persistPath?: string;
|
||||
identity?: Identity;
|
||||
proxyServer?: string;
|
||||
proxyUserAgent?: string;
|
||||
}
|
||||
|
||||
export interface PutOptions {
|
||||
id?: bigint;
|
||||
type?: number;
|
||||
userType?: string;
|
||||
permanent?: boolean;
|
||||
}
|
||||
|
||||
export interface Value {
|
||||
id: bigint;
|
||||
type: number;
|
||||
seq: number;
|
||||
data: Buffer;
|
||||
userType: string;
|
||||
owner: string | null;
|
||||
isSigned: boolean;
|
||||
isEncrypted: boolean;
|
||||
}
|
||||
|
||||
export interface Listener {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
export interface ListenEvent {
|
||||
value: Value;
|
||||
expired: boolean;
|
||||
}
|
||||
|
||||
export interface ValueIterator<T> extends AsyncIterableIterator<T, undefined>, Listener, AsyncDisposable {
|
||||
return(): Promise<IteratorResult<T, undefined>>;
|
||||
throw(error?: unknown): Promise<IteratorResult<T, undefined>>;
|
||||
}
|
||||
|
||||
export interface ListenerIterator extends ValueIterator<ListenEvent> { }
|
||||
|
||||
export type NodeStatus = 'disconnected' | 'connecting' | 'connected';
|
||||
|
||||
export interface ConnectivityStatus {
|
||||
ipv4: NodeStatus;
|
||||
ipv6: NodeStatus;
|
||||
}
|
||||
|
||||
export interface RunnerEvents {
|
||||
statusChanged: [status: ConnectivityStatus];
|
||||
error: [error: Error];
|
||||
}
|
||||
|
||||
export class DhtRunner extends EventEmitter<RunnerEvents> implements AsyncDisposable {
|
||||
run(options?: RunOptions): void;
|
||||
isRunning(): boolean;
|
||||
getBoundPort(family?: 4 | 6): number;
|
||||
getNodeId(): string;
|
||||
getStatus(): ConnectivityStatus;
|
||||
bootstrap(host: string, port: number): void;
|
||||
get(key: string): ValueIterator<Value>;
|
||||
getAll(key: string): Promise<Value[]>;
|
||||
put(key: string, data: Uint8Array, options?: PutOptions): Promise<boolean>;
|
||||
putSigned(key: string, data: Uint8Array, options?: PutOptions): Promise<boolean>;
|
||||
putEncrypted(key: string, data: Uint8Array, recipient: PublicKey, options?: PutOptions): Promise<boolean>;
|
||||
listen(key: string): ListenerIterator;
|
||||
listen(key: string, callback: (value: Value, expired: boolean) => void): Listener;
|
||||
close(): Promise<void>;
|
||||
ref(): this;
|
||||
unref(): this;
|
||||
[Symbol.asyncDispose](): Promise<void>;
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { constants } from 'node:os';
|
||||
import { dlopen } from 'node:process';
|
||||
import load from 'node-gyp-build';
|
||||
import createCrypto from './crypto.js';
|
||||
|
||||
const binding = { exports: {} };
|
||||
const flags = process.platform === 'linux'
|
||||
? constants.dlopen.RTLD_LAZY | constants.dlopen.RTLD_DEEPBIND
|
||||
: undefined;
|
||||
dlopen(binding, process.env.OPENDHT_NODE_BINDING || load.path(import.meta.dirname),
|
||||
flags);
|
||||
const native = binding.exports;
|
||||
const { PublicKey, PrivateKey, Certificate, Identity, handle } = createCrypto(native);
|
||||
|
||||
function eventReporter(owner, event) {
|
||||
return value => { owner.deref()?.emit(event, value); };
|
||||
}
|
||||
|
||||
class DhtRunner extends EventEmitter {
|
||||
#native;
|
||||
#closing;
|
||||
#listeners = 0;
|
||||
#pending = 0;
|
||||
#iterators = new Set();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
const owner = new WeakRef(this);
|
||||
this.#native = new native.NativeRunner(eventReporter(owner, 'statusChanged'));
|
||||
}
|
||||
|
||||
#updateOwner() {
|
||||
this.#native.setOwner(this.#listeners || this.#pending || this.listenerCount('statusChanged') ? this : null);
|
||||
}
|
||||
|
||||
#track(operation) {
|
||||
this.#pending++;
|
||||
this.#updateOwner();
|
||||
return operation.finally(() => {
|
||||
this.#pending--;
|
||||
this.#updateOwner();
|
||||
});
|
||||
}
|
||||
|
||||
on(event, listener) { super.on(event, listener); this.#updateOwner(); return this; }
|
||||
addListener(event, listener) { return this.on(event, listener); }
|
||||
prependListener(event, listener) { super.prependListener(event, listener); this.#updateOwner(); return this; }
|
||||
removeListener(event, listener) { super.removeListener(event, listener); this.#updateOwner(); return this; }
|
||||
off(event, listener) { return this.removeListener(event, listener); }
|
||||
removeAllListeners(...args) { super.removeAllListeners(...args); this.#updateOwner(); return this; }
|
||||
|
||||
run(options) {
|
||||
if (typeof options?.proxyServer === 'string' && options.proxyServer) {
|
||||
const proxy = new URL(options.proxyServer);
|
||||
if (proxy.protocol !== 'http:' && proxy.protocol !== 'https:')
|
||||
throw new TypeError('proxyServer must be an HTTP(S) URL');
|
||||
}
|
||||
if (options?.identity !== undefined) options = { ...options, identity: handle(options.identity, Identity) };
|
||||
this.#native.run(options);
|
||||
}
|
||||
isRunning() { return this.#native.isRunning(); }
|
||||
getBoundPort(family = 4) { return this.#native.getBoundPort(family); }
|
||||
getNodeId() { return this.#native.getNodeId(); }
|
||||
getStatus() { return this.#native.getStatus(); }
|
||||
bootstrap(host, port) { this.#native.bootstrap(host, port); }
|
||||
get(key) {
|
||||
return this.#iterate((push, finish) => {
|
||||
const operation = this.#native.get(key, push);
|
||||
this.#track(operation.done).then(() => finish(), finish);
|
||||
return () => this.#native.cancelGet(operation.token);
|
||||
}, true);
|
||||
}
|
||||
getAll(key) { return this.#track(this.#native.getAll(key)); }
|
||||
put(key, data, options) { return this.#track(this.#native.put(key, data, options)); }
|
||||
putSigned(key, data, options) { return this.#track(this.#native.putSigned(key, data, options)); }
|
||||
putEncrypted(key, data, recipient, options) {
|
||||
return this.#track(this.#native.putEncrypted(key, data, options, handle(recipient, PublicKey)));
|
||||
}
|
||||
|
||||
listen(key, callback) {
|
||||
if (callback === undefined) {
|
||||
return this.#iterate(push => {
|
||||
const subscription = this.listen(key, (value, expired) => push({ value, expired }));
|
||||
return () => subscription.cancel();
|
||||
});
|
||||
}
|
||||
const token = this.#native.listen(key, callback);
|
||||
this.#listeners++;
|
||||
this.#updateOwner();
|
||||
let cancelled = false;
|
||||
return {
|
||||
cancel: () => {
|
||||
if (cancelled) return;
|
||||
this.#native.cancelListen(token);
|
||||
cancelled = true;
|
||||
this.#listeners--;
|
||||
this.#updateOwner();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
#iterate(subscribe, rejectOnClose = false) {
|
||||
let values = [];
|
||||
let offset = 0;
|
||||
const pending = [];
|
||||
let done = false;
|
||||
let failure;
|
||||
const finish = error => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
failure = error;
|
||||
unsubscribe();
|
||||
this.#iterators.delete(onClose);
|
||||
if (failure) {
|
||||
values = [];
|
||||
offset = 0;
|
||||
}
|
||||
for (const { resolve, reject } of pending.splice(0)) {
|
||||
if (failure) reject(failure);
|
||||
else resolve({ value: undefined, done: true });
|
||||
}
|
||||
};
|
||||
const cancel = () => {
|
||||
values = [];
|
||||
offset = 0;
|
||||
failure = undefined;
|
||||
finish();
|
||||
};
|
||||
const onClose = () => {
|
||||
if (rejectOnClose) {
|
||||
const error = new Error('DHT runner is closed');
|
||||
error.code = 'ERR_DHT_CLOSED';
|
||||
finish(error);
|
||||
} else cancel();
|
||||
};
|
||||
const unsubscribe = subscribe(value => {
|
||||
if (done) return;
|
||||
const waiter = pending.shift();
|
||||
if (waiter) waiter.resolve({ value, done: false });
|
||||
else values.push(value);
|
||||
}, finish);
|
||||
this.#iterators.add(onClose);
|
||||
return {
|
||||
next() {
|
||||
if (failure) return Promise.reject(failure);
|
||||
if (offset < values.length) {
|
||||
const value = values[offset];
|
||||
values[offset++] = undefined;
|
||||
if (offset === values.length) {
|
||||
values = [];
|
||||
offset = 0;
|
||||
}
|
||||
return Promise.resolve({ value, done: false });
|
||||
}
|
||||
if (done) return Promise.resolve({ value: undefined, done: true });
|
||||
return new Promise((resolve, reject) => pending.push({ resolve, reject }));
|
||||
},
|
||||
return() {
|
||||
cancel();
|
||||
return Promise.resolve({ value: undefined, done: true });
|
||||
},
|
||||
throw(error) {
|
||||
cancel();
|
||||
return Promise.reject(error);
|
||||
},
|
||||
cancel,
|
||||
[Symbol.asyncIterator]() { return this; },
|
||||
[Symbol.asyncDispose]() { cancel(); return Promise.resolve(); },
|
||||
};
|
||||
}
|
||||
|
||||
close() {
|
||||
if (!this.#closing) {
|
||||
this.#closing = this.#native.close();
|
||||
for (const cancel of this.#iterators) cancel();
|
||||
}
|
||||
return this.#closing;
|
||||
}
|
||||
ref() { this.#native.ref(); return this; }
|
||||
unref() { this.#native.unref(); return this; }
|
||||
[Symbol.asyncDispose]() { return this.close(); }
|
||||
}
|
||||
|
||||
export { DhtRunner, PublicKey, PrivateKey, Certificate, Identity };
|
||||
export const hash = native.hash;
|
||||
export const version = native.version;
|
||||
Generated
+904
@@ -0,0 +1,904 @@
|
||||
{
|
||||
"name": "opendht",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "opendht",
|
||||
"version": "0.1.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"node-gyp-build": "^4.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"cmake-js": "^8.0.0",
|
||||
"node-addon-api": "^8.5.0",
|
||||
"typescript": "^7.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@isaacs/fs-minipass": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
|
||||
"integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"minipass": "^7.0.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-aix-ppc64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
|
||||
"integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"aix"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-darwin-arm64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
|
||||
"integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-darwin-x64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
|
||||
"integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-freebsd-arm64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
|
||||
"integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-freebsd-x64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
|
||||
"integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-arm": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
|
||||
"integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-arm64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
|
||||
"integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-loong64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
|
||||
"integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-mips64el": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
|
||||
"integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-ppc64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
|
||||
"integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-riscv64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
|
||||
"integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-s390x": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
|
||||
"integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-linux-x64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
|
||||
"integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-netbsd-arm64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
|
||||
"integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-netbsd-x64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
|
||||
"integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-openbsd-arm64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
|
||||
"integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-openbsd-x64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
|
||||
"integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-sunos-x64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
|
||||
"integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-win32-arm64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
|
||||
"integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/typescript-win32-x64": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
|
||||
"integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/ansi-styles": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
|
||||
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-convert": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/chownr": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
|
||||
"integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
|
||||
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.1",
|
||||
"wrap-ansi": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/cmake-js": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cmake-js/-/cmake-js-8.0.0.tgz",
|
||||
"integrity": "sha512-YbUP88RDwCvoQkZhRtGURYm9RIpWdtvZuhT87fKNoLjk8kIFIFeARpKfuZQGdwfH99GZpUmqSfcDrK62X7lTgg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"debug": "^4.4.3",
|
||||
"fs-extra": "^11.3.3",
|
||||
"node-api-headers": "^1.8.0",
|
||||
"rc": "1.2.8",
|
||||
"semver": "^7.7.3",
|
||||
"tar": "^7.5.6",
|
||||
"url-join": "^4.0.1",
|
||||
"which": "^6.0.0",
|
||||
"yargs": "^17.7.2"
|
||||
},
|
||||
"bin": {
|
||||
"cmake-js": "bin/cmake-js"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.17.0 || >=22.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"color-name": "~1.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=7.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-name": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
|
||||
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
|
||||
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"supports-color": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/deep-extend": {
|
||||
"version": "0.6.0",
|
||||
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
|
||||
"integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/emoji-regex": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
|
||||
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
|
||||
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/fs-extra": {
|
||||
"version": "11.4.1",
|
||||
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.4.1.tgz",
|
||||
"integrity": "sha512-KYAb4c9BJQI6QqGKthV68OHe0badztdXJWKo0WtBA9IuCFPTKvE5ZdUBglP833aMjhaSPNO4A5j/EkzZtGlKjA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"graceful-fs": "^4.2.0",
|
||||
"jsonfile": "^6.0.1",
|
||||
"universalify": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.14"
|
||||
}
|
||||
},
|
||||
"node_modules/get-caller-file": {
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
|
||||
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": "6.* || 8.* || >= 10.*"
|
||||
}
|
||||
},
|
||||
"node_modules/graceful-fs": {
|
||||
"version": "4.2.11",
|
||||
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
|
||||
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/ini": {
|
||||
"version": "1.3.8",
|
||||
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
|
||||
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/is-fullwidth-code-point": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
|
||||
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/isexe": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/isexe/-/isexe-4.0.0.tgz",
|
||||
"integrity": "sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonfile": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
|
||||
"integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"universalify": "^2.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"graceful-fs": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/minimist": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
|
||||
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/minipass": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
|
||||
"integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/minizlib": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",
|
||||
"integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"minipass": "^7.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
}
|
||||
},
|
||||
"node_modules/ms": {
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/node-addon-api": {
|
||||
"version": "8.9.2",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz",
|
||||
"integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^18 || ^20 || >= 21"
|
||||
}
|
||||
},
|
||||
"node_modules/node-api-headers": {
|
||||
"version": "1.9.0",
|
||||
"resolved": "https://registry.npmjs.org/node-api-headers/-/node-api-headers-1.9.0.tgz",
|
||||
"integrity": "sha512-2oNILP4jXwRB4ywnYKjVk1YyJ96n2D4EOVJO6S3oYZ5PtbJrw3Yt9TpAuX3nBLMuzn74rnfGQrv13pS9vC+YiA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/node-gyp-build": {
|
||||
"version": "4.8.4",
|
||||
"resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz",
|
||||
"integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"node-gyp-build": "bin.js",
|
||||
"node-gyp-build-optional": "optional.js",
|
||||
"node-gyp-build-test": "build-test.js"
|
||||
}
|
||||
},
|
||||
"node_modules/rc": {
|
||||
"version": "1.2.8",
|
||||
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
|
||||
"integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
|
||||
"dev": true,
|
||||
"license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
|
||||
"dependencies": {
|
||||
"deep-extend": "^0.6.0",
|
||||
"ini": "~1.3.0",
|
||||
"minimist": "^1.2.0",
|
||||
"strip-json-comments": "~2.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"rc": "cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/require-directory": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
|
||||
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.8.5",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
||||
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/string-width": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/strip-json-comments": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
|
||||
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tar": {
|
||||
"version": "7.5.22",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",
|
||||
"integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"@isaacs/fs-minipass": "^4.0.0",
|
||||
"chownr": "^3.0.0",
|
||||
"minipass": "^7.1.2",
|
||||
"minizlib": "^3.1.0",
|
||||
"yallist": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
|
||||
"integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.20.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@typescript/typescript-aix-ppc64": "7.0.2",
|
||||
"@typescript/typescript-darwin-arm64": "7.0.2",
|
||||
"@typescript/typescript-darwin-x64": "7.0.2",
|
||||
"@typescript/typescript-freebsd-arm64": "7.0.2",
|
||||
"@typescript/typescript-freebsd-x64": "7.0.2",
|
||||
"@typescript/typescript-linux-arm": "7.0.2",
|
||||
"@typescript/typescript-linux-arm64": "7.0.2",
|
||||
"@typescript/typescript-linux-loong64": "7.0.2",
|
||||
"@typescript/typescript-linux-mips64el": "7.0.2",
|
||||
"@typescript/typescript-linux-ppc64": "7.0.2",
|
||||
"@typescript/typescript-linux-riscv64": "7.0.2",
|
||||
"@typescript/typescript-linux-s390x": "7.0.2",
|
||||
"@typescript/typescript-linux-x64": "7.0.2",
|
||||
"@typescript/typescript-netbsd-arm64": "7.0.2",
|
||||
"@typescript/typescript-netbsd-x64": "7.0.2",
|
||||
"@typescript/typescript-openbsd-arm64": "7.0.2",
|
||||
"@typescript/typescript-openbsd-x64": "7.0.2",
|
||||
"@typescript/typescript-sunos-x64": "7.0.2",
|
||||
"@typescript/typescript-win32-arm64": "7.0.2",
|
||||
"@typescript/typescript-win32-x64": "7.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/universalify": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
|
||||
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/url-join": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz",
|
||||
"integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-6.0.1.tgz",
|
||||
"integrity": "sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"isexe": "^4.0.0"
|
||||
},
|
||||
"bin": {
|
||||
"node-which": "bin/which.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.17.0 || >=22.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
|
||||
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/chalk/wrap-ansi?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/yallist": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
|
||||
"integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "17.7.3",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz",
|
||||
"integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^8.0.1",
|
||||
"escalade": "^3.1.1",
|
||||
"get-caller-file": "^2.0.5",
|
||||
"require-directory": "^2.1.1",
|
||||
"string-width": "^4.2.3",
|
||||
"y18n": "^5.0.5",
|
||||
"yargs-parser": "^21.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "21.1.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
|
||||
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"name": "opendht",
|
||||
"version": "0.1.0",
|
||||
"description": "Distributed hash table for Node.js",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/savoirfairelinux/opendht.git",
|
||||
"directory": "nodejs"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org/"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"types": "index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"import": "./index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"crypto.js",
|
||||
"README.md",
|
||||
"examples/dhtnode.js",
|
||||
"examples/dhtnode.ts",
|
||||
"prebuilds/"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=22.9.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "cmake-js compile",
|
||||
"postbuild": "npm run build:examples",
|
||||
"build:examples": "tsc --strict --types node --target es2024 --module Node16 --moduleResolution Node16 --rootDir examples --outDir examples examples/dhtnode.ts",
|
||||
"dhtnode": "node examples/dhtnode.js",
|
||||
"prepack": "npm run build:examples",
|
||||
"bundle": "node scripts/bundle.js",
|
||||
"package": "npm run bundle && npm pack --pack-destination dist",
|
||||
"test:package": "node scripts/test-package.js",
|
||||
"test": "node --test test/*.test.js",
|
||||
"typecheck": "tsc --noEmit --strict --types node --target es2024 --module Node16 --moduleResolution Node16 test/types.ts examples/dhtnode.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"node-gyp-build": "^4.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"cmake-js": "^8.0.0",
|
||||
"node-addon-api": "^8.8.0",
|
||||
"typescript": "^7.0.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..');
|
||||
const repository = path.dirname(root);
|
||||
const input = path.resolve(process.argv[2] || path.join(root, 'build/Release/opendht.node'));
|
||||
const target = `${process.platform}-${process.arch}`;
|
||||
const output = path.join(root, 'prebuilds', target);
|
||||
const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'opendht-bundle-'));
|
||||
const run = (command, args) => execFileSync(command, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] });
|
||||
|
||||
function copyNotices(dependencies) {
|
||||
const directory = path.join(output, 'licenses');
|
||||
fs.mkdirSync(directory, { recursive: true });
|
||||
fs.copyFileSync(path.join(repository, 'LICENSE'), path.join(directory, 'OpenDHT-LICENSE.txt'));
|
||||
const copied = new Set();
|
||||
for (const dependency of dependencies) {
|
||||
const real = fs.realpathSync(dependency);
|
||||
if (!path.relative(repository, real).startsWith('..')) continue;
|
||||
let name;
|
||||
let notices;
|
||||
if (process.platform === 'darwin') {
|
||||
const match = real.match(/^(.*\/Cellar\/([^/]+)\/[^/]+)\//);
|
||||
if (!match) throw new Error(`Cannot locate license notices for ${dependency}`);
|
||||
name = match[2];
|
||||
notices = fs.readdirSync(match[1]).filter(file => /^(COPYING|LICENSE|COPYRIGHT)([._-]|$)/i.test(file))
|
||||
.map(file => path.join(match[1], file));
|
||||
} else if (process.platform === 'linux' && /^libllhttp\.so(?:\.|$)/.test(path.basename(real))) {
|
||||
name = 'llhttp';
|
||||
notices = [path.join(repository, 'resources', 'llhttp-LICENSE-MIT')];
|
||||
} else if (process.platform === 'linux') {
|
||||
let owner;
|
||||
try { owner = run('dpkg-query', ['-S', real]); }
|
||||
catch { owner = run('dpkg-query', ['-S', real.replace(/^\/usr\//, '/')]); }
|
||||
name = owner.split('\n')[0].split(': ')[0].split(':')[0];
|
||||
notices = [path.join('/usr/share/doc', name, 'copyright')];
|
||||
} else {
|
||||
const installed = process.env.VCPKG_INSTALLED_DIR;
|
||||
const triplet = process.env.VCPKG_DEFAULT_TRIPLET || 'x64-windows-release';
|
||||
if (!installed) throw new Error('VCPKG_INSTALLED_DIR is required for Windows dependency notices');
|
||||
const share = path.join(installed, triplet, 'share');
|
||||
for (const entry of fs.readdirSync(share)) {
|
||||
const copyright = path.join(share, entry, 'copyright');
|
||||
if (fs.existsSync(copyright)) fs.copyFileSync(copyright, path.join(directory, `${entry}-copyright.txt`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!notices.length) throw new Error(`Missing license notices for ${name}`);
|
||||
if (copied.has(name)) continue;
|
||||
for (const notice of notices) fs.copyFileSync(notice, path.join(directory, `${name}-${path.basename(notice)}.txt`));
|
||||
copied.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
function fixMachO(file) {
|
||||
const commands = run('otool', ['-l', file]);
|
||||
const rpaths = [...commands.matchAll(/cmd LC_RPATH\s+cmdsize \d+\s+path (.+?) \(offset \d+\)/g)];
|
||||
for (const rpath of new Set(rpaths.map(match => match[1]))) run('install_name_tool', ['-delete_rpath', rpath, file]);
|
||||
const dependencies = [...run('otool', ['-L', file]).matchAll(/^\s+(.+?) \(compatibility version/gm)];
|
||||
for (const [, dependency] of dependencies) {
|
||||
if (!/^(@loader_path\/|\/usr\/lib\/|\/System\/Library\/)/.test(dependency)) {
|
||||
throw new Error(`Non-relocatable dependency in ${path.basename(file)}: ${dependency}`);
|
||||
}
|
||||
}
|
||||
run('codesign', ['--force', '--sign', '-', file]);
|
||||
}
|
||||
|
||||
try {
|
||||
if (!['darwin', 'linux', 'win32'].includes(process.platform)) throw new Error(`Unsupported platform ${target}`);
|
||||
if (!fs.existsSync(input)) throw new Error(`Build the Release addon first: ${input}`);
|
||||
if (process.platform === 'linux' && !process.report.getReport().header.glibcVersionRuntime) {
|
||||
throw new Error('Linux prebuilds currently require glibc');
|
||||
}
|
||||
const directories = [path.dirname(input), ...(process.env.OPENDHT_LIBRARY_PATH || '').split(path.delimiter).filter(Boolean)];
|
||||
const dependencyList = path.join(temporary, 'dependencies.json');
|
||||
run('cmake', [`-DADDON=${input}`, `-DOUTPUT=${dependencyList}`, `-DSEARCH_DIRECTORIES=${directories.join(';')}`,
|
||||
'-P', path.join(import.meta.dirname, 'dependencies.cmake')]);
|
||||
const dependencies = JSON.parse(fs.readFileSync(dependencyList, 'utf8'));
|
||||
fs.rmSync(output, { recursive: true, force: true });
|
||||
fs.mkdirSync(output, { recursive: true });
|
||||
const binary = path.join(output, process.platform === 'linux' ? 'node.napi.glibc.node' : 'node.napi.node');
|
||||
fs.copyFileSync(input, binary);
|
||||
if (process.platform === 'darwin') {
|
||||
run('dylibbundler', ['-b', '-of', '-ns', '-x', binary, '-d', `${output}/`, '-p', '@loader_path/', '-s', path.dirname(input)]);
|
||||
for (const file of fs.readdirSync(output)) fixMachO(path.join(output, file));
|
||||
} else {
|
||||
for (const dependency of dependencies) fs.copyFileSync(dependency, path.join(output, path.basename(dependency)));
|
||||
if (process.platform === 'linux') {
|
||||
for (const file of fs.readdirSync(output)) run('patchelf', ['--set-rpath', '$ORIGIN', path.join(output, file)]);
|
||||
}
|
||||
}
|
||||
copyNotices(dependencies);
|
||||
fs.writeFileSync(path.join(output, 'manifest.json'), JSON.stringify({
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
napi: 8,
|
||||
libraries: fs.readdirSync(output).filter(file => /\.(node|dll|dylib)$|\.so(\.|$)/.test(file)).sort(),
|
||||
}, null, 2) + '\n');
|
||||
fs.mkdirSync(path.join(root, 'dist'), { recursive: true });
|
||||
console.log(`Bundled ${target}: ${output}`);
|
||||
} finally {
|
||||
fs.rmSync(temporary, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
|
||||
if(NOT EXISTS "${ADDON}" OR NOT DEFINED OUTPUT)
|
||||
message(FATAL_ERROR "ADDON and OUTPUT are required")
|
||||
endif()
|
||||
|
||||
set(pre_exclude)
|
||||
set(post_exclude)
|
||||
if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
|
||||
list(APPEND pre_exclude "^/usr/lib/" "^/System/Library/")
|
||||
list(APPEND post_exclude "^/usr/lib/" "^/System/Library/")
|
||||
elseif(CMAKE_HOST_SYSTEM_NAME STREQUAL "Linux")
|
||||
list(APPEND pre_exclude "^ld-linux" "^lib(c|m|dl|rt|pthread|resolv|util|gcc_s|stdc\\+\\+)\\.so")
|
||||
elseif(CMAKE_HOST_WIN32)
|
||||
list(APPEND pre_exclude "[Nn][Oo][Dd][Ee]\\.exe" "[Aa][Pp][Ii]-[Mm][Ss]-.*" "[Ee][Xx][Tt]-[Mm][Ss]-.*")
|
||||
list(APPEND post_exclude ".*[Ss][Yy][Ss][Tt][Ee][Mm]32[/\\\\].*")
|
||||
endif()
|
||||
|
||||
file(GET_RUNTIME_DEPENDENCIES
|
||||
MODULES "${ADDON}"
|
||||
DIRECTORIES ${SEARCH_DIRECTORIES}
|
||||
RESOLVED_DEPENDENCIES_VAR dependencies
|
||||
UNRESOLVED_DEPENDENCIES_VAR unresolved
|
||||
CONFLICTING_DEPENDENCIES_PREFIX conflicts
|
||||
PRE_EXCLUDE_REGEXES ${pre_exclude}
|
||||
POST_EXCLUDE_REGEXES ${post_exclude}
|
||||
)
|
||||
if(unresolved OR conflicts_FILENAMES)
|
||||
message(FATAL_ERROR "Unresolved dependencies: ${unresolved}; conflicting dependencies: ${conflicts_FILENAMES}")
|
||||
endif()
|
||||
|
||||
set(result "[]")
|
||||
set(index 0)
|
||||
foreach(dependency IN LISTS dependencies)
|
||||
file(TO_CMAKE_PATH "${dependency}" dependency)
|
||||
string(JSON result SET "${result}" ${index} "\"${dependency}\"")
|
||||
math(EXPR index "${index} + 1")
|
||||
endforeach()
|
||||
file(WRITE "${OUTPUT}" "${result}\n")
|
||||
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user