mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-23 07:20:34 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6d0d698dd | ||
|
|
54c85253e3 | ||
|
|
5061c0f2bc | ||
|
|
d7151fde2f | ||
|
|
83be931e74 | ||
|
|
a839ec05c6 | ||
|
|
7631c75afd | ||
|
|
5dadbd44bd | ||
|
|
dfb229bb4e | ||
|
|
82502fb72c | ||
|
|
5e35c9f9d9 | ||
|
|
0ce5a12a65 | ||
|
|
24db8a0245 | ||
|
|
3d53958892 | ||
|
|
137c84e390 | ||
|
|
dec159dae4 | ||
|
|
973b8a8cd4 | ||
|
|
428c22ff15 | ||
|
|
8ce5059a55 | ||
|
|
0e9bf3408a | ||
|
|
f6b1190eba | ||
|
|
2d77484f93 | ||
|
|
d29bc9c42c | ||
|
|
6d2dad4f55 | ||
|
|
d623f2a604 | ||
|
|
3bb885cd63 | ||
|
|
ee9190db0f | ||
|
|
2fccaf0410 | ||
|
|
168ba42f89 | ||
|
|
f03a0c739d | ||
|
|
65d683404b | ||
|
|
4c4418ca93 | ||
|
|
3cd4ecadaa | ||
|
|
3aaff26b22 | ||
|
|
559525c3a4 | ||
|
|
add9d4f4b2 | ||
|
|
a9d534add4 | ||
|
|
09bb5c84dc | ||
|
|
dc77cdf014 | ||
|
|
5a974ae115 | ||
|
|
d7ec577253 | ||
|
|
03b6f411ad | ||
|
|
80b64223dc | ||
|
|
9b9226218d | ||
|
|
403c8084ba | ||
|
|
b0125cea65 | ||
|
|
4845bc1f93 | ||
|
|
7358306512 | ||
|
|
f0eedf453e | ||
|
|
df7b142d34 | ||
|
|
0e937f32ff | ||
|
|
45172c1cac | ||
|
|
b160045758 | ||
|
|
031550bbd6 | ||
|
|
2988da3757 | ||
|
|
7005c32200 | ||
|
|
0f411d35fb | ||
|
|
422b978a61 | ||
|
|
26e4bc308d | ||
|
|
54cdcbcc74 | ||
|
|
3811338f39 | ||
|
|
e1ce7f0064 | ||
|
|
124cc1ca6b | ||
|
|
27de48acc1 | ||
|
|
ad8c98cd0d | ||
|
|
20ed5a07b1 | ||
|
|
3d04714a3b | ||
|
|
874f742c27 | ||
|
|
8bdd1f828a | ||
|
|
0842e9d86e | ||
|
|
9bd2b80fba | ||
|
|
8e2dbf2bb9 | ||
|
|
55e6f37140 | ||
|
|
e8a21ce00c | ||
|
|
5b7ac43a82 | ||
|
|
0fa0d5e978 | ||
|
|
a25e7d384e | ||
|
|
73ca12852d | ||
|
|
19e65d4da9 | ||
|
|
71497c858d | ||
|
|
5976f6bcce | ||
|
|
801c8a1035 | ||
|
|
34bad16f7d | ||
|
|
a088135b0e | ||
|
|
acab1fa55d | ||
|
|
ac1da396b5 | ||
|
|
9360fc8c4a | ||
|
|
2162c48b8f | ||
|
|
42888c7ac5 | ||
|
|
dcb94baa54 | ||
|
|
40aa3010a7 | ||
|
|
184bbfe59f | ||
|
|
1f5dde228f | ||
|
|
b2b30181e2 | ||
|
|
c4df19970d | ||
|
|
df5813a4b9 | ||
|
|
bbb3e52d52 | ||
|
|
81e6188e4c | ||
|
|
0680941fe4 | ||
|
|
0b295761c7 | ||
|
|
70e3d99279 | ||
|
|
fcdc8a93c5 | ||
|
|
d0a82bf199 | ||
|
|
cce85ec4e3 | ||
|
|
499a98aa03 | ||
|
|
2aee96ea4f | ||
|
|
21a22cbd2d | ||
|
|
5d8db3fd69 | ||
|
|
336373adcf | ||
|
|
31bdb54add | ||
|
|
a7f0ac2068 | ||
|
|
f31601fe71 | ||
|
|
fa70313858 | ||
|
|
8652acfaa3 | ||
|
|
0d98f0fd5b | ||
|
|
ce7f8aba55 | ||
|
|
75eb2313c6 | ||
|
|
aab917cb8c | ||
|
|
4d9d0d8c91 | ||
|
|
054e5922d6 | ||
|
|
c6d0abff64 | ||
|
|
4bfd0fa0fb | ||
|
|
a91e5577d9 | ||
|
|
cddf87d8d2 | ||
|
|
0de36832cb | ||
|
|
0d08659d8d | ||
|
|
0b619340ac | ||
|
|
92e76abd4c | ||
|
|
6e29443a7a | ||
|
|
4a815425ae | ||
|
|
b361752da3 | ||
|
|
73c6f7e92a | ||
|
|
a7af017149 | ||
|
|
a5131adc10 | ||
|
|
a0d8743651 | ||
|
|
31a62417f5 | ||
|
|
96035aa868 | ||
|
|
0072220024 | ||
|
|
42305b99c9 | ||
|
|
230efd113e | ||
|
|
df3ca5346a | ||
|
|
21e83307b0 | ||
|
|
c52cf3a5bb | ||
|
|
86e2ab637a | ||
|
|
213d40afa2 | ||
|
|
e3f7387c20 | ||
|
|
88724e75d0 | ||
|
|
8fade5d1e9 | ||
|
|
d098c5962a | ||
|
|
c14e2240dd | ||
|
|
058a9bf61c | ||
|
|
06ae0a0f17 | ||
|
|
acd7161f95 | ||
|
|
b93a257f4f | ||
|
|
3b45cc51b4 | ||
|
|
ca7f2e9fa1 | ||
|
|
29db8b25b8 | ||
|
|
29ab0d5abf | ||
|
|
7bb8a54e65 | ||
|
|
c478f7ffd6 | ||
|
|
631d0e8894 | ||
|
|
8aa892ef38 | ||
|
|
6236a77b43 | ||
|
|
29d0ec5607 | ||
|
|
38ec177192 | ||
|
|
b24d70537d | ||
|
|
3eec4e0995 | ||
|
|
fc62f7e94a | ||
|
|
f11acebb17 | ||
|
|
5cbd32ff34 | ||
|
|
6bc738385a | ||
|
|
7f6d964789 | ||
|
|
bd0c17a05a | ||
|
|
8fd968d6af | ||
|
|
a2e5baacc3 | ||
|
|
2f2994b128 | ||
|
|
8eb1c968d0 | ||
|
|
fff94dd18b | ||
|
|
8db3a4fecc | ||
|
|
0034e99fe8 | ||
|
|
e78bf7b9dd | ||
|
|
e1f82ac5bf | ||
|
|
af2071ed66 | ||
|
|
f3b777a700 | ||
|
|
e550ee20d3 | ||
|
|
49cb222f88 | ||
|
|
ee52f65aaa | ||
|
|
1a5b9d013f | ||
|
|
3d539fdd66 | ||
|
|
755f8c7a22 | ||
|
|
d7b58f3cbd | ||
|
|
a69b5f3b13 | ||
|
|
d9e46ba89a | ||
|
|
f8e542b4c4 | ||
|
|
293e8c313e | ||
|
|
0d57eabc6a | ||
|
|
0fa730990b | ||
|
|
92f2e10230 | ||
|
|
fc7e2f8349 | ||
|
|
8a1cc231e5 | ||
|
|
bff429454a | ||
|
|
a5a684fbb0 | ||
|
|
24b0021f98 | ||
|
|
3f115ae96c | ||
|
|
a81eee4a72 | ||
|
|
1897c8b666 | ||
|
|
fd005be9bd | ||
|
|
6225ed311d | ||
|
|
5d2ca072e8 | ||
|
|
fd43574c8a | ||
|
|
e008436d56 | ||
|
|
52488d778d | ||
|
|
12e3882b55 | ||
|
|
7611cc2bfb | ||
|
|
37abfc0434 | ||
|
|
8e69959b28 | ||
|
|
d208b61265 | ||
|
|
ceb4950ad2 | ||
|
|
d2205e31ba | ||
|
|
4b9e3409cd | ||
|
|
4518647728 | ||
|
|
939b28c0af | ||
|
|
24f7d1f259 | ||
|
|
fb50850632 | ||
|
|
92dbf5f0e8 | ||
|
|
b8c1446b93 | ||
|
|
14241a3839 | ||
|
|
302626c38a | ||
|
|
ac9ea27752 | ||
|
|
4bf5679bd5 | ||
|
|
6ce6aa8dba | ||
|
|
fdedbd2c8b | ||
|
|
7071bae90e | ||
|
|
b217cb3f59 | ||
|
|
dc50ce5390 | ||
|
|
5b38cae702 | ||
|
|
5a448fdebf | ||
|
|
bf7d16fc36 | ||
|
|
48adcf726e | ||
|
|
f1caa4571d | ||
|
|
30e433a9cb | ||
|
|
b56a427c4a | ||
|
|
0267f42001 | ||
|
|
5ac4820b32 | ||
|
|
c3b3fd1c1f | ||
|
|
55072d1ca2 | ||
|
|
06597b5869 | ||
|
|
442196c71a | ||
|
|
45b49db0c1 | ||
|
|
21100300fc | ||
|
|
6aa1d4bbf1 | ||
|
|
3311c0a7b1 | ||
|
|
6bdc82af93 | ||
|
|
215250d2b2 | ||
|
|
881f7b926d | ||
|
|
d1c6d508c9 | ||
|
|
5366b1d3d3 | ||
|
|
588fdfc123 | ||
|
|
a551770f63 | ||
|
|
416f1ae86c | ||
|
|
ad10380bbb | ||
|
|
708b37b017 | ||
|
|
6d2619cc48 | ||
|
|
8c841a92f1 | ||
|
|
56b6bcefa5 | ||
|
|
efbc495e84 | ||
|
|
2992377739 | ||
|
|
692260e79b | ||
|
|
48e355a943 | ||
|
|
cd091604d2 | ||
|
|
08d246ed22 | ||
|
|
04f9324cd5 | ||
|
|
e16c8b4d39 | ||
|
|
4683cb2c2a | ||
|
|
379312e305 | ||
|
|
b79bcdb38b | ||
|
|
4c6217597a | ||
|
|
cb929d5f65 | ||
|
|
ef551de12b | ||
|
|
09ae5d6e26 | ||
|
|
9d7b2bd429 | ||
|
|
f3f72ead60 | ||
|
|
53515b3d41 | ||
|
|
846833a197 | ||
|
|
c44744ecee | ||
|
|
4ea028eb75 | ||
|
|
fbbc311192 | ||
|
|
1801cf291a | ||
|
|
264b00eb3d | ||
|
|
2e8fa290dc | ||
|
|
feb11b0089 | ||
|
|
1371918851 | ||
|
|
65d95eed33 | ||
|
|
6e412dc9e0 | ||
|
|
b774544cbb | ||
|
|
af65181e49 | ||
|
|
acd59b178e | ||
|
|
52ab6c02d7 | ||
|
|
f9d848866e | ||
|
|
562bc99da7 | ||
|
|
d738238b4e | ||
|
|
e5e8401fc7 | ||
|
|
d047641898 | ||
|
|
76cfd48b29 | ||
|
|
42b53c5538 | ||
|
|
5468316087 | ||
|
|
c4788883f3 | ||
|
|
8b046794f1 | ||
|
|
85f29bcfd3 | ||
|
|
465ec096a5 | ||
|
|
b6f9e788b2 | ||
|
|
1a835f0acc | ||
|
|
506852837c | ||
|
|
8fcf0b678a | ||
|
|
817a640ed1 | ||
|
|
4bba059d93 | ||
|
|
7a33f4297f | ||
|
|
df94572ff6 | ||
|
|
799e946ac9 | ||
|
|
6a425e8d5a | ||
|
|
032c3fd6d3 | ||
|
|
1ff0134979 | ||
|
|
1a0a74ad06 | ||
|
|
5275fbb402 | ||
|
|
0f8731bb5b | ||
|
|
6bbac52ea0 | ||
|
|
cac8151fd8 | ||
|
|
f64b4d22d9 | ||
|
|
5edb8f22f5 | ||
|
|
d4183434fc | ||
|
|
3ce9909f78 | ||
|
|
56c7a6e5d8 | ||
|
|
49aa33db1b | ||
|
|
bdbb6e9f63 | ||
|
|
8be3725a35 | ||
|
|
306eaa8a18 | ||
|
|
6abe1f3d4a | ||
|
|
92b91d6ba3 | ||
|
|
25c69c6f37 | ||
|
|
0279d2475a | ||
|
|
a7515f3f5a | ||
|
|
61f9573bc1 | ||
|
|
c64f0d238a | ||
|
|
3e56135fd8 | ||
|
|
70fe70fbbe | ||
|
|
9122eba38c | ||
|
|
23045c6a0f | ||
|
|
f3518ff7c1 | ||
|
|
e209c8789c | ||
|
|
edc3964823 | ||
|
|
a90f7e1ec7 | ||
|
|
ca729453e0 | ||
|
|
62e144ed27 | ||
|
|
9bc7ee5ff9 | ||
|
|
bd3c1d61ba | ||
|
|
1af490682f | ||
|
|
f6523fd5c5 | ||
|
|
555bb33fdf | ||
|
|
9f65990536 | ||
|
|
8f1d650614 | ||
|
|
67b60362aa | ||
|
|
9a18435b75 | ||
|
|
795058e5bf | ||
|
|
c0fa43664b | ||
|
|
3b3eb29c16 | ||
|
|
6f2a6e8759 | ||
|
|
7ffefa5b8c | ||
|
|
5b6b5eb951 | ||
|
|
8fac96aed8 | ||
|
|
199eeb43cb | ||
|
|
d3c28b1247 | ||
|
|
1d27e8140b | ||
|
|
6705e9804f | ||
|
|
ef4b54b0a5 | ||
|
|
340291f234 | ||
|
|
45bbe47506 | ||
|
|
041cfbed91 | ||
|
|
8b7e20d5bf | ||
|
|
61f625e6ed | ||
|
|
b4c0358beb | ||
|
|
02e1b3f090 | ||
|
|
a1639cc065 | ||
|
|
e0889f7188 | ||
|
|
dc6bc4ee82 | ||
|
|
4a924ce281 | ||
|
|
ab53670f98 | ||
|
|
31472d9251 | ||
|
|
51763a97dc | ||
|
|
cfb7253f99 | ||
|
|
c9b210a52b | ||
|
|
47dbbf1feb | ||
|
|
b927f26ca6 | ||
|
|
092cf5ac30 | ||
|
|
ccf2f11419 | ||
|
|
d9a1024a16 | ||
|
|
bd8c2d8264 | ||
|
|
b3bcd2b886 | ||
|
|
31c5269695 | ||
|
|
9300253cee | ||
|
|
0aeb4f02c9 | ||
|
|
f66047e2a2 | ||
|
|
3c527bd5cf | ||
|
|
2252b83470 | ||
|
|
1d38688b8f | ||
|
|
0049231139 | ||
|
|
d1b5659169 | ||
|
|
2fd604b4aa | ||
|
|
a9d26472d0 | ||
|
|
e43fefbc54 | ||
|
|
e19944f6c1 | ||
|
|
921eac40c2 | ||
|
|
f7ae0274c3 | ||
|
|
fbc2f1938b | ||
|
|
2e0d0a6888 | ||
|
|
6c77c9e69d | ||
|
|
27352fd0d4 | ||
|
|
fd973420f2 | ||
|
|
b12f331082 | ||
|
|
04300ecdf4 | ||
|
|
a1b78564e0 | ||
|
|
70b739988b | ||
|
|
140d0aeed4 | ||
|
|
ec61a566d3 | ||
|
|
1285e06cf6 | ||
|
|
bc419b109d | ||
|
|
eee619ef3b | ||
|
|
e47a1d4932 | ||
|
|
07ca72179e | ||
|
|
d24e4e3ce3 | ||
|
|
869322fa80 | ||
|
|
2bce74c74c | ||
|
|
8e58e1b708 | ||
|
|
7a187a7aa0 | ||
|
|
d424c96fa3 | ||
|
|
6547f8370d | ||
|
|
740051c41e | ||
|
|
04db8c9f46 | ||
|
|
9928abed26 | ||
|
|
9e7dd7d9b6 | ||
|
|
690c0faf05 | ||
|
|
5db4ca3eb5 | ||
|
|
5d010fb6fb | ||
|
|
7119f8019d | ||
|
|
df7c8decc1 | ||
|
|
8c8ec46da8 | ||
|
|
b2068105ae | ||
|
|
fb250c7a83 | ||
|
|
52e501fcfc | ||
|
|
dabe75fbb5 | ||
|
|
b9130e6002 | ||
|
|
126d974909 | ||
|
|
f9b457d329 | ||
|
|
93c4e3c4b1 | ||
|
|
5003e0ec8d | ||
|
|
ed58938c99 | ||
|
|
ac3239d221 | ||
|
|
fc97b9931a | ||
|
|
e7b76f8272 | ||
|
|
ba2845e166 | ||
|
|
f9bb83e089 | ||
|
|
808430d26d | ||
|
|
01fa84bf1f | ||
|
|
52998569fb | ||
|
|
5e310b7069 | ||
|
|
580ff63224 | ||
|
|
6f24711a38 | ||
|
|
12b43cebac | ||
|
|
97193439db | ||
|
|
fb976c4bc3 | ||
|
|
6b79393f58 | ||
|
|
b9287b7ecf | ||
|
|
76410efa50 | ||
|
|
b671acd51b | ||
|
|
2aada8b4db | ||
|
|
390146247d | ||
|
|
31632d7a90 | ||
|
|
4146eeb743 | ||
|
|
60a3b72146 | ||
|
|
4e1abca4ea | ||
|
|
b1854b62aa | ||
|
|
b59e8849a7 | ||
|
|
88d3d38277 | ||
|
|
b2aee9dc2c | ||
|
|
ba4ee2881f | ||
|
|
d6c3a010c0 | ||
|
|
3cccd8c7b0 | ||
|
|
74eb9949cb | ||
|
|
731fddcf73 | ||
|
|
6f43913a6c | ||
|
|
987cc947c7 | ||
|
|
1c7a0ea035 | ||
|
|
aeeb3c1ab9 | ||
|
|
7100021b75 | ||
|
|
59d59d335a | ||
|
|
e3bb3d171f | ||
|
|
0362446b74 | ||
|
|
2ec94069a4 | ||
|
|
bb7395b284 | ||
|
|
4ae8638b3e | ||
|
|
69d9e8a5b5 | ||
|
|
06a9bdd63f | ||
|
|
ca9bcae376 | ||
|
|
2be764308e | ||
|
|
a72c1215c1 | ||
|
|
a788ab984a | ||
|
|
2a67960f1d | ||
|
|
8370a1be66 | ||
|
|
30b40d8333 | ||
|
|
a319855c62 | ||
|
|
ee2b882a50 | ||
|
|
24b3dc3cbc | ||
|
|
acc0a3f93b | ||
|
|
e663260b11 | ||
|
|
69fa830d52 | ||
|
|
d406d76b35 | ||
|
|
9eed85392e | ||
|
|
82195eb2de | ||
|
|
1562d72ce1 | ||
|
|
8ae733e68a | ||
|
|
9b64aea819 | ||
|
|
d9f510a5ad | ||
|
|
cd816bee68 | ||
|
|
10ec9e9b3e | ||
|
|
4830142458 | ||
|
|
dfe42f2194 | ||
|
|
2bf531180e | ||
|
|
f284317d8d | ||
|
|
e15466bfb8 | ||
|
|
226f4fa800 | ||
|
|
a1ca1daa39 | ||
|
|
062170c541 | ||
|
|
8777f62a38 | ||
|
|
8645fdfacd | ||
|
|
b9819d3d66 | ||
|
|
4220b8d3d7 | ||
|
|
e5cbded53f | ||
|
|
8a8256cf1c | ||
|
|
1605709a48 | ||
|
|
a945ba0744 | ||
|
|
0c71ce1e09 | ||
|
|
d986749660 | ||
|
|
065741d22b | ||
|
|
6e12be1489 | ||
|
|
ea9163338f | ||
|
|
a9d3d7998f | ||
|
|
25c5e448cf | ||
|
|
9b909c2093 | ||
|
|
d90f9390ca | ||
|
|
739e30d3da | ||
|
|
44d8a13c62 | ||
|
|
e8819edc3c | ||
|
|
3f8feb169c | ||
|
|
a79b9b3210 | ||
|
|
8ac58e5f5e | ||
|
|
670875008d | ||
|
|
f853086237 | ||
|
|
36fcfeb953 | ||
|
|
7267bd4f69 | ||
|
|
4095022ea6 | ||
|
|
c4c9f14448 | ||
|
|
141a6e8889 | ||
|
|
4509145b70 | ||
|
|
17e6107aa8 | ||
|
|
c4b1301e6f | ||
|
|
c65ce4c430 | ||
|
|
27e6d03235 | ||
|
|
6c8dba7dd4 | ||
|
|
87ac41d93c | ||
|
|
ef1ff3f90c | ||
|
|
0baf1b4ad6 | ||
|
|
3c1b43d8f6 | ||
|
|
46b699af1f | ||
|
|
7d38b3f8d9 | ||
|
|
05f38400b9 | ||
|
|
4aa505a7b6 | ||
|
|
4afefd6bba | ||
|
|
7e178ce8c4 | ||
|
|
ceafedd4ee | ||
|
|
cbb0fc83bc | ||
|
|
2336f166d7 | ||
|
|
011da1459c | ||
|
|
fade1f2e47 | ||
|
|
5e213f75cf | ||
|
|
a5ab014510 | ||
|
|
198564c65d | ||
|
|
24fc3e2912 | ||
|
|
20ad6061d8 | ||
|
|
7fb33dc83d | ||
|
|
f2751f4b57 | ||
|
|
7d5ee2121d | ||
|
|
1f6865c996 | ||
|
|
753b49b83c | ||
|
|
e9169eecbd | ||
|
|
6d2b284753 | ||
|
|
468d330322 | ||
|
|
be3ac91d8a | ||
|
|
936f19a200 | ||
|
|
b9522bfab1 | ||
|
|
e6dd6b3ab3 |
No files matched your search
+71
-13
@@ -10,6 +10,34 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
api-compat:
|
||||
name: Public API baseline
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: nightly-2026-08-01
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
cache-bin: true
|
||||
- name: Install API snapshot tool
|
||||
run: cargo install cargo-public-api --version 0.52.0 --locked
|
||||
- name: Check reviewed public API baseline
|
||||
run: python3 tools/check-api-baseline.py
|
||||
- name: Check manifest and feature contract
|
||||
run: python3 tools/check-api-manifest.py
|
||||
- name: Check additions-only compatibility floor
|
||||
run: python3 tools/check-api-compatibility.py
|
||||
- name: Check canonical and legacy external consumer
|
||||
run: |
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --locked
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --all-features --locked
|
||||
|
||||
test:
|
||||
name: Test (${{ matrix.os }})
|
||||
timeout-minutes: 30
|
||||
@@ -19,31 +47,61 @@ jobs:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.96.0
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Test (default features)
|
||||
run: cargo test --workspace
|
||||
- name: Test BLE interface features (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: cargo test -p rns-interface --features ble,ble_peer
|
||||
run: cargo test --workspace --locked --no-fail-fast
|
||||
- name: Build application examples
|
||||
run: cargo build -p rns-runtime --examples --locked
|
||||
- name: Test BLE interface features
|
||||
run: cargo test -p rns-interface --features ble --locked
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.96.0
|
||||
components: clippy, rustfmt
|
||||
- name: Install system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Check source-release contract
|
||||
run: python3 scripts/ci/check_source_release_contract.py
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
- run: cargo clippy -p rns-interface --features ble,ble_peer --all-targets -- -D warnings
|
||||
- run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
- name: Check public API documentation
|
||||
env:
|
||||
RUSTDOCFLAGS: "-D warnings"
|
||||
run: cargo doc --workspace --no-deps --locked
|
||||
- run: cargo check --workspace --no-default-features --locked
|
||||
|
||||
msrv:
|
||||
name: Rust 1.89 MSRV
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.89.0
|
||||
components: clippy
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev libpcsclite-dev pkg-config
|
||||
- name: Clippy (all targets and features)
|
||||
run: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
@@ -7,20 +7,55 @@ on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: "Release tag to create or update"
|
||||
description: "Version tag (also used for untagged qualification)"
|
||||
required: true
|
||||
qualify_only:
|
||||
description: "Build and verify archives without publishing or creating a tag"
|
||||
type: boolean
|
||||
default: true
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
env:
|
||||
SOURCE_REF: ${{ github.sha }}
|
||||
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
|
||||
PACKAGE_ROOT: rsReticulum
|
||||
RETICULUM_BINS: rnsd-rs rnstatus-rs rnpath-rs rnid-rs rnprobe-rs rncp-rs rnsh-rs rnodeconf-rs
|
||||
RETICULUM_BINS: rnsd-rs rnstatus-rs rnpath-rs rnid-rs rnprobe-rs rncp-rs rnsh-rs rnodeconf-rs rnx-rs rnir-rs rnpkg-rs rngit-rs rngcs-rs git-remote-rns
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
name: Verify release source
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
ref: ${{ env.SOURCE_REF }}
|
||||
fetch-depth: 0
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.89.0
|
||||
- shell: bash
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
QUALIFY_ONLY: ${{ github.event_name == 'workflow_dispatch' && inputs.qualify_only }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test "$(git rev-parse HEAD)" = "${SOURCE_REF}"
|
||||
gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?head_sha=${SOURCE_REF}&event=push&per_page=100" \
|
||||
--jq '.workflow_runs | any(.head_sha == env.SOURCE_REF and .conclusion == "success")' | grep -qx true
|
||||
if [[ "${QUALIFY_ONLY}" == "true" ]]; then
|
||||
python3 scripts/ci/check_source_release_contract.py --candidate-tag "${RELEASE_TAG}"
|
||||
else
|
||||
python3 scripts/ci/check_source_release_contract.py --release-tag "${RELEASE_TAG}"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.artifact_suffix }}
|
||||
needs: verify
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -39,22 +74,37 @@ jobs:
|
||||
env:
|
||||
ARCHIVE_NAME: rsReticulum-${{ github.event.inputs.tag_name || github.ref_name }}-${{ matrix.artifact_suffix }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
ref: ${{ env.RELEASE_TAG }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
ref: ${{ env.SOURCE_REF }}
|
||||
- uses: dtolnay/rust-toolchain@6c977a6ca4077a0ceb28ffbe03f59d46e9ac8772 # master
|
||||
with:
|
||||
toolchain: 1.89.0
|
||||
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
|
||||
with:
|
||||
cache-bin: false
|
||||
- name: Install system deps (Linux)
|
||||
if: runner.os == 'Linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y libudev-dev libdbus-1-dev pkg-config
|
||||
- name: Build release binaries
|
||||
run: cargo build -p rns-tools --release --bins
|
||||
run: cargo build -p rns-tools -p rns-git --release --bins --locked
|
||||
- name: Stage archive contents
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
suffix=""
|
||||
if [[ "${RUNNER_OS}" == "Windows" ]]; then suffix=".exe"; fi
|
||||
for bin in ${RETICULUM_BINS}; do
|
||||
case "${bin}" in
|
||||
# As upstream, these two have no --version.
|
||||
rngcs-rs) "target/release/${bin}${suffix}" --help > /dev/null ;;
|
||||
git-remote-rns)
|
||||
usage="$("target/release/${bin}${suffix}" 2>&1 || true)"
|
||||
[[ "${usage}" == "Usage: git-remote-rns <remote-name> <url>"* ]]
|
||||
;;
|
||||
*) "target/release/${bin}${suffix}" --version ;;
|
||||
esac
|
||||
done
|
||||
mkdir -p "dist/${PACKAGE_ROOT}/bin"
|
||||
for bin in ${RETICULUM_BINS}; do
|
||||
if [[ "${RUNNER_OS}" == "Windows" ]]; then
|
||||
@@ -63,7 +113,10 @@ jobs:
|
||||
cp "target/release/${bin}" "dist/${PACKAGE_ROOT}/bin/${bin}"
|
||||
fi
|
||||
done
|
||||
cp README.md LICENSE "dist/${PACKAGE_ROOT}/"
|
||||
# Read blobs directly so Windows checkout line endings cannot alter the package.
|
||||
for doc in README.md LICENSE CHANGELOG.md; do
|
||||
git show "HEAD:${doc}" > "dist/${PACKAGE_ROOT}/${doc}"
|
||||
done
|
||||
- name: Create tar archive
|
||||
if: runner.os != 'Windows'
|
||||
shell: bash
|
||||
@@ -72,7 +125,7 @@ jobs:
|
||||
if: runner.os == 'Windows'
|
||||
shell: pwsh
|
||||
run: Compress-Archive -Path "dist/${env:PACKAGE_ROOT}" -DestinationPath "${env:ARCHIVE_NAME}.zip" -Force
|
||||
- uses: actions/upload-artifact@v7
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ${{ env.ARCHIVE_NAME }}
|
||||
path: |
|
||||
@@ -80,22 +133,46 @@ jobs:
|
||||
*.zip
|
||||
if-no-files-found: error
|
||||
|
||||
package:
|
||||
name: Verify release archives
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5
|
||||
with:
|
||||
ref: ${{ env.SOURCE_REF }}
|
||||
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
with:
|
||||
pattern: rsReticulum-*
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
- name: Verify archive inventory and generate checksums
|
||||
run: python3 scripts/ci/check_release_archives.py --tag "${RELEASE_TAG}" --directory release-assets
|
||||
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: verified-release-assets
|
||||
path: release-assets/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
name: Publish GitHub release
|
||||
needs: build
|
||||
if: github.event_name == 'push' || !inputs.qualify_only
|
||||
needs: package
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@v7
|
||||
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7
|
||||
with:
|
||||
name: verified-release-assets
|
||||
path: release-assets
|
||||
merge-multiple: true
|
||||
- name: Generate checksums
|
||||
working-directory: release-assets
|
||||
run: sha256sum * > SHA256SUMS
|
||||
- uses: softprops/action-gh-release@v3
|
||||
- uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
|
||||
with:
|
||||
tag_name: ${{ env.RELEASE_TAG }}
|
||||
name: ${{ env.RELEASE_TAG }}
|
||||
body: ""
|
||||
generate_release_notes: false
|
||||
append_body: false
|
||||
prerelease: ${{ contains(env.RELEASE_TAG, '-') }}
|
||||
files: release-assets/*
|
||||
@@ -7,3 +7,6 @@ __pycache__/
|
||||
/rust_artifacts/
|
||||
proptest-regressions/
|
||||
/tools/*
|
||||
!/tools/check-api-manifest.py
|
||||
!/tools/check-api-compatibility.py
|
||||
/api/fixtures/target/
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 1.5.1 - 2026-11-18
|
||||
|
||||
- Bluetooth Peer runs in Gateway mode, so a node with transport on looks up the paths its Bluetooth peers ask for that it doesn't know yet. Nodes with transport off behave as before.
|
||||
- TCP and Backbone client interfaces report why they can't connect: `last_connect_error` (`refused`, `timed_out`, `dns`, `unreachable`, `closed_by_peer`, or `other`) and `connect_failures` in the interface stats, so an application can tell a hub that refuses or closes the connection from one still connecting. The shared-instance RPC doesn't carry them.
|
||||
- I2P interfaces log their `.b32.i2p` address once reachable, at loglevel 5 or higher, as Python Reticulum does.
|
||||
- Interface start-up code is compiled once instead of again in every crate that starts the runtime, which makes `rnsd-rs` about 1.5 MB smaller.
|
||||
- Bluetooth RNodes report battery, temperature, and channel load in the interface stats, as USB RNodes already do (`battery_state`, `battery_percent`, `cpu_temp`, `noise_floor`).
|
||||
- Bluetooth Peer: on Android, a link the app closes after a failed write reports `Disconnected`, so the peer no longer stays listed as connected. On Linux, disconnecting a peer reports it too, and the Central role keeps looking for a Bluetooth adapter that appears after start-up instead of giving up until restart.
|
||||
- Path requests are handled as in Python Reticulum 1.6.0. A node that knows a path but can't read its cached announce ignores the request instead of searching the network and blocking later requests for 45 seconds. A queued path response is dropped once other nodes are heard answering. Requests that arrive during a path-request burst are counted and checked before they wait, so duplicates no longer crowd out real ones. A search answer now also reaches a requester on the roaming interface it arrived on. A node asked again for a path it's about to answer keeps the answer's time, so a requester that repeats quickly is no longer left waiting forever.
|
||||
- Announce handler events carry `emitted`, the time the announcer stamped into the announce, so an application can tell an older cached announce in a path response from a newer one. `AnnounceHandlerEvent` struct literals need the new field.
|
||||
- **Follows Python Reticulum 1.6.1.** Announces and path requests are stamped by default, and `stamp_destinations` / `stamp_prs` can only turn stamping on, as upstream. New `[stamps] max_workers` and `worker_niceness`. Discovery stamps are accepted in both workblock forms. rngit takes `stamp_value` and `link_cost`.
|
||||
- Announces that can't change a known path are dropped before they are verified, each interface holds at most 64 announces during a burst and drops the useless ones early, and the announce rate table survives restarts. An announce isn't rebroadcast to an interface that already sent it to us, or after it only replaced an unresponsive path. A locally built announce must leave room for a relay's transport id, and is refused with `DestinationError::AnnounceTooLarge` (now `#[non_exhaustive]`) otherwise.
|
||||
- Paths to an instance's own local clients never time out, are marked responsive, and are answered only to the asker; a local client asking for a known path is answered from the table. A path request that leaves nothing in progress no longer blocks later requests for 45 seconds. Destination type filters take `<hash>` entries and the `known_destination_types` / `flagged_destination_types` files, Backbone listeners honour a `blocked_ips` file, interfaces take `hop_limiter`, and reverse-table entries expire after 3 minutes.
|
||||
- Tunnel synthesis carries signed stamp costs, version, and transport status, and hubs answer it; a bad signature or a blackholed hub detaches the interface, and an embedder hears each detach through `ReticulumHandle::subscribe_interface_detaches`. An unbound tunnel waits 10 minutes for its interface.
|
||||
- Received traffic is counted as accepted or filtered, links count their traffic and speeds, and the shared-instance RPC carries everything Python 1.6.1's `rnstatus` and `rnpath` read, plus `known_destinations`, `link_distribution`, and detach by tunnel id. rnstatus-rs and rnpath-rs show the 1.6.1 output, and the tools look for a path of their own before linking. `PathTableEntry.used` is now `Option<f64>`.
|
||||
- Backbone listeners take `client_limit` (default 500), and auto-connect stops at 12 discovered interfaces unless its caps are disabled.
|
||||
- A discovered interface's config entry drops line breaks and control characters from announced strings, so a pasted entry can't gain config sections.
|
||||
- `destination_stamper::prepare` makes and saves a destination's stamp before its first announce.
|
||||
- A shared-instance client's first announce is no longer lost: its registration path response now waits 250 ms, as upstream, so the shared instance passes the announce on. Integer config values take `_` digit groups (`1_0`), as Python's `int()` does.
|
||||
- rnsh-rs listeners no longer end a session when a client's identification and first message arrive together, rnx-rs sends results it used to drop silently (16 MB of output failed), and cuts output over about 30 MiB instead of dropping it, so the client prints its usual truncation notice, and rnpath-rs prints `Sending request...` only once its link is up.
|
||||
|
||||
## 1.5.0 - 2026-11-13
|
||||
|
||||
### Added
|
||||
|
||||
- **Network stamps**: announces, path requests, and link requests can carry Reticulum 1.6.0 stamps. Turn them on in the new `[stamps]` section (see `rnsd-rs --exampleconfig`). Stamps that arrive are checked, and required only with `enforce_stamps = yes`.
|
||||
- **Link MTU discovery**: Links use the largest packets the path allows, so transfers on fast links finish sooner. It's on by default; set `link_mtu_discovery = no` to turn it off.
|
||||
- **Resources as files**: an application can receive a Resource of any size straight to a file with `DestinationHandle::receive_resource_files` or `LinkSessionResourceOffer::accept_to_file`.
|
||||
- **Filters**: the new `[filter]` section can drop destination types you don't use and packets that have travelled too many hops.
|
||||
- **New tools**: `rngit-rs` hosts git repositories over Reticulum, `git-remote-rns` lets `git` clone, fetch, and push `rns://` repositories, `rngcs-rs` signs and checks commits, and `rnx-rs` runs commands on a remote node. `rngit-rs` stops a fork, mirror, or sync after 30 minutes or 1 GB by default.
|
||||
- **rnodeconf-rs**: every `rnodeconf` option now works, including firmware install and update, device signing, EEPROM bootstrap, and the `-a` guided installer. Flashing uses the same external tools as Python's `rnodeconf`.
|
||||
|
||||
### Fixed and improved
|
||||
|
||||
- `rnsd-rs` auto-connects to discovered Backbone servers running Python Reticulum 1.5.7 or later, or rsReticulum 1.5.0 or later. Set `autoconnect_unverified_implementations = yes` to allow any.
|
||||
- Every tool's `--version` names the Reticulum release it follows, for example `rnsd-rs 1.5.0 (Reticulum 1.6.0)`.
|
||||
- `rnsd-rs` logs at Notice by default, which is quieter than before; set `loglevel = 4` for the old output.
|
||||
- `rnstatus-rs`, `rnpath-rs`, `rnprobe-rs`, and `rnid-rs` match Python's tools in output, options, and exit codes, and `rnstatus-rs` can attach, detach, and reload interfaces on a running `rnsd-rs`.
|
||||
- `rncp-rs -f` now takes the remote file before the destination hash, as Python's `rncp` does. Listeners accept files only from allowed identities unless `-n` is given, and files of any size work.
|
||||
- In `rnsh-rs`, `-c` now names rnsh's own config directory, as in Python's `rnsh`; use `--rnsconfig` for the Reticulum one.
|
||||
- An interface that fails to start now stops start-up, as in Python Reticulum. Embedders can keep going with `InitOptions::keep_starting_after_interface_failure`.
|
||||
- RNodeMulti reads `interface_mode` from the device section and `flow_control` from each subinterface.
|
||||
- AutoInterface, Backbone, and I2P interfaces, path expiry, and announce queues behave as in Python Reticulum 1.6.0.
|
||||
- Key exchange rejects weak peer keys that would give an all-zero shared secret.
|
||||
|
||||
### Build and compatibility
|
||||
|
||||
- `ifac_size` is read in bits, as in Python Reticulum. A bare value set under 1.3.0 was in bytes, so multiply it by 8 (16 becomes 128), or convert it with `rnsd-rs config ifac-units`.
|
||||
- Bluetooth Peer uses new service identifiers, so it doesn't find peers on 1.4.0 or earlier until both update. Bluetooth RNodes aren't affected.
|
||||
- Known destinations, ratchets, and cached announces are stored in the same SQLite files as Python Reticulum 1.6.0. Old files are imported on first start, so going back to an older release starts with no known destinations.
|
||||
- Breaking API changes are listed in the [1.5 migration guide](api/migrations/1.5.md); use the `~1.5.0` line. The default `sqlite-store` feature builds a bundled SQLite, so builds need a C compiler.
|
||||
|
||||
## 1.4.0 - 2026-11-08
|
||||
|
||||
- RNode drivers confirm the settings the radio applies once it is on, on every transport, and stop with the rejected setting named (for example TX power below an amplifier's minimum) instead of transmitting at other settings or retrying forever.
|
||||
- Serial and TCP RNodes keep retrying a port that is missing, busy or not permitted every 5 seconds, as in Python Reticulum, and report which.
|
||||
- Android Bluetooth RNode sessions wait for the bridge before starting, so a slow reconnect no longer drops a healthy link.
|
||||
- Interface status reports IFAC like Python Reticulum: `rnstatus-rs` shows the network name and access line only for interfaces that use IFAC.
|
||||
- Interfaces start only when `enabled` or `interface_enabled` is yes, as in Python Reticulum. A section with neither key is now skipped with a warning instead of starting, so add `enabled = yes` to it. An RNodeMulti subinterface with its own flag follows that flag, so a subinterface set to no never transmits.
|
||||
- Durable storage works on any filesystem again, as in Python Reticulum, including ZFS, Docker overlays, external drives and network shares. A flush the filesystem lacks is skipped and logged once, and network or RAM-backed storage logs a warning instead of refusing to start.
|
||||
- A Link accepts the peer's identification as soon as its handshake completes, as in Python Reticulum, so a request a Python client sends right after identifying no longer fails for lack of an identity. Only the receiving side of a Link accepts identification.
|
||||
- The receiving side of a Link counts its Link proof as sent traffic, as in Python Reticulum, so it no longer answers keepalives before the Link is established and its traffic totals include the proof.
|
||||
- A connectable I2P interface now starts alongside a Unix-socket shared instance or another connectable I2P interface, and an I2P interface runs one connection for every configured peer, plus its server when connectable, as in Python Reticulum.
|
||||
- Hub restarts restore saved paths and tunnels as in Python Reticulum.
|
||||
- Transport hubs now accept tunnel synthesis, so a Python client that reconnects gets its paths back without announcing again, and losing a tunnel's interface no longer drops paths the hub learned through other interfaces, as in Python Reticulum.
|
||||
- PLAIN and GROUP packets that arrive from more than one hop away, and announces typed PLAIN or GROUP, are dropped before deduplication, as in Python Reticulum.
|
||||
- TCP, Backbone and I2P client interfaces open every connection with a tunnel synthesis, so a transport hub restores their paths after a reconnect, and traffic queued while a connection was down or failing to open is dropped when it opens, as in Python Reticulum.
|
||||
- A client of a Unix-socket shared instance drops traffic queued while the instance was unreachable, as in Python Reticulum.
|
||||
- I2P interfaces announce their own address for discovery, and the peers listed in `peers` keep Python's defaults, sharing only the interface's IFAC, as in Python Reticulum.
|
||||
- A bootstrap-only I2P interface keeps running once discovered interfaces connect, as in Python Reticulum, which never detaches an I2P interface.
|
||||
- A connectable I2P interface keeps its I2P address across restarts. Its key is stored in Python Reticulum's key file under `storage/i2p`, readable by its owner only; as in Python Reticulum, a node without `enable_transport` or `static_transport_identity` gets a new address each start.
|
||||
- Every validated announce refreshes the identity remembered for its destination, including path responses and replays that leave the path unchanged, so a destination's identity stays recallable as in Python Reticulum.
|
||||
- Python Reticulum 1.5 `rnstatus` and `rnpath` work against `rnsd-rs`, locally and with `-R`: interface stats carry every field they read, including announce and path request counts, violation counters and the transport instance, and remote management answers on the transport identity, as in Python Reticulum.
|
||||
- `rnstatus-rs -R` and `rnpath-rs -R` take the remote node's transport identity hash, which `rnstatus` shows as the transport instance on a transport node. A node with `enable_transport` off and no `static_transport_identity` gets a new management destination each start, as in Python Reticulum; set `static_transport_identity = yes` on a leaf you manage remotely. `storage/remote_management_identity` is no longer used and can be deleted.
|
||||
- Announces held during an ingress burst on an IFAC interface are processed when released instead of being dropped, and released or replayed announces no longer count as received traffic again, as in Python Reticulum.
|
||||
- Interface discovery announces name this stack, `rsRNS`, and its version. `rnsd-rs` auto-connects only to Backbone interfaces announced by Python Reticulum 1.5.2 or later, or to any announced Backbone interface with `autoconnect_unverified_implementations`, and no longer stores or lists discovered TCP client interfaces, as in Python Reticulum.
|
||||
- Discovery announces a KISS-framed TCP client as a KISS interface and sends and reads unset radio parameters as nil, so Python and `rnsd-rs` read each other's KISS, Weave and RNode announces, as in Python Reticulum.
|
||||
- `rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps counting while the system is suspended, for deadlines that must hold in real time across a sleep.
|
||||
- An interface counts a path request in its stats only once its tag passes the duplicate check, as in Python Reticulum 1.5.
|
||||
- A realtime Link packet dropped at a full transmit queue counts toward the interface's dropped bytes.
|
||||
- `rnpath -R` filters the remote path and rate tables as Python Reticulum compares them: a destination hash of another length matches nothing, and the hop limit compares as a number instead of wrapping above 255.
|
||||
- Remote management Links refuse Resources other than requests and responses, as Python Reticulum's do.
|
||||
- `rnsd-rs` never auto-connects a discovered interface at an onion address, at 127.0.0.1 or 0.0.0.0, or at a host and port that an interface already connects to, as in Python Reticulum.
|
||||
- Interface stats name the network an auto-connected interface was discovered through (`autoconnect_source`), as in Python Reticulum.
|
||||
- Decryption, key derivation and identity and ratchet file handling wipe temporary sensitive buffers, and decryption avoids an extra plaintext copy. Returned plaintext remains caller-owned and must be wrapped in `Zeroizing` when it needs wiping on drop. Identity files larger than 1 KiB are refused.
|
||||
- A 64-byte identity file always loads as a raw key, as in Python Reticulum. About one key in 29,000 began with bytes that were misread as the older envelope format, and its identity failed to load.
|
||||
- Writing, verifying and recovering state files retries a read that a signal interrupts instead of failing.
|
||||
- Interface options wipe their IFAC passphrase when dropped, and the debug output of IFAC settings no longer shows it.
|
||||
- Each interface's IFAC key lives in one allocation that is wiped when dropped, so interface tables no longer leave copies of it in freed memory.
|
||||
- I2P interfaces no longer leave their private key in freed memory when they read it, store it or exchange it with the SAM bridge. They refuse a key file larger than 16 KiB and, as Python Reticulum's SAM client does, a SAM reply line longer than 64 KiB.
|
||||
- Remote management answers the profiling flag of `rnstatus -R -z` with empty results, and leaves a status request that is not a list of flags unanswered, as Python Reticulum does.
|
||||
- `rnstatus-rs` shows the network an auto-connected interface was discovered through on a `Source` line under its name, as Python's `rnstatus` does, and its JSON output carries it as `autoconnect_source`.
|
||||
- AutoInterface's `devices` and `ignored_devices` take effect, and they and I2P `peers` are read as Python Reticulum reads lists: a quoted name that contains a comma stays one name, and `devices = ,` allows every interface.
|
||||
- TCP client interfaces read `i2p_tunneled`, as Python Reticulum does, and give a connection tunneled over I2P its longer I2P socket timeouts.
|
||||
- TCP server and Backbone interfaces are announced for discovery only with `reachable_on` set, and Backbone clients never, as in Python Reticulum. A discoverable server without `reachable_on` logs a warning and is not announced, so set `reachable_on` to keep announcing it. The `discovery_reachable_on` key is no longer read.
|
||||
- Corrected packet-size limits across interfaces and Links, including IFAC overhead, and reject unsupported Link setups before sending them.
|
||||
- Added application-controlled acknowledgements so propagation nodes can confirm a message only after safely storing it.
|
||||
- Prevent stale interface or Link callbacks from acknowledging a different connection after reconnect or cancellation.
|
||||
- Reject malformed Resource metadata and invalid timeout values without panics or excessive allocation.
|
||||
- Added checked durable file operations for identities, ratchets, and application storage, with explicit recovery after interrupted writes.
|
||||
- Updated public interface, Link, and storage APIs. Use the `~1.4.0` compatibility line for these source-breaking APIs.
|
||||
|
||||
## 1.3.0 - 2026-10-12
|
||||
|
||||
### Added
|
||||
|
||||
- Added Link bind-readiness polling so applications can start sending as soon as the transport is ready.
|
||||
|
||||
### Fixed and improved
|
||||
|
||||
- Represent unknown discovery latitude, longitude, and height independently as `None` instead of zero, accept Python nil coordinates, and preserve presence through configuration, storage, and `rnstatus-rs`.
|
||||
- Register and own the interface-discovery destination, advance publication intervals only after driver admission, and preserve pending announcements across bounded backpressure and reconnect.
|
||||
- Keep learned mesh announcements out of ordinary RNode control/data backlogs until the final writer can send them, while preserving same-radio relay and announce pacing.
|
||||
- Retain refused local announcements and attached path answers under bounded ownership tied to the exact interface generation.
|
||||
- Preserve multiple recursive-discovery requesters, slow-radio deadlines, interface replacement safety, and hidden-peer same-radio responses without letting one cancellation affect another requester.
|
||||
- Updated btleplug to 0.13.4, including upstream Windows discovery and reconnect fixes. Windows can try an explicitly configured RNode MAC or an eligible remembered BLE Peer absent from scan results, with bounded GATT setup, existing backoff, and signed peer identity checks.
|
||||
- Installed desktop BLE notification receivers before subscribing and limited packet fragments to the negotiated ATT payload.
|
||||
- Improved Bluetooth Peer packet sizing and flow control, including Apple write handling and queued sends.
|
||||
- Fixed a remotely triggerable Link panic when a peer reported an infinite, NaN, negative, or oversized RTT. Peer RTTs follow Python's handling and saturate at the 720-second stale window; initiators ignore LRRTT as Python does.
|
||||
- Require the corrected Windows socket backend so spawned helper processes cannot keep network listeners alive after the owning runtime shuts down.
|
||||
- Match Python RNS 1.4.2 Channel receive-window admission by dropping sequence numbers more than 48 slots ahead until a retry falls inside the window.
|
||||
- Report the bundled `rnsh` compatibility level as 0.3.0 and the `rnsd-rs` interactive compatibility level as RNS 1.4.2.
|
||||
|
||||
### Build and compatibility
|
||||
|
||||
- Discovery coordinates now use `Option<f64>`, and recursive discovery exposes detached observations and exact requester cancellation instead of public mutable state. Both source-breaking changes are covered by the [1.3 migration guide](api/migrations/1.3.md).
|
||||
- Project minor versions may include breaking APIs. Select `~1.3.0` or an exact reviewed source revision when adopting this release line.
|
||||
- Raised the full Rust workspace minimum compiler to Rust 1.89. Apple native BLE bindings declare their required features explicitly; Android consumers must use btleplug's matching 0.13.4 Java bridge and JNI 0.22 initialization.
|
||||
- Promote exact Python RNS 1.4.2 to the complete release baseline, including live interoperability, source oracles, utility vectors, and corpus provenance. RNS 1.5.0 remains deferred.
|
||||
|
||||
## 1.2.0 - 2026-08-17
|
||||
|
||||
- Designated the existing `rns_runtime::prelude` and compiled examples as the
|
||||
canonical application spine while retaining every module-qualified path,
|
||||
and added external-consumer, manifest/feature, and additions-only API
|
||||
compatibility gates without changing runtime behavior or public signatures.
|
||||
- Classified every library package and added pinned, CI-enforced public API
|
||||
snapshots so compatibility drift is reviewed before any boundary change;
|
||||
no visibility or signature changed in this baseline.
|
||||
- Made source releases reproducible from an existing immutable component tag:
|
||||
packages are non-publishable by default, release builds use the committed
|
||||
lockfile and Rust 1.87.0, actions are commit-pinned, and CI verifies the
|
||||
manifest, changelog, tag, and checkout contract.
|
||||
- Isolate exact announce subscriptions from legacy aspect-wide deregistration,
|
||||
and resolve finite destination identities through validated recall plus
|
||||
deadline-bounded path discovery instead of temporary announce handlers.
|
||||
- Distinguished the Reticulum 1.3.8 compatibility-floor corpus from the
|
||||
current 1.4.2 behavior reference instead of presenting the old oracle as the
|
||||
newest upstream target.
|
||||
- Enforce role-specific Link packet proofs: initiators sign with the transient
|
||||
LINKREQUEST key, responders sign with the destination identity, and external
|
||||
identity backends no longer fall back to an unrelated key.
|
||||
- Ignore unauthenticated invalid LRPROOF candidates without closing a pending
|
||||
initiator, allowing the authentic proof to win an interface race.
|
||||
- Bind every locally owned established Link endpoint to its validated
|
||||
interface and role, with fail-closed routing, bounded ordered control egress,
|
||||
terminal interface-loss notification, and bounded best-effort realtime
|
||||
egress. Typed send rejection closes only the exact owner, while final
|
||||
LINKCLOSE and temporary-destination cleanup drain atomically in order.
|
||||
Initial LINKREQUEST discovery remains path-routed or broadcast.
|
||||
- Forward authenticated non-Link packet delivery proofs from `LinkManager` to
|
||||
owning applications through a lossless completion channel.
|
||||
- Retain and retry destination announcements, including path responses, when
|
||||
the bounded transport ingress is temporarily saturated.
|
||||
- Let one-shot Link clients reuse a validated cached identity when its route is
|
||||
still live, matching Python recall behavior and avoiding redundant path
|
||||
discovery.
|
||||
- Keep completed `rncp` Links alive for Python's receiver-side Resource
|
||||
conclusion callback before sending the authenticated teardown.
|
||||
- This source line includes application and runtime API evolution since 1.1.0;
|
||||
downstream integrations should qualify against the 1.2 dependency line.
|
||||
|
||||
## 1.1.0 - 2026-07-26
|
||||
|
||||
- Added application-facing Destination, announce, receipt, Link, request,
|
||||
Channel, Buffer, and Resource APIs.
|
||||
- Added resilient long-running Link sessions with recovery, liveness,
|
||||
cancellation, progress, metrics, and responder lifecycle support.
|
||||
- Hardened delivery proofs, shared-instance authority and reconnection, IFAC
|
||||
ingress, persistence, routing snapshots, and orderly shutdown.
|
||||
- Expanded RNode lifecycle, capability, BLE, USB, TCP, serial, and safe
|
||||
`rnodeconf-rs` support.
|
||||
- Added compiled examples and stricter MSRV, Clippy, interoperability, and
|
||||
public-documentation gates.
|
||||
Generated
+769
-222
File diff suppressed because it is too large.
Load diff
+20
-14
@@ -11,21 +11,22 @@ members = [
|
||||
"crates/rns-runtime",
|
||||
"crates/rns-tools",
|
||||
"crates/rns-ratkey",
|
||||
"crates/rns-git",
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "1.0.1"
|
||||
version = "1.5.1"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-or-later"
|
||||
rust-version = "1.85"
|
||||
license-file = "LICENSE"
|
||||
rust-version = "1.89"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Crypto
|
||||
x25519-dalek = { version = "2", features = ["static_secrets"] }
|
||||
ed25519-dalek = { version = "2", features = ["hazmat", "rand_core"] }
|
||||
aes = "0.8"
|
||||
aes = { version = "0.8", features = ["zeroize"] }
|
||||
des = "0.8"
|
||||
cbc = { version = "0.1", features = ["alloc"] }
|
||||
cbc = { version = "0.1", features = ["alloc", "zeroize"] }
|
||||
hkdf = "0.12"
|
||||
hmac = "0.12"
|
||||
md-5 = "0.10"
|
||||
@@ -38,10 +39,14 @@ rand_core = { version = "0.6", features = ["getrandom"] }
|
||||
# Encoding
|
||||
base64 = "0.22"
|
||||
|
||||
# Storage
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
|
||||
# Serialization
|
||||
rmp-serde = "1"
|
||||
rmpv = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_bytes = "0.11"
|
||||
serde_json = "1"
|
||||
|
||||
# Async
|
||||
@@ -68,6 +73,7 @@ tracing-subscriber = "0.3"
|
||||
|
||||
# Error handling
|
||||
thiserror = "2"
|
||||
tempfile = "3"
|
||||
|
||||
# Misc
|
||||
hex = "0.4"
|
||||
@@ -79,12 +85,12 @@ nix = { version = "0.29", features = ["term", "fs"] }
|
||||
proptest = "1"
|
||||
|
||||
# Workspace crates
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "1.0.1", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "1.0.1", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "1.0.1" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "1.0.1" }
|
||||
rns-link = { path = "crates/rns-link", version = "1.0.1" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "1.0.1" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "1.0.1" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "1.0.1" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "1.0.1" }
|
||||
rns-crypto = { path = "crates/rns-crypto", version = "~1.5.1", default-features = false }
|
||||
rns-wire = { path = "crates/rns-wire", version = "~1.5.1", default-features = false }
|
||||
rns-identity = { path = "crates/rns-identity", version = "~1.5.1" }
|
||||
rns-transport = { path = "crates/rns-transport", version = "~1.5.1" }
|
||||
rns-link = { path = "crates/rns-link", version = "~1.5.1" }
|
||||
rns-protocol = { path = "crates/rns-protocol", version = "~1.5.1" }
|
||||
rns-interface = { path = "crates/rns-interface", version = "~1.5.1" }
|
||||
rns-runtime = { path = "crates/rns-runtime", version = "~1.5.1" }
|
||||
rns-ratkey = { path = "crates/rns-ratkey", version = "~1.5.1" }
|
||||
@@ -1,661 +1,34 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
Reticulum License
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
Derived from the reference implementation at
|
||||
https://github.com/markqvist/Reticulum
|
||||
|
||||
Preamble
|
||||
Copyright (c) 2016-2026 Mark Qvist, unless otherwise noted
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
Additions and modifications Copyright (c) 2026 Ratspeak LLC
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
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:
|
||||
|
||||
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.
|
||||
- The Software shall not be used in any kind of system which includes amongst
|
||||
its functions the ability to purposefully do harm to human beings.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
- The Software shall not be used, directly or indirectly, in the creation of
|
||||
an artificial intelligence, machine learning or language model training
|
||||
dataset, including but not limited to any use that contributes to the
|
||||
training or development of such a model or algorithm.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
- The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
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.
|
||||
@@ -5,10 +5,10 @@
|
||||
**A Rust implementation of Reticulum.**
|
||||
|
||||
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://reticulum.network/)
|
||||
[](#feature-status)
|
||||
[](LICENSE)
|
||||
[](https://www.rust-lang.org)
|
||||
[](https://reticulum.network/)
|
||||
[](#compatibility-notes)
|
||||
|
||||
[Reticulum Manual](https://reticulum.network/manual/) |
|
||||
[Ratspeak](https://github.com/ratspeak/Ratspeak) |
|
||||
@@ -19,25 +19,35 @@
|
||||
|
||||
---
|
||||
|
||||
rsReticulum is a Rust implementation of Reticulum. This is not a fork of
|
||||
Reticulum; it is Reticulum written in a different language, focused on staying
|
||||
interoperable. It is not the source-of-truth implementation, do not treat it as one.
|
||||
|
||||
Commands are intentionally namespaced for Rust with `*-rs` command names, so
|
||||
rsReticulum can live beside other Reticulum tools on `PATH` without worry.
|
||||
rsReticulum is a Rust port of
|
||||
[Reticulum](https://github.com/markqvist/Reticulum), the reference
|
||||
implementation by Mark Qvist. It was written from the reference source, not from
|
||||
a specification, and tracks the reference's wire behavior release by release.
|
||||
|
||||
## Contents
|
||||
|
||||
- [Build It](#build-it)
|
||||
- [Rust API](api/README.md)
|
||||
- [Tool Usage](#tool-usage)
|
||||
- [Configuration](#configuration)
|
||||
- [Interface Support](#interface-support)
|
||||
- [Compatibility Notes](#compatibility-notes)
|
||||
- [Contributing](#contributing)
|
||||
- [License](#license)
|
||||
|
||||
## Build It
|
||||
|
||||
This guide describes the 1.5.1 release, [v1.5.1](https://github.com/ratspeak/rsReticulum/releases/tag/v1.5.1), the source line Ratspeak builds from.
|
||||
|
||||
From a new working directory:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ratspeak/rsReticulum.git
|
||||
git -C rsReticulum checkout --detach v1.5.1
|
||||
cd rsReticulum
|
||||
```
|
||||
|
||||
Run the build commands below from that directory. The host crates require Rust 1.89 or newer. The default build compiles a bundled SQLite, so it also needs a C compiler; the build tools below provide one.
|
||||
|
||||
### macOS
|
||||
|
||||
Install Rust with `rustup`, then install Apple's command-line build tools:
|
||||
@@ -49,13 +59,12 @@ xcode-select --install
|
||||
Build the tools:
|
||||
|
||||
```bash
|
||||
cd rsReticulum
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
### Linux, Raspberry Pi, and VPS Hosts
|
||||
|
||||
##### Install Rust with `rustup`, then install the needed packages:
|
||||
Install Rust with `rustup`, then install the build packages:
|
||||
|
||||
Debian, Ubuntu, and Raspberry Pi OS:
|
||||
|
||||
@@ -76,11 +85,10 @@ Arch:
|
||||
sudo pacman -S --needed base-devel pkgconf
|
||||
```
|
||||
|
||||
##### Build the tools:
|
||||
Build the tools:
|
||||
|
||||
```bash
|
||||
cd rsReticulum
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
### Windows
|
||||
@@ -91,8 +99,7 @@ Build Tools, install the "Desktop development with C++" workload.
|
||||
Build from PowerShell:
|
||||
|
||||
```powershell
|
||||
cd rsReticulum
|
||||
cargo build --release
|
||||
cargo build --release --locked
|
||||
```
|
||||
|
||||
After the build, use the commands below with `./target/release/<tool>` on
|
||||
@@ -100,7 +107,7 @@ macOS/Linux or `.\target\release\<tool>.exe` on Windows.
|
||||
|
||||
## Tool Usage
|
||||
|
||||
The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
|
||||
The `rns-tools` and `rns-git` crates build these tools:
|
||||
|
||||
| Binary | Purpose |
|
||||
| --- | --- |
|
||||
@@ -110,79 +117,85 @@ The `rns-tools` crate builds Rust-namespaced Reticulum utilities:
|
||||
| rnid-rs | Identity generation, inspection, public/private import/export, hashing, signing, verification, encryption, and decryption. |
|
||||
| rnprobe-rs | Destination probe utility with loss and round-trip reporting. |
|
||||
| rncp-rs | File transfer utility with send, listen, and authenticated fetch modes. |
|
||||
| rnodeconf-rs | RNode inspection, safe configuration, EEPROM backup, and trust utility. |
|
||||
| rnodeconf-rs | RNode inspection, settings, signing, EEPROM bootstrap, firmware install and update, and the guided installer. |
|
||||
| rnsh-rs | Reticulum shell listener/client. |
|
||||
| rnx-rs | Remote command execution listener and client. |
|
||||
| rnir-rs | Distributed identity resolver. Like upstream's `rnir`, it starts Reticulum and exits. |
|
||||
| rnpkg-rs | Meta package manager. Like upstream's `rnpkg`, it starts Reticulum and exits. |
|
||||
| rngit-rs | Git repository node and its management commands, with forks, mirrors, releases, and NomadNet pages. |
|
||||
| git-remote-rns | Git remote helper for `rns://<destination_hash>/<group>/<repo>` URLs. Python's `rngit` installs one with the same name, so keep only one on `PATH`. |
|
||||
| rngcs-rs | Git commit signer and verifier for Reticulum identities, with the `ssh-keygen -Y` interface git uses for SSH signing. |
|
||||
|
||||
#### Commands:
|
||||
Common command forms (use each binary’s `--help` for the complete option list):
|
||||
|
||||
```text
|
||||
rnsd-rs [-c CONFIG_DIR] [-v|-q]... [--service] [--exampleconfig] [--version]
|
||||
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|held]
|
||||
rnsd-rs [--config CONFIG_DIR] [-v|-q]... [-i] [--service] [--exampleconfig] [--version]
|
||||
rnsd-rs [--config CONFIG_DIR] config ifac-units --interface NAME --source-units bytes|bits [--write]
|
||||
rnstatus-rs [--all] [--sort rate|traffic|rx|tx|rxs|txs|announces|arx|atx|arxc|atxc|prx|ptx|prxc|ptxc|held|pvs|ivs|flt|txdrp|txdrb|txbuf]
|
||||
[--reverse] [--announce-stats] [--link-stats] [--totals] [--json]
|
||||
[--discovered|-D] [-m [-I SECONDS]] [FILTER]
|
||||
[-d|--discovered] [-D] [-m [-I SECONDS]] [FILTER]
|
||||
[-R <transport_hash> -i <identity_file>]
|
||||
rnstatus-rs --attach NAME | --detach NAME | --reload NAME
|
||||
rnpath-rs [--table|--rates] [destination_hash] [--max HOPS]
|
||||
rnpath-rs <destination_hash>
|
||||
rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] <destination_hash>
|
||||
rnprobe-rs [-s SIZE] [-n COUNT] [-t TIMEOUT] [-w WAIT] [--json] <full_name> <destination_hash>
|
||||
rnid-rs [-i IDENTITY|-g FILE|-m PUB|-M PRV] [-p|-P] [-x|-X] [-H ASPECT]
|
||||
[-a [ASPECT]] [-e FILE|-d FILE|-s FILE|-V FILE] [-w FILE] [-f]
|
||||
[-R|-N] [-t SECONDS] [-b|-B] [--raw] [--version]
|
||||
rncp-rs <file> <destination_hash>
|
||||
rncp-rs -l [-b SECONDS] [-s DEST_DIR] [-a <allowed_hash>]...
|
||||
rncp-rs -l -F [-j <jail_dir>] [-a <allowed_hash>|-n]...
|
||||
rncp-rs -f <destination_hash> <remote_path> [-s DEST_DIR]
|
||||
rncp-rs -f <remote_path> <destination_hash> [-s DEST_DIR]
|
||||
rnodeconf-rs [-i] [--config] [--eeprom-backup|--eeprom-dump] [--version] [PORT]
|
||||
rnodeconf-rs -T --freq HZ --bw HZ --txp DBM --sf SF --cr CR PORT
|
||||
rnodeconf-rs -N PORT
|
||||
rnodeconf-rs -a [PORT]
|
||||
rnodeconf-rs -u [-U] [--fw-version V] [--fw-url URL] [--nocheck] PORT
|
||||
rnsh-rs -l [-i FILE] [-s NAME] [-b PERIOD] [-a HASH]... [-n] [-A|-C] [-- CMD...]
|
||||
rnsh-rs [-i FILE] [-s NAME] [-N] [-m] [-w SECONDS] <destination_hash> [-- CMD...]
|
||||
rnx-rs -l [-i FILE] [-b] [-a <allowed_hash>]... [-n]
|
||||
rnx-rs [-i FILE] [-N] [-d] [-m] [-w SECONDS] [-W SECONDS] <destination_hash> <command>
|
||||
rnx-rs -x [-i FILE] <destination_hash>
|
||||
rngit-rs [--config DIR] [--rnsconfig DIR] [-p] [-s]
|
||||
rngit-rs create|fork|mirror|sync|release|perms|work [OPTIONS] ...
|
||||
git clone rns://<destination_hash>/<group>/<repo>
|
||||
```
|
||||
|
||||
Add the release `bin/` directory or `target/release` to `PATH` if
|
||||
you want to call them without a path prefix.
|
||||
Add `target/release`, or the `bin/` directory of a release archive, to `PATH`
|
||||
to run the tools by name.
|
||||
|
||||
`rncp-rs` follows the established listener authentication model: without `-n`,
|
||||
incoming senders must match `-a <hash>` or an `allowed_identities` file.
|
||||
`rncp-rs -F` can serve fetch requests to authenticated clients; use
|
||||
`-j <jail>` to bound file access unless unrestricted fetch paths are
|
||||
intentional.
|
||||
### File transfer
|
||||
|
||||
`rnodeconf-rs` in the current build only covers safe inspection/device setting paths, EEPROM
|
||||
dump/backup, and trusted-key storage.
|
||||
An `rncp-rs` listener accepts files only from identities given with `-a` or
|
||||
listed in `allowed_identities`; `-n` accepts anyone. Add `-F` to also serve
|
||||
fetches, and `-j <dir>` to keep them inside one directory.
|
||||
|
||||
`rnid-rs` tracks the Reticulum 1.2.4 identity utility surface for normal
|
||||
software identities: public/private import and export, destination hashing,
|
||||
`.pub` public identity files, and signed `.rsg` signature files. The
|
||||
hardware-backed `rnid-rs hw` path is a Rust extension behind the `hardware`
|
||||
feature and should still be treated as experimental.
|
||||
### RNode setup
|
||||
|
||||
Common `rnid-rs` flows:
|
||||
`rnodeconf-rs` installs and updates RNode firmware, changes device settings,
|
||||
signs devices, and walks through a new device with `-a`. Flashing uses the same
|
||||
tools as Python's `rnodeconf`: `avrdude`, `adafruit-nrfutil`, or the firmware's
|
||||
own `esptool.py` through `python3`.
|
||||
|
||||
### Identities
|
||||
|
||||
`rnid-rs` creates, imports, and exports identities, and signs, verifies,
|
||||
encrypts, and decrypts with them. Exported private keys grant control of an
|
||||
identity, so keep them out of shared terminals, logs, and shell history.
|
||||
Hardware-backed identities (`rnid-rs hw`, behind the `hardware` feature) are
|
||||
experimental.
|
||||
|
||||
```bash
|
||||
# Generate and inspect an identity.
|
||||
rnid-rs -g ~/.rsReticulum/identities/mgmt
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -p
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -H lxmf.delivery
|
||||
|
||||
# Export text identity material. -x is public, -X is private.
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -x -b
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -X -B
|
||||
|
||||
# Write identity files. Without -X, -w writes a public .pub file.
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -w mgmt.pub
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -X -w mgmt.rid
|
||||
rnid-rs -m <public_identity_data> -w peer.pub
|
||||
rnid-rs -M <private_identity_data> -X -w restored_identity
|
||||
|
||||
# Sign and validate. New signatures are Reticulum 1.2.4 .rsg envelopes.
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -s message.txt
|
||||
rnid-rs -V message.txt.rsg
|
||||
rnid-rs -i <signer_hash> -N -V message.txt.rsg
|
||||
|
||||
# Encrypt to a public identity, decrypt with the matching private identity.
|
||||
rnid-rs -i mgmt.pub -e message.txt
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -d message.txt.rfe
|
||||
mkdir -p ~/.rsReticulum/identities
|
||||
rnid-rs -g ~/.rsReticulum/identities/mgmt # generate
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -p # show
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -w mgmt.pub # write the public half
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -s message.txt # sign: message.txt.rsg
|
||||
rnid-rs -V message.txt.rsg # verify
|
||||
rnid-rs -i mgmt.pub -e message.txt # encrypt: message.txt.rfe
|
||||
rnid-rs -i ~/.rsReticulum/identities/mgmt -d message.txt.rfe # decrypt
|
||||
```
|
||||
|
||||
Use `--raw -s <file>` only when a workflow intentionally needs the legacy raw
|
||||
64-byte signature form. Normal `rnid-rs -s <file>` produces a `.rsg` file that
|
||||
embeds the signer metadata needed for 1.2.4 validation.
|
||||
|
||||
## Configuration
|
||||
|
||||
`rnsd-rs` reads Reticulum INI config from `<config-dir>/config`. If no config
|
||||
@@ -193,18 +206,19 @@ directory is supplied, the default is:
|
||||
| Linux/macOS | `/etc/rsReticulum/config`, then `~/.config/rsReticulum/config`, then `~/.rsReticulum/config` |
|
||||
| Windows | `%APPDATA%\rsReticulum\config` |
|
||||
|
||||
Generate the annotated starter file:
|
||||
On Linux/macOS, the first two locations are selected only when their `config` file exists; otherwise the home-directory fallback is used.
|
||||
|
||||
Print the annotated starter configuration to standard output:
|
||||
|
||||
```bash
|
||||
rnsd-rs --exampleconfig
|
||||
```
|
||||
|
||||
Minimal TCP client example:
|
||||
Minimal TCP client example. Replace `reticulum.example.org` and the port with the endpoint supplied by your network operator:
|
||||
|
||||
```ini
|
||||
[reticulum]
|
||||
share_instance = yes
|
||||
instance_control_socket = yes
|
||||
enable_transport = no
|
||||
|
||||
[interfaces]
|
||||
@@ -212,17 +226,15 @@ enable_transport = no
|
||||
[[Default TCP]]
|
||||
type = TCPClientInterface
|
||||
enabled = yes
|
||||
target_host = rns.ratspeak.org
|
||||
target_host = reticulum.example.org
|
||||
target_port = 4242
|
||||
```
|
||||
|
||||
Existing Python Reticulum configs should work if every requested interface
|
||||
is implemented here. Unknown or not-yet-wired interfaces should be removed or
|
||||
disabled until support lands.
|
||||
Each interface needs a supported type and an explicit `enabled = yes` or `interface_enabled = yes`, and `ifac_size` is given in bits, as in Python Reticulum. Keep unsupported interfaces disabled.
|
||||
|
||||
The default shared-instance data/control ports are `37428`/`37429`. Ratspeak
|
||||
uses app-private `37430`/`37431` ports. If you run two daemons at the same
|
||||
time, give one config a distinct port pair to avoid confliction, like:
|
||||
time, give one config a distinct port pair to avoid a port conflict:
|
||||
|
||||
```ini
|
||||
[reticulum]
|
||||
@@ -230,60 +242,76 @@ shared_instance_port = 37432
|
||||
instance_control_port = 37433
|
||||
```
|
||||
|
||||
Programs use the control port with the instance's RPC key: `rpc_key` under
|
||||
`[reticulum]` when it is set, otherwise a key derived from the transport
|
||||
identity. That key is an admin credential: a program that has it can read the
|
||||
daemon's network state, drop its paths and block identities, so treat it like
|
||||
a password and give it only to programs you trust.
|
||||
|
||||
Runtime state is kept under `<config-dir>/storage/`. Known destinations and
|
||||
received ratchets are stored in `known_destinations.db` and cached announces in
|
||||
`cache/announces.db`, SQLite files in the format Python Reticulum 1.6.1 uses.
|
||||
A shared-instance client reads the owner's database and never
|
||||
writes it. A database that cannot be opened is replaced by in-memory state for
|
||||
that session, with one log line. These stores come from the default
|
||||
`sqlite-store` feature of `rns-transport`; without it, this state lasts only
|
||||
for the session.
|
||||
|
||||
## Interface Support
|
||||
|
||||
###### Note: This is alpha, if something doesn't work, open an issue with enough context/information to help contribute to fixing it.
|
||||
This stack is experimental. Include the source revision or binary version, platform, interface type and relevant logs when reporting a problem.
|
||||
|
||||
| Interface | Current behavior |
|
||||
| --- | --- |
|
||||
| TCP client/server | Config-backed IPv4 and IPv6 paths. |
|
||||
| UDP | Config-backed unicast and multicast paths. |
|
||||
| Auto | Config-backed UDP discovery plus TCP fallback. |
|
||||
| UDP | Unicast and IPv4 broadcast datagrams; this driver does not join multicast groups. |
|
||||
| Auto | IPv6 multicast discovery with unicast UDP data on the local network. |
|
||||
| Local shared instance | Config-backed TCP loopback or Unix socket depending on platform. |
|
||||
| I2P | Config-backed SAM v3.1 path. |
|
||||
| Pipe | Config-backed subprocess stdio pipe. |
|
||||
| Backbone | Config-backed high-latency WAN-style tunnel. |
|
||||
| Backbone | Config-backed `BackboneInterface` listener and `BackboneClientInterface`, HDLC over TCP. |
|
||||
| Serial, KISS, RNode, RNode Multi, AX.25 KISS | Config-backed with the `serial` feature. |
|
||||
| RNode over TCP | Config-backed `RNodeInterface` with a `tcp://` port, with the `serial` or `rnode-tcp` feature. |
|
||||
| BLE RNode | Config-backed with the `ble` feature. |
|
||||
| Bluetooth Peer | Runtime API used by Ratspeak. |
|
||||
| Bluetooth Peer | Runtime API used by Ratspeak, with the `ble` feature. |
|
||||
| Android USB-OTG | Runtime API for Android app embeddings. |
|
||||
| Weave | Not implemented. |
|
||||
| Weave | Not supported yet. |
|
||||
| Bluetooth Classic RFCOMM | Not implemented. |
|
||||
|
||||
## Established Link Routing
|
||||
|
||||
An initial Link Request uses normal Reticulum path discovery and may be
|
||||
broadcast when no path is known. Once the responder accepts that request and
|
||||
the initiator validates its proof, each local Link endpoint is bound to the
|
||||
exact interface and role selected by the handshake. Later Link packets,
|
||||
Channels, Resources, proofs, keepalives, and teardown never fall back to a
|
||||
different path or interface; loss of the selected interface closes that Link.
|
||||
|
||||
Reliable Link control uses a bounded ordered queue, while realtime media has a
|
||||
separate bounded best-effort path that cannot overtake retained control
|
||||
traffic. A proof sent by the initiator uses its temporary signing key from
|
||||
the Link Request; a proof sent by the responder uses the accepting destination
|
||||
identity.
|
||||
|
||||
## Compatibility Notes
|
||||
|
||||
Most daemon and utility flows are implemented for the public `*-rs` tools:
|
||||
`rnsd-rs`, `rnstatus-rs`, `rnpath-rs`, `rnid-rs`, `rnprobe-rs`, `rncp-rs`,
|
||||
`rnsh-rs`, and `rnodeconf-rs`.
|
||||
rsReticulum 1.5.1 follows Python Reticulum 1.6.1, and its tools name that
|
||||
release in `--version`.
|
||||
|
||||
The current compatibility target is Reticulum 1.2.4 where the matching Rust
|
||||
surface is implemented and tested. `rnid-rs` has explicit 1.2.4 coverage for
|
||||
the normal identity utility flow.
|
||||
|
||||
Known gaps and intentional limits:
|
||||
|
||||
- `rnx`, `rnir`, `rnpkg`, `rngit`, and `git-remote-rns` are not implemented. There is on-going work in progress for supporting these.
|
||||
- `rnodeconf-rs` is partial; safe inspection/configuration and EEPROM
|
||||
dump/backup are furthest along. Firmware flashing, autoinstall/update, ROM
|
||||
bootstrap, destructive EEPROM wipe, and full signing-key management are not
|
||||
implemented.
|
||||
- `rnstatus-rs` covers the practical operator surface, but does not implement
|
||||
every display/API behavior from upstream.
|
||||
- `rnpath-rs` remote mode is read-only for table/rates, including destination
|
||||
filters, apart from the remote blackhole-list query path. Remote mutations
|
||||
and remote active path requests are full gaps.
|
||||
- `rncp-rs` implements the listener `-b` announce interval. `-P/--phy-rates`
|
||||
is not supported for the time being.
|
||||
- `rns-ratkey` hardware identity support is feature-gated and still has known
|
||||
hardware-verification gaps before it should be described as release-ready.
|
||||
|
||||
## Contributing
|
||||
|
||||
If the issue or contribution belongs upstream as well, start there. Python LXMF
|
||||
and Reticulum remain the reference implementations.
|
||||
|
||||
PRs are closed for now until I have time to catch up on everything. I'm tired.
|
||||
Interface discovery announces this stack as `rsRNS`. `rnsd-rs` auto-connects to
|
||||
discovered Backbone interfaces announced by Python Reticulum 1.5.7 or later and
|
||||
by rsReticulum 1.5.0 or later; `autoconnect_unverified_implementations = yes`
|
||||
in `[reticulum]` allows any. Python Reticulum auto-connects to an rsReticulum
|
||||
interface only with that option set.
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 or later. See [LICENSE](LICENSE).
|
||||
rsReticulum is licensed under the [Reticulum License](LICENSE), the license of
|
||||
the reference implementation it is ported from. Copyright (c) 2016-2026 Mark
|
||||
Qvist, unless otherwise noted; additions and modifications Copyright (c) 2026
|
||||
Ratspeak LLC.
|
||||
|
||||
The license is permissive with two conditions: no use in systems built to
|
||||
purposefully harm people, and no use in or contribution to AI or language-model
|
||||
training. The copyright and permission notice must stay in every copy.
|
||||
[LICENSE](LICENSE) is the binding text.
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
# Rust API
|
||||
|
||||
This guide describes the 1.5.1 API, published as v1.5.1. The [1.5 migration
|
||||
guide](migrations/1.5.md) covers source and configuration changes.
|
||||
|
||||
Application code should begin with `rns_runtime::prelude`. It collects the
|
||||
runtime handle and the commonly used identity, destination, packet, Link,
|
||||
request, Channel, Resource, interface, and shutdown types without wrapping or
|
||||
replacing them. Existing module-qualified imports remain supported.
|
||||
|
||||
The examples in `crates/rns-runtime/examples/` are compiled as part of CI and
|
||||
show complete flows for runtime startup, Destinations, announces, receipts,
|
||||
Links, requests, Channels, Buffer streams, Resources, and RNode observation.
|
||||
|
||||
```rust
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use rns_runtime::prelude::*;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), ReticulumError> {
|
||||
let runtime = init(
|
||||
None,
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let identity = Identity::new();
|
||||
// Use `runtime` and `identity` to create application Destinations.
|
||||
|
||||
runtime.shutdown_and_wait().await;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Finite destination discovery uses `resolve_destination_on_transport` with one
|
||||
deadline and validated identity recall. Long-lived announce observation uses
|
||||
`ReticulumHandle::subscribe_announces`; the returned `AnnounceSubscription`
|
||||
owns exactly one registration. Finite lookups do not install or remove
|
||||
announce handlers.
|
||||
|
||||
## Explicit shared-instance ownership
|
||||
|
||||
Applications that require authenticated shared control can opt into
|
||||
`reticulum::init_with_policy` and `shared_instance::InstancePolicy`:
|
||||
|
||||
- `Configured` retains the normal config-driven automatic owner/client behavior.
|
||||
- `Standalone` owns local interfaces without exposing shared IPC.
|
||||
- `SharedOwner` binds both configured shared endpoints or fails; it never joins
|
||||
another owner. `SharedOwnerAt(endpoint)` selects them in memory without
|
||||
rewriting the configuration file.
|
||||
- `SharedClient(credentials)` requires the selected packet endpoint and
|
||||
authenticated interface-status RPC before becoming ready. It reauthenticates
|
||||
on reconnect and never falls back to local interfaces.
|
||||
|
||||
`SharedInstanceEndpoint::Tcp` is loopback-only. Explicit Unix endpoints use
|
||||
Linux/Android abstract instance names. Keys are opaque HMAC bytes, supplied via
|
||||
`SharedInstanceCredentials::new`; its debug representation redacts the key.
|
||||
`credentials.test().await` checks availability without starting a runtime.
|
||||
|
||||
Observe reconnect/authentication state through `shared_instance_state()` and
|
||||
typed control failures through `query_control_result()`. Client runtimes reject
|
||||
dynamic local interface spawns. Non-fatal configured-interface startup failures
|
||||
are available through `startup_interface_failures()`; other interfaces can
|
||||
remain usable.
|
||||
|
||||
Upstream packet IPC is unauthenticated: successful RPC authenticates the control
|
||||
endpoint, not the identity of the packet socket. Selecting a trustworthy matching
|
||||
pair remains the application's responsibility. These policies do not move
|
||||
AutoInterface's interoperable UDP ports or alter Reticulum wire formats.
|
||||
|
||||
The [capacity, IFAC, and receipt migration guide](migrations/capacity-and-receipts.md) describes the capacity boundary introduced in 1.4 and still current in 1.5, including custom-driver ownership and application-controlled admission.
|
||||
|
||||
## Stability
|
||||
|
||||
The 1.5 line follows Reticulum 1.6.0, and 1.6.1 from 1.5.1. It makes the transport actor's state
|
||||
private, marks growing enums and structs `#[non_exhaustive]`, keeps known
|
||||
destinations, ratchets, and cached announces in upstream's SQLite stores, and
|
||||
moves stamp costs and values to `f64`. See the
|
||||
[1.5 migration guide](migrations/1.5.md) for each source change and the
|
||||
behaviour an operator sees.
|
||||
|
||||
The 1.3 line changes the six discovery coordinate fields to `Option<f64>` so
|
||||
unknown values remain distinct from real zero. It also replaces publicly mutable
|
||||
recursive discovery state with detached observations and exact requester
|
||||
cancellation. See the [1.3 migration guide](migrations/1.3.md) for both changes
|
||||
and their source, wire, and storage behavior. Normal runtime lookup/recovery
|
||||
APIs remain unchanged. Project minor releases can include breaking API changes;
|
||||
select an explicit compatible dependency line or reviewed immutable source pin.
|
||||
|
||||
Applications that own retry policy can obtain
|
||||
`ReticulumHandle::path_recovery_handle()` (also available from the application
|
||||
prelude). `try_recover(destination, Some(failed_link_id))` requests an atomic
|
||||
comparison with the route actually used by that locally originated Link. Only
|
||||
the unchanged route can be invalidated; fresh routes on the same interface are
|
||||
not suppressed. `None` requests bounded discovery without route invalidation.
|
||||
The 64-operation admission queue reports backpressure; callers retain ownership
|
||||
and bound their reply wait. Discovery is coalesced per destination, and the
|
||||
result is not proof of radio transmission or delivery. Old or unobserved Link
|
||||
attempts cannot delete routes. Shared clients only affect their own local
|
||||
transport state and use normal packet IPC for discovery.
|
||||
|
||||
`try_recover_packet(destination, packet_hash)` provides the same comparison for
|
||||
an atomically tracked local `SendPacket` attempt. Packet and Link ownership are
|
||||
separate; failures cannot consume another kind of attempt. Packet receipt
|
||||
windows can use `rns_wire::receipt::receipt_timeout_for_route`, also used by the
|
||||
runtime's automatic packet receipt policy.
|
||||
|
||||
`try_invalidate_packet(destination, packet_hash)` and
|
||||
`try_invalidate_link(destination, link_id)` perform only the exact
|
||||
failed-attempt route comparison and invalidation, without starting a new path
|
||||
request. A shared-client application can use this result to sequence its own
|
||||
authenticated owner recovery before ordinary discovery. This does not make
|
||||
legacy Python's destination-only owner reset an atomic route comparison or
|
||||
cancel other callers' pre-existing discovery.
|
||||
|
||||
### Established-Link delivery clocks
|
||||
|
||||
Advanced Link owners can obtain `ReticulumHandle::link_endpoint_dispatch_handle()`.
|
||||
Its opt-in bind receipt publishes an opaque token for one exact endpoint
|
||||
generation. `token.try_send(request, deadline)` retains the ordinary packet in
|
||||
the existing ordered endpoint FIFO until driver/local-peer admission, local
|
||||
expiry, cancellation, or an exact terminal failure. The deadline includes
|
||||
mailbox wait and is limited to 120 seconds. `Sent` contains the original local
|
||||
dispatch time and packet hash; it is not physical transmission or delivery.
|
||||
Dropping an unread bind receipt retires only its unpublished binding; published
|
||||
bindings still require the normal explicit cleanup.
|
||||
|
||||
`LinkEndpointDispatchBindReceipt::poll_ready` registers a task waker without
|
||||
publishing the binding. It retains a ready result until `try_recv` or awaiting
|
||||
consumes it; cancellation between readiness and consumption still retires the
|
||||
unpublished endpoint. This supports event-driven delivery owners without
|
||||
changing existing periodic consumers or proof timing.
|
||||
|
||||
`try_send_cancellable` additionally returns an exact cancellation capability.
|
||||
It requests removal while the packet is still awaiting local admission; it
|
||||
cannot recall bytes already admitted to a driver or affect another binding.
|
||||
The actor's final pre-admission check is the concurrent cancellation boundary.
|
||||
|
||||
`LinkManager::set_link_endpoint_dispatch_handle` enables these observations for
|
||||
ordinary packet sends. Legacy mailbox `Queued` still means only FIFO acceptance.
|
||||
`Link::packet_proof_timeout()` provides the measured-RTT proof budget, distinct
|
||||
from local queue residence. The accounting stream's outbound wait events retain
|
||||
the owner's original start time and finite timeout; delayed consumers must not
|
||||
restart those clocks. `OutboundTransfer::timeout_window()` similarly describes
|
||||
the current bounded Resource phase. Only genuine protocol progress renews it.
|
||||
|
||||
The application prelude is the recommended integration path, but the workspace
|
||||
is not yet a blanket stability promise for every public Rust item.
|
||||
|
||||
- `rns-identity`, `rns-link`, `rns-protocol`, and `rns-interface` are candidate
|
||||
stable.
|
||||
- `rns-crypto`, `rns-wire`, and `rns-transport` are provisional low-level
|
||||
packages.
|
||||
- `rns-runtime` is provisional because it contains both the application
|
||||
prelude and lower-level actor, RPC, manager, and command APIs.
|
||||
- `rns-ratkey` is experimental, and the `rns-tools` and `rns-git` library
|
||||
targets support the repository's binaries rather than a public library
|
||||
integration.
|
||||
|
||||
Low-level actor, mailbox, RPC, path-table, concrete-driver, and Link
|
||||
endpoint ownership APIs remain available for compatibility. They should not be
|
||||
treated as stable merely because they are publicly reachable.
|
||||
|
||||
## Compatibility checks
|
||||
|
||||
The `api/` directory contains the evidence used by CI:
|
||||
|
||||
- `stability.json` records package tiers, compatibility baselines, and snapshot
|
||||
hashes;
|
||||
- `snapshots/` records the explicit all-feature Apple ARM64 Rust API and the
|
||||
manifest, feature, dependency, target, and MSRV contract; and
|
||||
- `fixtures/` compiles recommended and retained import paths as an external
|
||||
consumer.
|
||||
|
||||
These checks catch accidental changes, but they do not replace platform builds,
|
||||
protocol interoperability tests, or manual review. In particular, the API
|
||||
snapshot omits auto-derived, auto-trait, and blanket implementations and is not
|
||||
by itself a complete SemVer verdict.
|
||||
|
||||
Run the checks with:
|
||||
|
||||
```sh
|
||||
python3 tools/check-api-baseline.py
|
||||
python3 tools/check-api-manifest.py
|
||||
python3 tools/check-api-compatibility.py
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --locked
|
||||
cargo check --manifest-path api/fixtures/Cargo.toml --all-features --locked
|
||||
```
|
||||
|
||||
After reviewing an API change, run
|
||||
`python3 tools/check-api-baseline.py --update` and commit the source and snapshot
|
||||
changes together. CI compares snapshots with the current source; compatibility
|
||||
checks retain the historical baseline.
|
||||
Generated
+2261
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "rns-application-api-fixture"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
all = ["rns-runtime/ble", "rns-runtime/rnode-tcp", "rns-runtime/serial"]
|
||||
|
||||
[dependencies]
|
||||
rns-protocol = { path = "../../crates/rns-protocol" }
|
||||
rns-identity = { path = "../../crates/rns-identity" }
|
||||
rns-transport = { path = "../../crates/rns-transport" }
|
||||
rns-runtime = { path = "../../crates/rns-runtime", default-features = false }
|
||||
@@ -0,0 +1,193 @@
|
||||
//! External-consumer compile contract for canonical and retained Reticulum paths.
|
||||
|
||||
/// Advanced actor ownership uses detached discovery snapshots, never map edits.
|
||||
pub mod recursive_discovery {
|
||||
use rns_transport::actor::{DiscoveryPathRequest, TransportActor};
|
||||
use rns_transport::messages::InterfaceId;
|
||||
use rns_transport::path_discovery::{DiscoveryAdmission, DiscoveryError};
|
||||
|
||||
pub fn request(
|
||||
actor: &mut TransportActor,
|
||||
destination: [u8; 16],
|
||||
interface: InterfaceId,
|
||||
) -> Result<DiscoveryAdmission, DiscoveryError> {
|
||||
actor.request_recursive_discovery(destination, interface)
|
||||
}
|
||||
|
||||
pub fn observe_and_cancel(actor: &mut TransportActor, destination: &[u8; 16]) {
|
||||
if let Some(snapshot) = actor.discovery_path_request(destination) {
|
||||
let _: DiscoveryPathRequest = snapshot.clone(); // retained import
|
||||
let _ = (snapshot.destination_hash(), snapshot.deadline());
|
||||
for requester in snapshot.requesters() {
|
||||
let _ = (requester.interface_id(), requester.destination_hash());
|
||||
actor.cancel_discovery_requester(requester);
|
||||
}
|
||||
}
|
||||
let _ = actor.discovery_path_requests();
|
||||
}
|
||||
}
|
||||
|
||||
pub mod canonical {
|
||||
use rns_runtime::prelude::{
|
||||
AnnounceSubscription, DestinationResolveError, DestinationResolveOptions,
|
||||
LinkSessionHandle, PacketReceiptHandle, RecalledDestination, ReticulumHandle,
|
||||
resolve_destination_on_transport,
|
||||
};
|
||||
|
||||
pub fn compile_surface() {
|
||||
let _ = resolve_destination_on_transport;
|
||||
let _ = std::mem::size_of::<DestinationResolveOptions>();
|
||||
let _ = std::mem::size_of::<DestinationResolveError>();
|
||||
let _ = std::mem::size_of::<ReticulumHandle>();
|
||||
let _ = std::mem::size_of::<RecalledDestination>();
|
||||
let _ = std::mem::size_of::<AnnounceSubscription>();
|
||||
let _ = std::mem::size_of::<PacketReceiptHandle>();
|
||||
let _ = std::mem::size_of::<LinkSessionHandle>();
|
||||
let _ = ReticulumHandle::path_recovery_handle;
|
||||
let _ = ReticulumHandle::link_endpoint_dispatch_handle;
|
||||
let _ = rns_runtime::prelude::PathRecoveryHandle::try_invalidate_packet;
|
||||
let _ = rns_runtime::prelude::PathRecoveryHandle::try_invalidate_link;
|
||||
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryHandle>();
|
||||
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryOutcome>();
|
||||
let _ = std::mem::size_of::<rns_runtime::prelude::PathRecoveryError>();
|
||||
}
|
||||
}
|
||||
|
||||
/// Advanced ownership remains opt-in and module-qualified.
|
||||
pub mod delivery_ownership {
|
||||
use rns_runtime::link_manager::{LinkManager, LinkManagerAccountingEvent};
|
||||
use rns_runtime::prelude::ReticulumHandle;
|
||||
|
||||
pub fn install_dispatch(runtime: &ReticulumHandle, manager: &mut LinkManager) {
|
||||
manager.set_link_endpoint_dispatch_handle(runtime.link_endpoint_dispatch_handle());
|
||||
}
|
||||
|
||||
pub fn observe_wait(event: &LinkManagerAccountingEvent) {
|
||||
match event {
|
||||
LinkManagerAccountingEvent::OutboundPacketWait {
|
||||
receipt,
|
||||
started_at,
|
||||
timeout,
|
||||
awaiting_admission,
|
||||
cancellation,
|
||||
} => {
|
||||
let _ = (
|
||||
receipt.link_id,
|
||||
receipt.packet_hash,
|
||||
started_at,
|
||||
timeout,
|
||||
awaiting_admission,
|
||||
cancellation,
|
||||
);
|
||||
}
|
||||
LinkManagerAccountingEvent::OutboundResourceWait {
|
||||
link_id,
|
||||
resource_id,
|
||||
started_at,
|
||||
timeout,
|
||||
} => {
|
||||
let _ = (link_id, resource_id, started_at, timeout);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod legacy {
|
||||
use rns_runtime::destination_resolver::{
|
||||
DestinationResolveError, DestinationResolveOptions, resolve_destination_on_transport,
|
||||
};
|
||||
use rns_runtime::link_session::LinkSessionHandle;
|
||||
use rns_runtime::reticulum::{
|
||||
AnnounceSubscription, PacketReceiptHandle, RecalledDestination, ReticulumHandle,
|
||||
};
|
||||
|
||||
pub fn compile_surface() {
|
||||
let _ = resolve_destination_on_transport;
|
||||
let _ = std::mem::size_of::<DestinationResolveOptions>();
|
||||
let _ = std::mem::size_of::<DestinationResolveError>();
|
||||
let _ = std::mem::size_of::<ReticulumHandle>();
|
||||
let _ = std::mem::size_of::<RecalledDestination>();
|
||||
let _ = std::mem::size_of::<AnnounceSubscription>();
|
||||
let _ = std::mem::size_of::<PacketReceiptHandle>();
|
||||
let _ = std::mem::size_of::<LinkSessionHandle>();
|
||||
}
|
||||
}
|
||||
|
||||
/// Strict application ownership is additive; legacy imports above remain valid.
|
||||
pub mod shared_ownership {
|
||||
use rns_runtime::shared_instance::{
|
||||
InstancePolicy, SharedInstanceCredentials, SharedInstanceEndpoint,
|
||||
};
|
||||
|
||||
pub fn compile_surface() {
|
||||
let endpoint = SharedInstanceEndpoint::Tcp {
|
||||
packet_port: 37428,
|
||||
control_port: 37429,
|
||||
};
|
||||
let credentials = SharedInstanceCredentials::new(endpoint.clone(), vec![1; 17]).unwrap();
|
||||
let _ = InstancePolicy::SharedClient(credentials);
|
||||
let _ = InstancePolicy::SharedOwnerAt(endpoint);
|
||||
let _ = rns_runtime::reticulum::init_with_policy;
|
||||
let _ = rns_runtime::reticulum::ReticulumHandle::shared_instance_state;
|
||||
let _ = rns_runtime::reticulum::ReticulumHandle::startup_interface_failures;
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1.3 discovery API distinguishes unknown components from true zeros.
|
||||
pub mod nullable_discovery {
|
||||
use rns_transport::discovery::DiscoveryInterfaceConfig;
|
||||
use rns_transport::discovery::app_data::DiscoveryInfo;
|
||||
|
||||
pub fn literal() -> DiscoveryInfo {
|
||||
DiscoveryInfo {
|
||||
name: "coordinate-fixture".into(),
|
||||
interface_type: "BackboneInterface".into(),
|
||||
latitude: Some(0.0),
|
||||
longitude: Some(0.0),
|
||||
height: None,
|
||||
..DiscoveryInfo::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn configured() -> DiscoveryInterfaceConfig {
|
||||
let mut config =
|
||||
DiscoveryInterfaceConfig::backbone(Some("relay".into()), "127.0.0.1".into(), 4965);
|
||||
config.latitude = Some(0.0);
|
||||
config.longitude = None;
|
||||
config.height = Some(0.0);
|
||||
config
|
||||
}
|
||||
|
||||
pub fn read(info: &DiscoveryInfo) -> [Option<f64>; 3] {
|
||||
[info.latitude, info.longitude, info.height]
|
||||
}
|
||||
}
|
||||
|
||||
/// Application admission carries non-cloneable authority separately from bytes.
|
||||
pub mod application_packet_admission {
|
||||
use rns_runtime::link_manager::{
|
||||
InboundLinkPacket, LinkPacketReceiptOutcome, LinkPacketRejection,
|
||||
};
|
||||
pub async fn accept(packet: InboundLinkPacket) -> Option<LinkPacketReceiptOutcome> {
|
||||
let (payload, receipt) = packet.into_parts();
|
||||
let outcome = receipt?.accept().await.ok();
|
||||
drop(payload);
|
||||
outcome
|
||||
}
|
||||
pub fn compile_surface() {
|
||||
let _ = LinkPacketRejection::InvalidPropagationStamp;
|
||||
let _ = rns_runtime::link_manager::LinkManager::set_ordinary_packet_proof_strategy;
|
||||
let _ = rns_runtime::interface_factory::InterfacePostInit::try_from_section;
|
||||
let _ = rns_runtime::config::ifac::parse_ifac_size;
|
||||
let _ = rns_runtime::config::ifac_lock::ConfigWriteLock::acquire;
|
||||
let _ = rns_identity::persistence::durable_write;
|
||||
let _ = rns_identity::persistence::durable_reconcile_hash;
|
||||
let _ = rns_transport::messages::InterfacePacketCapacity::new(500, 508, false);
|
||||
let _ = rns_transport::messages::InterfaceTransportSender::new;
|
||||
let _ = rns_transport::link_messages::dispatch_link_request;
|
||||
let _ = rns_transport::link_messages::LinkRequestDispatchError::NoInterface;
|
||||
let _ = rns_transport::ifac::try_ifac_sign;
|
||||
let _ = rns_protocol::resource_control::check_control_frame;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
# Migrating to rsReticulum 1.3
|
||||
|
||||
Version 1.3 combines two discovery API changes since the published 1.2 release:
|
||||
owned recursive discovery operations and independently optional interface
|
||||
coordinates. Both changes belong to this release.
|
||||
|
||||
This project's version convention permits breaking Rust APIs in a minor release.
|
||||
Version 1.3 is not source-compatible with direct mutation of the 1.2 discovery
|
||||
map. Cargo's default caret requirement `"1.2"` permits 1.3; use an explicit
|
||||
compatible line (for example `"~1.3.0"`) or an exact reviewed Git revision.
|
||||
Existing external dependency requirements cannot be changed retroactively.
|
||||
Packet, signature, RPC, and AutoInterface port formats remain unchanged.
|
||||
|
||||
Normal applications keep runtime `request_path`, finite destination resolution
|
||||
and `PathRecoveryHandle`. They do not need this advanced actor API.
|
||||
|
||||
## Advanced synchronous actor owners
|
||||
|
||||
| Before | Supported replacement |
|
||||
| --- | --- |
|
||||
| Read `actor.discovery_path_requests[&destination]` | `actor.discovery_path_request(&destination)` returns an optional detached snapshot |
|
||||
| Iterate the public map | `actor.discovery_path_requests()` returns snapshots sorted by destination |
|
||||
| Read one `requesting_interface` | Iterate `snapshot.requesters()` and read each token's `interface_id()` |
|
||||
| Read `timeout` | `snapshot.deadline()` is the original absolute Unix-seconds expiry |
|
||||
| Insert a record to participate in recursive discovery | `actor.request_recursive_discovery(destination, interface)` validates admission and starts/joins the one bounded search |
|
||||
| Remove/edit a record to cancel one requester | `actor.cancel_discovery_requester(token)` removes only that registration |
|
||||
| Copy/extend a deadline | Clone a snapshot for observation; callers cannot renew an existing operation |
|
||||
|
||||
`actor::DiscoveryPathRequest` remains an import path, re-exporting the type in
|
||||
`path_discovery`. Its public fields and `Copy` contract are removed deliberately.
|
||||
The old single-requester shape could silently discard other registrations when
|
||||
edited. Keeping a mutable compatibility mirror would retain that defect.
|
||||
|
||||
One operation admits at most 64 distinct requester channel generations; the
|
||||
actor admits at most 1,024 destinations. Repeated joins of the same registration
|
||||
return the same token without a new fanout or deadline. Requester identity is an
|
||||
interface generation, not a count of individual people sharing one radio.
|
||||
|
||||
Snapshots are not live views. A removed first requester disappears from new
|
||||
snapshots while other requesters remain. Offline but still registered/open
|
||||
requesters may remain waiting; no response is sent while they are offline.
|
||||
Expiry and interface replacement are checked without requiring a prior tick.
|
||||
|
||||
Tokens are opaque and actor/operation/registration-specific. Cloning or dropping
|
||||
one does not change ownership. Cancellation is explicit and cannot act on a new
|
||||
operation, a cancelled-and-rejoined requester, another actor, or a replacement
|
||||
channel that reused the numeric ID. Cancelling the last waiter removes related
|
||||
unadmitted search bytes; cancellation cannot recall transmitted bytes.
|
||||
|
||||
The advanced request API requires transport forwarding, an unknown nonlocal
|
||||
destination, and an available normal interface with eligible discovery policy.
|
||||
Typed errors distinguish policy, availability and capacity failures. It uses
|
||||
normal ingress/egress limits and a new wire tag only for a newly started search.
|
||||
`DiscoveryAdmission::started()` is local ownership/fanout intent, not a radio or
|
||||
delivery receipt. Driver backpressure and network loss still require normal
|
||||
caller policy. Normal runtime lookups should not use recursive actor control.
|
||||
|
||||
Use the compiled external fixture's `recursive_discovery` module as an example.
|
||||
No shared IPC/JNI or application UI is added by this change. Package stability
|
||||
classifications remain provisional; the compatibility gate records exactly the
|
||||
approved removals and continues rejecting unrelated API loss.
|
||||
|
||||
## Interface discovery coordinates
|
||||
|
||||
The six public `latitude`, `longitude`, and `height` fields in `DiscoveryInfo`
|
||||
and `DiscoveryInterfaceConfig` change from `f64` to `Option<f64>`, including the
|
||||
re-export of `DiscoveryInterfaceConfig` from `rns_transport::discovery`.
|
||||
|
||||
Unknown coordinates are `None`; known coordinates, including zero, are `Some`.
|
||||
The components are independent, so a known latitude and longitude do not imply
|
||||
a known height. `Default` and discovery convenience constructors leave them
|
||||
unknown. Update struct literals and assignments accordingly:
|
||||
|
||||
```rust,ignore
|
||||
// Before
|
||||
config.latitude = 0.0;
|
||||
config.longitude = -105.0;
|
||||
config.height = 0.0;
|
||||
|
||||
// After: latitude is genuinely zero; height is unknown.
|
||||
config.latitude = Some(0.0);
|
||||
config.longitude = Some(-105.0);
|
||||
config.height = None;
|
||||
```
|
||||
|
||||
Consumers should match the options or use `if let Some(value)` when displaying
|
||||
or using a component. Do not use `unwrap_or(0.0)` to turn an unknown location
|
||||
into a real map position. This change does not add new coordinate range rules.
|
||||
|
||||
## Wire, configuration, and storage
|
||||
|
||||
The discovery map retains its existing keys. An unknown component is encoded
|
||||
as MessagePack `nil`, matching Python Reticulum; a known component remains a
|
||||
number. Missing configuration leaves a component unknown, while an explicit
|
||||
zero remains known. Existing configuration key precedence and units are retained.
|
||||
No new wire protocol version or storage directory is required.
|
||||
|
||||
The Rust decoder continues accepting integer coordinates and missing coordinate
|
||||
keys as a leniency: integers become `Some`, and missing values become `None`.
|
||||
Those forms are not a claim of strict Python validation parity. Valid Python
|
||||
`nil`, partial-coordinate, and floating-point records are supported.
|
||||
|
||||
Existing numeric discovery records remain numeric on disk reload. Old stored
|
||||
zero cannot reveal whether it was deliberately configured or produced by the
|
||||
previous defaulting behavior, so it is preserved as `Some(0.0)`. A fresh valid
|
||||
announcement can replace it. Records containing `nil` or absent location keys
|
||||
load as `None`. Downgrading to older Rust versions loses this distinction:
|
||||
those versions coerce stored unknown components to zero.
|
||||
|
||||
`rnstatus-rs` represents unknown components as JSON `null`; text output uses
|
||||
presence instead of treating zero as absent. This does not change an embedding
|
||||
application's separate map display or location-sharing policy.
|
||||
|
||||
The historical API compatibility floor is retained. The exact removal ledger
|
||||
contains three recursive-ownership paths and nine coordinate paths for six
|
||||
fields because three are also re-exported. No unrelated removals are authorized.
|
||||
@@ -0,0 +1,193 @@
|
||||
# Migrating to the 1.4 source API
|
||||
|
||||
The 1.4 line is published as v1.4.0 and is the source line Ratspeak builds
|
||||
from. These APIs and migration commands require a 1.4 build.
|
||||
|
||||
The 1.4 source line introduces explicit interface-capacity ownership and durable
|
||||
application admission. Existing published releases are unchanged. Migrate
|
||||
Reticulum dependents together to ~1.4.0; a source version alone is not publication.
|
||||
|
||||
Follow [capacity, IFAC configuration, receipts and timing](capacity-and-receipts.md)
|
||||
for the full API and configuration transition. In particular:
|
||||
|
||||
- Replace `InterfacePostInit::from_section` with fallible `try_from_section`,
|
||||
and propagate semantic configuration errors before spawning interfaces.
|
||||
- `LinkManager::set_link_packet_channel` returns a result. The legacy tuple
|
||||
receiver cannot enable ProveApp; use the bounded typed packet channel and
|
||||
exact endpoint binding for application-controlled receipts.
|
||||
- Custom interface handles and entries must supply exact owner and typed packet
|
||||
capacity facts. Construct their bound sender before producer tasks start.
|
||||
Link endpoint bindings retain the interface owner captured from the admitted
|
||||
request/proof, rather than looking up whichever interface currently has an ID.
|
||||
- Request admission and proof validation are separate. Retain one attempt-owned
|
||||
result and deadline; cancelled/refused attempts cannot change a replacement.
|
||||
- `rns_interface::rnode::RNodeStream` is an opaque struct; its `Serial` and `Tcp`
|
||||
variants are no longer public. Open streams with `open_serial` or
|
||||
`connect_tcp`; `try_clone`, `description`, and the `Read`/`Write`
|
||||
implementations are unchanged.
|
||||
|
||||
Build `InterfaceStatRpcEntry` with `..Default::default()` and `InterfaceEntry`
|
||||
with `..InterfaceEntry::new(...)`, so fields added on the 1.4 line stay
|
||||
source compatible.
|
||||
|
||||
`rns_link::mtu_discovery::SignallingData` remains a public re-export of the
|
||||
shared `rns_wire::link_signalling::SignallingData`; existing imports and checked
|
||||
handshake callers can continue using that alias. Cargo-public-api renders
|
||||
canonical type paths from rns-wire, so its twelve moved snapshot lines are
|
||||
explicitly recorded despite preserved source identity. `new/pack/unpack` remain
|
||||
low-level representation helpers; use checked signalling APIs for admission.
|
||||
|
||||
`rpc::InterfaceStatEntry::ifac_size` is now `Option<usize>`, `None` when the
|
||||
interface has no IFAC, and the entry gains `ifac_signature` and `ifac_netname`,
|
||||
as in Python's interface stats. Interface sections start only when
|
||||
`interface_enabled` or `enabled` is true; add `enabled = yes` to sections that
|
||||
relied on the old default. `ConfigSection::interface_enabled`, `has_enable_key`
|
||||
and `invalid_enable_key` expose that rule to embedders.
|
||||
|
||||
Strict persistence accepts every filesystem; `DurabilityUnsupported` no longer
|
||||
reports an unqualified filesystem. `persistence::storage_risk` classifies network
|
||||
or user-space (`Remote`) and RAM-backed (`Volatile`) storage so applications can
|
||||
warn their users.
|
||||
|
||||
`I2PServerConfig` gains `b32`, which receives the server's b32 address when
|
||||
SAM creates its session, and `key_path`, the file that keeps the server's
|
||||
private key, and so its address, across sessions; the runtime sets it to
|
||||
Python's key file under `storage/i2p`. `i2p::destination_b32` derives the
|
||||
address from a SAM private key; build the config with `new`.
|
||||
`discovery::announcer::Announcer::reconfigure` replaces a registered
|
||||
interface's config but keeps its announce interval.
|
||||
|
||||
`TunnelEntry::interface_id` is now `Option<InterfaceId>`, `None` while the
|
||||
tunnel is unbound, instead of the id-0 sentinel. `spawn_local_server` and
|
||||
`spawn_i2p_server` take the listener's allocated `InterfaceId`, which their
|
||||
accepted clients report as `parent_id`. `InterfaceEntry::parent_id` carries it
|
||||
into transport; set it from `InterfaceHandle::parent_id`. Persisted tunnels now
|
||||
load unbound into the tunnel table, so `TransportActor::pending_tunnel_entries`
|
||||
is gone.
|
||||
|
||||
`TransportActor::discovery_pr_tags` is a `HashSet<[u8; 32]>` of destination
|
||||
hash plus tag, with no timestamps, and `discovery_pr_tags_prev` holds the
|
||||
previous generation; a tag in either is a duplicate. `PacketHashlist::insert`
|
||||
no longer rotates: the owner calls `rotate_if_full` from its periodic job.
|
||||
`TransportMessage::RegisterAnnounceSubscription` takes a `paused` flag, which
|
||||
`AnnounceSubscription::pause` and `resume` set.
|
||||
|
||||
`TunnelSynthesisData::unpack` accepts exactly 176 bytes, and `is_signed` is
|
||||
the check transport applies before admitting one. The TCP, Backbone and I2P
|
||||
client configs' `python_name` is the Python `str()` their syntheses hash. Announces join the
|
||||
tunnel named by their interface's latest synthesis, which `handle_tunnel` and
|
||||
`TunnelTable::insert` record and `TunnelTable::void_interface` clears; writing
|
||||
`interface_id` directly no longer rebinds an interface. `handle_tunnel` no
|
||||
longer takes a timeout: a tunnel expires `TUNNEL_TIMEOUT` after its synthesis,
|
||||
as in Python. `TunnelTable::cull_expired` and `cull_expired_batch` also drop
|
||||
tunnels set to expire more than twice `TUNNEL_TIMEOUT` ahead.
|
||||
|
||||
`TcpClientConfig`, `BackboneClientConfig` and `I2PClientConfig` gain
|
||||
`tunnel_identity`. With a `TunnelIdentity` set, the client opens every
|
||||
connection with a tunnel synthesis signed by it; the runtime sets it from
|
||||
`ReticulumHandle::transport_identity`. Build these configs with `new` so the
|
||||
field defaults to `None`. A KISS-framed TCP client never synthesizes. Every
|
||||
TCP, Backbone and I2P client, the shared-instance TCP client included, drops
|
||||
its queued traffic when a connection opens after an outage or a failed
|
||||
attempt, and the Unix shared-instance client drops it when it reconnects.
|
||||
|
||||
`TcpClientConfig` gains `i2p_tunneled`, which gives a TCP connection tunneled
|
||||
over I2P Python's longer I2P socket timeouts; the runtime reads it from the
|
||||
interface's `i2p_tunneled` key. Build the config with `new` so it defaults to
|
||||
`false`.
|
||||
|
||||
Interface stats carry Python 1.5's per-interface counters.
|
||||
`IngressController` counts announces and path requests received and sent;
|
||||
`InterfaceEntry` gains `protocol_violations`, `ifac_violations`,
|
||||
`packet_filter_hits` and `tx_dropped_bytes`; `InterfaceStatRpcEntry` reports
|
||||
all of them plus `parent_id`; `rpc::InterfaceStatEntry` carries them, the
|
||||
listener's name, and now implements `Default`. Build it with
|
||||
`..Default::default()`. The control port and remote management answer with
|
||||
one Python-shaped stats dict, so `remote_management_schema` is removed:
|
||||
decode a `/status` answer as `[stats, link_count?]`, and a `/path` answer with
|
||||
`rpc::decode_response_for_request`. Remote management answers on the transport
|
||||
identity, so `rnstatus -R` and `rnpath -R` take its hash. A node with
|
||||
`enable_transport` off and no `static_transport_identity` gets a new management
|
||||
destination each start, as in Python. The runtime no longer reads
|
||||
`storage/remote_management_identity`, and leaves the file in place for the
|
||||
operator to delete.
|
||||
|
||||
Interface discovery carries Python 1.5's implementation keys.
|
||||
`DiscoveryInfo` gains `impl_name` and `impl_version`; build it with
|
||||
`..Default::default()`. `discovery::autoconnect::qualifies` applies Python's
|
||||
auto-connect rule, with `ReticulumConfig::autoconnect_unverified_implementations`
|
||||
as its opt-in. The receiver no longer stores types that are never listed, so
|
||||
`discovery::Reason` gains `UnlistedType` and becomes `#[non_exhaustive]`, so a
|
||||
match needs a wildcard arm.
|
||||
|
||||
`rns_link::clock::ContinuousInstant` reads a monotonic clock that keeps
|
||||
counting while the system is suspended: `CLOCK_BOOTTIME` on Linux and Android,
|
||||
`CLOCK_MONOTONIC_RAW` on Apple platforms and the performance counter on
|
||||
Windows, with `std::time::Instant` as a best-effort fallback elsewhere. Use it
|
||||
for a deadline that must hold in real time across a sleep. Check that deadline
|
||||
on a regular tick and when the runtime resumes; do not assume an outstanding
|
||||
async timer enforces the same suspend-inclusive deadline on every platform.
|
||||
Readings are process-local and do not convert to or from `std::time::Instant`.
|
||||
rns-link gains the target dependencies `libc` (unix) and `windows-sys`
|
||||
(Windows), so dependents that build with `--locked` refresh their lock files.
|
||||
|
||||
`hkdf::derive_key_64` returns `Zeroizing<[u8; 64]>` and `hkdf::hkdf_sha256`
|
||||
returns `Zeroizing<Vec<u8>>`, so derived keys are wiped when they are dropped.
|
||||
Pass `&key[..]` where a slice is expected and compare `&okm[..]` with a plain
|
||||
`Vec`; the bytes are unchanged. `Zeroizing<[u8; 64]>` is not `Copy`, so code
|
||||
that copied the key borrows it instead. `token::decrypt` still returns
|
||||
`Vec<u8>` and wipes its buffer when decryption fails; wrap a secret plaintext
|
||||
in `Zeroizing`. `Identity::from_file` reads at most 1025 bytes and refuses a
|
||||
file larger than 1 KiB.
|
||||
`InterfacePostInit::ifac_passphrase` is `Option<Zeroizing<String>>`, so the
|
||||
passphrase is wiped when the options are dropped: read it with
|
||||
`.as_deref().map(String::as_str)` and wrap a new one in `Zeroizing::new`.
|
||||
`RuntimeInterfaceIfacConfig` prints `<redacted>` in place of its passphrase.
|
||||
`InterfaceEntry::ifac_key` is `Option<rns_identity::ifac::IfacKey>`, one
|
||||
allocation that clones share and that is wiped when the last one drops, so
|
||||
interface tables never copy the key. `with_ifac` still takes the key bytes;
|
||||
otherwise set `Some(key.into())` or `IfacKey::derive(network_name,
|
||||
passphrase)`, and read the bytes through `&*key`.
|
||||
rns-crypto re-exports `zeroize` for crates that hold its wiped types without
|
||||
depending on it, and `rns_identity::persistence::read_secret_file` reads a
|
||||
bounded secret file into one wiped buffer. An I2P interface refuses a key file
|
||||
larger than 16 KiB and a SAM reply line longer than 64 KiB, and
|
||||
`I2PServerConfig` prints `<redacted>` in place of a configured key.
|
||||
rns-crypto enables the `zeroize` features of `aes` and `cbc`, so AES key
|
||||
schedules and CBC state are wiped when dropped; dependents that build with
|
||||
`--locked` refresh their lock files.
|
||||
|
||||
The compatibility floor remains unchanged. Its cumulative exact-removal list
|
||||
also retains the already-reviewed [1.3 migration](1.3.md) for discovery ownership
|
||||
and nullable coordinates; it is not reclassified as a new 1.4 change. Additive
|
||||
struct fields can require literal-construction updates even when no old public
|
||||
line disappears. No whole-crate waiver or baseline reset is used.
|
||||
|
||||
Disk-backed Destination handlers can use
|
||||
`LinkManager::register_deferred_request_handler` after installing an exact
|
||||
endpoint dispatch handle. Existing synchronous handlers remain supported. The
|
||||
new callback receives `DestinationRequest` and a one-shot
|
||||
`DeferredRequestResponder`; move both into the actual bounded worker and return
|
||||
promptly. Read `response_byte_limit()` before allocating or retiring stored
|
||||
items. Check `is_cancelled()` before work, and retain the responder until the
|
||||
worker has actually stopped. `respond(RequestOutcome)` returns a typed completion
|
||||
receiver: `Sent` means the packet was queued or the response Resource started,
|
||||
not that the remote application accepted it.
|
||||
|
||||
Admission reserves one of four process-wide slots and a conservative share of
|
||||
256 MiB before invoking the callback. Charge is sixteen times request capacity,
|
||||
eight times the effective response capacity, plus 16 MiB of construction scratch.
|
||||
The token may report a smaller limit than registration requested. This accounts
|
||||
for the bounded handler's planning structures and current response/Resource
|
||||
construction; arbitrary application allocations are outside this contract.
|
||||
Response allocation capacity, including optional follow-up Resource metadata,
|
||||
must fit the token. Requests expire after 120 seconds. Refused admission never
|
||||
invokes the callback. Dropping a manager revokes response authority while a live
|
||||
worker retains its reservation; completed response Resources retain that same
|
||||
reservation until terminal cleanup.
|
||||
|
||||
Deferred handlers require exact endpoint ownership. Queued response packets and
|
||||
Resource advertisement, part, request, hash-map update and cancellation commands
|
||||
carry `SendLinkEndpointExact` authority. The actor rejects an old token even when
|
||||
a replacement uses the same Link ID, interface and role. Existing legacy send
|
||||
commands remain available; they do not acquire this generation-bound guarantee.
|
||||
@@ -0,0 +1,518 @@
|
||||
# Migrating to rsReticulum 1.5
|
||||
|
||||
This guide covers source and behaviour changes from the published 1.4.0
|
||||
release (commit `14241a3`) to 1.5.0. The crates now follow Reticulum 1.6.0.
|
||||
Migrate Reticulum dependents together to `~1.5.0`.
|
||||
|
||||
Project minor releases can break the Rust API. Pin an explicit compatible line
|
||||
or a reviewed Git revision. Upstream line references below are to Reticulum
|
||||
1.6.0 (`RNS/...:line`).
|
||||
|
||||
`api/stability.json` lists every removed snapshot line under
|
||||
`approvedBreakingChanges`, and this guide explains each one. Most additions are
|
||||
new public fields and variants. Exhaustive struct literals and exhaustive
|
||||
`match`es over the types listed in "New fields and variants" no longer compile
|
||||
until you add the new members (or `..Default::default()` or `..T::new(..)`) or
|
||||
a wildcard arm. Types that are now `#[non_exhaustive]` cannot be built with a
|
||||
struct literal outside their crate at all: start from `Default` or a
|
||||
constructor and set the public fields.
|
||||
|
||||
## Stamps: fractional costs and values everywhere
|
||||
|
||||
Reticulum 1.6.0 measures stamp work as a fractional value (`RNS/Stamps.py:104-190`,
|
||||
`stamp_value` returns a float) and reads costs as floats. Every stamp cost,
|
||||
stamp value, and required value in the public API is now `f64`.
|
||||
|
||||
| Old | New |
|
||||
| --- | --- |
|
||||
| `DiscoveryStamper::generate(&self, &[u8; 32], u8)` | `generate(&self, &[u8; 32], f64, &StampControl)` |
|
||||
| `DiscoveryStamper::valid(.., u8)` / `value(..) -> u8` | `valid(.., f64)` / `value(..) -> f64` (also `NullStamper`, `RnsDiscoveryStamper`) |
|
||||
| `discovery::DEFAULT_STAMP_VALUE: u8` | `discovery::constants::DEFAULT_STAMP_VALUE: f64` (`RNS/Discovery.py:77`) |
|
||||
| `discovery::WORKBLOCK_EXPAND_ROUNDS: u32` | `discovery::constants::WORKBLOCK_EXPAND_ROUNDS: usize` |
|
||||
| `AnnounceRequest`, `DiscoveryInterfaceConfig`, `DiscoveredInterface::stamp_value: u8` | `f64` |
|
||||
| `ReceiverConfig::required_value: u8` | `f64` (`RNS/Discovery.py:262-264`) |
|
||||
| `ReticulumConfig::discover_interfaces_required_value: u8` | `f64` |
|
||||
|
||||
`rns_identity::stamps::StampControl { cancel, deadline, threads }` replaces the
|
||||
bare cancellation flag. `StampControl::default()` gives an uncancelled,
|
||||
unbounded, single-threaded search. Use one clone per search and set `cancel`
|
||||
to stop it.
|
||||
|
||||
```rust
|
||||
let control = rns_identity::stamps::StampControl::default();
|
||||
let stamp = stamper.generate(&infohash, 16.0, &control);
|
||||
```
|
||||
|
||||
`rns_identity::stamps` (`stamp_workblock`, `stamp_value`, `stamp_valid`,
|
||||
`generate_stamp`, `generate_stamped_key`) is the shared primitive the transport,
|
||||
link, and LXMF stampers use. The `[stamps]` config section
|
||||
(`RNS/Reticulum.py:505-512`) and `InitOptions::{enable_stamping, enforce_stamps}`
|
||||
control it.
|
||||
|
||||
## Starting the runtime
|
||||
|
||||
- `InitOptions` is `#[non_exhaustive]` and gains `enable_stamping`,
|
||||
`enforce_stamps`, `keep_starting_after_interface_failure`, and
|
||||
`start_interfaces_concurrently`. Start from the default and set fields:
|
||||
|
||||
```rust
|
||||
let mut options = InitOptions::default();
|
||||
options.enable_stamping = true;
|
||||
let runtime = init_with_options(None, None, shutdown, foreground, options).await?;
|
||||
```
|
||||
|
||||
`start_interfaces_concurrently` starts the configured interfaces at the same
|
||||
time, so a slow one does not hold up the rest. It is off by default; upstream
|
||||
starts them one at a time.
|
||||
- `ReticulumConfig` is `#[non_exhaustive]` and gains `filter`, `stamps`,
|
||||
`inbound_queue_lengths`, `enable_interface_management`, `default_gravity`,
|
||||
`autoconnect_interface_gravity`, and the autoconnect keys. Start from
|
||||
`ReticulumConfig::default()` or `try_from_config` and set fields.
|
||||
- `rns_tools::init_tracing` takes `rns_tools::LogLevel` instead of
|
||||
`tracing::Level`. This follows Python's nine numeric levels
|
||||
(`RNS/__init__.py:60-68`), including Notice (3) and Pathing (7), which
|
||||
`tracing` cannot express:
|
||||
|
||||
```rust
|
||||
// old
|
||||
rns_tools::init_tracing(tracing::Level::INFO, true, false, std::io::stderr);
|
||||
// new
|
||||
rns_tools::init_tracing(rns_tools::LogLevel::clamped(3), true, false, std::io::stderr);
|
||||
```
|
||||
|
||||
`LogLevel::filter()` gives the tracing filter. `Utility::loglevel` gives each
|
||||
tool's upstream level rule.
|
||||
- `rns_runtime::jobs::JobScheduler::request_persist` is removed. Persistence
|
||||
now runs on upstream's save cadence.
|
||||
- `rns_runtime::constants::ANNOUNCE_CAP`, `GRACIOUS_PERSIST_INTERVAL`,
|
||||
`MAX_QUEUED_ANNOUNCES`, and `QUEUED_ANNOUNCE_LIFE` are removed. Use the
|
||||
`rns_transport::constants` items of the same names; there the two intervals
|
||||
are `f64` seconds.
|
||||
|
||||
## Interfaces
|
||||
|
||||
| Old | New | Reason |
|
||||
| --- | --- | --- |
|
||||
| `TcpServerConfig::listen_ip: String`, `BackboneServerConfig::listen_ip: String` | `Option<String>`; `None` binds the device or wildcard address | `bindip = c["listen_ip"] if "listen_ip" in c else None` (`RNS/Interfaces/TCPInterface.py:518`) |
|
||||
| `RNodeConfig`, `BleRNodeConfig`, `SubInterfaceConfig`, and the runtime `*InterfaceConfig`/`*RuntimeArgs` `st_alock`/`lt_alock: Option<f32>` | `Option<f64>` | `float(c["airtime_limit_short"])` (`RNS/Interfaces/RNodeInterface.py:159`) |
|
||||
| `RNodeConfigValidationError::NonFinite { value: f32 }` | `value: f64` | same |
|
||||
| `SubInterfaceConfig::tx_power: u8` (and `RNodeSubInterfaceConfig`) | `i8` | `int(subinterface_config["txpower"])` (`RNS/Interfaces/RNodeMultiInterface.py:199`) |
|
||||
| `RNodeMultiConfig::flow_control` | `SubInterfaceConfig::flow_control` (per radio) | `RNS/Interfaces/RNodeMultiInterface.py:205-206` |
|
||||
| `SubInterfaceConfig::mode` | `RNodeMultiConfig::mode` (one mode for the device); sub-interfaces gain `outgoing` | `RNS/Interfaces/RNodeMultiInterface.py:212` |
|
||||
| `RNodeResponse::Ready(bool)` | `RNodeResponse::Ready` | |
|
||||
| `process_rnode_response(cmd, data, id, &mut Option<f32>, &mut Option<f32>)` | `process_rnode_response(cmd, data, id, &mut RNodeSignalStats, Option<u8>)` | RSSI, SNR, and Q are kept together, as the `r_stat_*` attributes are |
|
||||
| `spawn_auto_interface(cfg, id, transport_tx, running)` | `spawn_auto_interface(cfg, id, next_id: Arc<AtomicU64>, transport_tx, spawned_tx, running)` | AutoInterface spawns one child interface per peer (`RNS/Interfaces/AutoInterface.py:134`, `:392`) |
|
||||
| `McastAddrType: FromStr<Err = String>` | `Err = Infallible` | upstream accepts any value |
|
||||
| `DiscoveryInterfaceConfig::backbone(String, ..)`, `DiscoveryInterfaceConfig::name: String` | `Option<String>`; `None` sends nil | `interface.discovery_name` may be unset (`RNS/Discovery.py:173`) |
|
||||
| `DiscoveryInterfaceConfig::modulation`, `DiscoveryInfo::modulation: Option<String>` | `Option<DiscoveryModulation>` | |
|
||||
| `PipeInterfaceConfig::respawn_delay: u64` | `f64` seconds | `c.as_float("respawn_delay")` (`RNS/Interfaces/PipeInterface.py:68`) |
|
||||
| `TunnelIdentity::synthesis(&self, name)` (1.5.1) | removed; a client interface asks transport (`TransportMessage::SynthesizeTunnel`), which signs with the identity from `SetTunnelIdentity` | the synthesis carries transport's signed costs and status (`RNS/Transport.py:3170`) |
|
||||
|
||||
`ble_peer::RATSPEAK_SERVICE_UUID`, `RATSPEAK_RX_UUID`, `RATSPEAK_TX_UUID`, and
|
||||
`RATSPEAK_ID_UUID` now hold the peer mesh's own UUIDs, service
|
||||
`13370001-c7cb-4de2-98de-5d87fa06443d` with RX, TX, and ID at `13370002`,
|
||||
`13370003`, and `13370004` in the first group. A peer that still advertises the
|
||||
earlier placeholder UUIDs is not found.
|
||||
|
||||
These constants are removed. The reconnect waits are now fixed per driver, as
|
||||
upstream's are:
|
||||
|
||||
- `tcp::RECONNECT_WAIT_INITIAL`, `tcp::RECONNECT_WAIT_MAX`
|
||||
- `i2p::RECONNECT_WAIT_MAX`
|
||||
- `backbone::CHILD_BITRATE_GUESS`
|
||||
- `traits::IC_BURST_MIN_SAMPLES`
|
||||
- `rns_transport::constants::IC_BURST_MIN_SAMPLES`
|
||||
|
||||
TCP, Backbone, and server configs gain `bitrate` and `ifac_size`, which feed the
|
||||
hardware MTU (`RNS/Interfaces/Interface.py:255-267`). Build them with `new`.
|
||||
|
||||
## Transport tables and statistics
|
||||
|
||||
| Old | New | Reason |
|
||||
| --- | --- | --- |
|
||||
| `IngressController::{incoming,outgoing}_{announce,pr}_frequency(&self)` | `&mut self`; `outgoing_pr_frequency(&mut self, preemptive: bool)` | the frequency readers drop stale samples (`RNS/Interfaces/Interface.py:366-408`) |
|
||||
| the `announce`, `link_table`, `rate_limit`, `reverse_table`, and `traffic` modules (`AnnounceTable`, `LinkTable`, `ExpiredLink`, `RateTable`, `ReverseTable`, `TrafficCounter`, and their entries) | crate-private; read the tables through `TransportQuery` | the actor owns them |
|
||||
| `RateTable::record`, `get_rate`, `cull`, `RateEntry::rate` | `TransportQuery::GetRateTable` returns `RateTableRpcEntry` rows | `AnnounceRateTable` (`RNS/Storage.py:38`) |
|
||||
| `rate_limit::RATE_PENALTY_BASE`, `RATE_PENALTY_MAX`, `RATE_VIOLATIONS_BEFORE_PENALTY`, `RATE_VIOLATION_THRESHOLD` | removed | upstream has no such penalties |
|
||||
| `PathEntry::touch()` | `PathEntry::used: f64`; transport sets it on use | `path_entry[IDX_PT_USED] = outbound_time` (`RNS/Transport.py:1618`) |
|
||||
| `ifac::MAX_IFAC_WIRE_BYTES`, `IfacSignError::PacketTooLarge` | removed | |
|
||||
| `constants::ANNOUNCE_CACHE_SWEEP_GRACE_SECS`, `constants::LINKS_CHECK_INTERVAL` | removed | |
|
||||
| `TransportActor::packet_metrics`, `packet_metrics_order` | `TransportQuery::GetPacketRssi`, `GetPacketSnr`, `GetPacketQ` | |
|
||||
| `InterfaceStatRpcEntry::ifac_size: usize` | `Option<usize>`; `None`, like `ifac_netname` and `ifac_signature`, for an interface without IFAC | `get_interface_stats()` (`RNS/Reticulum.py`) |
|
||||
| `IngressController::hold_announce(..)` returning `()` (1.5.1) | returns `HoldOutcome` (`Held`, `Replaced`, `Refused`); `is_filtered()` says whether the announce counts as filtered | a dropped or replaced held announce is filtered (`RNS/Interfaces/Interface.py:297-306`) |
|
||||
| `TransportMessage::SynthesizeTunnel { interface_id, raw_packet }` (1.5.1) | `SynthesizeTunnel { interface_id }`; the actor builds the synthesis | it carries signed costs, version, and transport status (`RNS/Transport.py:3170`) |
|
||||
| `TimerTick { timestamp }` | `TimerTick`, with no fields | |
|
||||
| `discovery::storage::classify(u64)`, `DiscoveredInterface::{discovered,last_heard}: u64` | `f64` timestamps | `time.time()` (`RNS/Discovery.py:604`) |
|
||||
| `discovery::build_local_manifest` | `build_manifest` | |
|
||||
|
||||
**Discovery constants.** `discovery::key` and the constants re-exported at the
|
||||
`discovery` root (`APP_NAME`, `STAMP_SIZE`, `FLAG_SIGNED`, the aspect and
|
||||
interface-type lists, the `THRESHOLD_*_SECS` values, and the rest) are removed.
|
||||
Import them from `discovery::constants` and `discovery::constants::key`. The
|
||||
blackhole timings are `Duration`s: `blackhole_subscriber::{INITIAL_WAIT,
|
||||
JOB_INTERVAL, SOURCE_TIMEOUT, UPDATE_INTERVAL}` become
|
||||
`discovery::constants::BLACKHOLE_INITIAL_WAIT` and so on, and the
|
||||
`BLACKHOLE_*_SECS` integers are removed.
|
||||
|
||||
**Messages.** `TransportMessage`, `TransportQuery`, and `TransportQueryResponse`
|
||||
are `#[non_exhaustive]`; code that matches on them needs a wildcard arm.
|
||||
`TransportMessage` gains `SetFilterPolicy`, `SetLocalDestinationKey`, and
|
||||
`SetStampPolicy`. `TransportQuery` gains `GetActiveLinkCount`,
|
||||
`GetTrafficTotals`, `RecallLinkCost`, `RecallStampValue`, `SetRequiredOnly`,
|
||||
`WantsDestinationType`, `UnwantsDestinationType`, and
|
||||
`UnwantsAllDestinationTypes`. `TransportQueryResponse` gains `OptBoolResult` and
|
||||
`TrafficTotals`. Three existing variants gain fields a constructor must supply:
|
||||
`RegisterAnnounceSubscription::paused`, `SetStoragePaths::{role, done}` (see
|
||||
"Stored destinations, ratchets, and announces"), and
|
||||
`TransportQuery::ApplyBlackholeManifest::publisher`.
|
||||
|
||||
The RPC rows (`AnnounceRpcEntry`, `BlackholeRpcEntry`, `InterfaceStatRpcEntry`,
|
||||
`PathTableRpcEntry`, `RateTableRpcEntry`, `RecalledDestinationRpcEntry`,
|
||||
`TrafficTotalsRpcEntry`) and `InterfaceEntry` are `#[non_exhaustive]`.
|
||||
`PathTableRpcEntry` and `RecalledDestinationRpcEntry` implement `Default`. Build
|
||||
an `InterfaceEntry` with `InterfaceEntry::new(name, mode, direction, bitrate,
|
||||
mtu, tx)` and its `with_*` methods.
|
||||
|
||||
**Actor state.** `TransportActor`'s fields are private. Settings fixed at
|
||||
construction move to `TransportActorOptions` (`#[non_exhaustive]`, `Default`):
|
||||
|
||||
```rust
|
||||
let mut options = TransportActorOptions::default();
|
||||
options.local_hops_delta = 1;
|
||||
let (actor, tx) =
|
||||
TransportActor::new_with_options(channel_cap, hashlist_cap, InboundQueueLengths::default(), options);
|
||||
```
|
||||
|
||||
| Old field | New |
|
||||
| --- | --- |
|
||||
| `is_foreground`, `static_transport_identity`, `local_hops_delta`, `ephemeral_identity_hash` | `TransportActorOptions` |
|
||||
| `interfaces` | `TransportMessage::RegisterInterface` / `DeregisterInterface`; read with `TransportQuery::GetInterfaceStats` |
|
||||
| `local_destinations` | `TransportMessage::RegisterDestination` / `DeregisterDestination` |
|
||||
| `transport_identity_hash`, `internal_identity_hash` | `TransportMessage::SetTransportIdentity` |
|
||||
| `is_transport_enabled` | `TransportMessage::SetTransportEnabled` |
|
||||
| `storage_dir` | `initialize_storage` or `initialize_storage_as` before `run`, or `TransportMessage::SetStoragePaths` |
|
||||
| `blackhole_sources`, `blackhole_table` | `TransportMessage::SetBlackholeSources`; `TransportQuery::GetBlackholedIdentities`, `BlackholeIdentity`, `UnblackholeIdentity` |
|
||||
| `path_table`, `path_states` | `TransportQuery::GetPathTable`, `HasPath`, `HopsTo`, `GetPathState`, `SetPathState`, `DropPath` |
|
||||
| `rate_table` | `TransportQuery::GetRateTable` |
|
||||
| `recent_announces` | `TransportQuery::GetRecentAnnounces`, `RecallDestination` |
|
||||
| `traffic` | `TransportQuery::GetTrafficTotals`, `GetInterfaceStats` |
|
||||
| `link_table` | `TransportQuery::GetLinkCount`, `GetActiveLinkCount` |
|
||||
| `is_shared_instance`, `shared_instance_client_mode` | `TransportMessage::SharedConnectionLost` / `SharedConnectionRestored`; `StorageRole::SharedInstanceClient` |
|
||||
| the receipt maps, save flags, pending queues, `state_dirty`, and `last_state_save` | internal; no replacement |
|
||||
|
||||
`ReceiptUpdate::Delivered { rtt }` gains `proof_hash: Option<[u8; 32]>` and
|
||||
`metrics: PacketMetrics`, the proof packet's hash and reception statistics;
|
||||
match it with `Delivered { rtt, .. }`. `rns_runtime::probe::ProbeOutcome` gains
|
||||
the same two fields, which `rnprobe` prints as upstream reads them from the
|
||||
receipt's proof packet (`RNS/Utilities/rnprobe.py:166`).
|
||||
|
||||
## Stored destinations, ratchets, and announces
|
||||
|
||||
The transport keeps known destinations and received ratchets in upstream's
|
||||
SQLite store, `storage/known_destinations.db` (`KnownDestinationsStore`,
|
||||
`RNS/Storage.py`), and cached announces in `storage/cache/announces.db`
|
||||
(`AnnounceCache`). `rns_transport::store` holds the stores
|
||||
(`SqliteKnownDestinations`, `SqliteAnnounceCache`, `MemoryStore`, and the
|
||||
`KnownDestinationStore` and `AnnounceCacheStore` traits), and `store::legacy`
|
||||
the one-way importers for the earlier files.
|
||||
|
||||
- `rns_identity::ratchet::ReceivedRatchetStore` is removed. The transport
|
||||
remembers the ratchet of each announce it accepts; read it back through the
|
||||
runtime or a `TransportQuery::RecallDestination`:
|
||||
|
||||
```rust
|
||||
// old
|
||||
let ratchet = store.get(&destination_hash);
|
||||
// new
|
||||
let ratchet = runtime.recall(destination_hash).await?.and_then(|d| d.ratchet);
|
||||
```
|
||||
|
||||
- `persistence::load_announce_cache`, `save_announce_cache`,
|
||||
`sweep_announce_cache`, `load_announce_cache_legacy_v5`,
|
||||
`migrate_legacy_announce_entries`, and `LegacyPersistedAnnounceEntryV5` are
|
||||
removed. The actor writes the announce cache itself;
|
||||
`store::legacy::import_rust_announce_cache` and
|
||||
`import_python_announce_cache` read the earlier files.
|
||||
- `TransportActor::initialize_storage_as(dir, StorageRole)` and
|
||||
`TransportMessage::SetStoragePaths { storage_dir, role, done }` say who owns
|
||||
the directory. `StorageRole::Owner` (the default, and what
|
||||
`initialize_storage` uses) imports the earlier files and writes.
|
||||
`StorageRole::SharedInstanceClient` reads the owner's database once,
|
||||
read-only, and writes nothing. `done` is answered when loading has finished.
|
||||
- `rns-transport` has a default `sqlite-store` feature. It builds SQLite from
|
||||
source through `rusqlite`'s `bundled` feature, so the build needs a C
|
||||
compiler. Every crate here that depends on `rns-transport` keeps its default
|
||||
features; only a direct dependent of `rns-transport` alone can set
|
||||
`default-features = false`. Without the feature, the `Sqlite*` stores are
|
||||
absent and the transport keeps known destinations, ratchets, and cached
|
||||
announces in memory only, reading and writing none of these files.
|
||||
|
||||
## Links, requests, and channels
|
||||
|
||||
**Request replies.** Request handlers now produce upstream's reply forms
|
||||
(`RNS/Link.py:922-935`):
|
||||
|
||||
```rust
|
||||
// old
|
||||
RequestOutcome::Reply(packed_value)
|
||||
RequestOutcome::ReplyWithResource { ack, data, metadata, auto_compress }
|
||||
// new
|
||||
RequestOutcome::ReplyValue(packed_value) // one complete MessagePack value
|
||||
RequestOutcome::ReplyBytes(raw) // Python receives `bytes`
|
||||
RequestOutcome::ReplyFile { source: Box::new(file), metadata: None } // [file, metadata]
|
||||
RequestOutcome::ReplyWithResource { ack, source: Box::new(std::io::Cursor::new(data)), metadata, auto_compress }
|
||||
```
|
||||
|
||||
`source` is any `Read + Seek + Send` (`ResourceSource`).
|
||||
|
||||
**Compression policy.** `register_request_handler`,
|
||||
`register_deferred_request_handler`,
|
||||
`DestinationHandle::register_request_handler`, and
|
||||
`LinkManagerCommand::RegisterRequestHandler::auto_compress` take
|
||||
`impl Into<AutoCompress>` instead of `bool`. Existing `true`/`false` arguments
|
||||
still compile. `AutoCompress::Limit(bytes)` is Python's integer form
|
||||
(`RNS/Resource.py:372-381`).
|
||||
|
||||
**Deferred handlers on a destination.**
|
||||
`DestinationHandle::register_deferred_request_handler` registers a handler
|
||||
that answers later through its `DeferredRequestResponder`, so long work stays
|
||||
off the link-manager task. `register_deferred_request_handler_with` (also on
|
||||
`LinkManager`) takes a `DeferredAdmission` in place of the reply byte limit:
|
||||
|
||||
```rust
|
||||
let admission = DeferredAdmission::new(64 * 1024) // largest in-memory reply
|
||||
.request_copies(3) // copies of the request held
|
||||
.busy_reply(b"busy".to_vec()) // sent when the job limit is reached
|
||||
.too_large_reply(b"too large".to_vec()); // sent when the job cannot fit
|
||||
```
|
||||
|
||||
Without the two replies a refused job is dropped, as before. Jobs are admitted
|
||||
against a process-wide budget; upstream serves every request synchronously
|
||||
and has none (`RNS/Link.py:891-940`). `DeferredAdmission` is in the prelude.
|
||||
`LinkManagerCommand` gains `RegisterDeferredRequestHandler`, and
|
||||
`DestinationRuntimeOptions` gains `endpoint_dispatch`; build the options with
|
||||
`..Default::default()`.
|
||||
|
||||
**Close reasons.** `rns_link::link::CloseReason` is `#[non_exhaustive]` and
|
||||
gains `StampFailure` (`RNS/Link.py:116-119`). Add a wildcard arm.
|
||||
|
||||
**Link stamps.** `Link::new_stamped_initiator`, `rns_link::stamp`, and
|
||||
`LinkClientError`/`LinkSessionError::StampFailure(LinkStampError)` are new.
|
||||
Code that matches these errors exhaustively needs the new arms.
|
||||
|
||||
**Buffers.** The channel buffer types are renamed and follow `RNS/Buffer.py:298-349`:
|
||||
|
||||
| Old | New |
|
||||
| --- | --- |
|
||||
| `LinkSessionBuffer` | `BidirectionalBuffer` |
|
||||
| `LinkSessionBufferReader` / `LinkSessionBufferWriter` | `BufferReader` / `BufferWriter` |
|
||||
| `LinkSessionBufferError` | `BufferError` (gains `Link`, `Session`, `ManagerUnavailable`) |
|
||||
| `LinkSessionBuffer::reader()/writer()` | `into_split()` |
|
||||
| `LinkSessionBufferWriter::with_close_timeout`, `DEFAULT_CLOSE_TIMEOUT`, `DEFAULT_READER_CAPACITY` | removed; the writer's close follows the channel window |
|
||||
|
||||
`LinkSessionChannelHandle::create_reader`, `create_reader_with_capacity`,
|
||||
`create_writer`, and `create_bidirectional_buffer` return the new types.
|
||||
`DestinationHandle` gains the same constructors.
|
||||
|
||||
## Resources
|
||||
|
||||
- `MultiSegmentOutbound::with_options` takes a trailing `Option<usize>`, the
|
||||
link SDU to slice parts by. `None` keeps the base MTU. Parts follow the
|
||||
link's MTU (`RNS/Link.py:392-397`).
|
||||
- `WindowState::grow(&mut self, usize)` is now `grow(&mut self)`; the window
|
||||
grows by one per completed round (`RNS/Resource.py:917`).
|
||||
- `ResourceError::DecompressedTooLarge`, `TransferAction::QueryProofCache`, and
|
||||
`ResourceFlags::app_flag` are new. `InboundTransfer`, `OutboundTransfer`, and
|
||||
`MultiSegmentInbound` gain public fields.
|
||||
- An inbound Resource can be received as a file of any size, not bound by the
|
||||
in-memory limit (`inbound_reassembly_limit`, 128 MiB - 1 by default). Each
|
||||
verified segment is appended to the file before its proof is sent, as
|
||||
`Resource.assemble` writes it (`RNS/Resource.py`), and a transfer that
|
||||
fails, is cancelled, or cannot be written leaves no file behind. Additions,
|
||||
none of which changes a caller that takes bytes:
|
||||
- `LinkManager::set_resource_file_channel(dir, min_size, tx)` and
|
||||
`DestinationHandle::receive_resource_files(dir, min_size, capacity)`
|
||||
deliver `ResourceFileCompletion { path, size, .. }` for ordinary Resources
|
||||
that advertise `min_size` bytes or more. Without them a Resource above the
|
||||
in-memory limit is refused, as before.
|
||||
- `LinkSessionResourceOffer::accept_to_file(Option<PathBuf>)` assembles the
|
||||
offer into a file in that directory, or for `None` in the session's
|
||||
`LinkSessionConfig::resource_dir` (the system temporary directory when
|
||||
unset), and returns its path in `LinkSessionReceivedResource::file`.
|
||||
- A session now offers a Resource above its limit to the application
|
||||
instead of refusing it unseen. `accept` on such an offer rejects it with
|
||||
`LinkSessionResourceError::TooLarge`.
|
||||
|
||||
The receiver owns a delivered file and moves or removes it. Use the
|
||||
runtime's `storage/resources` directory (`StoragePaths::resource_dir`),
|
||||
where upstream keeps them; the cache job removes a spool left there by a
|
||||
crash after one day.
|
||||
|
||||
## Crypto
|
||||
|
||||
- `X25519PrivateKey::exchange` returns `Result<[u8; 32], X25519Error>` and
|
||||
rejects a low-order peer key (all-zero secret). This matches Python's default
|
||||
backend, which delegates to `cryptography` (`RNS/Cryptography/__init__.py:46-48`,
|
||||
`RNS/Cryptography/Proxies.py:60-61`):
|
||||
|
||||
```rust
|
||||
let shared = private.exchange(&peer)?; // X25519Error::LowOrderPoint
|
||||
```
|
||||
|
||||
- `HkdfError::OutputTooLong(usize)` is removed. The only length error is
|
||||
`InvalidLength` for zero, as `hkdf` raises only for `length < 1`
|
||||
(`RNS/Cryptography/HKDF.py:47`).
|
||||
- `IdentityError::EncryptionFailed` and `DestinationError::InvalidLinkCost` are
|
||||
new variants.
|
||||
|
||||
## Tools (rncp, rnsh, rns-tools)
|
||||
|
||||
- `RncpSendRequest::data: Vec<u8>` becomes `source: Box<dyn ResourceSource>`.
|
||||
The file is streamed, as `RNS.Resource(open(file_path, "rb"), ..)` does
|
||||
(`RNS/Utilities/rncp.py:721`).
|
||||
- `RncpSendRequest`/`RncpFetchRequest`: `overall_timeout` and `path_wait` are
|
||||
replaced by `path_timeout` (`timeout`, `RNS/Utilities/rncp.py:405`, `:662`)
|
||||
and `shutdown: Option<ShutdownSignal>`.
|
||||
- `progress_tx` carries `RncpProgress { progress, phy_bytes }` instead of `f32`,
|
||||
for `--phy-rates` (`RNS/Utilities/rncp.py:331`).
|
||||
- `RncpError` gains `Interrupted`, `NotFound`, `RemoteError`, `RequestFailed`,
|
||||
and `StampFailure`.
|
||||
- `spawn_rncp_listener_with_resource_dir` and
|
||||
`rncp_fetch_file_with_resource_dir` name the directory a received or fetched
|
||||
file is assembled in before it is moved to the save directory, as rncp moves
|
||||
`resource.data` (`RNS/Utilities/rncp.py`). `rncp-rs` passes
|
||||
`storage/resources`; the functions without the argument use the system
|
||||
temporary directory. Neither holds the file in memory.
|
||||
- `rnsh::RnshError` is `#[non_exhaustive]`. `Denied` carries the remote
|
||||
message, `Denied(String)`, and the enum gains `ClientException`, `LinkClosed`,
|
||||
`ProtocolError`, `StampFailure`, and `Terminated`
|
||||
(`RNS/Utilities/rnsh/initiator.py:135-149`).
|
||||
- `rns_protocol::rnsh::STREAM_DATA_OVERHEAD` is removed.
|
||||
- The `rns-git` library (tier `tool-internal`, `publish = false`) is new. It
|
||||
supports `rngit-rs`, `git-remote-rns`, and `rngcs-rs` and is not an
|
||||
integration API.
|
||||
- `rns-tools` has a default `rnodeconf-firmware` feature, which adds `ureq`
|
||||
(with TLS) and `zip` for `rnodeconf-rs` firmware download and extraction. A
|
||||
dependent of the `rns-tools` library that does not flash firmware sets
|
||||
`default-features = false`, as `rns-git` does. An `rnodeconf-rs` built
|
||||
without it refuses firmware download and update with one line.
|
||||
|
||||
## RPC
|
||||
|
||||
`rpc::RpcRequest` gains variants for 1.6.0 shared-instance requests:
|
||||
|
||||
- `GetActiveLinkCount`, `GetLinkDistribution`, `GetLowestInterfaceBitrate`,
|
||||
`GetMediumPathTimeout`, and `GetProfilingResults`;
|
||||
- `ManageInterface`;
|
||||
- `WantsDestinationType`, `UnwantsDestinationType`, and
|
||||
`UnwantsAllDestinationTypes`.
|
||||
|
||||
`rpc::InterfaceStatEntry` is removed. `RpcResponse::InterfaceStats` carries
|
||||
`rns_transport::messages::InterfaceStatRpcEntry`, the type
|
||||
`TransportQueryResponse::InterfaceStats` uses. It has every field the old type
|
||||
had in 1.4.0, plus the 1.6.0 stats fields, and is `#[non_exhaustive]`.
|
||||
`rpc::PathTableEntry` gains `value`, `used`, and `lr_cost`.
|
||||
|
||||
## New fields and variants
|
||||
|
||||
These types are now `#[non_exhaustive]`. Build them from `Default` or a
|
||||
constructor and match them with a wildcard arm:
|
||||
|
||||
- **rns-transport:** `TransportMessage`, `TransportQuery`,
|
||||
`TransportQueryResponse`, `InterfaceEntry`, and the `*RpcEntry` rows.
|
||||
- **rns-runtime:** `InitOptions`, `ReticulumConfig`, `LinkManagerCommand`,
|
||||
`RnshError`.
|
||||
- **rns-link:** `CloseReason`.
|
||||
- **rns-identity:** `DestinationError`, from 1.5.1, which adds `AnnounceTooLarge`.
|
||||
|
||||
Exhaustive literals and matches over these types need updating:
|
||||
|
||||
- **rns-transport:**
|
||||
- `InterfaceInspectionSnapshot`, `RecentAnnounce`, `TunnelPath`,
|
||||
`PathEntry`, `ReceiptUpdate`;
|
||||
- `DiscoveryInterfaceConfig` and `DiscoveryInfo` (`dst_cost`, `pr_cost`,
|
||||
`operator_lxmf_address`), `discovery::Reason` (`HopLimit`), `SkipReason`;
|
||||
- the persisted entries.
|
||||
- **rns-runtime:**
|
||||
- `RecalledDestination`, `LinkConnectOptions`, `DestinationRuntimeOptions`,
|
||||
`InterfacePostInit`, and the runtime interface configs;
|
||||
- `LinkSessionConfig`, `LinkSessionResponse`, `LinkSessionReceivedResource`,
|
||||
`LinkSessionResourceReceipt`, `ResourceCompletion`, `RnshClientConfig`,
|
||||
`DestinationRequest`, `ProbeOutcome`, `rpc::PathTableEntry`;
|
||||
- `RequestOutcome`, `ChannelSendError`, `LinkSessionError`,
|
||||
`LinkSessionResourceError`, `LinkClientError`, `RncpError`, `RpcRequest`,
|
||||
`RpcResponse`.
|
||||
- **rns-link:** `Link`, `HandshakeError`, `LinkKeyError`.
|
||||
- **rns-protocol:** `ResourceError`, `ResourceFlags`, `TransferAction`,
|
||||
`InboundTransfer`, `OutboundTransfer`, `MultiSegmentInbound`.
|
||||
- **rns-interface:** TCP, Backbone, Local, RNode, and BLE configs;
|
||||
`TcpInterfaceState`.
|
||||
- **rns-identity and rns-crypto:** `IdentityError`, `HkdfError`.
|
||||
|
||||
## Behaviour and configuration an operator sees
|
||||
|
||||
- **Strict config values for the new keys.** 1.4.0 already stopped start-up
|
||||
on an unparsable boolean or integer in `[reticulum]` and `[logging]`. The
|
||||
same rule now covers the new `[stamps]` section (`RNS/Reticulum.py:505-512`),
|
||||
the new `[filter]` section, and the keys added since 1.4.0:
|
||||
`egress_control`, `default_gravity`, `ic_max_held_announces`,
|
||||
`enable_interface_management`, `autoconnect_interface_gravity`,
|
||||
`required_discovery_value`, and `discover_interfaces_required_value` (now a
|
||||
float). Each fails with `invalid value for [section] key`, because
|
||||
ConfigObj's `as_bool`/`as_int` raise (`RNS/Reticulum.py:508`, `:625`).
|
||||
- **Interface start failures stop start-up.** An interface that fails to build
|
||||
or start (an occupied port, say) fails `init` and shuts down what started, as
|
||||
Python panics (`RNS/Reticulum.py:1306-1311`). Embedders that want the old
|
||||
behaviour set `InitOptions::keep_starting_after_interface_failure = true`
|
||||
and read `ReticulumHandle::startup_interface_failures()`.
|
||||
`panic_on_interface_error` still governs runtime driver errors.
|
||||
- **Server interfaces accept after registration.** TCP, Backbone, Local, and
|
||||
I2P servers accept connections only once the interface is registered with
|
||||
transport, so every accepted connection copies the interface's final
|
||||
settings. An embedder that builds a server interface and never registers it
|
||||
no longer accepts connections; there is no timeout.
|
||||
- **A plain `ifac_size` is bits.** Without `ifac_size_unit`, `ifac_size` is
|
||||
read as Python reads it, and a value from 1 to 64 logs a warning where 1.4.0
|
||||
refused it. See [Explicit IFAC units](capacity-and-receipts.md#explicit-ifac-units).
|
||||
- **Per-interface frequency keys are taken as written.** A negative
|
||||
`ic_burst_freq`, `ec_pr_freq`, or similar key on an interface is no longer
|
||||
refused at load. As in upstream, it puts the interface into permanent
|
||||
limiting (`RNS/Reticulum.py:1001-1010`, `RNS/Interfaces/Interface.py:206`).
|
||||
- **Announce cap timing.** On an interface with an announce cap, a queued
|
||||
announce leaves when the wait after the one before it ends, not on the next
|
||||
250 ms job pass, and each wait counts from that send
|
||||
(`RNS/Interfaces/Interface.py`, `process_announce_queue`).
|
||||
- **Stored files.**
|
||||
- Destination announce stamps persist as `<storage>/stamps/<hash>.dstamp`
|
||||
(`RNS/Stamps.py:869-875`) and are reused across restarts.
|
||||
- Known destinations and received ratchets move to
|
||||
`storage/known_destinations.db`, and cached announces to
|
||||
`storage/cache/announces.db`. On the first start as the directory's owner,
|
||||
the earlier files are imported once: `known_destinations` and
|
||||
`announce_cache.msgpack` are renamed with an `.imported` suffix, and the
|
||||
files under `storage/ratchets` and `storage/cache/announces` are removed
|
||||
as they are imported. A release before this one started on the same
|
||||
directory afterwards finds no known destinations.
|
||||
- A database that cannot be opened does not stop the node; it keeps that
|
||||
session's entries in memory and logs the files to remove.
|
||||
- The path table is written on upstream's save cadence.
|
||||
- **Log levels.** Every tool and daemon uses Python's numeric levels.
|
||||
Without a `loglevel` key, `rnsd` now runs at Notice (3), not Info (4)
|
||||
(`RNS/__init__.py:63`, `:76`). At Notice, only notice-tagged info events
|
||||
appear, so a default `rnsd` log is quieter than 1.4.0's. 1.4.0 mapped levels
|
||||
3 and 4 both to `INFO`. Set `loglevel = 4` for the old volume. `rnsd`
|
||||
ignores `-v`/`-q` in service mode, as it did before.
|
||||
- **Discovery auto-connect.** Without `autoconnect_unverified_implementations`,
|
||||
a discovered Backbone is auto-connected when it advertises `RNS` 1.5.7 or
|
||||
later (1.4.0 took 1.5.2; `RNS/Discovery.py:485-486`) or `rsRNS` 1.5.0 or
|
||||
later (1.4.0 required the opt-in for every `rsRNS` node). Any other
|
||||
implementation still needs the opt-in. Upstream trusts only `RNS`, so a
|
||||
Python node needs the opt-in to auto-connect to an `rsRNS` hub.
|
||||
- **Link MTU.** Links signal and adopt the next hop's hardware MTU when
|
||||
`link_mtu_discovery` is on. It is on by default (`RNS/Reticulum.py:105`,
|
||||
`RNS/Link.py:392-397`). Resources on such links use larger parts, and a
|
||||
transit node clamps the signalled MTU. Set `link_mtu_discovery = No` to keep
|
||||
the 500-byte link MTU.
|
||||
- **Stamps.** With `[stamps]` keys or the `InitOptions` switches,
|
||||
destinations stamp announces, path requests, and link requests. Enforcement
|
||||
drops unstamped traffic, as upstream does.
|
||||
@@ -0,0 +1,127 @@
|
||||
# Capacity, IFAC configuration, and application packet receipts
|
||||
|
||||
These changes are part of the 1.4.0 line, published as v1.4.0 and used by
|
||||
Ratspeak. They are not in the 1.3.0 tools. The migration command below
|
||||
requires a 1.4 build.
|
||||
|
||||
## Interface ownership and packet capacity
|
||||
|
||||
`InterfaceHandle` and `InterfaceEntry` carry an `InterfaceOwner` and an
|
||||
`InterfacePacketCapacity`. The historical `mtu` field remains available for
|
||||
statistics. Admission uses the separate clear-packet and IFAC-bearing wire
|
||||
budgets, and `link_mtu_upgrade` explicitly controls upgrade permission.
|
||||
|
||||
Custom drivers must create `InterfaceTransportSender` before starting any task
|
||||
or callback that can publish input or cleanup events. Copy its `owner()` into
|
||||
the handle, and retain clones of that sender across carrier reconnects. Each
|
||||
accepted child and replacement registration needs a fresh sender and owner.
|
||||
Send inbound packets and driver-originated deregistration through this sender;
|
||||
raw unowned events are refused. Do not wrap messages twice. Coordinated IFAC or
|
||||
capacity changes use a new owner revision and rebind producers; ordinary
|
||||
bitrate/online changes do not establish a new capacity promise.
|
||||
|
||||
Async driver sends wait until the actor accepts that owner registration. This
|
||||
keeps the first packet of a newly accepted connection from racing registration;
|
||||
retiring the owner releases pending sends with an error. Custom actor harnesses
|
||||
must explicitly mark the owner registered when they accept its registration.
|
||||
|
||||
The conservative custom-driver default is `InterfacePacketCapacity::base(mtu)`.
|
||||
Explicitly declare additional IFAC headroom or upgrade support only when the
|
||||
whole-packet driver guarantee supports it. Framing and BLE fragmentation are
|
||||
outside these budgets. TCP fixed MTUs must fit the actual wire budget after IFAC.
|
||||
Active IFAC also limits the complete wire packet to HKDF-SHA256's 8160-byte
|
||||
expansion limit; subtract the configured tag size for its clear-packet ceiling.
|
||||
|
||||
General Links require at least 500 clear packet bytes. An interface with less
|
||||
capacity can still carry fitting non-Link traffic, but reports
|
||||
`LinkCapacityUnavailable` for general Links. RNode's 508-byte wire budget carries
|
||||
500 clear bytes with IFAC tags up to eight bytes. Larger tags are never silently
|
||||
weakened. Current local endpoints remain capped at 500; safe transit can preserve
|
||||
larger peer offers. Legacy or zero Link signalling means 500; nonzero values below
|
||||
500, malformed shapes, disabled endpoint modes, and proofs above the original
|
||||
offer are rejected before endpoint state changes.
|
||||
|
||||
Initiators send `SendLinkRequest` with a per-attempt oneshot result, or call
|
||||
`link_messages::dispatch_link_request`. The result preserves typed capacity
|
||||
errors before waiting for a proof. Keep one establishment deadline around both
|
||||
admission and proof waiting. Drop the result receiver when cancelling: an actor
|
||||
that has not dispatched that attempt then emits no request. This acknowledgement
|
||||
means local driver admission, not peer receipt. It does not replace signature
|
||||
verification or the exact interface owner retained from the request/proof path.
|
||||
|
||||
## Explicit IFAC units
|
||||
|
||||
Use `ifac_size_unit = bits` with `ifac_size` to state the unit explicitly.
|
||||
Valid bit values are multiples of eight from 8 to 512. Without the unit key,
|
||||
values from 1 to 64 are rejected as ambiguous; valid values from 72 to 512
|
||||
are accepted as bits. The byte escape hatch is `ifac_size_bytes`, from 1 to 64;
|
||||
it cannot coexist with either bits field. Migrate ambiguous old values using
|
||||
their known source convention; the parser does not infer that convention.
|
||||
Omitting all size keys retains the interface class default. Explicit malformed
|
||||
sizes remain errors even when credentials are absent. Disabled interfaces may
|
||||
retain old settings, but must be migrated before enabling them.
|
||||
|
||||
From 1.5 the runtime reads a plain `ifac_size` as bits, as Python does: a value
|
||||
of 8 or more is divided by 8 and a smaller one keeps the class default. A value
|
||||
from 1 to 64 logs a warning instead of failing; `rnsd-rs config ifac-units`
|
||||
still converts it. `ifac_size_unit = bits` keeps the strict rules above, and
|
||||
`ifac_size_bytes` is still read, with a warning.
|
||||
|
||||
`InterfacePostInit::try_from_section` replaces the infallible constructor and
|
||||
reads sizes as the runtime does. The shared `config::ifac::parse_ifac_size`
|
||||
decoder keeps the strict 1.4 rules for all three keys.
|
||||
`validate_config_capacity` checks explicit driver promises before spawn.
|
||||
Malformed file syntax still fails the file; semantic errors isolate the affected
|
||||
enabled interface.
|
||||
|
||||
Preview an explicitly selected migration without starting the network:
|
||||
|
||||
```sh
|
||||
rnsd-rs --config /path/to/config-directory config ifac-units --source-units bytes --interface Radio
|
||||
```
|
||||
|
||||
Use `--source-units bits` when that is the known source convention. Add `--write`
|
||||
to publish the reviewed plan. Publication checks that the source is unchanged,
|
||||
takes the shared OS-backed config lock, and retains a unique private backup.
|
||||
An older binary requires restoring its original configuration before rollback.
|
||||
|
||||
## Ordinary Link packet proofs
|
||||
|
||||
Ordinary `DATA` with context `None` follows explicit `ProofStrategy` policy.
|
||||
`ProveNone` delivers without a proof. `ProveAll` preserves automatic proofs and
|
||||
delivers independently of proof queue admission. `ProveApp` requires both an
|
||||
exact endpoint dispatch handle and the bounded typed inbound channel; it cannot
|
||||
use the legacy tuple channel. Configuration setters return a result.
|
||||
|
||||
For application-controlled admission, receive `InboundLinkPacket`, retain its
|
||||
`Bytes` and non-cloneable `LinkPacketReceipt` through validation and persistence,
|
||||
then consume the receipt with `accept()`. Awaiting its result distinguishes local
|
||||
driver admission (`Sent`) from expiration, closed ownership, dropping, or failure.
|
||||
`Sent` does not mean physical radio transmission or remote delivery. Dropping the
|
||||
receipt produces no proof. `reject_and_close(InvalidPropagationStamp)` orders the
|
||||
protocol rejection before teardown when it can be admitted. Use
|
||||
`close_without_proof()` for a storage/quota failure that requires teardown without
|
||||
claiming an invalid propagation stamp; it retains the same exact-owner checks.
|
||||
|
||||
Authority is tied to the exact Link generation. Expired, closed, or replaced
|
||||
owners cannot send a late proof. Payload clones retain admission credits until
|
||||
they are actually dropped, even if the receipt expires. Limits are 64 packets
|
||||
and 2 MiB per Link, and 256 packets and 8 MiB process-wide for this ordinary
|
||||
application-controlled ingress. Resource, Channel, RPC, Direct, and voice
|
||||
protocol owners retain their own admission rules.
|
||||
|
||||
## Durable storage and local timing
|
||||
|
||||
`rns_identity::persistence::durable_write` returns a privately constructed receipt
|
||||
only after exact verification and the native platform barriers succeed. It is
|
||||
separate from the existing cache writer. Errors distinguish pre-publication
|
||||
failure from `CommitUncertain`; keep recovery material and withhold higher-level
|
||||
acceptance on uncertainty. `durable_reconcile` and bounded streaming
|
||||
`durable_reconcile_hash` renew barriers as well as verifying bytes. A receipt
|
||||
attests those calls, not hardware infallibility or the provenance of a message.
|
||||
Directory migration still requires an application journal and native recovery.
|
||||
|
||||
Use `Link::try_extend_establishment_timeout` for checked timeout extension.
|
||||
Invalid floating-point times and unrepresentable deadlines are rejected before
|
||||
transport side effects. Channel RTTs have a finite local ceiling and its sending
|
||||
window remains bounded even when public tuning fields contain extreme values.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,94 @@
|
||||
pub mod rns_crypto
|
||||
pub use rns_crypto::zeroize
|
||||
pub mod rns_crypto::aes_cbc
|
||||
pub enum rns_crypto::aes_cbc::AesCbcError
|
||||
pub rns_crypto::aes_cbc::AesCbcError::DecryptionFailed
|
||||
pub rns_crypto::aes_cbc::AesCbcError::EncryptionFailed
|
||||
pub rns_crypto::aes_cbc::AesCbcError::InvalidIvLength(usize)
|
||||
pub rns_crypto::aes_cbc::AesCbcError::InvalidKeyLength(usize)
|
||||
pub rns_crypto::aes_cbc::AesCbcError::NotBlockAligned
|
||||
pub fn rns_crypto::aes_cbc::decrypt(&[u8], &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::aes_cbc::AesCbcError>
|
||||
pub fn rns_crypto::aes_cbc::encrypt(&[u8], &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::aes_cbc::AesCbcError>
|
||||
pub mod rns_crypto::ed25519
|
||||
pub enum rns_crypto::ed25519::Ed25519Error
|
||||
pub rns_crypto::ed25519::Ed25519Error::InvalidPublicKey
|
||||
pub rns_crypto::ed25519::Ed25519Error::InvalidSignature
|
||||
pub rns_crypto::ed25519::Ed25519Error::VerificationFailed
|
||||
pub struct rns_crypto::ed25519::Ed25519PrivateKey
|
||||
impl rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[u8; 32]) -> Self
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::generate() -> Self
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::public_key(&self) -> rns_crypto::ed25519::Ed25519PublicKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::sign(&self, &[u8]) -> [u8; 64]
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::to_bytes(&self) -> [u8; 32]
|
||||
impl core::ops::drop::Drop for rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PrivateKey::zeroize(&mut self)
|
||||
pub struct rns_crypto::ed25519::Ed25519PublicKey
|
||||
impl rns_crypto::ed25519::Ed25519PublicKey
|
||||
pub fn rns_crypto::ed25519::Ed25519PublicKey::from_bytes(&[u8; 32]) -> core::result::Result<Self, rns_crypto::ed25519::Ed25519Error>
|
||||
pub fn rns_crypto::ed25519::Ed25519PublicKey::to_bytes(&self) -> [u8; 32]
|
||||
pub fn rns_crypto::ed25519::Ed25519PublicKey::verify(&self, &[u8], &[u8; 64]) -> core::result::Result<(), rns_crypto::ed25519::Ed25519Error>
|
||||
pub mod rns_crypto::hkdf
|
||||
pub enum rns_crypto::hkdf::HkdfError
|
||||
pub rns_crypto::hkdf::HkdfError::ExpansionFailed
|
||||
pub rns_crypto::hkdf::HkdfError::InvalidLength
|
||||
pub fn rns_crypto::hkdf::derive_key_64(&[u8], &[u8]) -> core::result::Result<zeroize::Zeroizing<[u8; 64]>, rns_crypto::hkdf::HkdfError>
|
||||
pub fn rns_crypto::hkdf::hkdf_sha256(usize, &[u8], core::option::Option<&[u8]>, core::option::Option<&[u8]>) -> core::result::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>, rns_crypto::hkdf::HkdfError>
|
||||
pub mod rns_crypto::hmac
|
||||
pub fn rns_crypto::hmac::hmac_sha256(&[u8], &[u8]) -> [u8; 32]
|
||||
pub fn rns_crypto::hmac::hmac_verify(&[u8], &[u8], &[u8; 32]) -> bool
|
||||
pub mod rns_crypto::pkcs7
|
||||
pub enum rns_crypto::pkcs7::Pkcs7Error
|
||||
pub rns_crypto::pkcs7::Pkcs7Error::EmptyInput
|
||||
pub rns_crypto::pkcs7::Pkcs7Error::InconsistentPadding
|
||||
pub rns_crypto::pkcs7::Pkcs7Error::InvalidPaddingValue(u8)
|
||||
pub fn rns_crypto::pkcs7::pad(&[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_crypto::pkcs7::unpad(&[u8]) -> core::result::Result<&[u8], rns_crypto::pkcs7::Pkcs7Error>
|
||||
pub mod rns_crypto::random
|
||||
pub fn rns_crypto::random::random_16() -> [u8; 16]
|
||||
pub fn rns_crypto::random::random_32() -> [u8; 32]
|
||||
pub fn rns_crypto::random::random_bytes(usize) -> alloc::vec::Vec<u8>
|
||||
pub mod rns_crypto::sha
|
||||
pub fn rns_crypto::sha::full_hash(&[u8]) -> [u8; 32]
|
||||
pub fn rns_crypto::sha::name_hash(&str) -> [u8; 10]
|
||||
pub fn rns_crypto::sha::sha256(&[u8]) -> [u8; 32]
|
||||
pub fn rns_crypto::sha::sha512(&[u8]) -> [u8; 64]
|
||||
pub fn rns_crypto::sha::truncated_hash(&[u8]) -> [u8; 16]
|
||||
pub mod rns_crypto::token
|
||||
pub enum rns_crypto::token::TokenError
|
||||
pub rns_crypto::token::TokenError::AuthenticationFailed
|
||||
pub rns_crypto::token::TokenError::DecryptionFailed
|
||||
pub rns_crypto::token::TokenError::EncryptionFailed
|
||||
pub rns_crypto::token::TokenError::InvalidKeyLength(usize)
|
||||
pub rns_crypto::token::TokenError::TooShort
|
||||
pub const rns_crypto::token::AES128_BLOCKSIZE: usize
|
||||
pub const rns_crypto::token::AES256_BLOCKSIZE: usize
|
||||
pub const rns_crypto::token::DERIVED_KEY_LENGTH_LEGACY: usize
|
||||
pub const rns_crypto::token::KEY_LENGTH: usize
|
||||
pub const rns_crypto::token::LEGACY_KEY_LENGTH: usize
|
||||
pub const rns_crypto::token::TOKEN_OVERHEAD: usize
|
||||
pub fn rns_crypto::token::decrypt(&[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::token::TokenError>
|
||||
pub fn rns_crypto::token::encrypt(&[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_crypto::token::TokenError>
|
||||
pub fn rns_crypto::token::generate_key() -> zeroize::Zeroizing<alloc::vec::Vec<u8>>
|
||||
pub mod rns_crypto::x25519
|
||||
pub enum rns_crypto::x25519::X25519Error
|
||||
pub rns_crypto::x25519::X25519Error::LowOrderPoint
|
||||
pub struct rns_crypto::x25519::X25519PrivateKey
|
||||
impl rns_crypto::x25519::X25519PrivateKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::exchange(&self, &rns_crypto::x25519::X25519PublicKey) -> core::result::Result<[u8; 32], rns_crypto::x25519::X25519Error>
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::from_bytes(&[u8; 32]) -> Self
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::generate() -> Self
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::public_key(&self) -> rns_crypto::x25519::X25519PublicKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::to_bytes(&self) -> [u8; 32]
|
||||
impl core::ops::drop::Drop for rns_crypto::x25519::X25519PrivateKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_crypto::x25519::X25519PrivateKey
|
||||
pub fn rns_crypto::x25519::X25519PrivateKey::zeroize(&mut self)
|
||||
pub struct rns_crypto::x25519::X25519PublicKey
|
||||
impl rns_crypto::x25519::X25519PublicKey
|
||||
pub fn rns_crypto::x25519::X25519PublicKey::from_bytes(&[u8; 32]) -> Self
|
||||
pub fn rns_crypto::x25519::X25519PublicKey::to_bytes(&self) -> [u8; 32]
|
||||
pub const rns_crypto::TOKEN_OVERHEAD: usize
|
||||
pub fn rns_crypto::hex_encode(&[u8]) -> alloc::string::String
|
||||
@@ -0,0 +1,605 @@
|
||||
pub mod rns_git
|
||||
pub mod rns_git::client
|
||||
pub mod rns_git::client::forks
|
||||
pub enum rns_git::client::forks::Operation
|
||||
pub rns_git::client::forks::Operation::Fork
|
||||
pub rns_git::client::forks::Operation::Mirror
|
||||
pub rns_git::client::forks::Operation::Sync
|
||||
pub struct rns_git::client::forks::ClientArgs
|
||||
pub rns_git::client::forks::ClientArgs::config: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::forks::ClientArgs::identity: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::forks::ClientArgs::quiet: u8
|
||||
pub rns_git::client::forks::ClientArgs::rnsconfig: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::forks::ClientArgs::source: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::forks::ClientArgs::target: alloc::string::String
|
||||
pub rns_git::client::forks::ClientArgs::verbose: u8
|
||||
pub fn rns_git::client::forks::outcome(rns_git::client::forks::Operation, &str, core::option::Option<&[u8]>) -> core::result::Result<alloc::string::String, alloc::string::String>
|
||||
pub async fn rns_git::client::forks::run(rns_git::client::forks::Operation, rns_git::client::forks::ClientArgs) -> never
|
||||
pub mod rns_git::client::perms
|
||||
pub enum rns_git::client::perms::PermsTarget
|
||||
pub rns_git::client::perms::PermsTarget::Group
|
||||
pub rns_git::client::perms::PermsTarget::Repository
|
||||
pub fn rns_git::client::perms::perms_target(&str) -> core::option::Option<(alloc::string::String, rns_git::client::perms::PermsTarget)>
|
||||
pub fn rns_git::client::perms::run_perms(&mut dyn core::io::write::Write, &rns_git::server::client::ClientConfig, &mut rns_git::client::releases::Connect<'_>, &str, rns_git::client::perms::PermsTarget) -> core::result::Result<i32, rns_git::client::releases::Fail>
|
||||
pub mod rns_git::client::releases
|
||||
pub enum rns_git::client::releases::Fail
|
||||
pub rns_git::client::releases::Fail::Abort(alloc::string::String)
|
||||
pub rns_git::client::releases::Fail::Raised(alloc::string::String)
|
||||
pub enum rns_git::client::releases::ReleaseOp
|
||||
pub rns_git::client::releases::ReleaseOp::Create
|
||||
pub rns_git::client::releases::ReleaseOp::Delete
|
||||
pub rns_git::client::releases::ReleaseOp::Fetch
|
||||
pub rns_git::client::releases::ReleaseOp::Latest
|
||||
pub rns_git::client::releases::ReleaseOp::List
|
||||
pub rns_git::client::releases::ReleaseOp::Verify
|
||||
pub rns_git::client::releases::ReleaseOp::View
|
||||
impl rns_git::client::releases::ReleaseOp
|
||||
pub fn rns_git::client::releases::ReleaseOp::offline(self) -> bool
|
||||
pub fn rns_git::client::releases::ReleaseOp::parse(&str) -> core::option::Option<Self>
|
||||
pub enum rns_git::client::releases::Response
|
||||
pub rns_git::client::releases::Response::Bytes(alloc::vec::Vec<u8>)
|
||||
pub rns_git::client::releases::Response::File
|
||||
pub rns_git::client::releases::Response::File::metadata: rmpv::Value
|
||||
pub rns_git::client::releases::Response::File::path: std::path::PathBuf
|
||||
pub rns_git::client::releases::Response::Other(rmpv::Value)
|
||||
pub trait rns_git::client::releases::Remote
|
||||
pub fn rns_git::client::releases::Remote::request(&mut self, rmpv::Value, core::time::Duration) -> core::option::Option<rns_git::client::releases::Response>
|
||||
pub fn rns_git::client::releases::confirm_and_send(&mut dyn core::io::write::Write, &mut dyn alloc::io::buf_read::BufRead, &mut dyn rns_git::client::releases::Remote, &str, &str, &str) -> core::result::Result<(), rns_git::client::releases::Fail>
|
||||
pub fn rns_git::client::releases::create_release(&mut dyn core::io::write::Write, &rns_git::server::client::ClientConfig, &mut rns_git::client::releases::Connect<'_>, &rns_identity::identity::Identity, core::option::Option<&str>, core::option::Option<&str>, core::option::Option<&str>, core::option::Option<&str>, bool) -> core::result::Result<i32, rns_git::client::releases::Fail>
|
||||
pub fn rns_git::client::releases::expand_user(&str) -> std::path::PathBuf
|
||||
pub fn rns_git::client::releases::fetch_release(&mut dyn core::io::write::Write, &rns_git::server::client::ClientConfig, &mut rns_git::client::releases::Connect<'_>, core::option::Option<&str>, core::option::Option<&str>, core::option::Option<&str>, bool) -> core::result::Result<i32, rns_git::client::releases::Fail>
|
||||
pub fn rns_git::client::releases::fnmatch(&str, &str) -> bool
|
||||
pub fn rns_git::client::releases::iso_utc(i64) -> alloc::string::String
|
||||
pub fn rns_git::client::releases::list_releases(&mut dyn core::io::write::Write, &mut dyn rns_git::client::releases::Remote, &str) -> core::result::Result<(), rns_git::client::releases::Fail>
|
||||
pub fn rns_git::client::releases::prettyhexrep(&[u8]) -> alloc::string::String
|
||||
pub fn rns_git::client::releases::request_field<'a>(&'a [(rmpv::Value, rmpv::Value)], &str) -> core::option::Option<&'a rmpv::Value>
|
||||
pub fn rns_git::client::releases::required_signer(core::option::Option<&str>) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_git::client::releases::Fail>
|
||||
pub fn rns_git::client::releases::run_simple(&mut dyn core::io::write::Write, &mut dyn alloc::io::buf_read::BufRead, &rns_git::server::client::ClientConfig, &mut rns_git::client::releases::Connect<'_>, &str, core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<i32, rns_git::client::releases::Fail>
|
||||
pub fn rns_git::client::releases::view_release(&mut dyn core::io::write::Write, &mut dyn rns_git::client::releases::Remote, &str, &str) -> core::result::Result<(), rns_git::client::releases::Fail>
|
||||
pub type rns_git::client::releases::Connect<'a> = (dyn core::ops::function::FnMut(&str, &str) -> core::result::Result<alloc::boxed::Box<dyn rns_git::client::releases::Remote>, rns_git::client::releases::Fail> + 'a)
|
||||
pub mod rns_git::client::work
|
||||
pub enum rns_git::client::work::WorkOp
|
||||
pub rns_git::client::work::WorkOp::Activate
|
||||
pub rns_git::client::work::WorkOp::Complete
|
||||
pub rns_git::client::work::WorkOp::Create
|
||||
pub rns_git::client::work::WorkOp::Delete
|
||||
pub rns_git::client::work::WorkOp::Edit
|
||||
pub rns_git::client::work::WorkOp::List
|
||||
pub rns_git::client::work::WorkOp::Perms
|
||||
pub rns_git::client::work::WorkOp::Propose
|
||||
pub rns_git::client::work::WorkOp::Update
|
||||
pub rns_git::client::work::WorkOp::View
|
||||
impl rns_git::client::work::WorkOp
|
||||
pub fn rns_git::client::work::WorkOp::parse(&str) -> core::option::Option<Self>
|
||||
pub struct rns_git::client::work::CommonArgs
|
||||
pub rns_git::client::work::CommonArgs::config: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::work::CommonArgs::identity: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::work::CommonArgs::quiet: u8
|
||||
pub rns_git::client::work::CommonArgs::rnsconfig: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::work::CommonArgs::verbose: u8
|
||||
pub struct rns_git::client::work::WorkArgs
|
||||
pub rns_git::client::work::WorkArgs::doc_id: core::option::Option<i64>
|
||||
pub rns_git::client::work::WorkArgs::remote: core::option::Option<alloc::string::String>
|
||||
pub rns_git::client::work::WorkArgs::scope: alloc::string::String
|
||||
pub rns_git::client::work::WorkArgs::title: core::option::Option<alloc::string::String>
|
||||
pub const rns_git::client::work::COMMENT_TEMPLATE: &str
|
||||
pub const rns_git::client::work::CREATE_DOC_TEMPLATE: &str
|
||||
pub const rns_git::client::work::PERMISSIONS_TEMPLATE: &str
|
||||
pub fn rns_git::client::work::edit_permissions(&mut dyn core::io::write::Write, &str) -> core::option::Option<alloc::string::String>
|
||||
pub fn rns_git::client::work::edit_work_content(&mut dyn core::io::write::Write, &str, bool) -> core::option::Option<alloc::string::String>
|
||||
pub async fn rns_git::client::work::run_client(rns_git::client::work::CommonArgs, &'static str, rns_git::client::work::ClientBody) -> never
|
||||
pub fn rns_git::client::work::run_work(&mut dyn core::io::write::Write, &mut dyn alloc::io::buf_read::BufRead, &rns_git::server::client::ClientConfig, &mut rns_git::client::releases::Connect<'_>, &rns_identity::identity::Identity, core::option::Option<&str>, &rns_git::client::work::WorkArgs) -> core::result::Result<i32, rns_git::client::releases::Fail>
|
||||
pub type rns_git::client::work::ClientBody = alloc::boxed::Box<(dyn core::ops::function::FnOnce(&mut dyn core::io::write::Write, &mut dyn alloc::io::buf_read::BufRead, &rns_git::server::client::ClientConfig, &mut rns_git::client::releases::Connect<'_>, &rns_identity::identity::Identity) -> core::result::Result<i32, rns_git::client::releases::Fail> + core::marker::Send)>
|
||||
pub mod rns_git::commitsigs
|
||||
pub enum rns_git::commitsigs::HeaderEmail
|
||||
pub rns_git::commitsigs::HeaderEmail::DecodeError
|
||||
pub rns_git::commitsigs::HeaderEmail::Email(alloc::string::String)
|
||||
impl core::fmt::Display for rns_git::commitsigs::HeaderEmail
|
||||
pub fn rns_git::commitsigs::HeaderEmail::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_git::commitsigs::SshSignature
|
||||
pub rns_git::commitsigs::SshSignature::hash_algorithm: alloc::vec::Vec<u8>
|
||||
pub rns_git::commitsigs::SshSignature::namespace: alloc::vec::Vec<u8>
|
||||
pub rns_git::commitsigs::SshSignature::public_key: alloc::vec::Vec<u8>
|
||||
pub rns_git::commitsigs::SshSignature::reserved: alloc::vec::Vec<u8>
|
||||
pub rns_git::commitsigs::SshSignature::signature_data: alloc::vec::Vec<u8>
|
||||
pub rns_git::commitsigs::SshSignature::version: u32
|
||||
pub const rns_git::commitsigs::HASH_ALGORITHM: &[u8]
|
||||
pub const rns_git::commitsigs::NAMESPACE_GIT: &[u8]
|
||||
pub const rns_git::commitsigs::RESERVED_EMPTY: &[u8]
|
||||
pub const rns_git::commitsigs::SSHSIG_MAGIC: &[u8]
|
||||
pub const rns_git::commitsigs::SSHSIG_VERSION: u32
|
||||
pub fn rns_git::commitsigs::armor_ssh_signature(&[u8]) -> alloc::string::String
|
||||
pub fn rns_git::commitsigs::create_ssh_signature(&[u8], &[u8], &[u8], &[u8], &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_git::commitsigs::extract_commit_author(&[u8]) -> rns_git::commitsigs::HeaderEmail
|
||||
pub fn rns_git::commitsigs::extract_commit_committer(&[u8]) -> rns_git::commitsigs::HeaderEmail
|
||||
pub fn rns_git::commitsigs::extract_commit_tagger(&[u8]) -> core::option::Option<(alloc::string::String, bool)>
|
||||
pub fn rns_git::commitsigs::get_pubkey_wire_format(&rns_identity::identity::Identity) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_git::commitsigs::parse_ssh_signature(&[u8]) -> core::result::Result<rns_git::commitsigs::SshSignature, alloc::string::String>
|
||||
pub fn rns_git::commitsigs::ssh_string(&[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_git::commitsigs::unarmor_ssh_signature(&str) -> core::result::Result<alloc::vec::Vec<u8>, alloc::string::String>
|
||||
pub mod rns_git::highlight
|
||||
pub struct rns_git::highlight::MicronFormatter
|
||||
pub rns_git::highlight::MicronFormatter::theme: rns_git::highlight::Theme
|
||||
impl rns_git::highlight::MicronFormatter
|
||||
pub fn rns_git::highlight::MicronFormatter::format<'a>(&self, impl core::iter::traits::collect::IntoIterator<Item = (&'a str, &'a str)>) -> alloc::string::String
|
||||
pub fn rns_git::highlight::MicronFormatter::new(rns_git::highlight::Theme) -> Self
|
||||
pub struct rns_git::highlight::SyntaxHighlighter
|
||||
pub rns_git::highlight::SyntaxHighlighter::theme: rns_git::highlight::Theme
|
||||
impl rns_git::highlight::SyntaxHighlighter
|
||||
pub fn rns_git::highlight::SyntaxHighlighter::highlight(&self, &str, core::option::Option<&str>, core::option::Option<&str>) -> alloc::string::String
|
||||
pub fn rns_git::highlight::SyntaxHighlighter::new(core::option::Option<rns_git::highlight::Theme>) -> Self
|
||||
pub fn rns_git::highlight::SyntaxHighlighter::pygments_available(&self) -> bool
|
||||
impl core::default::Default for rns_git::highlight::SyntaxHighlighter
|
||||
pub fn rns_git::highlight::SyntaxHighlighter::default() -> Self
|
||||
pub fn rns_git::highlight::default_theme() -> rns_git::highlight::Theme
|
||||
pub fn rns_git::highlight::highlight_code(&str, core::option::Option<&str>, core::option::Option<&str>, core::option::Option<rns_git::highlight::Theme>) -> alloc::string::String
|
||||
pub type rns_git::highlight::Theme = std::collections::hash::map::HashMap<alloc::string::String, core::option::Option<alloc::string::String>>
|
||||
pub mod rns_git::md2micron
|
||||
pub enum rns_git::md2micron::Align
|
||||
pub rns_git::md2micron::Align::Center
|
||||
pub rns_git::md2micron::Align::Left
|
||||
pub rns_git::md2micron::Align::Right
|
||||
pub enum rns_git::md2micron::MarkdownError
|
||||
pub rns_git::md2micron::MarkdownError::PlaceholderDigits
|
||||
pub rns_git::md2micron::MarkdownError::PlaceholderIndex
|
||||
impl core::error::Error for rns_git::md2micron::MarkdownError
|
||||
impl core::fmt::Display for rns_git::md2micron::MarkdownError
|
||||
pub fn rns_git::md2micron::MarkdownError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_git::md2micron::MarkdownToMicron
|
||||
pub rns_git::md2micron::MarkdownToMicron::bold_links: bool
|
||||
pub rns_git::md2micron::MarkdownToMicron::link_color: core::option::Option<alloc::string::String>
|
||||
pub rns_git::md2micron::MarkdownToMicron::local_url_scope: alloc::string::String
|
||||
pub rns_git::md2micron::MarkdownToMicron::max_width: usize
|
||||
pub rns_git::md2micron::MarkdownToMicron::syntax_highlighter: core::option::Option<rns_git::highlight::SyntaxHighlighter>
|
||||
pub rns_git::md2micron::MarkdownToMicron::underline_links: bool
|
||||
impl rns_git::md2micron::MarkdownToMicron
|
||||
pub const rns_git::md2micron::MarkdownToMicron::BOLD: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::BOLD_END: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::BULLET: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::CODE_BG: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::CODE_BG_INLINE: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::CODE_FG: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::CODE_RESET: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::ITALIC: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::ITALIC_END: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::LITERAL_END: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::LITERAL_START: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_BL: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_BM: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_BR: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_H: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_MIN_COL_WIDTH: usize
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_ML: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_MM: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_MR: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_TL: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_TM: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_TR: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::TABLE_V: char
|
||||
pub const rns_git::md2micron::MarkdownToMicron::UNDERLINE: &'static str
|
||||
pub const rns_git::md2micron::MarkdownToMicron::UNDERLINE_END: &'static str
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::display_width(&self, &[char]) -> usize
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::format_block(&self, &str) -> core::result::Result<alloc::string::String, rns_git::md2micron::MarkdownError>
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::format_codeblock_line(&self, &str) -> alloc::string::String
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::format_inline(&self, &str) -> core::result::Result<alloc::string::String, rns_git::md2micron::MarkdownError>
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::format_line(&self, &str) -> core::result::Result<alloc::string::String, rns_git::md2micron::MarkdownError>
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::format_table(&self, &[alloc::string::String], &str) -> core::result::Result<alloc::vec::Vec<alloc::string::String>, rns_git::md2micron::MarkdownError>
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::format_table_raw(&self, &[alloc::string::String], &str) -> alloc::vec::Vec<alloc::string::String>
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::new(usize, core::option::Option<rns_git::highlight::SyntaxHighlighter>, core::option::Option<&str>) -> Self
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::restore_url_scope(&mut self)
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::set_url_scope(&mut self, &str)
|
||||
impl core::default::Default for rns_git::md2micron::MarkdownToMicron
|
||||
pub fn rns_git::md2micron::MarkdownToMicron::default() -> Self
|
||||
pub fn rns_git::md2micron::convert_markdown_to_micron(&str) -> core::result::Result<alloc::string::String, rns_git::md2micron::MarkdownError>
|
||||
pub mod rns_git::media
|
||||
pub const rns_git::media::BACKENDS: [(&str, &[&str]); 5]
|
||||
pub const rns_git::media::CONVERSION_TIMEOUT: core::time::Duration
|
||||
pub fn rns_git::media::convert_to_webp(&[&str], &std::path::Path, core::option::Option<&std::path::Path>, &str) -> bool
|
||||
pub fn rns_git::media::encoder_argv(&[&str], &str) -> core::option::Option<alloc::vec::Vec<alloc::string::String>>
|
||||
pub fn rns_git::media::select_backend(core::option::Option<&str>, &dyn core::ops::function::Fn(&str) -> bool, core::option::Option<&str>) -> core::option::Option<(&'static str, &'static [&'static str])>
|
||||
pub fn rns_git::media::webp_info(&[u8]) -> core::option::Option<(u32, u32)>
|
||||
pub fn rns_git::media::which(&str) -> bool
|
||||
pub mod rns_git::pages
|
||||
pub mod rns_git::pages::git
|
||||
pub enum rns_git::pages::git::RunError
|
||||
pub rns_git::pages::git::RunError::Failed
|
||||
pub rns_git::pages::git::RunError::Timeout
|
||||
pub struct rns_git::pages::git::BlobInfo
|
||||
pub rns_git::pages::git::BlobInfo::is_binary: bool
|
||||
pub rns_git::pages::git::BlobInfo::is_symlink: bool
|
||||
pub rns_git::pages::git::BlobInfo::is_tree: bool
|
||||
pub rns_git::pages::git::BlobInfo::size: u64
|
||||
pub rns_git::pages::git::BlobInfo::symlink_target: core::option::Option<alloc::string::String>
|
||||
pub struct rns_git::pages::git::ChangedFile
|
||||
pub rns_git::pages::git::ChangedFile::additions: i64
|
||||
pub rns_git::pages::git::ChangedFile::deletions: i64
|
||||
pub rns_git::pages::git::ChangedFile::path: alloc::string::String
|
||||
pub rns_git::pages::git::ChangedFile::status: &'static str
|
||||
pub struct rns_git::pages::git::CommitEntry
|
||||
pub rns_git::pages::git::CommitEntry::author: alloc::string::String
|
||||
pub rns_git::pages::git::CommitEntry::hash: alloc::string::String
|
||||
pub rns_git::pages::git::CommitEntry::subject: alloc::string::String
|
||||
pub rns_git::pages::git::CommitEntry::timestamp: i64
|
||||
pub struct rns_git::pages::git::CommitInfo
|
||||
pub rns_git::pages::git::CommitInfo::author_date: alloc::string::String
|
||||
pub rns_git::pages::git::CommitInfo::author_email: alloc::string::String
|
||||
pub rns_git::pages::git::CommitInfo::author_name: alloc::string::String
|
||||
pub rns_git::pages::git::CommitInfo::committer_date: alloc::string::String
|
||||
pub rns_git::pages::git::CommitInfo::committer_email: alloc::string::String
|
||||
pub rns_git::pages::git::CommitInfo::committer_name: alloc::string::String
|
||||
pub rns_git::pages::git::CommitInfo::diff: core::option::Option<alloc::string::String>
|
||||
pub rns_git::pages::git::CommitInfo::files: alloc::vec::Vec<rns_git::pages::git::ChangedFile>
|
||||
pub rns_git::pages::git::CommitInfo::message: alloc::string::String
|
||||
pub rns_git::pages::git::CommitInfo::parents: alloc::vec::Vec<alloc::string::String>
|
||||
pub struct rns_git::pages::git::RefInfo
|
||||
pub rns_git::pages::git::RefInfo::commit_subject: alloc::string::String
|
||||
pub rns_git::pages::git::RefInfo::is_annotated: bool
|
||||
pub rns_git::pages::git::RefInfo::is_default: bool
|
||||
pub rns_git::pages::git::RefInfo::name: alloc::string::String
|
||||
pub rns_git::pages::git::RefInfo::short_hash: alloc::string::String
|
||||
pub rns_git::pages::git::RefInfo::tag_message: core::option::Option<alloc::string::String>
|
||||
pub struct rns_git::pages::git::SignatureStatus
|
||||
pub rns_git::pages::git::SignatureStatus::author_match: bool
|
||||
pub rns_git::pages::git::SignatureStatus::message: alloc::string::String
|
||||
pub rns_git::pages::git::SignatureStatus::signed: bool
|
||||
pub rns_git::pages::git::SignatureStatus::valid: bool
|
||||
pub struct rns_git::pages::git::TreeEntry
|
||||
pub rns_git::pages::git::TreeEntry::kind: alloc::string::String
|
||||
pub rns_git::pages::git::TreeEntry::link_target: core::option::Option<alloc::string::String>
|
||||
pub rns_git::pages::git::TreeEntry::name: alloc::string::String
|
||||
pub rns_git::pages::git::TreeEntry::size: u64
|
||||
pub const rns_git::pages::git::GIT_COMMAND_TIMEOUT: core::time::Duration
|
||||
pub fn rns_git::pages::git::blob_content(&std::path::Path, &str, &str) -> core::option::Option<alloc::string::String>
|
||||
pub fn rns_git::pages::git::blob_info(&std::path::Path, &str, &str) -> core::option::Option<rns_git::pages::git::BlobInfo>
|
||||
pub fn rns_git::pages::git::blob_stream(&std::path::Path, &str, &str) -> core::option::Option<std::fs::File>
|
||||
pub fn rns_git::pages::git::commit_count(&std::path::Path, &str) -> u64
|
||||
pub fn rns_git::pages::git::commit_info(&std::path::Path, &str) -> core::option::Option<rns_git::pages::git::CommitInfo>
|
||||
pub fn rns_git::pages::git::commit_signature(&std::path::Path, &str) -> rns_git::pages::git::SignatureStatus
|
||||
pub fn rns_git::pages::git::commits(&std::path::Path, &str, &str, u64, u64) -> core::option::Option<alloc::vec::Vec<rns_git::pages::git::CommitEntry>>
|
||||
pub fn rns_git::pages::git::default_branch(&std::path::Path) -> core::option::Option<alloc::string::String>
|
||||
pub fn rns_git::pages::git::is_commit(&std::path::Path, &str) -> core::result::Result<bool, rns_git::pages::git::RunError>
|
||||
pub fn rns_git::pages::git::readme_content(&std::path::Path) -> core::option::Option<(alloc::string::String, bool)>
|
||||
pub fn rns_git::pages::git::refs_info(&std::path::Path, core::option::Option<&str>) -> (alloc::vec::Vec<rns_git::pages::git::RefInfo>, alloc::vec::Vec<rns_git::pages::git::RefInfo>)
|
||||
pub fn rns_git::pages::git::repository_description(&std::path::Path) -> core::option::Option<alloc::string::String>
|
||||
pub fn rns_git::pages::git::repository_ref_counts(&std::path::Path) -> (usize, usize)
|
||||
pub fn rns_git::pages::git::resolve_ref(&std::path::Path, &str) -> core::option::Option<alloc::string::String>
|
||||
pub fn rns_git::pages::git::tree_entries(&std::path::Path, &str, &str) -> core::option::Option<alloc::vec::Vec<rns_git::pages::git::TreeEntry>>
|
||||
pub enum rns_git::pages::PageReply
|
||||
pub rns_git::pages::PageReply::Drop
|
||||
pub rns_git::pages::PageReply::File
|
||||
pub rns_git::pages::PageReply::File::file: std::fs::File
|
||||
pub rns_git::pages::PageReply::File::name: alloc::string::String
|
||||
pub rns_git::pages::PageReply::Page(alloc::vec::Vec<u8>)
|
||||
pub rns_git::pages::PageReply::Value(alloc::vec::Vec<u8>)
|
||||
pub struct rns_git::pages::PageNode
|
||||
pub rns_git::pages::PageNode::node_name: alloc::string::String
|
||||
pub rns_git::pages::PageNode::options: rns_git::pages::PageOptions
|
||||
pub rns_git::pages::PageNode::recall: core::option::Option<rns_git::pages::Recall>
|
||||
pub rns_git::pages::PageNode::repos: alloc::sync::Arc<std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>>
|
||||
pub rns_git::pages::PageNode::repositories_destination: [u8; 16]
|
||||
pub rns_git::pages::PageNode::stats: alloc::sync::Arc<rns_git::server::stats::Stats>
|
||||
pub rns_git::pages::PageNode::templates_dir: std::path::PathBuf
|
||||
impl rns_git::pages::PageNode
|
||||
pub fn rns_git::pages::PageNode::handle(&self, &rns_git::pages::PageRequest<'_>) -> rns_git::pages::PageReply
|
||||
pub fn rns_git::pages::PageNode::new(alloc::sync::Arc<std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>>, alloc::sync::Arc<rns_git::server::stats::Stats>, alloc::string::String, [u8; 16], &std::path::Path, rns_git::pages::PageOptions) -> Self
|
||||
pub struct rns_git::pages::PageOptions
|
||||
pub rns_git::pages::PageOptions::link_cost: f64
|
||||
pub rns_git::pages::PageOptions::media_conversion: bool
|
||||
pub rns_git::pages::PageOptions::stamp_value: core::option::Option<f64>
|
||||
pub rns_git::pages::PageOptions::use_nerdfonts: bool
|
||||
impl rns_git::pages::PageOptions
|
||||
pub fn rns_git::pages::PageOptions::from_config_text(&str) -> core::result::Result<Self, rns_runtime::config::ConfigError>
|
||||
impl core::default::Default for rns_git::pages::PageOptions
|
||||
pub fn rns_git::pages::PageOptions::default() -> Self
|
||||
pub struct rns_git::pages::PageRequest<'a>
|
||||
pub rns_git::pages::PageRequest::data: &'a rmpv::Value
|
||||
pub rns_git::pages::PageRequest::identity: core::option::Option<[u8; 16]>
|
||||
pub rns_git::pages::PageRequest::link_id: [u8; 16]
|
||||
pub rns_git::pages::PageRequest::path: &'a str
|
||||
pub const rns_git::pages::APP_NAME: &str
|
||||
pub const rns_git::pages::FILE_ARTIFACT: &str
|
||||
pub const rns_git::pages::FILE_DOWNLOAD: &str
|
||||
pub const rns_git::pages::FILE_WORKDOC: &str
|
||||
pub const rns_git::pages::JOBS_INTERVAL: u64
|
||||
pub const rns_git::pages::PATHS: [&str; 17]
|
||||
pub const rns_git::pages::PATH_BLOB: &str
|
||||
pub const rns_git::pages::PATH_COMMIT: &str
|
||||
pub const rns_git::pages::PATH_COMMITS: &str
|
||||
pub const rns_git::pages::PATH_GROUP: &str
|
||||
pub const rns_git::pages::PATH_INDEX: &str
|
||||
pub const rns_git::pages::PATH_MEDIA: &str
|
||||
pub const rns_git::pages::PATH_REFS: &str
|
||||
pub const rns_git::pages::PATH_RELEASE: &str
|
||||
pub const rns_git::pages::PATH_RELEASES: &str
|
||||
pub const rns_git::pages::PATH_REPO: &str
|
||||
pub const rns_git::pages::PATH_STATS: &str
|
||||
pub const rns_git::pages::PATH_TREE: &str
|
||||
pub const rns_git::pages::PATH_WORK: &str
|
||||
pub const rns_git::pages::PATH_WORK_DOC: &str
|
||||
pub const rns_git::pages::VERSION: &str
|
||||
pub fn rns_git::pages::file_metadata(&str) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_git::pages::m_divider() -> alloc::string::String
|
||||
pub fn rns_git::pages::m_escape(&str) -> alloc::string::String
|
||||
pub fn rns_git::pages::m_heading(&str, usize) -> alloc::string::String
|
||||
pub fn rns_git::pages::m_italic(&str) -> alloc::string::String
|
||||
pub fn rns_git::pages::m_link(&str, &str, &[(&str, &str)]) -> alloc::string::String
|
||||
pub fn rns_git::pages::m_link_e(&str, &str, &str, &[(&str, &str)]) -> alloc::string::String
|
||||
pub fn rns_git::pages::m_link_r(&str, &str, &[(&str, &str)]) -> alloc::string::String
|
||||
pub fn rns_git::pages::quote_plus(&str) -> alloc::string::String
|
||||
pub fn rns_git::pages::render_chart(&[i64], &[alloc::string::String], &str, core::option::Option<&str>, core::option::Option<f64>) -> alloc::string::String
|
||||
pub fn rns_git::pages::render_combined_chart(&[i64], &[i64], &[i64], &[i64], &[alloc::string::String]) -> alloc::string::String
|
||||
pub fn rns_git::pages::unquote_plus(&str) -> alloc::string::String
|
||||
pub type rns_git::pages::Recall = alloc::boxed::Box<(dyn core::ops::function::Fn([u8; 16]) -> core::option::Option<[u8; 16]> + core::marker::Send + core::marker::Sync)>
|
||||
pub mod rns_git::remote_helper
|
||||
pub enum rns_git::remote_helper::ClientConfigError
|
||||
pub rns_git::remote_helper::ClientConfigError::Io(std::path::PathBuf, core::io::error::Error)
|
||||
pub rns_git::remote_helper::ClientConfigError::Parse(std::path::PathBuf, rns_runtime::config::ConfigError)
|
||||
pub rns_git::remote_helper::ClientConfigError::Value(rns_runtime::config::ConfigError)
|
||||
impl core::fmt::Display for rns_git::remote_helper::ClientConfigError
|
||||
pub fn rns_git::remote_helper::ClientConfigError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub enum rns_git::remote_helper::Response
|
||||
pub rns_git::remote_helper::Response::Bytes(alloc::vec::Vec<u8>)
|
||||
pub rns_git::remote_helper::Response::File
|
||||
pub rns_git::remote_helper::Response::File::metadata: rmpv::Value
|
||||
pub rns_git::remote_helper::Response::File::path: std::path::PathBuf
|
||||
pub rns_git::remote_helper::Response::Other(rmpv::Value)
|
||||
pub struct rns_git::remote_helper::Abort
|
||||
pub rns_git::remote_helper::Abort::code: i32
|
||||
pub rns_git::remote_helper::Abort::reason: alloc::string::String
|
||||
pub rns_git::remote_helper::Abort::traceback: bool
|
||||
impl rns_git::remote_helper::Abort
|
||||
pub fn rns_git::remote_helper::Abort::message(&self) -> alloc::string::String
|
||||
pub fn rns_git::remote_helper::Abort::new(impl core::convert::Into<alloc::string::String>) -> Self
|
||||
pub struct rns_git::remote_helper::ClientConfig
|
||||
pub rns_git::remote_helper::ClientConfig::aliases: alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>
|
||||
pub rns_git::remote_helper::ClientConfig::loglevel: core::option::Option<i64>
|
||||
pub rns_git::remote_helper::ClientConfig::ref_batch_size: usize
|
||||
impl rns_git::remote_helper::ClientConfig
|
||||
pub fn rns_git::remote_helper::ClientConfig::load(&std::path::Path) -> core::result::Result<Self, rns_git::remote_helper::ClientConfigError>
|
||||
pub fn rns_git::remote_helper::ClientConfig::resolve_destination(&self, &str) -> alloc::string::String
|
||||
pub struct rns_git::remote_helper::HelperUrl
|
||||
pub rns_git::remote_helper::HelperUrl::destination: alloc::string::String
|
||||
pub rns_git::remote_helper::HelperUrl::group: alloc::string::String
|
||||
pub rns_git::remote_helper::HelperUrl::repo: alloc::string::String
|
||||
impl rns_git::remote_helper::HelperUrl
|
||||
pub fn rns_git::remote_helper::HelperUrl::repo_path(&self) -> alloc::string::String
|
||||
pub struct rns_git::remote_helper::RemoteHelper<T: rns_git::remote_helper::Transport>
|
||||
pub rns_git::remote_helper::RemoteHelper::git_dir: std::path::PathBuf
|
||||
pub rns_git::remote_helper::RemoteHelper::progress_enabled: bool
|
||||
pub rns_git::remote_helper::RemoteHelper::ref_batch_size: usize
|
||||
pub rns_git::remote_helper::RemoteHelper::repo_path: alloc::string::String
|
||||
pub rns_git::remote_helper::RemoteHelper::transport: T
|
||||
impl<T: rns_git::remote_helper::Transport> rns_git::remote_helper::RemoteHelper<T>
|
||||
pub fn rns_git::remote_helper::RemoteHelper<T>::new(T, alloc::string::String, usize, std::path::PathBuf) -> Self
|
||||
pub fn rns_git::remote_helper::RemoteHelper<T>::run(&mut self, &mut dyn alloc::io::buf_read::BufRead, &mut dyn core::io::write::Write, &mut dyn core::io::write::Write) -> core::result::Result<(), rns_git::remote_helper::Abort>
|
||||
pub const rns_git::remote_helper::DEFAULT_CLIENT_CONFIG: &str
|
||||
pub const rns_git::remote_helper::PATH_TIMEOUT: f64
|
||||
pub const rns_git::remote_helper::REF_BATCH_SIZE: usize
|
||||
pub const rns_git::remote_helper::REQUEST_TIMEOUT: f64
|
||||
pub trait rns_git::remote_helper::Transport
|
||||
pub fn rns_git::remote_helper::Transport::request(&mut self, &str, rmpv::Value) -> core::option::Option<rns_git::remote_helper::Response>
|
||||
pub fn rns_git::remote_helper::escape_for_stdout(&str) -> alloc::string::String
|
||||
pub fn rns_git::remote_helper::load_or_create_identity(&std::path::Path) -> core::option::Option<rns_identity::identity::Identity>
|
||||
pub fn rns_git::remote_helper::parse_args(&[alloc::string::String]) -> core::result::Result<rns_git::remote_helper::HelperUrl, (alloc::string::String, i32)>
|
||||
pub fn rns_git::remote_helper::resolve_config_dir(core::option::Option<&std::path::Path>, &std::path::Path) -> std::path::PathBuf
|
||||
pub mod rns_git::server
|
||||
pub mod rns_git::server::client
|
||||
pub struct rns_git::server::client::ClientConfig
|
||||
pub rns_git::server::client::ClientConfig::aliases: alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>
|
||||
pub rns_git::server::client::ClientConfig::loglevel: core::option::Option<i64>
|
||||
impl rns_git::server::client::ClientConfig
|
||||
pub fn rns_git::server::client::ClientConfig::load_or_create(&std::path::Path) -> core::result::Result<Self, alloc::string::String>
|
||||
pub fn rns_git::server::client::ClientConfig::parse(&str) -> core::result::Result<Self, alloc::string::String>
|
||||
pub fn rns_git::server::client::ClientConfig::parse_remote_destination_url(&self, &str) -> core::result::Result<alloc::vec::Vec<u8>, alloc::string::String>
|
||||
pub fn rns_git::server::client::ClientConfig::parse_remote_group_url(&self, &str) -> core::result::Result<(alloc::vec::Vec<u8>, alloc::string::String), alloc::string::String>
|
||||
pub fn rns_git::server::client::ClientConfig::parse_remote_url(&self, &str) -> core::result::Result<(alloc::vec::Vec<u8>, alloc::string::String, alloc::string::String), alloc::string::String>
|
||||
pub const rns_git::server::client::DEFAULT_CLIENT_CONFIG: &str
|
||||
pub fn rns_git::server::client::client_config_dir(core::option::Option<&std::path::Path>) -> std::path::PathBuf
|
||||
pub fn rns_git::server::client::create_outcome(&str, core::option::Option<&[u8]>) -> core::result::Result<alloc::string::String, alloc::string::String>
|
||||
pub mod rns_git::server::config
|
||||
pub struct rns_git::server::config::FetchLimits
|
||||
pub rns_git::server::config::FetchLimits::size: u64
|
||||
pub rns_git::server::config::FetchLimits::time: core::time::Duration
|
||||
impl core::default::Default for rns_git::server::config::FetchLimits
|
||||
pub fn rns_git::server::config::FetchLimits::default() -> Self
|
||||
pub struct rns_git::server::config::NodeConfig
|
||||
pub rns_git::server::config::NodeConfig::access: alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::vec::Vec<alloc::string::String>>
|
||||
pub rns_git::server::config::NodeConfig::aliases: alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>
|
||||
pub rns_git::server::config::NodeConfig::announce_interval: i64
|
||||
pub rns_git::server::config::NodeConfig::blocked_identities: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_git::server::config::NodeConfig::fetch_limits: rns_git::server::config::FetchLimits
|
||||
pub rns_git::server::config::NodeConfig::link_cost: f64
|
||||
pub rns_git::server::config::NodeConfig::loglevel: core::option::Option<i64>
|
||||
pub rns_git::server::config::NodeConfig::mirror_interval: i64
|
||||
pub rns_git::server::config::NodeConfig::node_name: alloc::string::String
|
||||
pub rns_git::server::config::NodeConfig::record_stats: bool
|
||||
pub rns_git::server::config::NodeConfig::repositories: alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>
|
||||
pub rns_git::server::config::NodeConfig::serve_nomadnet: bool
|
||||
pub rns_git::server::config::NodeConfig::stamp_value: core::option::Option<f64>
|
||||
pub rns_git::server::config::NodeConfig::stats_ignored: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_git::server::config::NodeConfig::stats_push_ignored: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
impl rns_git::server::config::NodeConfig
|
||||
pub fn rns_git::server::config::NodeConfig::parse(&str, i64) -> core::result::Result<Self, rns_runtime::config::ConfigError>
|
||||
impl core::default::Default for rns_git::server::config::NodeConfig
|
||||
pub fn rns_git::server::config::NodeConfig::default() -> Self
|
||||
pub const rns_git::server::config::DEFAULT_CONFIG: &str
|
||||
pub const rns_git::server::config::DEFAULT_LINK_COST: f64
|
||||
pub const rns_git::server::config::DEFAULT_NODE_NAME: &str
|
||||
pub fn rns_git::server::config::expand_user(&str) -> std::path::PathBuf
|
||||
pub fn rns_git::server::config::load_or_create_identity(&std::path::Path) -> core::result::Result<rns_identity::identity::Identity, rns_identity::identity::IdentityError>
|
||||
pub fn rns_git::server::config::read_or_create_config(&std::path::Path) -> core::io::error::Result<alloc::string::String>
|
||||
pub fn rns_git::server::config::resolve_config_dir(core::option::Option<&std::path::Path>) -> std::path::PathBuf
|
||||
pub mod rns_git::server::forks
|
||||
pub enum rns_git::server::forks::RepoType
|
||||
pub rns_git::server::forks::RepoType::Fork
|
||||
pub rns_git::server::forks::RepoType::Mirror
|
||||
pub const rns_git::server::forks::CLONE_PROTOS: [&str; 4]
|
||||
pub const rns_git::server::forks::SYNC_CHECK_INTERVAL: u64
|
||||
pub fn rns_git::server::forks::handle_fork(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::forks::handle_mirror(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::forks::handle_sync(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::forks::mirror_synced(&std::path::Path) -> i64
|
||||
pub fn rns_git::server::forks::set_mirror_synced(&std::path::Path) -> bool
|
||||
pub fn rns_git::server::forks::stop_fetches()
|
||||
pub fn rns_git::server::forks::sync_mirrors(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, i64, &std::sync::poison::mutex::Mutex<()>)
|
||||
pub fn rns_git::server::forks::update_head_to_source_default(&std::path::Path, &str) -> bool
|
||||
pub mod rns_git::server::handlers
|
||||
pub enum rns_git::server::handlers::Reply
|
||||
pub rns_git::server::handlers::Reply::Bytes(alloc::vec::Vec<u8>)
|
||||
pub rns_git::server::handlers::Reply::File
|
||||
pub rns_git::server::handlers::Reply::File::file: std::fs::File
|
||||
pub rns_git::server::handlers::Reply::File::metadata: alloc::vec::Vec<u8>
|
||||
pub rns_git::server::handlers::Reply::File::tmpdir: tempfile::dir::TempDir
|
||||
pub fn rns_git::server::handlers::handle_create(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::handlers::handle_delete(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, &rns_git::server::stats::Stats, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::handlers::handle_fetch(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, &rns_git::server::stats::Stats, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<rns_git::server::handlers::Reply>
|
||||
pub fn rns_git::server::handlers::handle_list(&rns_git::server::layout::Repositories, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::handlers::handle_push(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, &rns_git::server::stats::Stats, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::handlers::identity_text(core::option::Option<&[u8; 16]>) -> alloc::string::String
|
||||
pub fn rns_git::server::handlers::log_request(&rns_git::server::layout::Repositories, &str, core::option::Option<&[u8; 16]>)
|
||||
pub mod rns_git::server::layout
|
||||
pub struct rns_git::server::layout::Group
|
||||
pub rns_git::server::layout::Group::dynamic_perms: bool
|
||||
pub rns_git::server::layout::Group::name: alloc::string::String
|
||||
pub rns_git::server::layout::Group::path: alloc::string::String
|
||||
pub rns_git::server::layout::Group::permissions: rns_git::server::perms::Permissions
|
||||
pub rns_git::server::layout::Group::repositories: alloc::collections::btree::map::BTreeMap<alloc::string::String, rns_git::server::layout::Repository>
|
||||
pub struct rns_git::server::layout::Repositories
|
||||
pub rns_git::server::layout::Repositories::aliases: alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>
|
||||
pub rns_git::server::layout::Repositories::blocked: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_git::server::layout::Repositories::fetch_limits: rns_git::server::config::FetchLimits
|
||||
pub rns_git::server::layout::Repositories::groups: alloc::collections::btree::map::BTreeMap<alloc::string::String, rns_git::server::layout::Group>
|
||||
impl rns_git::server::layout::Repositories
|
||||
pub fn rns_git::server::layout::Repositories::is_blocked(&self, &[u8; 16]) -> bool
|
||||
pub fn rns_git::server::layout::Repositories::load(&rns_git::server::config::NodeConfig) -> core::result::Result<Self, rns_git::server::perms::AllowedError>
|
||||
pub fn rns_git::server::layout::Repositories::load_group(&mut self, &str, &str, &rns_git::server::config::NodeConfig) -> core::result::Result<(), rns_git::server::perms::AllowedError>
|
||||
pub fn rns_git::server::layout::Repositories::load_repository(&mut self, &str, &std::path::Path) -> core::result::Result<bool, rns_git::server::perms::AllowedError>
|
||||
pub fn rns_git::server::layout::Repositories::repository(&self, &str, &str) -> core::option::Option<&rns_git::server::layout::Repository>
|
||||
pub fn rns_git::server::layout::Repositories::resolve_group_permission(&self, &[u8; 16], &str, rns_git::server::perms::Perm) -> bool
|
||||
pub fn rns_git::server::layout::Repositories::resolve_permission(&self, &[u8; 16], &str, &str, rns_git::server::perms::Perm) -> bool
|
||||
pub fn rns_git::server::layout::Repositories::update_group_permissions(&mut self, &str, &rns_git::server::config::NodeConfig)
|
||||
pub struct rns_git::server::layout::Repository
|
||||
pub rns_git::server::layout::Repository::fork: core::option::Option<alloc::string::String>
|
||||
pub rns_git::server::layout::Repository::group: alloc::string::String
|
||||
pub rns_git::server::layout::Repository::mirror: core::option::Option<alloc::string::String>
|
||||
pub rns_git::server::layout::Repository::name: alloc::string::String
|
||||
pub rns_git::server::layout::Repository::path: std::path::PathBuf
|
||||
pub rns_git::server::layout::Repository::permissions: rns_git::server::perms::Permissions
|
||||
pub fn rns_git::server::layout::git_available() -> bool
|
||||
pub fn rns_git::server::layout::parse_group_path(&str) -> core::option::Option<&str>
|
||||
pub fn rns_git::server::layout::parse_repository_path(&str) -> core::option::Option<(&str, &str)>
|
||||
pub mod rns_git::server::perms
|
||||
pub enum rns_git::server::perms::AllowedError
|
||||
pub rns_git::server::perms::AllowedError::Io(core::io::error::Error)
|
||||
pub rns_git::server::perms::AllowedError::NotUtf8
|
||||
pub enum rns_git::server::perms::Perm
|
||||
pub rns_git::server::perms::Perm::Admin
|
||||
pub rns_git::server::perms::Perm::Create
|
||||
pub rns_git::server::perms::Perm::Interact
|
||||
pub rns_git::server::perms::Perm::Propose
|
||||
pub rns_git::server::perms::Perm::Read
|
||||
pub rns_git::server::perms::Perm::ReadWrite
|
||||
pub rns_git::server::perms::Perm::Release
|
||||
pub rns_git::server::perms::Perm::Stats
|
||||
pub rns_git::server::perms::Perm::Write
|
||||
impl rns_git::server::perms::Perm
|
||||
pub fn rns_git::server::perms::Perm::code(self) -> u8
|
||||
pub enum rns_git::server::perms::PermList
|
||||
pub rns_git::server::perms::PermList::Admin
|
||||
pub rns_git::server::perms::PermList::Create
|
||||
pub rns_git::server::perms::PermList::Interact
|
||||
pub rns_git::server::perms::PermList::Propose
|
||||
pub rns_git::server::perms::PermList::Read
|
||||
pub rns_git::server::perms::PermList::Release
|
||||
pub rns_git::server::perms::PermList::Stats
|
||||
pub rns_git::server::perms::PermList::Write
|
||||
impl rns_git::server::perms::PermList
|
||||
pub const rns_git::server::perms::PermList::ALL: [rns_git::server::perms::PermList; 8]
|
||||
pub fn rns_git::server::perms::PermList::name(self) -> &'static str
|
||||
pub enum rns_git::server::perms::Target
|
||||
pub rns_git::server::perms::Target::All
|
||||
pub rns_git::server::perms::Target::Identity(alloc::vec::Vec<u8>)
|
||||
pub rns_git::server::perms::Target::None
|
||||
impl rns_git::server::perms::Target
|
||||
pub fn rns_git::server::perms::Target::code(&self) -> core::option::Option<u8>
|
||||
pub struct rns_git::server::perms::Permissions
|
||||
impl rns_git::server::perms::Permissions
|
||||
pub fn rns_git::server::perms::Permissions::add_statement(&mut self, &str, &alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>)
|
||||
pub fn rns_git::server::perms::Permissions::from_allowed_input(&str, &alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>) -> Self
|
||||
pub fn rns_git::server::perms::Permissions::get(&self, rns_git::server::perms::PermList) -> &[rns_git::server::perms::Target]
|
||||
pub const rns_git::server::perms::ALL_TGTS: [&str; 6]
|
||||
pub const rns_git::server::perms::TGT_ALL_SMPHR: [&str; 3]
|
||||
pub const rns_git::server::perms::TGT_NONE_SMPHR: [&str; 3]
|
||||
pub fn rns_git::server::perms::load_allowed_permissions(&std::path::Path, &alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>) -> core::result::Result<(rns_git::server::perms::Permissions, bool), rns_git::server::perms::AllowedError>
|
||||
pub fn rns_git::server::perms::parse_permission(&str, &alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>) -> (core::option::Option<rns_git::server::perms::Perm>, core::option::Option<rns_git::server::perms::Target>)
|
||||
pub fn rns_git::server::perms::resolve_group(&rns_git::server::perms::Permissions, &[u8; 16], rns_git::server::perms::Perm) -> bool
|
||||
pub fn rns_git::server::perms::resolve_identity_alias(&str, &alloc::collections::btree::map::BTreeMap<alloc::string::String, alloc::string::String>) -> alloc::string::String
|
||||
pub fn rns_git::server::perms::resolve_repository(&rns_git::server::perms::Permissions, &rns_git::server::perms::Permissions, &[u8; 16], rns_git::server::perms::Perm) -> bool
|
||||
pub mod rns_git::server::perms_mgmt
|
||||
pub fn rns_git::server::perms_mgmt::handle_perms(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, &rns_git::server::config::NodeConfig, core::option::Option<&[u8; 16]>, &rmpv::Value) -> alloc::vec::Vec<u8>
|
||||
pub mod rns_git::server::releases
|
||||
pub fn rns_git::server::releases::handle_release(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, core::option::Option<&[u8; 16]>, &rmpv::Value) -> core::option::Option<rns_git::server::handlers::Reply>
|
||||
pub mod rns_git::server::stats
|
||||
pub struct rns_git::server::stats::RepositoryStats
|
||||
pub rns_git::server::stats::RepositoryStats::activity_level: &'static str
|
||||
pub rns_git::server::stats::RepositoryStats::activity_score: i64
|
||||
pub rns_git::server::stats::RepositoryStats::actual_days: i64
|
||||
pub rns_git::server::stats::RepositoryStats::date_range: alloc::string::String
|
||||
pub rns_git::server::stats::RepositoryStats::day_labels: alloc::vec::Vec<alloc::string::String>
|
||||
pub rns_git::server::stats::RepositoryStats::days: alloc::vec::Vec<alloc::string::String>
|
||||
pub rns_git::server::stats::RepositoryStats::downloads: rns_git::server::stats::Series
|
||||
pub rns_git::server::stats::RepositoryStats::downloads_combined: rns_git::server::stats::Series
|
||||
pub rns_git::server::stats::RepositoryStats::fetches: rns_git::server::stats::Series
|
||||
pub rns_git::server::stats::RepositoryStats::group: alloc::string::String
|
||||
pub rns_git::server::stats::RepositoryStats::lookback_days: u32
|
||||
pub rns_git::server::stats::RepositoryStats::pushes: rns_git::server::stats::Series
|
||||
pub rns_git::server::stats::RepositoryStats::release_downloads: rns_git::server::stats::Series
|
||||
pub rns_git::server::stats::RepositoryStats::repository: alloc::string::String
|
||||
pub rns_git::server::stats::RepositoryStats::timeline_labels: [alloc::string::String; 2]
|
||||
pub rns_git::server::stats::RepositoryStats::views: rns_git::server::stats::Series
|
||||
pub struct rns_git::server::stats::Series
|
||||
pub rns_git::server::stats::Series::daily: alloc::vec::Vec<i64>
|
||||
pub rns_git::server::stats::Series::peak: i64
|
||||
pub rns_git::server::stats::Series::peak_day: core::option::Option<alloc::string::String>
|
||||
pub rns_git::server::stats::Series::total: i64
|
||||
pub struct rns_git::server::stats::Stats
|
||||
impl rns_git::server::stats::Stats
|
||||
pub fn rns_git::server::stats::Stats::download_succeeded(&self, &str, &str, core::option::Option<&[u8; 16]>)
|
||||
pub fn rns_git::server::stats::Stats::fetch_succeeded(&self, &str, &str, core::option::Option<&[u8; 16]>)
|
||||
pub fn rns_git::server::stats::Stats::load(std::path::PathBuf, bool, alloc::vec::Vec<alloc::vec::Vec<u8>>) -> Self
|
||||
pub fn rns_git::server::stats::Stats::path(&self) -> &std::path::Path
|
||||
pub fn rns_git::server::stats::Stats::persist(&self)
|
||||
pub fn rns_git::server::stats::Stats::push_succeeded(&self, &str, &str)
|
||||
pub fn rns_git::server::stats::Stats::release_download_succeeded(&self, &str, &str, core::option::Option<&[u8; 16]>)
|
||||
pub fn rns_git::server::stats::Stats::repository_stats(&self, &rns_git::server::layout::Repositories, &[u8; 16], &str, &str, u32) -> core::option::Option<rns_git::server::stats::RepositoryStats>
|
||||
pub fn rns_git::server::stats::Stats::view_succeeded(&self, core::option::Option<&str>, core::option::Option<&str>, core::option::Option<&[u8; 16]>)
|
||||
pub const rns_git::server::stats::STATS_JOB_INTERVAL: u64
|
||||
pub fn rns_git::server::stats::local_day(i64) -> alloc::string::String
|
||||
pub mod rns_git::server::work
|
||||
pub const rns_git::server::work::WORK_DOC_LIMIT: usize
|
||||
pub fn rns_git::server::work::handle_work(&std::sync::poison::rwlock::RwLock<rns_git::server::layout::Repositories>, core::option::Option<&rns_identity::identity::Identity>, &rmpv::Value) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_git::server::work::resolve_doc_permission(&rns_git::server::layout::Repositories, &[u8; 16], core::option::Option<(&str, &str)>, i128, rns_git::server::perms::Perm) -> bool
|
||||
pub const rns_git::server::APP_NAME: &str
|
||||
pub const rns_git::server::IDX_GROUP: u8
|
||||
pub const rns_git::server::IDX_REPOSITORY: u8
|
||||
pub const rns_git::server::IDX_RESULT_CODE: u8
|
||||
pub const rns_git::server::PATH_CREATE: &str
|
||||
pub const rns_git::server::PATH_DELETE: &str
|
||||
pub const rns_git::server::PATH_FETCH: &str
|
||||
pub const rns_git::server::PATH_FORK: &str
|
||||
pub const rns_git::server::PATH_LIST: &str
|
||||
pub const rns_git::server::PATH_MIRROR: &str
|
||||
pub const rns_git::server::PATH_PERMS: &str
|
||||
pub const rns_git::server::PATH_PUSH: &str
|
||||
pub const rns_git::server::PATH_RELEASE: &str
|
||||
pub const rns_git::server::PATH_SYNC: &str
|
||||
pub const rns_git::server::PATH_WORK: &str
|
||||
pub const rns_git::server::RES_DISALLOWED: u8
|
||||
pub const rns_git::server::RES_INVALID_REQ: u8
|
||||
pub const rns_git::server::RES_NOT_FOUND: u8
|
||||
pub const rns_git::server::RES_OK: u8
|
||||
pub const rns_git::server::RES_REMOTE_FAIL: u8
|
||||
pub mod rns_git::util
|
||||
pub fn rns_git::util::san_ref(&str) -> core::option::Option<&str>
|
||||
pub fn rns_git::util::san_refs<S: core::convert::AsRef<str>>(&[S]) -> core::option::Option<&[S]>
|
||||
pub fn rns_git::util::san_sha(&str) -> core::option::Option<&str>
|
||||
@@ -0,0 +1,537 @@
|
||||
pub mod rns_identity
|
||||
pub mod rns_identity::announce
|
||||
pub enum rns_identity::announce::AnnounceError
|
||||
pub rns_identity::announce::AnnounceError::HashCollision
|
||||
pub rns_identity::announce::AnnounceError::HashMismatch
|
||||
pub rns_identity::announce::AnnounceError::InvalidPublicKey
|
||||
pub rns_identity::announce::AnnounceError::InvalidWireTime(u64)
|
||||
pub rns_identity::announce::AnnounceError::NoPrivateKey
|
||||
pub rns_identity::announce::AnnounceError::SignatureInvalid
|
||||
pub rns_identity::announce::AnnounceError::TooShort(usize)
|
||||
pub enum rns_identity::announce::AnnounceExtParse<'a>
|
||||
pub rns_identity::announce::AnnounceExtParse::Absent
|
||||
pub rns_identity::announce::AnnounceExtParse::Present(rns_identity::announce::AnnounceExt<'a>)
|
||||
pub rns_identity::announce::AnnounceExtParse::Unknown
|
||||
pub struct rns_identity::announce::AnnounceData
|
||||
pub rns_identity::announce::AnnounceData::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_identity::announce::AnnounceData::name_hash: [u8; 10]
|
||||
pub rns_identity::announce::AnnounceData::public_key: [u8; 64]
|
||||
pub rns_identity::announce::AnnounceData::random_hash: [u8; 10]
|
||||
pub rns_identity::announce::AnnounceData::ratchet: core::option::Option<[u8; 32]>
|
||||
pub rns_identity::announce::AnnounceData::signature: [u8; 64]
|
||||
impl rns_identity::announce::AnnounceData
|
||||
pub fn rns_identity::announce::AnnounceData::check_stamp(&self, &[u8; 16], f64) -> rns_identity::announce::AnnounceStampCheck
|
||||
impl rns_identity::announce::AnnounceData
|
||||
pub fn rns_identity::announce::AnnounceData::create(&rns_identity::identity::Identity, &str, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::create_at(&rns_identity::identity::Identity, &str, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, u64) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_identity::announce::AnnounceData::unpack(&[u8], bool) -> core::result::Result<Self, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::validate(&self, &[u8; 16]) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::validate_destination_binding(&self, &[u8; 16], &rns_identity::identity::Identity, core::option::Option<&[u8; 64]>) -> core::result::Result<(), rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::validate_with_known_key(&self, &[u8; 16], core::option::Option<&[u8; 64]>) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
|
||||
pub fn rns_identity::announce::AnnounceData::verify_signature(&self, &[u8; 16]) -> core::result::Result<rns_identity::identity::Identity, rns_identity::announce::AnnounceError>
|
||||
pub struct rns_identity::announce::AnnounceExt<'a>
|
||||
pub rns_identity::announce::AnnounceExt::flags: u8
|
||||
pub rns_identity::announce::AnnounceExt::lr_cost: f64
|
||||
pub rns_identity::announce::AnnounceExt::stamp: &'a [u8; 14]
|
||||
pub struct rns_identity::announce::AnnounceStampCheck
|
||||
pub rns_identity::announce::AnnounceStampCheck::lr_cost: core::option::Option<f64>
|
||||
pub rns_identity::announce::AnnounceStampCheck::stamp: core::option::Option<[u8; 14]>
|
||||
pub rns_identity::announce::AnnounceStampCheck::stamped: bool
|
||||
pub rns_identity::announce::AnnounceStampCheck::validated: bool
|
||||
pub rns_identity::announce::AnnounceStampCheck::value: core::option::Option<f64>
|
||||
impl rns_identity::announce::AnnounceStampCheck
|
||||
pub fn rns_identity::announce::AnnounceStampCheck::app_data<'a>(&self, core::option::Option<&'a [u8]>) -> core::option::Option<&'a [u8]>
|
||||
pub struct rns_identity::announce::AnnounceStampExt
|
||||
pub rns_identity::announce::AnnounceStampExt::lr_cost: f64
|
||||
pub rns_identity::announce::AnnounceStampExt::stamp: [u8; 14]
|
||||
impl rns_identity::announce::AnnounceStampExt
|
||||
pub fn rns_identity::announce::AnnounceStampExt::encode(&self) -> core::result::Result<[u8; 18], rns_identity::stamps::StampError>
|
||||
pub const rns_identity::announce::ANNOUNCE_EXT_FLAGS: u8
|
||||
pub const rns_identity::announce::ANNOUNCE_EXT_HEADER_LENGTH: usize
|
||||
pub const rns_identity::announce::ANNOUNCE_EXT_LENGTH: usize
|
||||
pub const rns_identity::announce::ANNOUNCE_EXT_MARKER: u8
|
||||
pub const rns_identity::announce::ANNOUNCE_TIME_MAX: u64
|
||||
pub const rns_identity::announce::DESTINATION_STAMP_MATERIAL_LENGTH: usize
|
||||
pub fn rns_identity::announce::destination_stamp_material(&[u8; 16], &[u8; 64], &[u8; 10]) -> [u8; 90]
|
||||
pub fn rns_identity::announce::generate_destination_stamp(&[u8; 16], &[u8; 64], &[u8; 10], f64, &rns_identity::stamps::StampControl) -> core::result::Result<core::option::Option<([u8; 14], f64)>, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::announce::parse_announce_ext(core::option::Option<&[u8]>) -> rns_identity::announce::AnnounceExtParse<'_>
|
||||
pub mod rns_identity::announce_state
|
||||
pub struct rns_identity::announce_state::RatchetControlState
|
||||
impl rns_identity::announce_state::RatchetControlState
|
||||
pub fn rns_identity::announce_state::RatchetControlState::anchor_rotation_if_unknown(&mut self, u64)
|
||||
pub fn rns_identity::announce_state::RatchetControlState::destination_hash(&self) -> [u8; 16]
|
||||
pub fn rns_identity::announce_state::RatchetControlState::identity_hash(&self) -> [u8; 16]
|
||||
pub fn rns_identity::announce_state::RatchetControlState::last_announce_wire(&self) -> core::option::Option<u64>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::last_rotation_wall(&self) -> core::option::Option<u64>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::load_verified(&std::path::Path, &rns_identity::identity::Identity, [u8; 16]) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::new([u8; 16], [u8; 16]) -> Self
|
||||
pub fn rns_identity::announce_state::RatchetControlState::prepare_announce(&self, u64) -> core::io::error::Result<core::option::Option<Self>>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::rotation_due(&self, u64, u64) -> bool
|
||||
pub fn rns_identity::announce_state::RatchetControlState::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::announce_state::RatchetControlState::with_rotation_at(&self, u64) -> Self
|
||||
pub mod rns_identity::destination
|
||||
#[repr(u8)] pub enum rns_identity::destination::AllowPolicy
|
||||
pub rns_identity::destination::AllowPolicy::AllowAll = 1
|
||||
pub rns_identity::destination::AllowPolicy::AllowList = 2
|
||||
pub rns_identity::destination::AllowPolicy::AllowNone = 0
|
||||
pub enum rns_identity::destination::DefaultAppData
|
||||
pub rns_identity::destination::DefaultAppData::Dynamic(alloc::boxed::Box<(dyn core::ops::function::Fn() -> core::option::Option<alloc::vec::Vec<u8>> + core::marker::Send + core::marker::Sync)>)
|
||||
pub rns_identity::destination::DefaultAppData::Static(alloc::vec::Vec<u8>)
|
||||
#[repr(u8)] pub enum rns_identity::destination::DestType
|
||||
pub rns_identity::destination::DestType::Group = 1
|
||||
pub rns_identity::destination::DestType::Link = 3
|
||||
pub rns_identity::destination::DestType::Plain = 2
|
||||
pub rns_identity::destination::DestType::Single = 0
|
||||
#[non_exhaustive] pub enum rns_identity::destination::DestinationError
|
||||
pub rns_identity::destination::DestinationError::AnnounceTooLarge(usize)
|
||||
pub rns_identity::destination::DestinationError::DecryptionFailed
|
||||
pub rns_identity::destination::DestinationError::EncryptionUnavailable
|
||||
pub rns_identity::destination::DestinationError::Identity(rns_identity::identity::IdentityError)
|
||||
pub rns_identity::destination::DestinationError::IdentityMismatch
|
||||
pub rns_identity::destination::DestinationError::InvalidAnnounceTime(f64)
|
||||
pub rns_identity::destination::DestinationError::InvalidGroupKeyLength(usize)
|
||||
pub rns_identity::destination::DestinationError::InvalidLinkCost(f64)
|
||||
pub rns_identity::destination::DestinationError::InvalidNameComponent(alloc::string::String)
|
||||
pub rns_identity::destination::DestinationError::MissingIdentity
|
||||
pub rns_identity::destination::DestinationError::NotGroup
|
||||
pub rns_identity::destination::DestinationError::NotInbound
|
||||
pub rns_identity::destination::DestinationError::NotSingle
|
||||
pub rns_identity::destination::DestinationError::OutboundMissingIdentity
|
||||
pub rns_identity::destination::DestinationError::PlainWithIdentity
|
||||
pub rns_identity::destination::DestinationError::ProveNotSingle
|
||||
pub rns_identity::destination::DestinationError::SigningUnavailable
|
||||
pub enum rns_identity::destination::DestinationPacketError
|
||||
pub rns_identity::destination::DestinationPacketError::Destination(rns_identity::destination::DestinationError)
|
||||
pub rns_identity::destination::DestinationPacketError::LinkRuntimeRequired
|
||||
pub rns_identity::destination::DestinationPacketError::LrproofRequiresLink
|
||||
pub rns_identity::destination::DestinationPacketError::MissingIdentity
|
||||
pub rns_identity::destination::DestinationPacketError::MissingTransportId
|
||||
pub rns_identity::destination::DestinationPacketError::Packet(rns_wire::packet::PacketError)
|
||||
pub enum rns_identity::destination::Direction
|
||||
pub rns_identity::destination::Direction::In
|
||||
pub rns_identity::destination::Direction::Out
|
||||
#[repr(u8)] pub enum rns_identity::destination::ProofStrategy
|
||||
pub rns_identity::destination::ProofStrategy::ProveAll = 35
|
||||
pub rns_identity::destination::ProofStrategy::ProveApp = 34
|
||||
pub rns_identity::destination::ProofStrategy::ProveNone = 33
|
||||
pub struct rns_identity::destination::AnnounceTime
|
||||
pub rns_identity::destination::AnnounceTime::cache: f64
|
||||
pub rns_identity::destination::AnnounceTime::wire: u64
|
||||
impl rns_identity::destination::AnnounceTime
|
||||
pub fn rns_identity::destination::AnnounceTime::new(u64, f64) -> core::result::Result<Self, rns_identity::destination::DestinationError>
|
||||
pub struct rns_identity::destination::Destination
|
||||
pub rns_identity::destination::Destination::accept_link_requests: bool
|
||||
pub rns_identity::destination::Destination::app_name: alloc::string::String
|
||||
pub rns_identity::destination::Destination::dest_type: rns_identity::destination::DestType
|
||||
pub rns_identity::destination::Destination::direction: rns_identity::destination::Direction
|
||||
pub rns_identity::destination::Destination::hash: [u8; 16]
|
||||
pub rns_identity::destination::Destination::identity_hash: core::option::Option<[u8; 16]>
|
||||
pub rns_identity::destination::Destination::links: alloc::vec::Vec<[u8; 16]>
|
||||
pub rns_identity::destination::Destination::local_ratchet_pub: core::option::Option<[u8; 32]>
|
||||
pub rns_identity::destination::Destination::name: alloc::string::String
|
||||
pub rns_identity::destination::Destination::name_hash: [u8; 10]
|
||||
pub rns_identity::destination::Destination::only_validate_signature: bool
|
||||
pub rns_identity::destination::Destination::proof_strategy: rns_identity::destination::ProofStrategy
|
||||
pub rns_identity::destination::Destination::ratchets_enabled: bool
|
||||
pub rns_identity::destination::Destination::ratchets_enforced: bool
|
||||
pub rns_identity::destination::Destination::remote_ratchet_pub: core::option::Option<[u8; 32]>
|
||||
impl rns_identity::destination::Destination
|
||||
pub const rns_identity::destination::Destination::PR_TAG_WINDOW: f64
|
||||
pub const rns_identity::destination::Destination::RATCHET_COUNT: usize
|
||||
pub const rns_identity::destination::Destination::RATCHET_INTERVAL: u64
|
||||
pub fn rns_identity::destination::Destination::accepts_links(&self) -> bool
|
||||
pub fn rns_identity::destination::Destination::announce_packet(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>, f64) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::announce_packet_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::announce_packet_with_ext_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, bool, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime, core::option::Option<&rns_identity::announce::AnnounceStampExt>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::announce_stamp_ext(&self, f64) -> core::option::Option<rns_identity::announce::AnnounceStampExt>
|
||||
pub fn rns_identity::destination::Destination::app_and_aspects_from_name(&str) -> (&str, alloc::vec::Vec<&str>)
|
||||
pub fn rns_identity::destination::Destination::auto_identity(&self) -> core::option::Option<&rns_identity::identity::Identity>
|
||||
pub fn rns_identity::destination::Destination::cached_path_response_packet(&mut self, &[u8], f64) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::check_request_allowed(&self, &[u8; 16], core::option::Option<&[u8; 16]>) -> bool
|
||||
pub fn rns_identity::destination::Destination::clear_default_app_data(&mut self)
|
||||
pub fn rns_identity::destination::Destination::compute_hash(&[u8; 10], core::option::Option<&[u8; 16]>) -> [u8; 16]
|
||||
pub fn rns_identity::destination::Destination::create_announce(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, core::option::Option<&[u8]>, f64) -> core::result::Result<(alloc::vec::Vec<u8>, bool), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::create_announce_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime) -> core::result::Result<(alloc::vec::Vec<u8>, bool), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::create_announce_with_ext_at(&mut self, &rns_identity::identity::Identity, core::option::Option<&[u8]>, core::option::Option<&[u8; 32]>, core::option::Option<&[u8]>, rns_identity::destination::AnnounceTime, core::option::Option<&rns_identity::announce::AnnounceStampExt>) -> core::result::Result<(alloc::vec::Vec<u8>, bool), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::decrypt(&self, &[u8], &rns_identity::identity::Identity) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::decrypt_with_ratchet_id(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<rns_identity::identity::DecryptionResult, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::decrypt_with_ratchets(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::deregister_request_handler(&mut self, &str) -> bool
|
||||
pub fn rns_identity::destination::Destination::destination_stamp(&self) -> core::option::Option<([u8; 14], f64)>
|
||||
pub fn rns_identity::destination::Destination::destination_stamp_meets(&self, f64) -> bool
|
||||
pub fn rns_identity::destination::Destination::disable_ratchets(&mut self)
|
||||
pub fn rns_identity::destination::Destination::enable_ratchets(&mut self, bool)
|
||||
pub fn rns_identity::destination::Destination::encrypt(&self, &[u8], &rns_identity::identity::Identity, core::option::Option<&[u8; 32]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::expand_name(core::option::Option<&rns_identity::identity::Identity>, &str, &[&str]) -> core::result::Result<alloc::string::String, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::generate_group_key(&mut self) -> core::result::Result<(), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::get_ratchet_for_announce(&self) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::destination::Destination::get_request_handler(&self, &[u8; 16]) -> core::option::Option<&rns_identity::destination::RequestHandler>
|
||||
pub fn rns_identity::destination::Destination::group_key(&self) -> core::result::Result<&[u8], rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::hash_from_name_and_identity(&str, core::option::Option<&[u8; 16]>) -> [u8; 16]
|
||||
pub fn rns_identity::destination::Destination::hex_hash(&self) -> alloc::string::String
|
||||
pub fn rns_identity::destination::Destination::hexhash(&self) -> alloc::string::String
|
||||
pub fn rns_identity::destination::Destination::incoming_link_request(&mut self, [u8; 16]) -> bool
|
||||
pub fn rns_identity::destination::Destination::link_cost(&self, f64) -> f64
|
||||
pub fn rns_identity::destination::Destination::link_count(&self) -> usize
|
||||
pub fn rns_identity::destination::Destination::load_group_key(&mut self, &[u8]) -> core::result::Result<(), rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::new(core::option::Option<&rns_identity::identity::Identity>, rns_identity::destination::Direction, rns_identity::destination::DestType, &str) -> core::result::Result<Self, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::new_with_aspects(core::option::Option<&rns_identity::identity::Identity>, rns_identity::destination::Direction, rns_identity::destination::DestType, &str, &[&str]) -> core::result::Result<Self, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::on_link_established(&self, [u8; 16])
|
||||
pub fn rns_identity::destination::Destination::pack_packet(&self, &[u8], core::option::Option<&rns_identity::identity::Identity>, core::option::Option<&[u8; 32]>, rns_identity::destination::DestinationPacketOptions) -> core::result::Result<rns_identity::destination::PackedDestinationPacket, rns_identity::destination::DestinationPacketError>
|
||||
pub fn rns_identity::destination::Destination::prove(&self, &[u8], &rns_identity::identity::Identity, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::ratchets_active(&self) -> bool
|
||||
pub fn rns_identity::destination::Destination::receive(&self, u8, &[u8], &rns_identity::identity::Identity) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::receive_packet(&self, u8, &[u8], &[u8], &rns_identity::identity::Identity) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::receive_packet_with_ratchets(&self, u8, &[u8], &[u8], &rns_identity::identity::Identity, core::option::Option<&[[u8; 32]]>) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::register_request_handler(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool) -> bool
|
||||
pub fn rns_identity::destination::Destination::remove_link(&mut self, &[u8; 16])
|
||||
pub fn rns_identity::destination::Destination::resolve_app_data(&self) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_identity::destination::Destination::set_accepts_links(&mut self, bool)
|
||||
pub fn rns_identity::destination::Destination::set_default_app_data(&mut self, rns_identity::destination::DefaultAppData)
|
||||
pub fn rns_identity::destination::Destination::set_destination_stamp(&mut self, [u8; 14], f64)
|
||||
pub fn rns_identity::destination::Destination::set_group_key(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_identity::destination::Destination::set_link_cost(&mut self, f64)
|
||||
pub fn rns_identity::destination::Destination::set_link_established_callback(&mut self, rns_identity::destination::LinkEstablishedCallback)
|
||||
pub fn rns_identity::destination::Destination::set_local_ratchet(&mut self, [u8; 32])
|
||||
pub fn rns_identity::destination::Destination::set_only_validate_signature(&mut self, bool)
|
||||
pub fn rns_identity::destination::Destination::set_packet_callback(&mut self, rns_identity::destination::PacketCallback)
|
||||
pub fn rns_identity::destination::Destination::set_proof_requested_callback(&mut self, rns_identity::destination::ProofRequestedCallback)
|
||||
pub fn rns_identity::destination::Destination::set_proof_strategy(&mut self, rns_identity::destination::ProofStrategy)
|
||||
pub fn rns_identity::destination::Destination::set_remote_ratchet(&mut self, [u8; 32])
|
||||
pub fn rns_identity::destination::Destination::set_value(&mut self, f64, f64)
|
||||
pub fn rns_identity::destination::Destination::should_prove(&self, &[u8]) -> bool
|
||||
pub fn rns_identity::destination::Destination::sign(&self, &[u8], &rns_identity::identity::Identity) -> core::result::Result<[u8; 64], rns_identity::destination::DestinationError>
|
||||
pub fn rns_identity::destination::Destination::stamp_material(&self, &[u8; 64]) -> [u8; 90]
|
||||
pub fn rns_identity::destination::Destination::take_auto_identity(&mut self) -> core::option::Option<rns_identity::identity::Identity>
|
||||
pub fn rns_identity::destination::Destination::target_value(&self, f64) -> f64
|
||||
impl core::fmt::Display for rns_identity::destination::Destination
|
||||
pub fn rns_identity::destination::Destination::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_identity::destination::DestinationPacketOptions
|
||||
pub rns_identity::destination::DestinationPacketOptions::context: rns_wire::context::PacketContext
|
||||
pub rns_identity::destination::DestinationPacketOptions::context_flag: bool
|
||||
pub rns_identity::destination::DestinationPacketOptions::header_type: rns_wire::flags::HeaderType
|
||||
pub rns_identity::destination::DestinationPacketOptions::packet_type: rns_wire::flags::PacketType
|
||||
pub rns_identity::destination::DestinationPacketOptions::transport_id: core::option::Option<[u8; 16]>
|
||||
pub rns_identity::destination::DestinationPacketOptions::transport_type: rns_wire::flags::TransportType
|
||||
impl core::default::Default for rns_identity::destination::DestinationPacketOptions
|
||||
pub fn rns_identity::destination::DestinationPacketOptions::default() -> Self
|
||||
pub struct rns_identity::destination::PackedDestinationPacket
|
||||
pub rns_identity::destination::PackedDestinationPacket::packet: rns_wire::packet::Packet
|
||||
pub rns_identity::destination::PackedDestinationPacket::ratchet_id: core::option::Option<[u8; 10]>
|
||||
pub struct rns_identity::destination::RequestHandler
|
||||
pub rns_identity::destination::RequestHandler::allow: rns_identity::destination::AllowPolicy
|
||||
pub rns_identity::destination::RequestHandler::allowed_list: alloc::vec::Vec<[u8; 16]>
|
||||
pub rns_identity::destination::RequestHandler::auto_compress: bool
|
||||
pub rns_identity::destination::RequestHandler::path: alloc::string::String
|
||||
pub const rns_identity::destination::DESTINATION_STAMP_EXTENSION: &str
|
||||
pub const rns_identity::destination::GROUP_KEY_LENGTH: usize
|
||||
pub const rns_identity::destination::PR_TAG_WINDOW: f64
|
||||
pub const rns_identity::destination::STAMP_FILE_VERSION: u64
|
||||
pub fn rns_identity::destination::destination_stamp_path(&std::path::Path, &[u8; 16]) -> std::path::PathBuf
|
||||
pub fn rns_identity::destination::load_destination_stamp(&std::path::Path, &[u8; 16], &[u8], f64) -> core::option::Option<([u8; 14], f64)>
|
||||
pub fn rns_identity::destination::store_destination_stamp(&std::path::Path, &[u8; 16], &[u8; 14], f64) -> core::io::error::Result<()>
|
||||
pub type rns_identity::destination::LinkEstablishedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn([u8; 16]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_identity::destination::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8], &[u8]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_identity::destination::ProofRequestedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) -> bool + core::marker::Send + core::marker::Sync)>
|
||||
pub mod rns_identity::identity
|
||||
pub enum rns_identity::identity::IdentityError
|
||||
pub rns_identity::identity::IdentityError::DecryptionFailed
|
||||
pub rns_identity::identity::IdentityError::Ed25519(rns_crypto::ed25519::Ed25519Error)
|
||||
pub rns_identity::identity::IdentityError::EncryptionFailed
|
||||
pub rns_identity::identity::IdentityError::InvalidPrivateKeyLength(usize)
|
||||
pub rns_identity::identity::IdentityError::InvalidPublicKeyLength(usize)
|
||||
pub rns_identity::identity::IdentityError::Io(core::io::error::Error)
|
||||
pub rns_identity::identity::IdentityError::VerificationFailed
|
||||
pub struct rns_identity::identity::DecryptionResult
|
||||
pub rns_identity::identity::DecryptionResult::plaintext: alloc::vec::Vec<u8>
|
||||
pub rns_identity::identity::DecryptionResult::ratchet_id: core::option::Option<[u8; 10]>
|
||||
pub struct rns_identity::identity::Identity
|
||||
pub rns_identity::identity::Identity::hash: [u8; 16]
|
||||
impl rns_identity::identity::Identity
|
||||
pub const rns_identity::identity::Identity::CURVE: &'static str
|
||||
pub const rns_identity::identity::Identity::HASH_LENGTH_BITS: usize
|
||||
pub const rns_identity::identity::Identity::KEY_SIZE_BITS: usize
|
||||
pub const rns_identity::identity::Identity::RATCHETSIZE: usize
|
||||
pub const rns_identity::identity::Identity::RATCHET_SIZE_BITS: usize
|
||||
pub fn rns_identity::identity::Identity::decrypt(&self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::decrypt_with_ratchet_id(&self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<rns_identity::identity::DecryptionResult, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::encrypt(&self, &[u8], core::option::Option<&[u8; 32]>) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_backend(&[u8], alloc::sync::Arc<dyn rns_identity::identity::LocalKeyBackend>) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_file(&std::path::Path) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_private_key(&[u8]) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::from_public_key(&[u8]) -> core::result::Result<Self, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::get_private_key(&self) -> core::option::Option<zeroize::Zeroizing<[u8; 64]>>
|
||||
pub fn rns_identity::identity::Identity::get_public_key(&self) -> [u8; 64]
|
||||
pub fn rns_identity::identity::Identity::get_signing_key(&self) -> core::option::Option<rns_crypto::ed25519::Ed25519PrivateKey>
|
||||
pub fn rns_identity::identity::Identity::get_value(&self) -> f64
|
||||
pub fn rns_identity::identity::Identity::has_backend(&self) -> bool
|
||||
pub fn rns_identity::identity::Identity::has_private_key(&self) -> bool
|
||||
pub fn rns_identity::identity::Identity::hexhash(&self) -> alloc::string::String
|
||||
pub fn rns_identity::identity::Identity::lock(&self)
|
||||
pub fn rns_identity::identity::Identity::new() -> Self
|
||||
pub fn rns_identity::identity::Identity::new_with_value(f64, &rns_identity::stamps::StampControl) -> core::result::Result<core::option::Option<Self>, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::identity::Identity::prove(&self, &[u8], bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::pub_to_file(&self, &std::path::Path) -> core::result::Result<(), rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::ratchet_id(&[u8; 32]) -> [u8; 10]
|
||||
pub fn rns_identity::identity::Identity::sign(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_identity::identity::Identity::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_identity::identity::IdentityError>
|
||||
pub fn rns_identity::identity::Identity::verify(&self, &[u8], &[u8; 64]) -> bool
|
||||
impl core::clone::Clone for rns_identity::identity::Identity
|
||||
pub fn rns_identity::identity::Identity::clone(&self) -> Self
|
||||
impl core::default::Default for rns_identity::identity::Identity
|
||||
pub fn rns_identity::identity::Identity::default() -> Self
|
||||
impl core::fmt::Display for rns_identity::identity::Identity
|
||||
pub fn rns_identity::identity::Identity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub const rns_identity::identity::CURVE: &str
|
||||
pub const rns_identity::identity::DERIVED_KEY_LENGTH: usize
|
||||
pub const rns_identity::identity::HASH_LENGTH_BITS: usize
|
||||
pub const rns_identity::identity::IDENTITY_OVERHEAD: usize
|
||||
pub const rns_identity::identity::KEY_SIZE_BITS: usize
|
||||
pub const rns_identity::identity::RATCHETSIZE: usize
|
||||
pub const rns_identity::identity::RATCHET_ID_LENGTH: usize
|
||||
pub const rns_identity::identity::RATCHET_SIZE_BITS: usize
|
||||
pub trait rns_identity::identity::LocalKeyBackend: core::marker::Send + core::marker::Sync
|
||||
pub fn rns_identity::identity::LocalKeyBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::identity::LocalKeyBackend::lock(&self)
|
||||
pub fn rns_identity::identity::LocalKeyBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub mod rns_identity::ifac
|
||||
pub enum rns_identity::ifac::IfacError
|
||||
pub rns_identity::ifac::IfacError::HkdfFailed(rns_crypto::hkdf::HkdfError)
|
||||
pub rns_identity::ifac::IfacError::InvalidSalt
|
||||
pub struct rns_identity::ifac::IfacKey(_)
|
||||
impl rns_identity::ifac::IfacKey
|
||||
pub fn rns_identity::ifac::IfacKey::derive(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<Self, rns_identity::ifac::IfacError>
|
||||
impl core::cmp::Eq for rns_identity::ifac::IfacKey
|
||||
impl core::cmp::PartialEq for rns_identity::ifac::IfacKey
|
||||
pub fn rns_identity::ifac::IfacKey::eq(&self, &Self) -> bool
|
||||
impl core::convert::From<[u8; 64]> for rns_identity::ifac::IfacKey
|
||||
pub fn rns_identity::ifac::IfacKey::from([u8; 64]) -> Self
|
||||
impl core::fmt::Debug for rns_identity::ifac::IfacKey
|
||||
pub fn rns_identity::ifac::IfacKey::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_identity::ifac::IfacKey
|
||||
pub type rns_identity::ifac::IfacKey::Target = [u8; 64]
|
||||
pub fn rns_identity::ifac::IfacKey::deref(&self) -> &[u8; 64]
|
||||
pub const rns_identity::ifac::IFAC_SALT: &str
|
||||
pub fn rns_identity::ifac::derive_ifac_identity(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<(rns_identity::identity::Identity, [u8; 64], [u8; 64]), rns_identity::ifac::IfacError>
|
||||
pub fn rns_identity::ifac::derive_ifac_key(core::option::Option<&str>, core::option::Option<&str>) -> core::result::Result<[u8; 64], rns_identity::ifac::IfacError>
|
||||
pub fn rns_identity::ifac::ifac_signature(&[u8; 64]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_identity::ifac::split_ifac_key(&[u8; 64]) -> (&[u8], &[u8])
|
||||
pub mod rns_identity::known_destinations
|
||||
pub struct rns_identity::known_destinations::KnownDestination
|
||||
pub rns_identity::known_destinations::KnownDestination::app_data: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_identity::known_destinations::KnownDestination::packet_hash: [u8; 32]
|
||||
pub rns_identity::known_destinations::KnownDestination::public_key: [u8; 64]
|
||||
pub rns_identity::known_destinations::KnownDestination::retained: bool
|
||||
pub rns_identity::known_destinations::KnownDestination::timestamp: f64
|
||||
pub struct rns_identity::known_destinations::KnownDestinations
|
||||
impl rns_identity::known_destinations::KnownDestinations
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::cleanup(&mut self, f64, f64, impl core::ops::function::Fn(&[u8; 16]) -> bool) -> alloc::vec::Vec<[u8; 16]>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::contains(&self, &[u8; 16]) -> bool
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::get(&self, &[u8; 16]) -> core::option::Option<&rns_identity::known_destinations::KnownDestination>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::is_empty(&self) -> bool
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::is_known_or_registered(&self, &[u8; 16], &std::collections::hash::set::HashSet<[u8; 16]>) -> bool
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::iter(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&[u8; 16], &rns_identity::known_destinations::KnownDestination)>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::len(&self) -> usize
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::load(&std::path::Path) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::merge(&mut self, &rns_identity::known_destinations::KnownDestinations)
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::new() -> Self
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::recall_app_data(&self, &[u8; 16]) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::recall_by_identity(&self, &[u8; 16]) -> core::option::Option<(&[u8; 16], &rns_identity::known_destinations::KnownDestination)>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::remember(&mut self, [u8; 16], f64, [u8; 32], [u8; 64], core::option::Option<alloc::vec::Vec<u8>>)
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_identity::known_destinations::KnownDestination>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::retain(&mut self, &[u8; 16])
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::retain_identity(&mut self, &[u8; 16]) -> usize
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::save(&self, &std::path::Path) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::unretain(&mut self, &[u8; 16])
|
||||
impl core::default::Default for rns_identity::known_destinations::KnownDestinations
|
||||
pub fn rns_identity::known_destinations::KnownDestinations::default() -> Self
|
||||
pub mod rns_identity::name_hash
|
||||
pub fn rns_identity::name_hash::name_hash(&str) -> [u8; 10]
|
||||
pub mod rns_identity::persistence
|
||||
pub enum rns_identity::persistence::DurableCleanupOutcome
|
||||
pub rns_identity::persistence::DurableCleanupOutcome::AlreadyAbsent
|
||||
pub rns_identity::persistence::DurableCleanupOutcome::Removed
|
||||
pub enum rns_identity::persistence::DurableCommitPhase
|
||||
pub rns_identity::persistence::DurableCommitPhase::CommitUncertain
|
||||
pub rns_identity::persistence::DurableCommitPhase::NotCommitted
|
||||
pub enum rns_identity::persistence::DurableErrorKind
|
||||
pub rns_identity::persistence::DurableErrorKind::DurabilityUnsupported
|
||||
pub rns_identity::persistence::DurableErrorKind::InvalidInput
|
||||
pub rns_identity::persistence::DurableErrorKind::Io
|
||||
pub rns_identity::persistence::DurableErrorKind::Verification
|
||||
#[non_exhaustive] pub enum rns_identity::persistence::StorageRisk
|
||||
pub rns_identity::persistence::StorageRisk::Remote
|
||||
pub rns_identity::persistence::StorageRisk::Volatile
|
||||
impl core::fmt::Display for rns_identity::persistence::StorageRisk
|
||||
pub fn rns_identity::persistence::StorageRisk::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_identity::persistence::DurableDirectoryReceipt
|
||||
impl rns_identity::persistence::DurableDirectoryReceipt
|
||||
pub fn rns_identity::persistence::DurableDirectoryReceipt::path(&self) -> &std::path::Path
|
||||
pub struct rns_identity::persistence::DurableFileReceipt
|
||||
impl rns_identity::persistence::DurableFileReceipt
|
||||
pub fn rns_identity::persistence::DurableFileReceipt::content_hash(&self) -> [u8; 32]
|
||||
pub fn rns_identity::persistence::DurableFileReceipt::is_empty(&self) -> bool
|
||||
pub fn rns_identity::persistence::DurableFileReceipt::len(&self) -> usize
|
||||
pub fn rns_identity::persistence::DurableFileReceipt::path(&self) -> &std::path::Path
|
||||
pub struct rns_identity::persistence::DurableWriteError
|
||||
pub rns_identity::persistence::DurableWriteError::kind: rns_identity::persistence::DurableErrorKind
|
||||
pub rns_identity::persistence::DurableWriteError::phase: rns_identity::persistence::DurableCommitPhase
|
||||
pub rns_identity::persistence::DurableWriteError::recovery_paths: alloc::vec::Vec<std::path::PathBuf>
|
||||
pub fn rns_identity::persistence::atomic_write(&std::path::Path, &[u8]) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::persistence::durable_create_dir_all(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
|
||||
pub fn rns_identity::persistence::durable_reconcile(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
|
||||
pub fn rns_identity::persistence::durable_reconcile_directory(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
|
||||
pub fn rns_identity::persistence::durable_reconcile_hash(&std::path::Path, [u8; 32], usize) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
|
||||
pub fn rns_identity::persistence::durable_remove(&std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableCleanupOutcome, rns_identity::persistence::DurableWriteError>
|
||||
pub fn rns_identity::persistence::durable_rename_directory(&std::path::Path, &std::path::Path, &rns_identity::persistence::DurableFileReceipt) -> core::result::Result<rns_identity::persistence::DurableDirectoryReceipt, rns_identity::persistence::DurableWriteError>
|
||||
pub fn rns_identity::persistence::durable_write(&std::path::Path, &[u8]) -> core::result::Result<rns_identity::persistence::DurableFileReceipt, rns_identity::persistence::DurableWriteError>
|
||||
pub fn rns_identity::persistence::read_file(&std::path::Path) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub fn rns_identity::persistence::read_file_bounded(&std::path::Path, usize) -> core::io::error::Result<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub fn rns_identity::persistence::read_secret_file(&std::path::Path, usize) -> core::io::error::Result<zeroize::Zeroizing<alloc::vec::Vec<u8>>>
|
||||
pub fn rns_identity::persistence::storage_risk(&std::path::Path) -> core::io::error::Result<core::option::Option<rns_identity::persistence::StorageRisk>>
|
||||
pub fn rns_identity::persistence::try_lock_exclusive(&std::fs::File) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::persistence::validate_durable_storage_directory(&std::path::Path) -> core::result::Result<(), rns_identity::persistence::DurableWriteError>
|
||||
pub mod rns_identity::ratchet
|
||||
pub enum rns_identity::ratchet::RatchetRingFormat
|
||||
pub rns_identity::ratchet::RatchetRingFormat::Canonical
|
||||
pub rns_identity::ratchet::RatchetRingFormat::LegacyRust
|
||||
pub struct rns_identity::ratchet::LoadedRatchetRing
|
||||
impl rns_identity::ratchet::LoadedRatchetRing
|
||||
pub fn rns_identity::ratchet::LoadedRatchetRing::format(&self) -> rns_identity::ratchet::RatchetRingFormat
|
||||
pub fn rns_identity::ratchet::LoadedRatchetRing::into_ring(self) -> rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::LoadedRatchetRing::ring(&self) -> &rns_identity::ratchet::RatchetRing
|
||||
pub struct rns_identity::ratchet::PersistentRatchetRing
|
||||
impl rns_identity::ratchet::PersistentRatchetRing
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::current_public_key(&self) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::ensure_current(&mut self, &rns_identity::identity::Identity) -> core::io::error::Result<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::ensure_current_at(&mut self, &rns_identity::identity::Identity, f64) -> core::io::error::Result<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::is_empty(&self) -> bool
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::len(&self) -> usize
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::open(impl core::convert::AsRef<std::path::Path>, &rns_identity::identity::Identity) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::path(&self) -> &std::path::Path
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::private_keys(&self) -> &[[u8; 32]]
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::reload(&mut self, &rns_identity::identity::Identity) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::ring(&self) -> &rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::rotate(&mut self, &rns_identity::identity::Identity) -> core::io::error::Result<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::rotate_at(&mut self, &rns_identity::identity::Identity, f64) -> core::io::error::Result<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::set_ratchet_interval(&mut self, u64) -> bool
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::set_retained_ratchets(&mut self, usize) -> bool
|
||||
impl core::fmt::Debug for rns_identity::ratchet::PersistentRatchetRing
|
||||
pub fn rns_identity::ratchet::PersistentRatchetRing::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_identity::ratchet::PreparedRatchetRotation
|
||||
impl rns_identity::ratchet::PreparedRatchetRotation
|
||||
pub fn rns_identity::ratchet::PreparedRatchetRotation::public_key(&self) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::PreparedRatchetRotation::ring(&self) -> &rns_identity::ratchet::RatchetRing
|
||||
pub struct rns_identity::ratchet::RatchetRing
|
||||
impl rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::anchor_rotation_at(&mut self, f64) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::commit_prepared_rotation(&mut self, rns_identity::ratchet::PreparedRatchetRotation) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::RatchetRing::current_public_key(&self) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_identity::ratchet::RatchetRing::is_empty(&self) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::last_rotation(&self) -> f64
|
||||
pub fn rns_identity::ratchet::RatchetRing::len(&self) -> usize
|
||||
pub fn rns_identity::ratchet::RatchetRing::load(&std::path::Path) -> core::io::error::Result<(Self, [u8; 64])>
|
||||
pub fn rns_identity::ratchet::RatchetRing::load_verified(&std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<rns_identity::ratchet::LoadedRatchetRing>
|
||||
pub fn rns_identity::ratchet::RatchetRing::needs_rotation(&self) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::needs_rotation_at(&self, f64) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::new() -> Self
|
||||
pub fn rns_identity::ratchet::RatchetRing::prepare_rotation_at(&self, f64) -> rns_identity::ratchet::PreparedRatchetRotation
|
||||
pub fn rns_identity::ratchet::RatchetRing::private_keys(&self) -> &[[u8; 32]]
|
||||
pub fn rns_identity::ratchet::RatchetRing::ratchet_interval(&self) -> u64
|
||||
pub fn rns_identity::ratchet::RatchetRing::retained_ratchets(&self) -> usize
|
||||
pub fn rns_identity::ratchet::RatchetRing::rotate(&mut self) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::RatchetRing::rotate_at(&mut self, f64) -> [u8; 32]
|
||||
pub fn rns_identity::ratchet::RatchetRing::save(&self, &std::path::Path, &[u8; 64]) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::ratchet::RatchetRing::save_verified(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::ratchet::RatchetRing::save_verified_durable(&self, &std::path::Path, &rns_identity::identity::Identity) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::ratchet::RatchetRing::set_ratchet_interval(&mut self, u64) -> bool
|
||||
pub fn rns_identity::ratchet::RatchetRing::set_retained_ratchets(&mut self, usize) -> bool
|
||||
impl core::default::Default for rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::default() -> Self
|
||||
impl core::ops::drop::Drop for rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_identity::ratchet::RatchetRing
|
||||
pub fn rns_identity::ratchet::RatchetRing::zeroize(&mut self)
|
||||
pub struct rns_identity::ratchet::ReceivedRatchet
|
||||
pub rns_identity::ratchet::ReceivedRatchet::ratchet_pub: [u8; 32]
|
||||
pub rns_identity::ratchet::ReceivedRatchet::received_at: f64
|
||||
impl rns_identity::ratchet::ReceivedRatchet
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::is_expired(&self) -> bool
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::is_expired_at(&self, f64) -> bool
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::load(&std::path::Path) -> core::io::error::Result<Self>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::new([u8; 32]) -> Self
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::new_at([u8; 32], f64) -> Self
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::ratchet_id(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::save(&self, &std::path::Path) -> core::io::error::Result<()>
|
||||
pub fn rns_identity::ratchet::ReceivedRatchet::save_durable(&self, &std::path::Path) -> core::io::error::Result<()>
|
||||
pub const rns_identity::ratchet::RATCHET_RING_MAX_KEYS: usize
|
||||
pub fn rns_identity::ratchet::clean_received_ratchets_dir(&std::path::Path) -> usize
|
||||
pub fn rns_identity::ratchet::get_ratchet_id(&[u8; 32]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_identity::ratchet::purge_expired_ratchets_in_memory<K: core::cmp::Eq + core::hash::Hash>(&mut std::collections::hash::map::HashMap<K, rns_identity::ratchet::ReceivedRatchet>) -> usize
|
||||
pub fn rns_identity::ratchet::ratchet_public_bytes(&[u8; 32]) -> [u8; 32]
|
||||
pub mod rns_identity::stamps
|
||||
pub enum rns_identity::stamps::StampError
|
||||
pub rns_identity::stamps::StampError::FpOutOfRange(u16)
|
||||
pub rns_identity::stamps::StampError::InvalidCost(f64)
|
||||
pub rns_identity::stamps::StampError::NonFiniteCost
|
||||
pub struct rns_identity::stamps::StampControl
|
||||
pub rns_identity::stamps::StampControl::cancel: alloc::sync::Arc<core::sync::atomic::AtomicBool>
|
||||
pub rns_identity::stamps::StampControl::deadline: core::option::Option<std::time::Instant>
|
||||
pub rns_identity::stamps::StampControl::threads: core::num::nonzero::NonZeroUsize
|
||||
impl core::default::Default for rns_identity::stamps::StampControl
|
||||
pub fn rns_identity::stamps::StampControl::default() -> Self
|
||||
pub struct rns_identity::stamps::StampTarget(_)
|
||||
impl rns_identity::stamps::StampTarget
|
||||
pub fn rns_identity::stamps::StampTarget::accepts(&self, &[u8; 32]) -> bool
|
||||
pub fn rns_identity::stamps::StampTarget::to_be_bytes(&self) -> [u8; 33]
|
||||
pub struct rns_identity::stamps::StampWorkers
|
||||
pub rns_identity::stamps::StampWorkers::max_workers: core::option::Option<core::num::nonzero::NonZeroUsize>
|
||||
pub rns_identity::stamps::StampWorkers::niceness: u8
|
||||
impl rns_identity::stamps::StampWorkers
|
||||
pub fn rns_identity::stamps::StampWorkers::cap(&self, core::num::nonzero::NonZeroUsize) -> core::num::nonzero::NonZeroUsize
|
||||
pub fn rns_identity::stamps::StampWorkers::clamp_max_workers(i64) -> core::num::nonzero::NonZeroUsize
|
||||
pub fn rns_identity::stamps::StampWorkers::clamp_niceness(i64) -> u8
|
||||
pub fn rns_identity::stamps::StampWorkers::current() -> Self
|
||||
pub fn rns_identity::stamps::StampWorkers::install(self)
|
||||
impl core::default::Default for rns_identity::stamps::StampWorkers
|
||||
pub fn rns_identity::stamps::StampWorkers::default() -> Self
|
||||
pub struct rns_identity::stamps::StampedKey
|
||||
pub rns_identity::stamps::StampedKey::private: rns_crypto::x25519::X25519PrivateKey
|
||||
pub rns_identity::stamps::StampedKey::public: [u8; 32]
|
||||
pub rns_identity::stamps::StampedKey::value: f64
|
||||
pub const rns_identity::stamps::COST_FP: u32
|
||||
pub const rns_identity::stamps::COST_FP_BITS: u32
|
||||
pub const rns_identity::stamps::DEFAULT_WORKER_NICENESS: u8
|
||||
pub const rns_identity::stamps::LINK_COST_CAP: f64
|
||||
pub const rns_identity::stamps::MANTISSA_BITS: u32
|
||||
pub const rns_identity::stamps::MAX_VALUE_FP: u32
|
||||
pub const rns_identity::stamps::MAX_WORKER_NICENESS: u8
|
||||
pub const rns_identity::stamps::NETWORK_STAMP_SIZE: usize
|
||||
pub const rns_identity::stamps::PRM_DIGEST: &str
|
||||
pub const rns_identity::stamps::STAMP_COST_CAP: f64
|
||||
pub const rns_identity::stamps::STAMP_COST_CAP_FP: u16
|
||||
pub const rns_identity::stamps::STAMP_SIZE: usize
|
||||
pub const rns_identity::stamps::STOP_CHECK_INTERVAL: u32
|
||||
pub const rns_identity::stamps::TAB: [u64; 256]
|
||||
pub const rns_identity::stamps::TAB_DIGEST: &str
|
||||
pub const rns_identity::stamps::WORKBLOCK_EXPAND_CHUNK: usize
|
||||
pub const rns_identity::stamps::WORKBLOCK_EXPAND_ROUNDS: usize
|
||||
pub fn rns_identity::stamps::cost_from_bytes([u8; 2]) -> f64
|
||||
pub fn rns_identity::stamps::cost_from_fp(u32) -> f64
|
||||
pub fn rns_identity::stamps::cost_to_bytes(f64) -> core::result::Result<[u8; 2], rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::cost_to_fp(f64) -> core::result::Result<u16, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::fp_from_bytes([u8; 2]) -> u16
|
||||
pub fn rns_identity::stamps::fp_to_bytes(u16) -> [u8; 2]
|
||||
pub fn rns_identity::stamps::generate_stamp(&[u8], f64, usize, usize, &rns_identity::stamps::StampControl) -> core::result::Result<core::option::Option<(alloc::vec::Vec<u8>, f64)>, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::generate_stamped_key(&[u8], f64, &rns_identity::stamps::StampControl) -> core::result::Result<core::option::Option<rns_identity::stamps::StampedKey>, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::quantize_cost(f64) -> core::result::Result<f64, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::stamp_valid(&[u8], f64, &[u8]) -> core::result::Result<bool, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::stamp_valid_fp(&[u8], u16, &[u8]) -> core::result::Result<bool, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::stamp_value(&[u8], &[u8]) -> f64
|
||||
pub fn rns_identity::stamps::stamp_value_fp(&[u8], &[u8]) -> u32
|
||||
pub fn rns_identity::stamps::stamp_value_fp_from_hash(&[u8; 32]) -> u32
|
||||
pub fn rns_identity::stamps::stamp_workblock(&[u8], usize) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_identity::stamps::target_from_cost(f64) -> core::result::Result<rns_identity::stamps::StampTarget, rns_identity::stamps::StampError>
|
||||
pub fn rns_identity::stamps::target_from_fp(u16) -> core::result::Result<rns_identity::stamps::StampTarget, rns_identity::stamps::StampError>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,440 @@
|
||||
pub mod rns_link
|
||||
pub mod rns_link::clock
|
||||
pub struct rns_link::clock::ContinuousInstant(_)
|
||||
impl rns_link::clock::ContinuousInstant
|
||||
pub fn rns_link::clock::ContinuousInstant::checked_add(self, core::time::Duration) -> core::option::Option<Self>
|
||||
pub fn rns_link::clock::ContinuousInstant::checked_duration_since(self, Self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_link::clock::ContinuousInstant::checked_sub(self, core::time::Duration) -> core::option::Option<Self>
|
||||
pub fn rns_link::clock::ContinuousInstant::duration_since(self, Self) -> core::time::Duration
|
||||
pub fn rns_link::clock::ContinuousInstant::elapsed(self) -> core::time::Duration
|
||||
pub fn rns_link::clock::ContinuousInstant::now() -> Self
|
||||
pub fn rns_link::clock::ContinuousInstant::saturating_duration_since(self, Self) -> core::time::Duration
|
||||
impl core::ops::arith::Add<core::time::Duration> for rns_link::clock::ContinuousInstant
|
||||
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
|
||||
pub fn rns_link::clock::ContinuousInstant::add(self, core::time::Duration) -> Self
|
||||
impl core::ops::arith::AddAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
|
||||
pub fn rns_link::clock::ContinuousInstant::add_assign(&mut self, core::time::Duration)
|
||||
impl core::ops::arith::Sub for rns_link::clock::ContinuousInstant
|
||||
pub type rns_link::clock::ContinuousInstant::Output = core::time::Duration
|
||||
pub fn rns_link::clock::ContinuousInstant::sub(self, Self) -> core::time::Duration
|
||||
impl core::ops::arith::Sub<core::time::Duration> for rns_link::clock::ContinuousInstant
|
||||
pub type rns_link::clock::ContinuousInstant::Output = rns_link::clock::ContinuousInstant
|
||||
pub fn rns_link::clock::ContinuousInstant::sub(self, core::time::Duration) -> Self
|
||||
impl core::ops::arith::SubAssign<core::time::Duration> for rns_link::clock::ContinuousInstant
|
||||
pub fn rns_link::clock::ContinuousInstant::sub_assign(&mut self, core::time::Duration)
|
||||
pub mod rns_link::constants
|
||||
pub const rns_link::constants::ACCEPT_ALL: u8
|
||||
pub const rns_link::constants::ACCEPT_APP: u8
|
||||
pub const rns_link::constants::ACCEPT_NONE: u8
|
||||
pub const rns_link::constants::AES128_DERIVED_KEY_LENGTH: usize
|
||||
pub const rns_link::constants::AES256_DERIVED_KEY_LENGTH: usize
|
||||
pub const rns_link::constants::DEFAULT_MODE: u8
|
||||
pub const rns_link::constants::DESTINATION_CLOSED: u8
|
||||
pub const rns_link::constants::ECPUBSIZE: usize
|
||||
pub const rns_link::constants::ENABLED_MODES: &[u8]
|
||||
pub const rns_link::constants::ESTABLISHMENT_TIMEOUT_PER_HOP: f64
|
||||
pub const rns_link::constants::INITIATOR_CLOSED: u8
|
||||
pub const rns_link::constants::KEEPALIVE_DEFAULT: f64
|
||||
pub const rns_link::constants::KEEPALIVE_MAX: f64
|
||||
pub const rns_link::constants::KEEPALIVE_MAX_RTT: f64
|
||||
pub const rns_link::constants::KEEPALIVE_MIN: f64
|
||||
pub const rns_link::constants::KEEPALIVE_REQUEST: u8
|
||||
pub const rns_link::constants::KEEPALIVE_RESPONSE: u8
|
||||
pub const rns_link::constants::KEEPALIVE_SEND_MARGIN: f64
|
||||
pub const rns_link::constants::KEEPALIVE_TIMEOUT_FACTOR: f64
|
||||
pub const rns_link::constants::KEYSIZE: usize
|
||||
pub const rns_link::constants::LINK_MTU_SIZE: usize
|
||||
pub const rns_link::constants::MODE_AES128_CBC: u8
|
||||
pub const rns_link::constants::MODE_AES256_CBC: u8
|
||||
pub const rns_link::constants::MODE_AES256_GCM: u8
|
||||
pub const rns_link::constants::MODE_BYTEMASK: u32
|
||||
pub const rns_link::constants::MODE_OTP_RESERVED: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_1: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_2: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_3: u8
|
||||
pub const rns_link::constants::MODE_PQ_RESERVED_4: u8
|
||||
pub const rns_link::constants::MTU_BYTEMASK: u32
|
||||
pub const rns_link::constants::RESPONSE_MAX_GRACE_TIME: f64
|
||||
pub const rns_link::constants::STALE_FACTOR: f64
|
||||
pub const rns_link::constants::STALE_GRACE: f64
|
||||
pub const rns_link::constants::STALE_TIME_DEFAULT: f64
|
||||
pub const rns_link::constants::STAMP_FAILURE: u8
|
||||
pub const rns_link::constants::TIMEOUT: u8
|
||||
pub const rns_link::constants::TRAFFIC_TIMEOUT_FACTOR: f64
|
||||
pub const rns_link::constants::TRAFFIC_TIMEOUT_FLOOR_MS: u64
|
||||
pub const rns_link::constants::WATCHDOG_MAX_SLEEP: f64
|
||||
pub mod rns_link::encryption
|
||||
pub enum rns_link::encryption::LinkCryptoError
|
||||
pub rns_link::encryption::LinkCryptoError::DecryptionFailed
|
||||
pub rns_link::encryption::LinkCryptoError::EncryptionFailed
|
||||
pub fn rns_link::encryption::link_decrypt(&rns_link::key_derivation::LinkKeys, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::encryption::link_encrypt(&rns_link::key_derivation::LinkKeys, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub mod rns_link::handshake
|
||||
pub enum rns_link::handshake::HandshakeError
|
||||
pub rns_link::handshake::HandshakeError::InvalidLength(usize)
|
||||
pub rns_link::handshake::HandshakeError::InvalidSignature
|
||||
pub rns_link::handshake::HandshakeError::KeyDerivation(rns_link::key_derivation::LinkKeyError)
|
||||
pub rns_link::handshake::HandshakeError::MalformedRtt
|
||||
pub rns_link::handshake::HandshakeError::Signalling(rns_wire::link_signalling::LinkSignallingError)
|
||||
pub rns_link::handshake::HandshakeError::TooShort
|
||||
pub rns_link::handshake::HandshakeError::UnsupportedMode(u8)
|
||||
pub struct rns_link::handshake::EphemeralKeys
|
||||
pub rns_link::handshake::EphemeralKeys::ed25519_prv: rns_crypto::ed25519::Ed25519PrivateKey
|
||||
pub rns_link::handshake::EphemeralKeys::ed25519_pub: rns_crypto::ed25519::Ed25519PublicKey
|
||||
pub rns_link::handshake::EphemeralKeys::x25519_prv: rns_crypto::x25519::X25519PrivateKey
|
||||
pub rns_link::handshake::EphemeralKeys::x25519_pub: rns_crypto::x25519::X25519PublicKey
|
||||
impl rns_link::handshake::EphemeralKeys
|
||||
pub fn rns_link::handshake::EphemeralKeys::from_parts(rns_crypto::x25519::X25519PrivateKey, rns_crypto::ed25519::Ed25519PrivateKey) -> Self
|
||||
pub fn rns_link::handshake::EphemeralKeys::generate() -> Self
|
||||
impl core::ops::drop::Drop for rns_link::handshake::EphemeralKeys
|
||||
pub fn rns_link::handshake::EphemeralKeys::drop(&mut self)
|
||||
impl zeroize::Zeroize for rns_link::handshake::EphemeralKeys
|
||||
pub fn rns_link::handshake::EphemeralKeys::zeroize(&mut self)
|
||||
pub struct rns_link::handshake::LinkProofData
|
||||
pub rns_link::handshake::LinkProofData::responder_x25519_pub: [u8; 32]
|
||||
pub rns_link::handshake::LinkProofData::signalling: rns_wire::link_signalling::SignallingData
|
||||
pub rns_link::handshake::LinkProofData::signature: [u8; 64]
|
||||
impl rns_link::handshake::LinkProofData
|
||||
pub fn rns_link::handshake::LinkProofData::create(&rns_crypto::ed25519::Ed25519PrivateKey, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self
|
||||
pub fn rns_link::handshake::LinkProofData::create_with<F>(F, &[u8; 32], &[u8; 32], &[u8; 16], rns_wire::link_signalling::SignallingData) -> Self where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
|
||||
pub fn rns_link::handshake::LinkProofData::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_link::handshake::LinkProofData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::handshake::LinkProofData::validate(&self, &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 16], &[u8; 32]) -> bool
|
||||
pub struct rns_link::handshake::LinkRequestData
|
||||
pub rns_link::handshake::LinkRequestData::peer_ed25519_pub: [u8; 32]
|
||||
pub rns_link::handshake::LinkRequestData::peer_x25519_pub: [u8; 32]
|
||||
pub rns_link::handshake::LinkRequestData::signalling: rns_wire::link_signalling::SignallingData
|
||||
impl rns_link::handshake::LinkRequestData
|
||||
pub fn rns_link::handshake::LinkRequestData::pack(&rns_link::handshake::EphemeralKeys, rns_wire::link_signalling::SignallingData) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_link::handshake::LinkRequestData::unpack(&[u8]) -> core::result::Result<Self, rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::handshake::compute_link_id(&[u8; 16], &[u8]) -> [u8; 16]
|
||||
pub fn rns_link::handshake::compute_link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
|
||||
pub fn rns_link::handshake::perform_handshake(&rns_crypto::x25519::X25519PrivateKey, &[u8; 32], &[u8; 16], u8) -> core::result::Result<rns_link::key_derivation::LinkKeys, rns_link::key_derivation::LinkKeyError>
|
||||
pub mod rns_link::keepalive
|
||||
pub struct rns_link::keepalive::KeepaliveState
|
||||
pub rns_link::keepalive::KeepaliveState::activated_at: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::is_initiator: bool
|
||||
pub rns_link::keepalive::KeepaliveState::keepalive_interval: core::time::Duration
|
||||
pub rns_link::keepalive::KeepaliveState::last_data: std::time::Instant
|
||||
pub rns_link::keepalive::KeepaliveState::last_inbound: std::time::Instant
|
||||
pub rns_link::keepalive::KeepaliveState::last_keepalive_sent: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::last_outbound: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::last_proof: core::option::Option<std::time::Instant>
|
||||
pub rns_link::keepalive::KeepaliveState::stale_time: core::time::Duration
|
||||
impl rns_link::keepalive::KeepaliveState
|
||||
pub fn rns_link::keepalive::KeepaliveState::is_stale(&self) -> bool
|
||||
pub fn rns_link::keepalive::KeepaliveState::mark_activated(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::mark_keepalive_sent(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::new(bool) -> Self
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_data(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_inbound(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_outbound(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::record_proof(&mut self)
|
||||
pub fn rns_link::keepalive::KeepaliveState::should_send_keepalive(&self) -> bool
|
||||
pub fn rns_link::keepalive::KeepaliveState::since_inbound(&self) -> core::time::Duration
|
||||
pub fn rns_link::keepalive::KeepaliveState::stale_grace_timeout(&self, core::time::Duration) -> core::time::Duration
|
||||
pub fn rns_link::keepalive::KeepaliveState::update_from_rtt(&mut self, core::time::Duration)
|
||||
pub mod rns_link::key_derivation
|
||||
pub enum rns_link::key_derivation::LinkKeyError
|
||||
pub rns_link::key_derivation::LinkKeyError::HkdfFailed
|
||||
pub rns_link::key_derivation::LinkKeyError::LowOrderPoint
|
||||
pub rns_link::key_derivation::LinkKeyError::UnsupportedMode(u8)
|
||||
pub struct rns_link::key_derivation::LinkKeys
|
||||
pub rns_link::key_derivation::LinkKeys::encryption_key: alloc::vec::Vec<u8>
|
||||
pub rns_link::key_derivation::LinkKeys::signing_key: alloc::vec::Vec<u8>
|
||||
impl rns_link::key_derivation::LinkKeys
|
||||
pub fn rns_link::key_derivation::LinkKeys::derive(&rns_crypto::x25519::X25519PrivateKey, &rns_crypto::x25519::X25519PublicKey, &[u8; 16], u8) -> core::result::Result<Self, rns_link::key_derivation::LinkKeyError>
|
||||
impl core::ops::drop::Drop for rns_link::key_derivation::LinkKeys
|
||||
pub fn rns_link::key_derivation::LinkKeys::drop(&mut self)
|
||||
pub mod rns_link::link
|
||||
#[non_exhaustive] pub enum rns_link::link::CloseReason
|
||||
pub rns_link::link::CloseReason::DestinationClosed
|
||||
pub rns_link::link::CloseReason::InitiatorClosed
|
||||
pub rns_link::link::CloseReason::StampFailure
|
||||
pub rns_link::link::CloseReason::Timeout
|
||||
pub enum rns_link::link::LinkAction
|
||||
pub rns_link::link::LinkAction::Closed(rns_link::link::CloseReason)
|
||||
pub rns_link::link::LinkAction::None
|
||||
pub rns_link::link::LinkAction::SendKeepalive
|
||||
pub rns_link::link::LinkAction::SendTeardownAndClose(alloc::vec::Vec<u8>)
|
||||
pub rns_link::link::LinkAction::TransitionedToStale
|
||||
pub enum rns_link::link::LinkRole
|
||||
pub rns_link::link::LinkRole::Initiator
|
||||
pub rns_link::link::LinkRole::Responder
|
||||
pub enum rns_link::link::LinkState
|
||||
pub rns_link::link::LinkState::Active = 2
|
||||
pub rns_link::link::LinkState::Closed = 4
|
||||
pub rns_link::link::LinkState::Handshake = 1
|
||||
pub rns_link::link::LinkState::Pending = 0
|
||||
pub rns_link::link::LinkState::Stale = 3
|
||||
pub enum rns_link::link::OutboundResourceState
|
||||
pub rns_link::link::OutboundResourceState::AwaitingProof
|
||||
pub rns_link::link::OutboundResourceState::Complete
|
||||
pub rns_link::link::OutboundResourceState::Failed
|
||||
pub rns_link::link::OutboundResourceState::Transferring
|
||||
pub enum rns_link::link::PacketProofError
|
||||
pub rns_link::link::PacketProofError::HashMismatch
|
||||
pub rns_link::link::PacketProofError::InvalidSignature
|
||||
pub rns_link::link::PacketProofError::InvalidState(rns_link::link::LinkState)
|
||||
pub rns_link::link::PacketProofError::MalformedProof
|
||||
pub rns_link::link::PacketProofError::PeerKeyUnavailable
|
||||
pub rns_link::link::PacketProofError::SignerUnavailable
|
||||
pub rns_link::link::PacketProofError::WrongRole
|
||||
pub enum rns_link::link::RequestSendMode
|
||||
pub rns_link::link::RequestSendMode::Packet(alloc::vec::Vec<u8>)
|
||||
pub rns_link::link::RequestSendMode::Resource(alloc::vec::Vec<u8>)
|
||||
pub enum rns_link::link::ResourceAcceptance
|
||||
pub rns_link::link::ResourceAcceptance::Accept
|
||||
pub rns_link::link::ResourceAcceptance::AskApp
|
||||
pub rns_link::link::ResourceAcceptance::Reject
|
||||
pub enum rns_link::link::ResourceStrategy
|
||||
pub rns_link::link::ResourceStrategy::AcceptAll
|
||||
pub rns_link::link::ResourceStrategy::AcceptApp
|
||||
pub rns_link::link::ResourceStrategy::AcceptNone
|
||||
pub struct rns_link::link::Link
|
||||
pub rns_link::link::Link::activated_at: core::option::Option<std::time::Instant>
|
||||
pub rns_link::link::Link::destination_hash: [u8; 16]
|
||||
pub rns_link::link::Link::establishment_cost: usize
|
||||
pub rns_link::link::Link::establishment_rate: core::option::Option<f64>
|
||||
pub rns_link::link::Link::establishment_timeout: core::time::Duration
|
||||
pub rns_link::link::Link::expected_hops: core::option::Option<u8>
|
||||
pub rns_link::link::Link::expected_rate: core::option::Option<f64>
|
||||
pub rns_link::link::Link::has_channel: bool
|
||||
pub rns_link::link::Link::identified: bool
|
||||
pub rns_link::link::Link::incoming_resource_count: usize
|
||||
pub rns_link::link::Link::incoming_resources: alloc::vec::Vec<[u8; 32]>
|
||||
pub rns_link::link::Link::is_initiator: bool
|
||||
pub rns_link::link::Link::keepalive: rns_link::keepalive::KeepaliveState
|
||||
pub rns_link::link::Link::link_closed_callback: core::option::Option<rns_link::link::LinkCallback>
|
||||
pub rns_link::link::Link::link_established_callback: core::option::Option<rns_link::link::LinkCallback>
|
||||
pub rns_link::link::Link::link_id: [u8; 16]
|
||||
pub rns_link::link::Link::mdu: usize
|
||||
pub rns_link::link::Link::mode: u8
|
||||
pub rns_link::link::Link::mtu: u32
|
||||
pub rns_link::link::Link::outgoing_resource_states: alloc::vec::Vec<rns_link::link::OutboundResourceState>
|
||||
pub rns_link::link::Link::outgoing_resources: alloc::vec::Vec<[u8; 32]>
|
||||
pub rns_link::link::Link::packet_callback: core::option::Option<rns_link::link::PacketCallback>
|
||||
pub rns_link::link::Link::pending_requests: alloc::vec::Vec<rns_link::request::RequestReceipt>
|
||||
pub rns_link::link::Link::q: core::option::Option<f64>
|
||||
pub rns_link::link::Link::remote_identified_callback: core::option::Option<rns_link::link::RemoteIdentifiedCallback>
|
||||
pub rns_link::link::Link::request_time: std::time::Instant
|
||||
pub rns_link::link::Link::resource_callback: core::option::Option<rns_link::link::ResourceCallback>
|
||||
pub rns_link::link::Link::resource_strategy: rns_link::link::ResourceStrategy
|
||||
pub rns_link::link::Link::rssi: core::option::Option<f64>
|
||||
pub rns_link::link::Link::rtt: core::option::Option<core::time::Duration>
|
||||
pub rns_link::link::Link::rx_bytes: u64
|
||||
pub rns_link::link::Link::rx_count: u64
|
||||
pub rns_link::link::Link::snr: core::option::Option<f64>
|
||||
pub rns_link::link::Link::stale_since: core::option::Option<std::time::Instant>
|
||||
pub rns_link::link::Link::stamp_value: core::option::Option<f64>
|
||||
pub rns_link::link::Link::state: rns_link::link::LinkState
|
||||
pub rns_link::link::Link::teardown_reason: core::option::Option<rns_link::link::CloseReason>
|
||||
pub rns_link::link::Link::tx_bytes: u64
|
||||
pub rns_link::link::Link::tx_count: u64
|
||||
impl rns_link::link::Link
|
||||
pub fn rns_link::link::Link::add_establishment_cost(&mut self, usize)
|
||||
pub fn rns_link::link::Link::age(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_link::link::Link::classify_request(&self, alloc::vec::Vec<u8>) -> rns_link::link::RequestSendMode
|
||||
pub fn rns_link::link::Link::create_response(&self, &[u8; 16], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::create_response_value(&self, &[u8; 16], &rmpv::Value) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::create_rtt_packet(&self) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::decrypt(&self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::default_request_timeout(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::deliver_response_data(&mut self, &[u8; 16], alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_link::link::Link::encrypt(&self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::extend_establishment_timeout(&mut self, f64)
|
||||
pub fn rns_link::link::Link::fail_pending_request(&mut self, &[u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::get_age(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_establishment_rate(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_expected_rate(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_mdu(&self) -> core::option::Option<usize>
|
||||
pub const fn rns_link::link::Link::get_mode(&self) -> u8
|
||||
pub fn rns_link::link::Link::get_mtu(&self) -> core::option::Option<u32>
|
||||
pub fn rns_link::link::Link::get_q(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_rssi(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::get_snr(&self) -> core::option::Option<f64>
|
||||
pub fn rns_link::link::Link::handle_identification(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::handle_request(&self, &[u8]) -> core::result::Result<rns_link::link::ParsedRequestData, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::handle_response(&mut self, &[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::handle_response_plaintext(&mut self, &[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::has_keys(&self) -> bool
|
||||
pub fn rns_link::link::Link::identify(&self, &[u8; 64], &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::identify_with<F>(&self, &[u8; 64], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
|
||||
pub fn rns_link::link::Link::identify_with_fallible<F>(&self, &[u8; 64], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::inactive_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::is_active(&self) -> bool
|
||||
pub fn rns_link::link::Link::mark_channel_created(&mut self)
|
||||
pub fn rns_link::link::Link::mark_closed(&mut self, rns_link::link::CloseReason)
|
||||
pub fn rns_link::link::Link::mark_request_receiving(&mut self, &[u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::mark_request_resource_sending(&mut self, &[u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::mark_request_resource_sent(&mut self, &[u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::new_initiator([u8; 16], u8) -> (Self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_link::link::Link::new_initiator_with_keys([u8; 16], u8, rns_link::handshake::EphemeralKeys, u32) -> (Self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_link::link::Link::new_responder(&[u8], &rns_crypto::ed25519::Ed25519PrivateKey, [u8; 16], u8) -> core::result::Result<(Self, alloc::vec::Vec<u8>), rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::link::Link::new_responder_with<F>(&[u8], &[u8; 32], [u8; 16], u8, F) -> core::result::Result<(Self, alloc::vec::Vec<u8>), rns_link::handshake::HandshakeError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::new_stamped_initiator([u8; 16], u8, core::option::Option<f64>, &rns_identity::stamps::StampControl, u32) -> core::result::Result<(Self, alloc::vec::Vec<u8>), rns_link::stamp::LinkStampError>
|
||||
pub fn rns_link::link::Link::no_data_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::no_inbound_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::no_outbound_for(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::pack_response(&[u8; 16], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::pack_response_value(&[u8; 16], &rmpv::Value) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::packet_proof_timeout(&self) -> core::time::Duration
|
||||
pub fn rns_link::link::Link::parse_request(&[u8]) -> core::result::Result<rns_link::link::ParsedRequestData, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::parse_request_value(&[u8]) -> core::result::Result<rns_link::link::ParsedRequest, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::parse_response_plaintext(&[u8]) -> core::result::Result<([u8; 16], alloc::vec::Vec<u8>), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::parse_response_value(&[u8]) -> core::result::Result<([u8; 16], rmpv::Value), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::phy_stats(&self) -> (core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
|
||||
pub fn rns_link::link::Link::phy_stats_snapshot(&self) -> rns_link::link::LinkPhyStats
|
||||
pub fn rns_link::link::Link::phy_stats_tracking_enabled(&self) -> bool
|
||||
pub fn rns_link::link::Link::prepare_request(&mut self, &str, core::option::Option<&[u8]>, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::prepare_request_value(&mut self, &str, &rmpv::Value, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::prove_packet(&self, &[u8; 32], &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::prove_packet_with<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> [u8; 64]
|
||||
pub fn rns_link::link::Link::prove_packet_with_fallible<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::prove_packet_with_link_key(&self, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::prove_packet_with_local_signer(&self, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::link::PacketProofError>
|
||||
pub fn rns_link::link::Link::prove_responder_packet_with<F>(&self, &[u8; 32], F) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::link::PacketProofError> where F: core::ops::function::FnOnce(&[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::ready_for_new_resource(&self) -> bool
|
||||
pub fn rns_link::link::Link::receive_rtt_packet(&mut self, &[u8]) -> core::result::Result<(), rns_link::handshake::HandshakeError>
|
||||
pub fn rns_link::link::Link::receive_teardown(&mut self, &[u8]) -> bool
|
||||
pub fn rns_link::link::Link::record_inbound(&mut self)
|
||||
pub fn rns_link::link::Link::record_inbound_data(&mut self)
|
||||
pub fn rns_link::link::Link::record_rx(&mut self, usize)
|
||||
pub fn rns_link::link::Link::record_tx(&mut self, usize)
|
||||
pub fn rns_link::link::Link::record_tx_keepalive(&mut self, usize)
|
||||
pub fn rns_link::link::Link::register_incoming_resource(&mut self)
|
||||
pub fn rns_link::link::Link::register_outgoing_resource(&mut self)
|
||||
pub fn rns_link::link::Link::remote_identity(&self) -> core::option::Option<&[u8; 64]>
|
||||
pub fn rns_link::link::Link::request(&mut self, &str, core::option::Option<&[u8]>, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::request_str(&mut self, &str, &str, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::request_value(&mut self, &str, &rmpv::Value, core::time::Duration) -> core::result::Result<(alloc::vec::Vec<u8>, [u8; 16]), rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::resource_concluded(&mut self, usize, f64, bool)
|
||||
pub fn rns_link::link::Link::resource_sdu(&self) -> usize
|
||||
pub fn rns_link::link::Link::role(&self) -> rns_link::link::LinkRole
|
||||
pub fn rns_link::link::Link::rtt_secs(&self) -> f64
|
||||
pub fn rns_link::link::Link::session_keys(&self) -> core::option::Option<rns_link::key_derivation::LinkKeys>
|
||||
pub fn rns_link::link::Link::set_link_closed_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_link_established_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_packet_callback(&mut self, impl core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_remote_identified_callback(&mut self, impl core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_resource_callback(&mut self, impl core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::link::Link::set_resource_strategy(&mut self, rns_link::link::ResourceStrategy)
|
||||
pub fn rns_link::link::Link::set_signing_key(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey)
|
||||
pub fn rns_link::link::Link::should_accept_resource(&self) -> rns_link::link::ResourceAcceptance
|
||||
pub fn rns_link::link::Link::should_respond_to_keepalive(&self) -> bool
|
||||
pub fn rns_link::link::Link::sign(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_link::link::Link::teardown(&mut self, rns_link::link::CloseReason) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_link::link::Link::tick(&mut self) -> rns_link::link::LinkAction
|
||||
pub fn rns_link::link::Link::track_incoming_resource(&mut self, [u8; 32])
|
||||
pub fn rns_link::link::Link::track_outgoing_resource(&mut self, [u8; 32])
|
||||
pub fn rns_link::link::Link::track_phy_stats(&mut self, bool)
|
||||
pub fn rns_link::link::Link::traffic_stats(&self) -> (u64, u64, u64, u64)
|
||||
pub fn rns_link::link::Link::try_extend_establishment_timeout(&mut self, f64) -> core::result::Result<(), rns_link::link::TimeoutError>
|
||||
pub fn rns_link::link::Link::untrack_resource(&mut self, &[u8; 32])
|
||||
pub fn rns_link::link::Link::update_outgoing_resource_state(&mut self, usize, rns_link::link::OutboundResourceState)
|
||||
pub fn rns_link::link::Link::update_pending_request_id(&mut self, &[u8; 16], [u8; 16]) -> bool
|
||||
pub fn rns_link::link::Link::update_phy_stats(&mut self, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
|
||||
pub fn rns_link::link::Link::update_phy_stats_force(&mut self, core::option::Option<f64>, core::option::Option<f64>, core::option::Option<f64>)
|
||||
pub fn rns_link::link::Link::update_rtt_from_packet(&mut self, &[u8]) -> core::result::Result<core::time::Duration, rns_link::encryption::LinkCryptoError>
|
||||
pub fn rns_link::link::Link::validate(&self, &[u8], &[u8]) -> bool
|
||||
pub fn rns_link::link::Link::validate_packet_proof(&self, &[u8; 32], &[u8]) -> bool
|
||||
pub fn rns_link::link::Link::validate_peer_packet_proof(&self, &[u8; 32], &[u8]) -> core::result::Result<(), rns_link::link::PacketProofError>
|
||||
pub fn rns_link::link::Link::validate_proof(&mut self, &[u8], &rns_crypto::ed25519::Ed25519PublicKey, &[u8; 32]) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::handshake::HandshakeError>
|
||||
pub struct rns_link::link::LinkPhyStats
|
||||
pub rns_link::link::LinkPhyStats::q: core::option::Option<f64>
|
||||
pub rns_link::link::LinkPhyStats::rssi: core::option::Option<f64>
|
||||
pub rns_link::link::LinkPhyStats::snr: core::option::Option<f64>
|
||||
pub struct rns_link::link::ParsedRequest
|
||||
pub rns_link::link::ParsedRequest::data: rmpv::Value
|
||||
pub rns_link::link::ParsedRequest::path_hash: [u8; 16]
|
||||
pub rns_link::link::ParsedRequest::request_id: [u8; 16]
|
||||
pub rns_link::link::ParsedRequest::requested_at: f64
|
||||
pub struct rns_link::link::TimeoutError
|
||||
pub fn rns_link::link::decode_single_value(&[u8]) -> core::option::Option<rmpv::Value>
|
||||
pub fn rns_link::link::value_bytes_view(&rmpv::Value) -> core::result::Result<alloc::vec::Vec<u8>, rns_link::encryption::LinkCryptoError>
|
||||
pub type rns_link::link::LinkCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::link::PacketCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&[u8]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::link::ParsedRequestData = ([u8; 16], [u8; 16], f64, alloc::vec::Vec<u8>)
|
||||
pub type rns_link::link::RemoteIdentifiedCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(&rns_link::link::Link, &[u8; 64]) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::link::ResourceCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(bool) -> bool + core::marker::Send + core::marker::Sync)>
|
||||
pub mod rns_link::mtu_discovery
|
||||
pub use rns_link::mtu_discovery::LinkMtu
|
||||
pub use rns_link::mtu_discovery::LinkSignalling
|
||||
pub use rns_link::mtu_discovery::LinkSignallingError
|
||||
pub use rns_link::mtu_discovery::SignallingData
|
||||
pub use rns_link::mtu_discovery::parse_proof_signalling
|
||||
pub use rns_link::mtu_discovery::parse_request_signalling
|
||||
pub mod rns_link::request
|
||||
pub enum rns_link::request::RequestState
|
||||
pub rns_link::request::RequestState::Delivered
|
||||
pub rns_link::request::RequestState::Failed
|
||||
pub rns_link::request::RequestState::Receiving
|
||||
pub rns_link::request::RequestState::ResponseReceived
|
||||
pub rns_link::request::RequestState::SendingResource
|
||||
pub rns_link::request::RequestState::Sent
|
||||
pub struct rns_link::request::RequestCallbacks
|
||||
pub rns_link::request::RequestCallbacks::failed: core::option::Option<rns_link::request::RequestCallback>
|
||||
pub rns_link::request::RequestCallbacks::progress: core::option::Option<rns_link::request::ProgressCallback>
|
||||
pub rns_link::request::RequestCallbacks::response: core::option::Option<rns_link::request::RequestCallback>
|
||||
pub struct rns_link::request::RequestReceipt
|
||||
pub rns_link::request::RequestReceipt::callbacks: rns_link::request::RequestCallbacks
|
||||
pub rns_link::request::RequestReceipt::link_id: [u8; 16]
|
||||
pub rns_link::request::RequestReceipt::progress: f32
|
||||
pub rns_link::request::RequestReceipt::request_id: [u8; 32]
|
||||
pub rns_link::request::RequestReceipt::response: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_link::request::RequestReceipt::rtt: core::option::Option<core::time::Duration>
|
||||
pub rns_link::request::RequestReceipt::sent_at: std::time::Instant
|
||||
pub rns_link::request::RequestReceipt::state: rns_link::request::RequestState
|
||||
pub rns_link::request::RequestReceipt::timeout: core::time::Duration
|
||||
impl rns_link::request::RequestReceipt
|
||||
pub fn rns_link::request::RequestReceipt::check_timeout(&mut self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::concluded(&self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::deliver(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_link::request::RequestReceipt::fail(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::get_progress(&self) -> f32
|
||||
pub fn rns_link::request::RequestReceipt::get_response_time(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_link::request::RequestReceipt::is_pending(&self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::is_timed_out(&self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::mark_delivered(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::mark_failed(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::mark_receiving(&mut self) -> bool
|
||||
pub fn rns_link::request::RequestReceipt::mark_resource_sending(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::mark_resource_sent(&mut self)
|
||||
pub fn rns_link::request::RequestReceipt::new([u8; 32], [u8; 16], core::time::Duration) -> Self
|
||||
pub fn rns_link::request::RequestReceipt::receive_response(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_link::request::RequestReceipt::set_failed_callback(&mut self, impl core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_link::request::RequestReceipt::set_progress_callback(&mut self, impl core::ops::function::Fn(f32) + core::marker::Send + core::marker::Sync + 'static)
|
||||
pub fn rns_link::request::RequestReceipt::set_response_callback(&mut self, impl core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_link::request::RequestReceipt::update_progress(&mut self, f32)
|
||||
pub type rns_link::request::ProgressCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(f32) + core::marker::Send + core::marker::Sync)>
|
||||
pub type rns_link::request::RequestCallback = alloc::boxed::Box<(dyn core::ops::function::FnOnce(&rns_link::request::RequestReceipt) + core::marker::Send)>
|
||||
pub mod rns_link::stamp
|
||||
pub enum rns_link::stamp::LinkStampError
|
||||
pub rns_link::stamp::LinkStampError::Cost(rns_identity::stamps::StampError)
|
||||
pub rns_link::stamp::LinkStampError::Mismatch
|
||||
pub rns_link::stamp::LinkStampError::Stopped
|
||||
pub struct rns_link::stamp::LinkRequestStamper
|
||||
pub rns_link::stamp::LinkRequestStamper::link_mtu_discovery: bool
|
||||
pub rns_link::stamp::LinkRequestStamper::policy: rns_link::stamp::LinkStampPolicy
|
||||
impl rns_link::stamp::LinkRequestStamper
|
||||
pub fn rns_link::stamp::LinkRequestStamper::new(rns_link::stamp::LinkStampPolicy, rns_link::stamp::LinkCostRecall) -> Self
|
||||
pub fn rns_link::stamp::LinkRequestStamper::new_initiator(&self, [u8; 16], u8, u32) -> core::result::Result<(rns_link::link::Link, alloc::vec::Vec<u8>), rns_link::stamp::LinkStampError>
|
||||
pub fn rns_link::stamp::LinkRequestStamper::request_cost(&self, &[u8; 16]) -> core::option::Option<f64>
|
||||
pub fn rns_link::stamp::LinkRequestStamper::without_recall(rns_link::stamp::LinkStampPolicy) -> Self
|
||||
impl core::fmt::Debug for rns_link::stamp::LinkRequestStamper
|
||||
pub fn rns_link::stamp::LinkRequestStamper::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
pub struct rns_link::stamp::LinkStampPolicy
|
||||
pub rns_link::stamp::LinkStampPolicy::always_stamp_lrs: bool
|
||||
pub rns_link::stamp::LinkStampPolicy::lr_cost: f64
|
||||
pub rns_link::stamp::LinkStampPolicy::stamp_lrs: bool
|
||||
pub rns_link::stamp::LinkStampPolicy::timeout: core::time::Duration
|
||||
impl rns_link::stamp::LinkStampPolicy
|
||||
pub fn rns_link::stamp::LinkStampPolicy::control(&self, f64) -> rns_identity::stamps::StampControl
|
||||
pub fn rns_link::stamp::LinkStampPolicy::request_cost(&self, core::option::Option<f64>) -> core::option::Option<f64>
|
||||
impl core::default::Default for rns_link::stamp::LinkStampPolicy
|
||||
pub fn rns_link::stamp::LinkStampPolicy::default() -> Self
|
||||
pub fn rns_link::stamp::generate_stamped_ephemeral_keys(&[u8; 16], f64, &rns_identity::stamps::StampControl) -> core::result::Result<rns_link::handshake::EphemeralKeys, rns_link::stamp::LinkStampError>
|
||||
pub fn rns_link::stamp::link_request_stamp_valid(&[u8; 16], &[u8], f64) -> bool
|
||||
pub fn rns_link::stamp::link_request_stamp_value(&[u8; 16], &[u8]) -> core::option::Option<f64>
|
||||
pub fn rns_link::stamp::link_stamp_material(&[u8; 16], &[u8; 32]) -> [u8; 48]
|
||||
pub type rns_link::stamp::LinkCostRecall = alloc::sync::Arc<(dyn core::ops::function::Fn(&[u8; 16]) -> core::option::Option<f64> + core::marker::Send + core::marker::Sync)>
|
||||
@@ -0,0 +1,673 @@
|
||||
pub mod rns_protocol
|
||||
pub mod rns_protocol::buffer
|
||||
pub enum rns_protocol::buffer::BufferError
|
||||
pub rns_protocol::buffer::BufferError::WriterClosed
|
||||
pub struct rns_protocol::buffer::ChannelBuffer
|
||||
impl rns_protocol::buffer::ChannelBuffer
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::available(&self) -> usize
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::close_writer(&mut self) -> rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::drain_and_close_writer(&mut self) -> rns_protocol::buffer::DrainClose
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::feed_reader(&mut self, &rns_protocol::stream_data::StreamDataMessage) -> bool
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::is_done(&self) -> bool
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::is_writer_closed(&self) -> bool
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::new(u16, usize) -> Self
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::read(&mut self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::read_all(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::stream_id(&self) -> u16
|
||||
pub fn rns_protocol::buffer::ChannelBuffer::write(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<rns_protocol::stream_data::StreamDataMessage>, rns_protocol::buffer::BufferError>
|
||||
pub struct rns_protocol::buffer::DrainClose
|
||||
pub rns_protocol::buffer::DrainClose::eof_message: rns_protocol::stream_data::StreamDataMessage
|
||||
pub struct rns_protocol::buffer::StreamReader
|
||||
impl rns_protocol::buffer::StreamReader
|
||||
pub fn rns_protocol::buffer::StreamReader::available(&self) -> usize
|
||||
pub fn rns_protocol::buffer::StreamReader::feed(&mut self, &rns_protocol::stream_data::StreamDataMessage) -> bool
|
||||
pub fn rns_protocol::buffer::StreamReader::is_done(&self) -> bool
|
||||
pub fn rns_protocol::buffer::StreamReader::is_eof(&self) -> bool
|
||||
pub fn rns_protocol::buffer::StreamReader::new(u16) -> Self
|
||||
pub fn rns_protocol::buffer::StreamReader::read(&mut self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::buffer::StreamReader::read_all(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub struct rns_protocol::buffer::StreamWriter
|
||||
impl rns_protocol::buffer::StreamWriter
|
||||
pub fn rns_protocol::buffer::StreamWriter::close(&mut self) -> rns_protocol::buffer::DrainClose
|
||||
pub fn rns_protocol::buffer::StreamWriter::close_simple(&mut self) -> rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::buffer::StreamWriter::is_closed(&self) -> bool
|
||||
pub fn rns_protocol::buffer::StreamWriter::new(u16, usize) -> Self
|
||||
pub fn rns_protocol::buffer::StreamWriter::write(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<rns_protocol::stream_data::StreamDataMessage>, rns_protocol::buffer::BufferError>
|
||||
pub fn rns_protocol::buffer::StreamWriter::write_once(&mut self, &[u8]) -> core::result::Result<core::option::Option<(rns_protocol::stream_data::StreamDataMessage, usize)>, rns_protocol::buffer::BufferError>
|
||||
pub const rns_protocol::buffer::COMPRESSION_TRIES: usize
|
||||
pub const rns_protocol::buffer::MAX_CHUNK_LEN: usize
|
||||
pub mod rns_protocol::channel
|
||||
pub enum rns_protocol::channel::ChannelError
|
||||
pub rns_protocol::channel::ChannelError::ChannelClosed
|
||||
pub rns_protocol::channel::ChannelError::InvalidEnvelope
|
||||
pub rns_protocol::channel::ChannelError::InvalidMessageType(u16)
|
||||
pub rns_protocol::channel::ChannelError::MaxRetriesExceeded
|
||||
pub rns_protocol::channel::ChannelError::MessageTooLarge
|
||||
pub rns_protocol::channel::ChannelError::MessageTooLarge::actual: usize
|
||||
pub rns_protocol::channel::ChannelError::MessageTooLarge::max: usize
|
||||
pub rns_protocol::channel::ChannelError::NotReady
|
||||
pub rns_protocol::channel::ChannelError::UnknownMessageType(u16)
|
||||
pub struct rns_protocol::channel::Channel
|
||||
pub rns_protocol::channel::Channel::active: bool
|
||||
pub rns_protocol::channel::Channel::window: rns_protocol::channel::ChannelWindow
|
||||
impl rns_protocol::channel::Channel
|
||||
pub fn rns_protocol::channel::Channel::add_message_handler(&mut self, rns_protocol::channel::MessageCallback) -> rns_protocol::channel::HandlerId
|
||||
pub fn rns_protocol::channel::Channel::channel_mdu(usize) -> usize
|
||||
pub fn rns_protocol::channel::Channel::clear_message_handlers(&mut self)
|
||||
pub fn rns_protocol::channel::Channel::compute_timeout(&self, usize) -> f64
|
||||
pub fn rns_protocol::channel::Channel::deliverable_types(&self, &[u8]) -> alloc::vec::Vec<u16>
|
||||
pub fn rns_protocol::channel::Channel::delivered(&mut self, u16, f64)
|
||||
pub fn rns_protocol::channel::Channel::is_drained(&self) -> bool
|
||||
pub fn rns_protocol::channel::Channel::is_ready_to_send(&self) -> bool
|
||||
pub fn rns_protocol::channel::Channel::new(f64) -> Self
|
||||
pub fn rns_protocol::channel::Channel::next_timeout_duration(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_protocol::channel::Channel::outstanding_count(&self) -> usize
|
||||
pub fn rns_protocol::channel::Channel::receive(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::receive_unhandled(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::register_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::register_system_type(&mut self, u16)
|
||||
pub fn rns_protocol::channel::Channel::remove_message_handler(&mut self, rns_protocol::channel::HandlerId) -> bool
|
||||
pub fn rns_protocol::channel::Channel::send(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::send_tracked(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<(u16, alloc::vec::Vec<u8>), rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::shutdown(&mut self)
|
||||
pub fn rns_protocol::channel::Channel::timed_out_sequences(&self) -> alloc::vec::Vec<u16>
|
||||
pub fn rns_protocol::channel::Channel::timeout(&mut self, u16) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::Channel::update_rtt(&mut self, f64)
|
||||
pub struct rns_protocol::channel::ChannelWindow
|
||||
pub rns_protocol::channel::ChannelWindow::fast_rate_rounds: usize
|
||||
pub rns_protocol::channel::ChannelWindow::medium_rate_rounds: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window_flexibility: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window_max: usize
|
||||
pub rns_protocol::channel::ChannelWindow::window_min: usize
|
||||
impl rns_protocol::channel::ChannelWindow
|
||||
pub fn rns_protocol::channel::ChannelWindow::grow(&mut self, f64)
|
||||
pub fn rns_protocol::channel::ChannelWindow::new(f64) -> Self
|
||||
pub fn rns_protocol::channel::ChannelWindow::shrink(&mut self)
|
||||
pub struct rns_protocol::channel::Envelope
|
||||
pub rns_protocol::channel::Envelope::msg_type: u16
|
||||
pub rns_protocol::channel::Envelope::packed: bool
|
||||
pub rns_protocol::channel::Envelope::raw: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::channel::Envelope::sequence: u16
|
||||
pub rns_protocol::channel::Envelope::state: rns_protocol::channel_message::MessageState
|
||||
pub rns_protocol::channel::Envelope::tries: usize
|
||||
impl rns_protocol::channel::Envelope
|
||||
pub fn rns_protocol::channel::Envelope::pack(&dyn rns_protocol::channel_message::MessageBase, u16) -> Self
|
||||
pub fn rns_protocol::channel::Envelope::payload(&self) -> &[u8]
|
||||
pub fn rns_protocol::channel::Envelope::unpack(&[u8]) -> core::result::Result<Self, rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::channel::HandlerId(_)
|
||||
pub struct rns_protocol::channel::LinkChannel
|
||||
impl rns_protocol::channel::LinkChannel
|
||||
pub fn rns_protocol::channel::LinkChannel::add_message_handler(&mut self, rns_protocol::channel::MessageCallback) -> rns_protocol::channel::HandlerId
|
||||
pub fn rns_protocol::channel::LinkChannel::clear_message_handlers(&mut self)
|
||||
pub fn rns_protocol::channel::LinkChannel::deliverable_types(&self, &[u8]) -> alloc::vec::Vec<u16>
|
||||
pub fn rns_protocol::channel::LinkChannel::delivered(&mut self, u16, f64)
|
||||
pub fn rns_protocol::channel::LinkChannel::delivered_by_packet_hash(&mut self, &[u8; 32], f64) -> core::option::Option<u16>
|
||||
pub fn rns_protocol::channel::LinkChannel::is_active(&self) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::is_drained(&self) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::is_ready_to_send(&self) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::link_id(&self) -> &[u8; 16]
|
||||
pub fn rns_protocol::channel::LinkChannel::mdu(&self) -> usize
|
||||
pub fn rns_protocol::channel::LinkChannel::new([u8; 16], f64) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::new_encrypted([u8; 16], f64, rns_link::key_derivation::LinkKeys) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::new_encrypted_with_mdu([u8; 16], f64, usize, rns_link::key_derivation::LinkKeys) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::new_with_mdu([u8; 16], f64, usize) -> Self
|
||||
pub fn rns_protocol::channel::LinkChannel::next_timeout_duration(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_protocol::channel::LinkChannel::outstanding_count(&self) -> usize
|
||||
pub fn rns_protocol::channel::LinkChannel::prepare_send(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::prepare_send_tracked(&mut self, &dyn rns_protocol::channel_message::MessageBase) -> core::result::Result<rns_protocol::channel::PreparedChannelData, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::receive_data(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::receive_data_unhandled(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<(u16, alloc::vec::Vec<u8>)>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::register_message_type(&mut self, u16) -> core::result::Result<(), rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::register_system_type(&mut self, u16)
|
||||
pub fn rns_protocol::channel::LinkChannel::remove_message_handler(&mut self, rns_protocol::channel::HandlerId) -> bool
|
||||
pub fn rns_protocol::channel::LinkChannel::shutdown(&mut self)
|
||||
pub fn rns_protocol::channel::LinkChannel::timed_out_sequences(&self) -> alloc::vec::Vec<u16>
|
||||
pub fn rns_protocol::channel::LinkChannel::timeout(&mut self, u16) -> core::result::Result<core::option::Option<alloc::vec::Vec<u8>>, rns_protocol::channel::ChannelError>
|
||||
pub fn rns_protocol::channel::LinkChannel::track_outbound_packet_hash(&mut self, [u8; 32], u16)
|
||||
pub fn rns_protocol::channel::LinkChannel::update_rtt(&mut self, f64)
|
||||
pub struct rns_protocol::channel::PreparedChannelData
|
||||
pub rns_protocol::channel::PreparedChannelData::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::channel::PreparedChannelData::sequence: u16
|
||||
pub const rns_protocol::channel::ENVELOPE_HEADER_SIZE: usize
|
||||
pub const rns_protocol::channel::FAST_RATE_THRESHOLD: usize
|
||||
pub const rns_protocol::channel::MAX_TRIES: usize
|
||||
pub const rns_protocol::channel::MIN_TIMEOUT_BASE: f64
|
||||
pub const rns_protocol::channel::RTT_FAST: f64
|
||||
pub const rns_protocol::channel::RTT_MAX: f64
|
||||
pub const rns_protocol::channel::RTT_MEDIUM: f64
|
||||
pub const rns_protocol::channel::RTT_SLOW: f64
|
||||
pub const rns_protocol::channel::SEQ_MAX: u16
|
||||
pub const rns_protocol::channel::SEQ_MODULUS: u32
|
||||
pub const rns_protocol::channel::WINDOW_FLEXIBILITY: usize
|
||||
pub const rns_protocol::channel::WINDOW_INITIAL: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX_FAST: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX_MEDIUM: usize
|
||||
pub const rns_protocol::channel::WINDOW_MAX_SLOW: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_FAST: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_MEDIUM: usize
|
||||
pub const rns_protocol::channel::WINDOW_MIN_LIMIT_SLOW: usize
|
||||
pub type rns_protocol::channel::MessageCallback = alloc::boxed::Box<(dyn core::ops::function::Fn(u16, &[u8]) -> bool + core::marker::Send)>
|
||||
pub mod rns_protocol::channel_message
|
||||
pub enum rns_protocol::channel_message::ChannelMessageError
|
||||
pub rns_protocol::channel_message::ChannelMessageError::InvalidType
|
||||
pub rns_protocol::channel_message::ChannelMessageError::TooShort
|
||||
pub rns_protocol::channel_message::ChannelMessageError::UnpackFailed
|
||||
pub enum rns_protocol::channel_message::MessageState
|
||||
pub rns_protocol::channel_message::MessageState::Delivered
|
||||
pub rns_protocol::channel_message::MessageState::Failed
|
||||
pub rns_protocol::channel_message::MessageState::New
|
||||
pub rns_protocol::channel_message::MessageState::Sent
|
||||
pub const rns_protocol::channel_message::SMT_STREAM_DATA: u16
|
||||
pub const rns_protocol::channel_message::SYSTEM_MESSAGE_TYPE_MIN: u16
|
||||
pub trait rns_protocol::channel_message::MessageBase: core::marker::Send
|
||||
pub fn rns_protocol::channel_message::MessageBase::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::channel_message::MessageBase::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::channel_message::MessageBase::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::CommandExitedMessage
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ErrorMessage
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::NoopMessage
|
||||
pub fn rns_protocol::rnsh::NoopMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::NoopMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::NoopMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::WindowSizeMessage
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub mod rns_protocol::compression
|
||||
pub enum rns_protocol::compression::CompressionError
|
||||
pub rns_protocol::compression::CompressionError::CompressFailed
|
||||
pub rns_protocol::compression::CompressionError::DecompressFailed
|
||||
pub rns_protocol::compression::CompressionError::DecompressedTooLarge
|
||||
pub const rns_protocol::compression::AUTO_COMPRESS_MAX_SIZE: usize
|
||||
pub fn rns_protocol::compression::bz2_compress(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::compression::CompressionError>
|
||||
pub fn rns_protocol::compression::bz2_decompress(&[u8], usize) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::compression::CompressionError>
|
||||
pub fn rns_protocol::compression::try_compress(&[u8]) -> (alloc::vec::Vec<u8>, bool)
|
||||
pub mod rns_protocol::resource
|
||||
pub enum rns_protocol::resource::CancelType
|
||||
pub rns_protocol::resource::CancelType::Icl
|
||||
pub rns_protocol::resource::CancelType::Rcl
|
||||
pub enum rns_protocol::resource::ResourceError
|
||||
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge
|
||||
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::context: rns_wire::context::PacketContext
|
||||
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::encoded_len: usize
|
||||
pub rns_protocol::resource::ResourceError::ControlFrameTooLarge::mtu: usize
|
||||
pub rns_protocol::resource::ResourceError::Corrupt
|
||||
pub rns_protocol::resource::ResourceError::DecompressedTooLarge
|
||||
pub rns_protocol::resource::ResourceError::DecompressionFailed
|
||||
pub rns_protocol::resource::ResourceError::DecryptFailed
|
||||
pub rns_protocol::resource::ResourceError::DuplicateSegment
|
||||
pub rns_protocol::resource::ResourceError::HashMismatch
|
||||
pub rns_protocol::resource::ResourceError::Incomplete
|
||||
pub rns_protocol::resource::ResourceError::InvalidAdvertisement
|
||||
pub rns_protocol::resource::ResourceError::InvalidMetadata
|
||||
pub rns_protocol::resource::ResourceError::InvalidMetadata::available: usize
|
||||
pub rns_protocol::resource::ResourceError::InvalidMetadata::declared: usize
|
||||
pub rns_protocol::resource::ResourceError::MapHashCollision
|
||||
pub rns_protocol::resource::ResourceError::MetadataTooLarge
|
||||
pub rns_protocol::resource::ResourceError::TooLarge
|
||||
#[repr(u8)] pub enum rns_protocol::resource::ResourceState
|
||||
pub rns_protocol::resource::ResourceState::Advertised = 2
|
||||
pub rns_protocol::resource::ResourceState::Assembling = 5
|
||||
pub rns_protocol::resource::ResourceState::AwaitingProof = 4
|
||||
pub rns_protocol::resource::ResourceState::Complete = 6
|
||||
pub rns_protocol::resource::ResourceState::Corrupt = 8
|
||||
pub rns_protocol::resource::ResourceState::Failed = 7
|
||||
pub rns_protocol::resource::ResourceState::None = 0
|
||||
pub rns_protocol::resource::ResourceState::Queued = 1
|
||||
pub rns_protocol::resource::ResourceState::Rejected = 9
|
||||
pub rns_protocol::resource::ResourceState::Transferring = 3
|
||||
pub enum rns_protocol::resource::TransferAction
|
||||
pub rns_protocol::resource::TransferAction::Complete
|
||||
pub rns_protocol::resource::TransferAction::Failed(alloc::string::String)
|
||||
pub rns_protocol::resource::TransferAction::None
|
||||
pub rns_protocol::resource::TransferAction::QueryProofCache(alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendAdvertisement(alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendCancel(rns_protocol::resource::CancelType, [u8; 32])
|
||||
pub rns_protocol::resource::TransferAction::SendHmu(alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendPart(usize, alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendProof(alloc::vec::Vec<u8>)
|
||||
pub rns_protocol::resource::TransferAction::SendRequest(alloc::vec::Vec<u8>)
|
||||
pub struct rns_protocol::resource::InboundLinkFacts
|
||||
pub rns_protocol::resource::InboundLinkFacts::establishment_cost: usize
|
||||
pub rns_protocol::resource::InboundLinkFacts::previous_eifr: core::option::Option<f64>
|
||||
pub rns_protocol::resource::InboundLinkFacts::previous_window: core::option::Option<usize>
|
||||
pub rns_protocol::resource::InboundLinkFacts::rtt: core::time::Duration
|
||||
pub struct rns_protocol::resource::InboundResource
|
||||
pub rns_protocol::resource::InboundResource::consecutive_completed: usize
|
||||
pub rns_protocol::resource::InboundResource::data_size: usize
|
||||
pub rns_protocol::resource::InboundResource::flags: rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource::InboundResource::map_hashes: alloc::vec::Vec<[u8; 4]>
|
||||
pub rns_protocol::resource::InboundResource::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::InboundResource::parts: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub rns_protocol::resource::InboundResource::random_hash: [u8; 4]
|
||||
pub rns_protocol::resource::InboundResource::resource_hash: [u8; 32]
|
||||
pub rns_protocol::resource::InboundResource::sdu: usize
|
||||
pub rns_protocol::resource::InboundResource::state: rns_protocol::resource::ResourceState
|
||||
pub rns_protocol::resource::InboundResource::total_parts: usize
|
||||
pub rns_protocol::resource::InboundResource::total_size: usize
|
||||
pub rns_protocol::resource::InboundResource::window: rns_protocol::resource::WindowState
|
||||
impl rns_protocol::resource::InboundResource
|
||||
pub fn rns_protocol::resource::InboundResource::assemble(&mut self, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundResource::generate_proof(&self, &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::resource::InboundResource::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::InboundResource::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::InboundResource::new(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundResource::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::InboundResource::receive_part(&mut self, alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_protocol::resource::InboundResource::received_count(&self) -> usize
|
||||
pub fn rns_protocol::resource::InboundResource::with_sdu(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>, core::option::Option<usize>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::InboundTransfer
|
||||
pub rns_protocol::resource::InboundTransfer::accepted: bool
|
||||
pub rns_protocol::resource::InboundTransfer::eifr: core::option::Option<f64>
|
||||
pub rns_protocol::resource::InboundTransfer::establishment_cost: usize
|
||||
pub rns_protocol::resource::InboundTransfer::hashmap_height: usize
|
||||
pub rns_protocol::resource::InboundTransfer::last_activity: std::time::Instant
|
||||
pub rns_protocol::resource::InboundTransfer::outstanding_parts: usize
|
||||
pub rns_protocol::resource::InboundTransfer::part_timeout_factor: f64
|
||||
pub rns_protocol::resource::InboundTransfer::parts_since_hmu: usize
|
||||
pub rns_protocol::resource::InboundTransfer::previous_eifr: core::option::Option<f64>
|
||||
pub rns_protocol::resource::InboundTransfer::req_data_rtt_rate: f64
|
||||
pub rns_protocol::resource::InboundTransfer::req_resp: core::option::Option<std::time::Instant>
|
||||
pub rns_protocol::resource::InboundTransfer::req_resp_rtt_rate: f64
|
||||
pub rns_protocol::resource::InboundTransfer::req_sent: core::option::Option<std::time::Instant>
|
||||
pub rns_protocol::resource::InboundTransfer::req_sent_bytes: usize
|
||||
pub rns_protocol::resource::InboundTransfer::resource: rns_protocol::resource::InboundResource
|
||||
pub rns_protocol::resource::InboundTransfer::retries_left: usize
|
||||
pub rns_protocol::resource::InboundTransfer::rtt: core::time::Duration
|
||||
pub rns_protocol::resource::InboundTransfer::rtt_rxd_bytes: usize
|
||||
pub rns_protocol::resource::InboundTransfer::rtt_rxd_bytes_at_part_req: usize
|
||||
pub rns_protocol::resource::InboundTransfer::started_at: std::time::Instant
|
||||
pub rns_protocol::resource::InboundTransfer::waiting_for_hmu: bool
|
||||
impl rns_protocol::resource::InboundTransfer
|
||||
pub fn rns_protocol::resource::InboundTransfer::cancel(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::check_timeout(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::complete(&mut self, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<(alloc::vec::Vec<u8>, alloc::vec::Vec<u8>), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundTransfer::create_hmu(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::resource::InboundTransfer::from_advertisement(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>, core::time::Duration) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundTransfer::from_advertisement_with_link(usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>, rns_protocol::resource::InboundLinkFacts) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::InboundTransfer::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::InboundTransfer::hashmap_update(&mut self, usize, &[u8]) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::InboundTransfer::receive_part(&mut self, alloc::vec::Vec<u8>) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::request_next(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::InboundTransfer::seed_previous_eifr(&mut self, f64)
|
||||
pub fn rns_protocol::resource::InboundTransfer::update_eifr(&mut self)
|
||||
pub struct rns_protocol::resource::LazyMultiSegmentOutbound
|
||||
pub rns_protocol::resource::LazyMultiSegmentOutbound::data_size: usize
|
||||
pub rns_protocol::resource::LazyMultiSegmentOutbound::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource::LazyMultiSegmentOutbound::total_segments: usize
|
||||
impl rns_protocol::resource::LazyMultiSegmentOutbound
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::new(alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::next_segment(&mut self, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<core::option::Option<rns_protocol::resource::OutboundResource>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::remaining_segments(&self) -> usize
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::with_app_flag(self, bool) -> Self
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::with_link_sdu(self, core::option::Option<usize>) -> Self
|
||||
pub fn rns_protocol::resource::LazyMultiSegmentOutbound::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::LinkResource
|
||||
pub rns_protocol::resource::LinkResource::inbound: core::option::Option<rns_protocol::resource::InboundResource>
|
||||
pub rns_protocol::resource::LinkResource::link_id: [u8; 16]
|
||||
pub rns_protocol::resource::LinkResource::outbound: core::option::Option<rns_protocol::resource::OutboundResource>
|
||||
pub rns_protocol::resource::LinkResource::session_keys: core::option::Option<rns_link::key_derivation::LinkKeys>
|
||||
impl rns_protocol::resource::LinkResource
|
||||
pub fn rns_protocol::resource::LinkResource::assemble(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::LinkResource::new_inbound([u8; 16], usize, usize, usize, [u8; 4], [u8; 32], rns_protocol::resource::ResourceFlags, alloc::vec::Vec<[u8; 4]>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::new_outbound([u8; 16], alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::new_outbound_encrypted([u8; 16], alloc::vec::Vec<u8>, bool, rns_link::key_derivation::LinkKeys) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::LinkResource::next_part(&self, usize) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_protocol::resource::LinkResource::num_parts(&self) -> usize
|
||||
pub fn rns_protocol::resource::LinkResource::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::LinkResource::receive_part(&mut self, alloc::vec::Vec<u8>) -> bool
|
||||
pub fn rns_protocol::resource::LinkResource::validate_proof(&mut self, &[u8]) -> bool
|
||||
pub struct rns_protocol::resource::MultiSegmentInbound
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled_segments: alloc::vec::Vec<core::option::Option<alloc::vec::Vec<u8>>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::assembled_through: usize
|
||||
pub rns_protocol::resource::MultiSegmentInbound::data_size: usize
|
||||
pub rns_protocol::resource::MultiSegmentInbound::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource::MultiSegmentInbound::segments: alloc::vec::Vec<core::option::Option<rns_protocol::resource::InboundResource>>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::size_bound: core::option::Option<usize>
|
||||
pub rns_protocol::resource::MultiSegmentInbound::total_segments: usize
|
||||
impl rns_protocol::resource::MultiSegmentInbound
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::assemble_segment(&mut self, usize, core::option::Option<&rns_protocol::resource::ResourceDecryptor<'_>>) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::assembled_count(&self) -> usize
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::new(usize, [u8; 32]) -> Self
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::reassemble(&self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_metadata(&mut self, alloc::vec::Vec<u8>)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment(&mut self, usize, rns_protocol::resource::InboundResource)
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::set_segment_data(&mut self, usize, alloc::vec::Vec<u8>) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::take_reassembled(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentInbound::with_size_bound(self, usize) -> Self
|
||||
pub struct rns_protocol::resource::MultiSegmentOutbound
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::data_size: usize
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::segments: alloc::vec::Vec<rns_protocol::resource::OutboundResource>
|
||||
pub rns_protocol::resource::MultiSegmentOutbound::total_segments: usize
|
||||
impl rns_protocol::resource::MultiSegmentOutbound
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::cancel_all(&mut self) -> usize
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::get_segment(&self, usize) -> core::option::Option<&rns_protocol::resource::OutboundResource>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::get_segment_mut(&mut self, usize) -> core::option::Option<&mut rns_protocol::resource::OutboundResource>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::is_complete(&self) -> bool
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::new(alloc::vec::Vec<u8>, bool) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::num_segments(&self) -> usize
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::with_encrypt(alloc::vec::Vec<u8>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::MultiSegmentOutbound::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>, core::option::Option<usize>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::OutboundResource
|
||||
pub rns_protocol::resource::OutboundResource::advertisement_data_size: usize
|
||||
pub rns_protocol::resource::OutboundResource::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource::OutboundResource::expected_proof: [u8; 32]
|
||||
pub rns_protocol::resource::OutboundResource::flags: rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource::OutboundResource::map_hashes: alloc::vec::Vec<[u8; 4]>
|
||||
pub rns_protocol::resource::OutboundResource::metadata: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::OutboundResource::metadata_size: usize
|
||||
pub rns_protocol::resource::OutboundResource::original_hash: core::option::Option<[u8; 32]>
|
||||
pub rns_protocol::resource::OutboundResource::parts: alloc::vec::Vec<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::OutboundResource::random_hash: [u8; 4]
|
||||
pub rns_protocol::resource::OutboundResource::request_id: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource::OutboundResource::resource_hash: [u8; 32]
|
||||
pub rns_protocol::resource::OutboundResource::retries: usize
|
||||
pub rns_protocol::resource::OutboundResource::sdu: usize
|
||||
pub rns_protocol::resource::OutboundResource::segment_index: usize
|
||||
pub rns_protocol::resource::OutboundResource::state: rns_protocol::resource::ResourceState
|
||||
pub rns_protocol::resource::OutboundResource::total_segments: usize
|
||||
pub rns_protocol::resource::OutboundResource::total_size: usize
|
||||
pub rns_protocol::resource::OutboundResource::window: rns_protocol::resource::WindowState
|
||||
impl rns_protocol::resource::OutboundResource
|
||||
pub fn rns_protocol::resource::OutboundResource::get_part(&self, usize) -> core::option::Option<&[u8]>
|
||||
pub fn rns_protocol::resource::OutboundResource::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::OutboundResource::handle_hmu(&mut self, &[u8]) -> alloc::vec::Vec<usize>
|
||||
pub fn rns_protocol::resource::OutboundResource::new(alloc::vec::Vec<u8>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::OutboundResource::num_parts(&self) -> usize
|
||||
pub fn rns_protocol::resource::OutboundResource::validate_proof(&mut self, &[u8]) -> bool
|
||||
pub fn rns_protocol::resource::OutboundResource::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<usize>, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub struct rns_protocol::resource::OutboundTransfer
|
||||
pub rns_protocol::resource::OutboundTransfer::advertised: bool
|
||||
pub rns_protocol::resource::OutboundTransfer::advertisement_mdu: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::advertisement_timeout: core::option::Option<core::time::Duration>
|
||||
pub rns_protocol::resource::OutboundTransfer::awaiting_hmu: bool
|
||||
pub rns_protocol::resource::OutboundTransfer::confirmed_parts: alloc::vec::Vec<bool>
|
||||
pub rns_protocol::resource::OutboundTransfer::cursor: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::last_part_sent: core::option::Option<std::time::Instant>
|
||||
pub rns_protocol::resource::OutboundTransfer::receiver_min_consecutive_height: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::resource: rns_protocol::resource::OutboundResource
|
||||
pub rns_protocol::resource::OutboundTransfer::retries: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::rtt: core::time::Duration
|
||||
pub rns_protocol::resource::OutboundTransfer::sent_parts: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::started_at: std::time::Instant
|
||||
pub rns_protocol::resource::OutboundTransfer::window_cursor: usize
|
||||
pub rns_protocol::resource::OutboundTransfer::window_max_sent: usize
|
||||
impl rns_protocol::resource::OutboundTransfer
|
||||
pub fn rns_protocol::resource::OutboundTransfer::all_confirmed(&self) -> bool
|
||||
pub fn rns_protocol::resource::OutboundTransfer::cancel(&mut self, &str) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::OutboundTransfer::check_timeout(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::OutboundTransfer::failure_reason(&self) -> core::option::Option<&str>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::from_prebuilt(rns_protocol::resource::OutboundResource, core::time::Duration) -> Self
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_cancel(&mut self)
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_hmu(&mut self, &[u8])
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_proof(&mut self, &[u8]) -> bool
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_request(&mut self, &[u8]) -> alloc::vec::Vec<rns_protocol::resource::TransferAction>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::handle_request_packet(&mut self, [u8; 32], &[u8]) -> alloc::vec::Vec<rns_protocol::resource::TransferAction>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::new(alloc::vec::Vec<u8>, bool, core::time::Duration) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::new_encrypted(alloc::vec::Vec<u8>, bool, core::time::Duration, rns_link::key_derivation::LinkKeys) -> core::result::Result<Self, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::progress(&self) -> f64
|
||||
pub fn rns_protocol::resource::OutboundTransfer::tick(&mut self) -> rns_protocol::resource::TransferAction
|
||||
pub fn rns_protocol::resource::OutboundTransfer::timeout_window(&self) -> core::option::Option<(std::time::Instant, core::time::Duration)>
|
||||
pub fn rns_protocol::resource::OutboundTransfer::with_app_flag(self, bool) -> Self
|
||||
pub struct rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource::ResourceFlags::app_flag: bool
|
||||
pub rns_protocol::resource::ResourceFlags::compressed: bool
|
||||
pub rns_protocol::resource::ResourceFlags::encrypted: bool
|
||||
pub rns_protocol::resource::ResourceFlags::has_metadata: bool
|
||||
pub rns_protocol::resource::ResourceFlags::is_request: bool
|
||||
pub rns_protocol::resource::ResourceFlags::is_response: bool
|
||||
pub rns_protocol::resource::ResourceFlags::split: bool
|
||||
impl rns_protocol::resource::ResourceFlags
|
||||
pub fn rns_protocol::resource::ResourceFlags::from_byte(u8) -> Self
|
||||
pub fn rns_protocol::resource::ResourceFlags::to_byte(&self) -> u8
|
||||
pub struct rns_protocol::resource::WindowState
|
||||
pub rns_protocol::resource::WindowState::fast_rate_rounds: usize
|
||||
pub rns_protocol::resource::WindowState::very_slow_rate_rounds: usize
|
||||
pub rns_protocol::resource::WindowState::window: usize
|
||||
pub rns_protocol::resource::WindowState::window_max: usize
|
||||
pub rns_protocol::resource::WindowState::window_min: usize
|
||||
impl rns_protocol::resource::WindowState
|
||||
pub fn rns_protocol::resource::WindowState::grow(&mut self)
|
||||
pub fn rns_protocol::resource::WindowState::new() -> Self
|
||||
pub fn rns_protocol::resource::WindowState::on_first_part(&mut self, f64)
|
||||
pub fn rns_protocol::resource::WindowState::on_window_drained(&mut self, f64)
|
||||
pub fn rns_protocol::resource::WindowState::shrink(&mut self)
|
||||
impl core::default::Default for rns_protocol::resource::WindowState
|
||||
pub fn rns_protocol::resource::WindowState::default() -> Self
|
||||
pub const rns_protocol::resource::DEFAULT_INBOUND_REASSEMBLY_LIMIT: usize
|
||||
pub const rns_protocol::resource::EIFR_COLD_START_BYTES: usize
|
||||
pub const rns_protocol::resource::FAST_RATE_THRESHOLD: usize
|
||||
pub const rns_protocol::resource::HASHMAP_IS_EMPTY: u8
|
||||
pub const rns_protocol::resource::HASHMAP_IS_EXHAUSTED: u8
|
||||
pub const rns_protocol::resource::HASHMAP_IS_NOT_EXHAUSTED: u8
|
||||
pub const rns_protocol::resource::HMU_WAIT_FACTOR: f64
|
||||
pub const rns_protocol::resource::MAPHASH_LEN: usize
|
||||
pub const rns_protocol::resource::MAX_ADV_RETRIES: usize
|
||||
pub const rns_protocol::resource::MAX_EFFICIENT_SIZE: usize
|
||||
pub const rns_protocol::resource::MAX_RESOURCE_SIZE: usize
|
||||
pub const rns_protocol::resource::MAX_RETRIES: usize
|
||||
pub const rns_protocol::resource::MAX_SEGMENTS: usize
|
||||
pub const rns_protocol::resource::METADATA_MAX_SIZE: usize
|
||||
pub const rns_protocol::resource::PART_TIMEOUT_FACTOR: f64
|
||||
pub const rns_protocol::resource::PART_TIMEOUT_FACTOR_AFTER_RTT: f64
|
||||
pub const rns_protocol::resource::PER_RETRY_DELAY: f64
|
||||
pub const rns_protocol::resource::PROCESSING_GRACE: f64
|
||||
pub const rns_protocol::resource::PROOF_CACHE_QUERIES: usize
|
||||
pub const rns_protocol::resource::PROOF_TIMEOUT_FACTOR: f64
|
||||
pub const rns_protocol::resource::RANDOM_HASH_SIZE: usize
|
||||
pub const rns_protocol::resource::RATE_FAST: usize
|
||||
pub const rns_protocol::resource::RATE_VERY_SLOW: usize
|
||||
pub const rns_protocol::resource::RETRY_GRACE_TIME: f64
|
||||
pub const rns_protocol::resource::SDU: usize
|
||||
pub const rns_protocol::resource::SENDER_GRACE_TIME: f64
|
||||
pub const rns_protocol::resource::VERY_SLOW_RATE_THRESHOLD: usize
|
||||
pub const rns_protocol::resource::WATCHDOG_MAX_SLEEP: f64
|
||||
pub const rns_protocol::resource::WINDOW_FLEXIBILITY: usize
|
||||
pub const rns_protocol::resource::WINDOW_INITIAL: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX_FAST: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX_SLOW: usize
|
||||
pub const rns_protocol::resource::WINDOW_MAX_VERY_SLOW: usize
|
||||
pub const rns_protocol::resource::WINDOW_MIN: usize
|
||||
pub fn rns_protocol::resource::compute_expected_proof(&[u8], &[u8; 32]) -> [u8; 32]
|
||||
pub fn rns_protocol::resource::compute_resource_hash(&[u8], &[u8]) -> [u8; 32]
|
||||
pub fn rns_protocol::resource::get_map_hash(&[u8], &[u8]) -> [u8; 4]
|
||||
pub fn rns_protocol::resource::parse_hashmap_update(&[u8]) -> core::result::Result<([u8; 32], usize, alloc::vec::Vec<u8>), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource::resource_proof_packet_hash(&[u8; 16], &[u8]) -> [u8; 32]
|
||||
pub type rns_protocol::resource::ResourceDecryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_protocol::resource::ResourceError> + 'a)
|
||||
pub type rns_protocol::resource::ResourceEncryptor<'a> = (dyn core::ops::function::Fn(&[u8]) -> alloc::vec::Vec<u8> + 'a)
|
||||
pub mod rns_protocol::resource_adv
|
||||
pub struct rns_protocol::resource_adv::ResourceAdvertisement
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::data_size: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::flags: rns_protocol::resource::ResourceFlags
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::hashmap: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::metadata_size: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::num_parts: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::original_hash: [u8; 32]
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::random_hash: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::request_id: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::resource_hash: [u8; 32]
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::segment_index: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::total_segments: usize
|
||||
pub rns_protocol::resource_adv::ResourceAdvertisement::transfer_size: usize
|
||||
impl rns_protocol::resource_adv::ResourceAdvertisement
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::defer_hashmap_if_over(&mut self, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::encoded_len(&self) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::get_map_hashes(&self) -> alloc::vec::Vec<[u8; 4]>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::new(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize) -> Self
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::pack_into<W: core::io::write::Write>(&self, W) -> core::result::Result<(), rmp_serde::encode::Error>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::unpack(&[u8]) -> core::result::Result<Self, alloc::string::String>
|
||||
pub fn rns_protocol::resource_adv::ResourceAdvertisement::with_metadata_size(usize, usize, usize, [u8; 32], alloc::vec::Vec<u8>, rns_protocol::resource::ResourceFlags, &[[u8; 4]], usize, usize) -> Self
|
||||
pub const rns_protocol::resource_adv::OVERHEAD: usize
|
||||
pub fn rns_protocol::resource_adv::collision_guard_size(usize) -> usize
|
||||
pub fn rns_protocol::resource_adv::hashmap_max_len(usize) -> usize
|
||||
pub mod rns_protocol::resource_control
|
||||
pub const rns_protocol::resource_control::HASHMAP_STRIDE: usize
|
||||
pub fn rns_protocol::resource_control::check_advertisement(&rns_protocol::resource_adv::ResourceAdvertisement, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource_control::check_control_frame(rns_wire::context::PacketContext, usize, bool, usize, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource_control::encode_hashmap_update(&[u8; 32], usize, &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::resource_control::encrypted_len(usize) -> core::result::Result<usize, rns_protocol::resource::ResourceError>
|
||||
pub fn rns_protocol::resource_control::preflight_outbound(usize, core::option::Option<usize>, core::option::Option<&[u8]>, bool, bool, usize) -> core::result::Result<(), rns_protocol::resource::ResourceError>
|
||||
pub mod rns_protocol::rnsh
|
||||
pub enum rns_protocol::rnsh::RnshCodecError
|
||||
pub rns_protocol::rnsh::RnshCodecError::Decode(alloc::string::String)
|
||||
pub rns_protocol::rnsh::RnshCodecError::Encode(alloc::string::String)
|
||||
pub rns_protocol::rnsh::RnshCodecError::InvalidShape(&'static str)
|
||||
pub rns_protocol::rnsh::RnshCodecError::InvalidUtf8
|
||||
pub rns_protocol::rnsh::RnshCodecError::StreamData
|
||||
pub rns_protocol::rnsh::RnshCodecError::UnknownMessageType(u16)
|
||||
pub enum rns_protocol::rnsh::RnshMessage
|
||||
pub rns_protocol::rnsh::RnshMessage::CommandExited(rns_protocol::rnsh::CommandExitedMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::Error(rns_protocol::rnsh::ErrorMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::ExecuteCommand(rns_protocol::rnsh::ExecuteCommandMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::Noop(rns_protocol::rnsh::NoopMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::StreamData(rns_protocol::rnsh::RnshStreamDataMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::VersionInfo(rns_protocol::rnsh::VersionInfoMessage)
|
||||
pub rns_protocol::rnsh::RnshMessage::WindowSize(rns_protocol::rnsh::WindowSizeMessage)
|
||||
impl rns_protocol::rnsh::RnshMessage
|
||||
pub fn rns_protocol::rnsh::RnshMessage::decode(u16, &[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
pub fn rns_protocol::rnsh::RnshMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::RnshMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub struct rns_protocol::rnsh::CommandExitedMessage
|
||||
pub rns_protocol::rnsh::CommandExitedMessage::return_code: i64
|
||||
impl rns_protocol::rnsh::CommandExitedMessage
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::new(i64) -> Self
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::CommandExitedMessage
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::CommandExitedMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::ErrorMessage
|
||||
pub rns_protocol::rnsh::ErrorMessage::data: core::option::Option<rmpv::Value>
|
||||
pub rns_protocol::rnsh::ErrorMessage::fatal: bool
|
||||
pub rns_protocol::rnsh::ErrorMessage::msg: core::option::Option<alloc::string::String>
|
||||
impl rns_protocol::rnsh::ErrorMessage
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::new(core::option::Option<alloc::string::String>, bool, core::option::Option<rmpv::Value>) -> Self
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ErrorMessage
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ErrorMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::cmdline: core::option::Option<alloc::vec::Vec<alloc::string::String>>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::cols: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::hpix: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stderr: bool
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stdin: bool
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::pipe_stdout: bool
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::rows: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::tcflags: core::option::Option<rmpv::Value>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::term: core::option::Option<alloc::string::String>
|
||||
pub rns_protocol::rnsh::ExecuteCommandMessage::vpix: core::option::Option<u32>
|
||||
impl rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::new(core::option::Option<alloc::vec::Vec<alloc::string::String>>, bool, bool, bool, core::option::Option<rmpv::Value>, core::option::Option<alloc::string::String>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>) -> Self
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::ExecuteCommandMessage
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::ExecuteCommandMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::NoopMessage
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::NoopMessage
|
||||
pub fn rns_protocol::rnsh::NoopMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::NoopMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::NoopMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::compressed: bool
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::eof: bool
|
||||
pub rns_protocol::rnsh::RnshStreamDataMessage::stream_id: u16
|
||||
impl rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::new(u16, alloc::vec::Vec<u8>, bool) -> Self
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl core::default::Default for rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::default() -> Self
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::RnshStreamDataMessage
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::RnshStreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::VersionInfoMessage
|
||||
pub rns_protocol::rnsh::VersionInfoMessage::protocol_version: u64
|
||||
pub rns_protocol::rnsh::VersionInfoMessage::sw_version: alloc::string::String
|
||||
impl rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::new(impl core::convert::Into<alloc::string::String>) -> Self
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl core::default::Default for rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::default() -> Self
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::VersionInfoMessage
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::VersionInfoMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub struct rns_protocol::rnsh::WindowSizeMessage
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::cols: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::hpix: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::rows: core::option::Option<u32>
|
||||
pub rns_protocol::rnsh::WindowSizeMessage::vpix: core::option::Option<u32>
|
||||
impl rns_protocol::rnsh::WindowSizeMessage
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::new(core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>, core::option::Option<u32>) -> Self
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack_payload(&[u8]) -> core::result::Result<Self, rns_protocol::rnsh::RnshCodecError>
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::rnsh::WindowSizeMessage
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::rnsh::WindowSizeMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub const rns_protocol::rnsh::MESSAGE_TYPES: [u16; 7]
|
||||
pub const rns_protocol::rnsh::MSG_MAGIC: u8
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_COMMAND_EXITED: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_ERROR: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_EXECUTE_COMMAND: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_NOOP: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_STREAM_DATA: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_VERSION_INFO: u16
|
||||
pub const rns_protocol::rnsh::MSG_TYPE_WINDOW_SIZE: u16
|
||||
pub const rns_protocol::rnsh::PROTOCOL_VERSION: u64
|
||||
pub const rns_protocol::rnsh::STREAM_ID_MAX: u16
|
||||
pub const rns_protocol::rnsh::STREAM_ID_STDERR: u16
|
||||
pub const rns_protocol::rnsh::STREAM_ID_STDIN: u16
|
||||
pub const rns_protocol::rnsh::STREAM_ID_STDOUT: u16
|
||||
pub const fn rns_protocol::rnsh::make_msg_type(u8) -> u16
|
||||
pub mod rns_protocol::stream_data
|
||||
pub struct rns_protocol::stream_data::StreamDataMessage
|
||||
pub rns_protocol::stream_data::StreamDataMessage::compressed: bool
|
||||
pub rns_protocol::stream_data::StreamDataMessage::data: alloc::vec::Vec<u8>
|
||||
pub rns_protocol::stream_data::StreamDataMessage::eof: bool
|
||||
pub rns_protocol::stream_data::StreamDataMessage::stream_id: u16
|
||||
impl rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::new(u16, alloc::vec::Vec<u8>, bool) -> Self
|
||||
impl rns_protocol::channel_message::MessageBase for rns_protocol::stream_data::StreamDataMessage
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::msg_type(&self) -> u16
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_protocol::stream_data::StreamDataMessage::unpack(&mut self, &[u8]) -> core::result::Result<(), rns_protocol::channel_message::ChannelMessageError>
|
||||
pub const rns_protocol::stream_data::OVERHEAD: usize
|
||||
pub const rns_protocol::stream_data::STREAM_ID_MAX: u16
|
||||
@@ -0,0 +1,618 @@
|
||||
pub mod rns_ratkey
|
||||
pub mod rns_ratkey::apdu
|
||||
pub const rns_ratkey::apdu::ALG_ECCP256: u8
|
||||
pub const rns_ratkey::apdu::ALG_ECCP384: u8
|
||||
pub const rns_ratkey::apdu::ALG_ED25519: u8
|
||||
pub const rns_ratkey::apdu::ALG_X25519: u8
|
||||
pub const rns_ratkey::apdu::INS_ATTEST: u8
|
||||
pub const rns_ratkey::apdu::INS_CHANGE_REFERENCE: u8
|
||||
pub const rns_ratkey::apdu::INS_GENERAL_AUTHENTICATE: u8
|
||||
pub const rns_ratkey::apdu::INS_GENERATE_ASYMMETRIC: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_DATA: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_METADATA: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_SERIAL: u8
|
||||
pub const rns_ratkey::apdu::INS_GET_VERSION: u8
|
||||
pub const rns_ratkey::apdu::INS_IMPORT_KEY: u8
|
||||
pub const rns_ratkey::apdu::INS_RESET_PIV: u8
|
||||
pub const rns_ratkey::apdu::INS_RESET_RETRY: u8
|
||||
pub const rns_ratkey::apdu::INS_SELECT: u8
|
||||
pub const rns_ratkey::apdu::INS_VERIFY: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_AES128: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_AES192: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_AES256: u8
|
||||
pub const rns_ratkey::apdu::MGMT_ALG_TDES: u8
|
||||
pub const rns_ratkey::apdu::OBJ_ID_9A: &[u8]
|
||||
pub const rns_ratkey::apdu::OBJ_ID_9D: &[u8]
|
||||
pub const rns_ratkey::apdu::OBJ_ID_F9: &[u8]
|
||||
pub const rns_ratkey::apdu::PIN_POLICY_ALWAYS: u8
|
||||
pub const rns_ratkey::apdu::PIN_POLICY_NEVER: u8
|
||||
pub const rns_ratkey::apdu::PIN_POLICY_ONCE: u8
|
||||
pub const rns_ratkey::apdu::PIV_AID: &[u8]
|
||||
pub const rns_ratkey::apdu::SLOT_ATTESTATION: u8
|
||||
pub const rns_ratkey::apdu::SLOT_AUTHENTICATION: u8
|
||||
pub const rns_ratkey::apdu::SLOT_CARD_AUTH: u8
|
||||
pub const rns_ratkey::apdu::SLOT_CARD_MANAGEMENT: u8
|
||||
pub const rns_ratkey::apdu::SLOT_KEY_MANAGEMENT: u8
|
||||
pub const rns_ratkey::apdu::SLOT_SIGNATURE: u8
|
||||
pub const rns_ratkey::apdu::TOUCH_POLICY_ALWAYS: u8
|
||||
pub const rns_ratkey::apdu::TOUCH_POLICY_CACHED: u8
|
||||
pub const rns_ratkey::apdu::TOUCH_POLICY_NEVER: u8
|
||||
pub fn rns_ratkey::apdu::attest_key(u8) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::auth_witness_request(u8) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::auth_witness_response(u8, &[u8], &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::change_pin(&str, &str) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::check_response(&[u8]) -> core::result::Result<&[u8], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::ecdh_x25519(u8, &[u8; 32]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::generate_key(u8, u8, core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::get_data(u8) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_ratkey::apdu::get_metadata(u8) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::get_serial() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::get_version() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::import_ed25519(u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::import_x25519(u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::parse_auth_response(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_auth_witness(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_certificate_object(&[u8]) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_ratkey::apdu::parse_ecdh_response(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_generate_response(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_metadata_algorithm(&[u8]) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_metadata_public_key(&[u8]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_serial_response(&[u8]) -> core::result::Result<u32, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_sign_response(&[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::parse_version_response(&[u8]) -> core::result::Result<(u8, u8, u8), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::apdu::reset_piv() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::reset_retry(&str, &str) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::select_piv() -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::sign_ed25519(u8, &[u8]) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_ratkey::apdu::slot_to_object_id(u8) -> core::option::Option<&'static [u8]>
|
||||
pub fn rns_ratkey::apdu::verify_pin(&str) -> alloc::vec::Vec<u8>
|
||||
pub mod rns_ratkey::attestation
|
||||
pub struct rns_ratkey::attestation::AttestationInfo
|
||||
pub rns_ratkey::attestation::AttestationInfo::attestation_cert_der: alloc::vec::Vec<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::device_cert_der: alloc::vec::Vec<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::firmware_version: core::option::Option<(u8, u8, u8)>
|
||||
pub rns_ratkey::attestation::AttestationInfo::form_factor: core::option::Option<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::pin_policy: core::option::Option<u8>
|
||||
pub rns_ratkey::attestation::AttestationInfo::serial_number: core::option::Option<u32>
|
||||
pub rns_ratkey::attestation::AttestationInfo::touch_policy: core::option::Option<u8>
|
||||
pub struct rns_ratkey::attestation::AttestationVerification
|
||||
pub rns_ratkey::attestation::AttestationVerification::chain_verified: bool
|
||||
pub rns_ratkey::attestation::AttestationVerification::description: alloc::string::String
|
||||
pub rns_ratkey::attestation::AttestationVerification::info: rns_ratkey::attestation::AttestationInfo
|
||||
pub rns_ratkey::attestation::AttestationVerification::metadata_extracted: bool
|
||||
pub rns_ratkey::attestation::AttestationVerification::root_ca: alloc::string::String
|
||||
pub rns_ratkey::attestation::AttestationVerification::verified: bool
|
||||
pub const rns_ratkey::attestation::OID_FIRMWARE_VERSION: &[u8]
|
||||
pub const rns_ratkey::attestation::OID_FORM_FACTOR: &[u8]
|
||||
pub const rns_ratkey::attestation::OID_SERIAL_NUMBER: &[u8]
|
||||
pub const rns_ratkey::attestation::OID_USAGE_POLICY: &[u8]
|
||||
pub const rns_ratkey::attestation::YUBICO_ATTESTATION_ROOT_1_PEM: &str
|
||||
pub const rns_ratkey::attestation::YUBICO_LEGACY_ROOT_SHA256: &str
|
||||
pub const rns_ratkey::attestation::YUBICO_NEW_ROOT_SHA256: &str
|
||||
pub const rns_ratkey::attestation::YUBICO_PIV_ROOT_CA_LEGACY_PEM: &str
|
||||
pub fn rns_ratkey::attestation::pem_to_der(&str) -> core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub fn rns_ratkey::attestation::supports_attestation(&str) -> bool
|
||||
pub fn rns_ratkey::attestation::verify_attestation(&[u8], &[u8]) -> core::result::Result<rns_ratkey::attestation::AttestationVerification, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::backend
|
||||
pub struct rns_ratkey::backend::HardwareBackend
|
||||
impl rns_identity::identity::LocalKeyBackend for rns_ratkey::backend::HardwareBackend
|
||||
pub fn rns_ratkey::backend::HardwareBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_ratkey::backend::HardwareBackend::lock(&self)
|
||||
pub fn rns_ratkey::backend::HardwareBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub fn rns_ratkey::backend::load_hardware_identity(&rns_ratkey::hwid::HwidConfig, &str) -> core::result::Result<rns_identity::identity::Identity, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::detect
|
||||
pub enum rns_ratkey::detect::DeviceType
|
||||
pub rns_ratkey::detect::DeviceType::Nitrokey3
|
||||
pub rns_ratkey::detect::DeviceType::Unknown
|
||||
pub rns_ratkey::detect::DeviceType::YubiKey5
|
||||
impl rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::detect::DeviceType::as_str(&self) -> &'static str
|
||||
pub struct rns_ratkey::detect::DeviceInfo
|
||||
pub rns_ratkey::detect::DeviceInfo::device_type: alloc::string::String
|
||||
pub rns_ratkey::detect::DeviceInfo::firmware: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::detect::DeviceInfo::has_encryption_key: bool
|
||||
pub rns_ratkey::detect::DeviceInfo::has_signing_key: bool
|
||||
pub rns_ratkey::detect::DeviceInfo::reader_name: alloc::string::String
|
||||
pub rns_ratkey::detect::DeviceInfo::serial: core::option::Option<u32>
|
||||
pub fn rns_ratkey::detect::detect_device_type(&str) -> rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::detect::detect_devices() -> core::result::Result<alloc::vec::Vec<rns_ratkey::detect::DeviceInfo>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::detect::list_readers() -> core::result::Result<alloc::vec::Vec<alloc::string::String>, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::error
|
||||
pub enum rns_ratkey::error::RatkeyError
|
||||
pub rns_ratkey::error::RatkeyError::Apdu
|
||||
pub rns_ratkey::error::RatkeyError::Apdu::sw1: u8
|
||||
pub rns_ratkey::error::RatkeyError::Apdu::sw2: u8
|
||||
pub rns_ratkey::error::RatkeyError::Disconnected
|
||||
pub rns_ratkey::error::RatkeyError::EcdhFailed(alloc::string::String)
|
||||
pub rns_ratkey::error::RatkeyError::EmptySlot
|
||||
pub rns_ratkey::error::RatkeyError::EmptySlot::slot: u8
|
||||
pub rns_ratkey::error::RatkeyError::FirmwareVersion
|
||||
pub rns_ratkey::error::RatkeyError::FirmwareVersion::found: alloc::string::String
|
||||
pub rns_ratkey::error::RatkeyError::FirmwareVersion::required: alloc::string::String
|
||||
pub rns_ratkey::error::RatkeyError::InvalidHwid(alloc::string::String)
|
||||
pub rns_ratkey::error::RatkeyError::Io(core::io::error::Error)
|
||||
pub rns_ratkey::error::RatkeyError::KeyMismatch
|
||||
pub rns_ratkey::error::RatkeyError::ManagementAuthFailed
|
||||
pub rns_ratkey::error::RatkeyError::NoDevice
|
||||
pub rns_ratkey::error::RatkeyError::Pcsc(pcsc::Error)
|
||||
pub rns_ratkey::error::RatkeyError::PinFailed
|
||||
pub rns_ratkey::error::RatkeyError::PinFailed::remaining: u8
|
||||
pub rns_ratkey::error::RatkeyError::PinLocked
|
||||
pub rns_ratkey::error::RatkeyError::PinRequired
|
||||
pub rns_ratkey::error::RatkeyError::PukFailed
|
||||
pub rns_ratkey::error::RatkeyError::PukFailed::remaining: u8
|
||||
pub rns_ratkey::error::RatkeyError::PukLocked
|
||||
pub rns_ratkey::error::RatkeyError::ResetRequiresBlockedPinAndPuk
|
||||
pub rns_ratkey::error::RatkeyError::SigningFailed(alloc::string::String)
|
||||
pub rns_ratkey::error::RatkeyError::SlotOccupied
|
||||
pub rns_ratkey::error::RatkeyError::SlotOccupied::slot: u8
|
||||
pub rns_ratkey::error::RatkeyError::TouchRequired
|
||||
pub rns_ratkey::error::RatkeyError::UnsupportedDevice(alloc::string::String)
|
||||
pub mod rns_ratkey::hardware
|
||||
pub struct rns_ratkey::hardware::HardwareIdentity
|
||||
pub rns_ratkey::hardware::HardwareIdentity::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::hardware::HardwareIdentity::identity: rns_identity::identity::Identity
|
||||
impl rns_ratkey::hardware::HardwareIdentity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::as_identity(&self) -> &rns_identity::identity::Identity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::decrypt(&mut self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ecdh(&mut self, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ed25519_public(&self) -> &[u8; 32]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_file(&std::path::Path, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_hwid(rns_ratkey::hwid::HwidConfig, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_keys([u8; 32], [u8; 32], alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::get_public_key(&self) -> [u8; 64]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash(&self) -> &[u8; 16]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash_hex(&self) -> alloc::string::String
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::sign(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::verify(&self, &[u8], &[u8; 64]) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::x25519_public(&self) -> &[u8; 32]
|
||||
pub trait rns_ratkey::hardware::IdentityBackend
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::IdentityBackend::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::hwid
|
||||
pub struct rns_ratkey::hwid::HwidApp
|
||||
pub rns_ratkey::hwid::HwidApp::app_hash: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidAttestation
|
||||
pub rns_ratkey::hwid::HwidAttestation::ed25519_cert: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidAttestation::verified: bool
|
||||
pub rns_ratkey::hwid::HwidAttestation::x25519_cert: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidBackup
|
||||
pub rns_ratkey::hwid::HwidBackup::backup_serial: core::option::Option<u32>
|
||||
pub rns_ratkey::hwid::HwidBackup::encrypted_backup_hash: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::hwid::HwidBackup::tier: u8
|
||||
pub struct rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::hwid::HwidConfig::app: rns_ratkey::hwid::HwidApp
|
||||
pub rns_ratkey::hwid::HwidConfig::attestation: rns_ratkey::hwid::HwidAttestation
|
||||
pub rns_ratkey::hwid::HwidConfig::backup: rns_ratkey::hwid::HwidBackup
|
||||
pub rns_ratkey::hwid::HwidConfig::device: rns_ratkey::hwid::HwidDevice
|
||||
pub rns_ratkey::hwid::HwidConfig::identity: rns_ratkey::hwid::HwidIdentity
|
||||
pub rns_ratkey::hwid::HwidConfig::keys: rns_ratkey::hwid::HwidKeys
|
||||
pub rns_ratkey::hwid::HwidConfig::policy: rns_ratkey::hwid::HwidPolicy
|
||||
pub rns_ratkey::hwid::HwidConfig::slots: rns_ratkey::hwid::HwidSlots
|
||||
impl rns_ratkey::hwid::HwidConfig
|
||||
pub fn rns_ratkey::hwid::HwidConfig::ed25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::encryption_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_file(&std::path::Path) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::signing_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_string(&self) -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::x25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
impl core::str::traits::FromStr for rns_ratkey::hwid::HwidConfig
|
||||
pub type rns_ratkey::hwid::HwidConfig::Err = rns_ratkey::error::RatkeyError
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_str(&str) -> core::result::Result<Self, Self::Err>
|
||||
pub struct rns_ratkey::hwid::HwidDevice
|
||||
pub rns_ratkey::hwid::HwidDevice::device_type: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidDevice::firmware: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidDevice::serial: u32
|
||||
pub struct rns_ratkey::hwid::HwidIdentity
|
||||
pub rns_ratkey::hwid::HwidIdentity::created_at: u64
|
||||
pub rns_ratkey::hwid::HwidIdentity::hash: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidIdentity::nickname: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidKeys
|
||||
pub rns_ratkey::hwid::HwidKeys::ed25519_pub: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidKeys::x25519_pub: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidPolicy
|
||||
pub rns_ratkey::hwid::HwidPolicy::pin_cache_timeout: u64
|
||||
pub rns_ratkey::hwid::HwidPolicy::touch_encryption: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidPolicy::touch_signing: alloc::string::String
|
||||
pub struct rns_ratkey::hwid::HwidSlots
|
||||
pub rns_ratkey::hwid::HwidSlots::encryption: alloc::string::String
|
||||
pub rns_ratkey::hwid::HwidSlots::signing: alloc::string::String
|
||||
pub mod rns_ratkey::mgmt
|
||||
pub fn rns_ratkey::mgmt::block_len(u8) -> core::option::Option<usize>
|
||||
pub fn rns_ratkey::mgmt::ecb_decrypt(u8, &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mgmt::ecb_encrypt(u8, &[u8], &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mgmt::key_len(u8) -> core::option::Option<usize>
|
||||
pub mod rns_ratkey::mock
|
||||
pub enum rns_ratkey::mock::MockOperation
|
||||
pub rns_ratkey::mock::MockOperation::EcdhX25519
|
||||
pub rns_ratkey::mock::MockOperation::EcdhX25519::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::GenerateEd25519
|
||||
pub rns_ratkey::mock::MockOperation::GenerateEd25519::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::GenerateX25519
|
||||
pub rns_ratkey::mock::MockOperation::GenerateX25519::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::PinUnblock
|
||||
pub rns_ratkey::mock::MockOperation::PinUnblock::success: bool
|
||||
pub rns_ratkey::mock::MockOperation::PinVerify
|
||||
pub rns_ratkey::mock::MockOperation::PinVerify::success: bool
|
||||
pub rns_ratkey::mock::MockOperation::ReadPublicKey
|
||||
pub rns_ratkey::mock::MockOperation::ReadPublicKey::slot: u8
|
||||
pub rns_ratkey::mock::MockOperation::ResetPiv
|
||||
pub rns_ratkey::mock::MockOperation::ResetPiv::success: bool
|
||||
pub rns_ratkey::mock::MockOperation::SignEd25519
|
||||
pub rns_ratkey::mock::MockOperation::SignEd25519::data_len: usize
|
||||
pub rns_ratkey::mock::MockOperation::SignEd25519::slot: u8
|
||||
pub enum rns_ratkey::mock::TouchPolicy
|
||||
pub rns_ratkey::mock::TouchPolicy::Always
|
||||
pub rns_ratkey::mock::TouchPolicy::Cached
|
||||
pub rns_ratkey::mock::TouchPolicy::Never
|
||||
pub struct rns_ratkey::mock::MockPivSession
|
||||
pub rns_ratkey::mock::MockPivSession::device_type: alloc::string::String
|
||||
pub rns_ratkey::mock::MockPivSession::firmware: alloc::string::String
|
||||
pub rns_ratkey::mock::MockPivSession::operations: alloc::vec::Vec<rns_ratkey::mock::MockOperation>
|
||||
pub rns_ratkey::mock::MockPivSession::serial: u32
|
||||
impl rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::disconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_ed25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_x25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::new() -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::reconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::require_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_pin(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_puk(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::simulate_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_key_bytes(&[u8; 32], &[u8; 32]) -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_keys() -> Self
|
||||
impl core::default::Default for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::default() -> Self
|
||||
impl core::ops::drop::Drop for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::drop(&mut self)
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub const rns_ratkey::mock::SLOT_9A: u8
|
||||
pub const rns_ratkey::mock::SLOT_9D: u8
|
||||
pub mod rns_ratkey::pin
|
||||
pub struct rns_ratkey::pin::PinCache
|
||||
impl rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::cache(&mut self, &str)
|
||||
pub fn rns_ratkey::pin::PinCache::clear(&mut self)
|
||||
pub fn rns_ratkey::pin::PinCache::default_timeout() -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::get(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::pin::PinCache::is_cached(&self) -> bool
|
||||
pub fn rns_ratkey::pin::PinCache::new(core::time::Duration) -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::remaining(&self) -> core::option::Option<core::time::Duration>
|
||||
impl core::ops::drop::Drop for rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::drop(&mut self)
|
||||
pub mod rns_ratkey::provision
|
||||
pub struct rns_ratkey::provision::ProvisionConfig
|
||||
pub rns_ratkey::provision::ProvisionConfig::identities_dir: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::provision::ProvisionConfig::nickname: alloc::string::String
|
||||
pub rns_ratkey::provision::ProvisionConfig::pin: alloc::string::String
|
||||
pub rns_ratkey::provision::ProvisionConfig::touch_encryption: rns_ratkey::mock::TouchPolicy
|
||||
pub rns_ratkey::provision::ProvisionConfig::touch_signing: rns_ratkey::mock::TouchPolicy
|
||||
impl core::default::Default for rns_ratkey::provision::ProvisionConfig
|
||||
pub fn rns_ratkey::provision::ProvisionConfig::default() -> Self
|
||||
pub struct rns_ratkey::provision::ProvisionResult
|
||||
pub rns_ratkey::provision::ProvisionResult::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::provision::ProvisionResult::ed25519_pub: [u8; 32]
|
||||
pub rns_ratkey::provision::ProvisionResult::hwid_path: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::provision::ProvisionResult::identity_hash: [u8; 16]
|
||||
pub rns_ratkey::provision::ProvisionResult::identity_hash_hex: alloc::string::String
|
||||
pub rns_ratkey::provision::ProvisionResult::x25519_pub: [u8; 32]
|
||||
pub fn rns_ratkey::provision::compute_identity_hash(&[u8; 32], &[u8; 32]) -> [u8; 16]
|
||||
pub fn rns_ratkey::provision::import_recoverable_identity<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig, &str) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::provision_hardware_only<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::provision_mock(&mut rns_ratkey::mock::MockPivSession, &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::provision_recoverable<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<(rns_ratkey::provision::ProvisionResult, alloc::string::String), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::read_existing<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &rns_ratkey::provision::ProvisionConfig) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::provision::restore<T: rns_ratkey::transport::PivTransport>(&mut rns_ratkey::session::PivSession<T>, &[u8], &rns_ratkey::provision::ProvisionConfig, &str) -> core::result::Result<rns_ratkey::provision::ProvisionResult, rns_ratkey::error::RatkeyError>
|
||||
pub mod rns_ratkey::seed
|
||||
pub struct rns_ratkey::seed::DerivedIdentity
|
||||
pub rns_ratkey::seed::DerivedIdentity::ed25519_pub: [u8; 32]
|
||||
pub rns_ratkey::seed::DerivedIdentity::ed25519_seed: [u8; 32]
|
||||
pub rns_ratkey::seed::DerivedIdentity::x25519_pub: [u8; 32]
|
||||
pub rns_ratkey::seed::DerivedIdentity::x25519_secret: [u8; 32]
|
||||
impl core::ops::drop::Drop for rns_ratkey::seed::DerivedIdentity
|
||||
pub fn rns_ratkey::seed::DerivedIdentity::drop(&mut self)
|
||||
pub fn rns_ratkey::seed::derive_identity(&str) -> core::result::Result<rns_ratkey::seed::DerivedIdentity, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::seed::generate_mnemonic() -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::seed::validate_mnemonic(&str) -> bool
|
||||
pub mod rns_ratkey::session
|
||||
pub struct rns_ratkey::session::DeviceMeta
|
||||
pub rns_ratkey::session::DeviceMeta::device_type: rns_ratkey::detect::DeviceType
|
||||
pub rns_ratkey::session::DeviceMeta::firmware: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::session::DeviceMeta::serial: core::option::Option<u32>
|
||||
pub struct rns_ratkey::session::PivSession<T: rns_ratkey::transport::PivTransport>
|
||||
impl rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect() -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect_reader(&str) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::attest_key(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::authenticate_management_key(&mut self, &[u8]) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::change_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::device_type(&self) -> rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::firmware(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_ed25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_x25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_ed25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_x25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::new(T, rns_ratkey::session::DeviceMeta) -> Self
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_attestation_cert(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_certificate(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_metadata(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_public_key(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::serial(&self) -> core::option::Option<u32>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub type rns_ratkey::session::PcscPivSession = rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
pub mod rns_ratkey::transport
|
||||
pub struct rns_ratkey::transport::PcscTransport
|
||||
impl rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::connect() -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::PcscTransport::connect_reader(&str) -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub trait rns_ratkey::transport::PivTransport
|
||||
pub fn rns_ratkey::transport::PivTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::transport::PivTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub enum rns_ratkey::RatkeyError
|
||||
pub rns_ratkey::RatkeyError::Apdu
|
||||
pub rns_ratkey::RatkeyError::Apdu::sw1: u8
|
||||
pub rns_ratkey::RatkeyError::Apdu::sw2: u8
|
||||
pub rns_ratkey::RatkeyError::Disconnected
|
||||
pub rns_ratkey::RatkeyError::EcdhFailed(alloc::string::String)
|
||||
pub rns_ratkey::RatkeyError::EmptySlot
|
||||
pub rns_ratkey::RatkeyError::EmptySlot::slot: u8
|
||||
pub rns_ratkey::RatkeyError::FirmwareVersion
|
||||
pub rns_ratkey::RatkeyError::FirmwareVersion::found: alloc::string::String
|
||||
pub rns_ratkey::RatkeyError::FirmwareVersion::required: alloc::string::String
|
||||
pub rns_ratkey::RatkeyError::InvalidHwid(alloc::string::String)
|
||||
pub rns_ratkey::RatkeyError::Io(core::io::error::Error)
|
||||
pub rns_ratkey::RatkeyError::KeyMismatch
|
||||
pub rns_ratkey::RatkeyError::ManagementAuthFailed
|
||||
pub rns_ratkey::RatkeyError::NoDevice
|
||||
pub rns_ratkey::RatkeyError::Pcsc(pcsc::Error)
|
||||
pub rns_ratkey::RatkeyError::PinFailed
|
||||
pub rns_ratkey::RatkeyError::PinFailed::remaining: u8
|
||||
pub rns_ratkey::RatkeyError::PinLocked
|
||||
pub rns_ratkey::RatkeyError::PinRequired
|
||||
pub rns_ratkey::RatkeyError::PukFailed
|
||||
pub rns_ratkey::RatkeyError::PukFailed::remaining: u8
|
||||
pub rns_ratkey::RatkeyError::PukLocked
|
||||
pub rns_ratkey::RatkeyError::ResetRequiresBlockedPinAndPuk
|
||||
pub rns_ratkey::RatkeyError::SigningFailed(alloc::string::String)
|
||||
pub rns_ratkey::RatkeyError::SlotOccupied
|
||||
pub rns_ratkey::RatkeyError::SlotOccupied::slot: u8
|
||||
pub rns_ratkey::RatkeyError::TouchRequired
|
||||
pub rns_ratkey::RatkeyError::UnsupportedDevice(alloc::string::String)
|
||||
pub struct rns_ratkey::DeviceMeta
|
||||
pub rns_ratkey::DeviceMeta::device_type: rns_ratkey::detect::DeviceType
|
||||
pub rns_ratkey::DeviceMeta::firmware: core::option::Option<alloc::string::String>
|
||||
pub rns_ratkey::DeviceMeta::serial: core::option::Option<u32>
|
||||
pub struct rns_ratkey::HardwareBackend
|
||||
impl rns_identity::identity::LocalKeyBackend for rns_ratkey::backend::HardwareBackend
|
||||
pub fn rns_ratkey::backend::HardwareBackend::ecdh(&self, &[u8; 32]) -> core::option::Option<[u8; 32]>
|
||||
pub fn rns_ratkey::backend::HardwareBackend::lock(&self)
|
||||
pub fn rns_ratkey::backend::HardwareBackend::sign_ed25519(&self, &[u8]) -> core::option::Option<[u8; 64]>
|
||||
pub struct rns_ratkey::HardwareIdentity
|
||||
pub rns_ratkey::HardwareIdentity::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::HardwareIdentity::identity: rns_identity::identity::Identity
|
||||
impl rns_ratkey::hardware::HardwareIdentity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::as_identity(&self) -> &rns_identity::identity::Identity
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::decrypt(&mut self, &[u8], core::option::Option<&[&[u8; 32]]>, bool) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ecdh(&mut self, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::ed25519_public(&self) -> &[u8; 32]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_file(&std::path::Path, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_hwid(rns_ratkey::hwid::HwidConfig, alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::from_keys([u8; 32], [u8; 32], alloc::boxed::Box<dyn rns_ratkey::hardware::IdentityBackend>) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::get_public_key(&self) -> [u8; 64]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash(&self) -> &[u8; 16]
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::hash_hex(&self) -> alloc::string::String
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::sign(&mut self, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::verify(&self, &[u8], &[u8; 64]) -> bool
|
||||
pub fn rns_ratkey::hardware::HardwareIdentity::x25519_public(&self) -> &[u8; 32]
|
||||
pub struct rns_ratkey::HwidConfig
|
||||
pub rns_ratkey::HwidConfig::app: rns_ratkey::hwid::HwidApp
|
||||
pub rns_ratkey::HwidConfig::attestation: rns_ratkey::hwid::HwidAttestation
|
||||
pub rns_ratkey::HwidConfig::backup: rns_ratkey::hwid::HwidBackup
|
||||
pub rns_ratkey::HwidConfig::device: rns_ratkey::hwid::HwidDevice
|
||||
pub rns_ratkey::HwidConfig::identity: rns_ratkey::hwid::HwidIdentity
|
||||
pub rns_ratkey::HwidConfig::keys: rns_ratkey::hwid::HwidKeys
|
||||
pub rns_ratkey::HwidConfig::policy: rns_ratkey::hwid::HwidPolicy
|
||||
pub rns_ratkey::HwidConfig::slots: rns_ratkey::hwid::HwidSlots
|
||||
impl rns_ratkey::hwid::HwidConfig
|
||||
pub fn rns_ratkey::hwid::HwidConfig::ed25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::encryption_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_file(&std::path::Path) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::signing_slot(&self) -> core::result::Result<u8, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_file(&self, &std::path::Path) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::to_string(&self) -> core::result::Result<alloc::string::String, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::hwid::HwidConfig::x25519_pub_bytes(&self) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
impl core::str::traits::FromStr for rns_ratkey::hwid::HwidConfig
|
||||
pub type rns_ratkey::hwid::HwidConfig::Err = rns_ratkey::error::RatkeyError
|
||||
pub fn rns_ratkey::hwid::HwidConfig::from_str(&str) -> core::result::Result<Self, Self::Err>
|
||||
pub struct rns_ratkey::MockPivSession
|
||||
pub rns_ratkey::MockPivSession::device_type: alloc::string::String
|
||||
pub rns_ratkey::MockPivSession::firmware: alloc::string::String
|
||||
pub rns_ratkey::MockPivSession::operations: alloc::vec::Vec<rns_ratkey::mock::MockOperation>
|
||||
pub rns_ratkey::MockPivSession::serial: u32
|
||||
impl rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::disconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_ed25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::generate_x25519(&mut self, u8, rns_ratkey::mock::TouchPolicy) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::new() -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::reconnect(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::require_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_pin(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::set_puk(&mut self, &str)
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::simulate_touch(&mut self)
|
||||
pub fn rns_ratkey::mock::MockPivSession::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_key_bytes(&[u8; 32], &[u8; 32]) -> Self
|
||||
pub fn rns_ratkey::mock::MockPivSession::with_keys() -> Self
|
||||
impl core::default::Default for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::default() -> Self
|
||||
impl core::ops::drop::Drop for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::drop(&mut self)
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub struct rns_ratkey::PcscTransport
|
||||
impl rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::connect() -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::PcscTransport::connect_reader(&str) -> core::result::Result<(Self, rns_ratkey::session::DeviceMeta), rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub struct rns_ratkey::PinCache
|
||||
impl rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::cache(&mut self, &str)
|
||||
pub fn rns_ratkey::pin::PinCache::clear(&mut self)
|
||||
pub fn rns_ratkey::pin::PinCache::default_timeout() -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::get(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::pin::PinCache::is_cached(&self) -> bool
|
||||
pub fn rns_ratkey::pin::PinCache::new(core::time::Duration) -> Self
|
||||
pub fn rns_ratkey::pin::PinCache::remaining(&self) -> core::option::Option<core::time::Duration>
|
||||
impl core::ops::drop::Drop for rns_ratkey::pin::PinCache
|
||||
pub fn rns_ratkey::pin::PinCache::drop(&mut self)
|
||||
pub struct rns_ratkey::PivSession<T: rns_ratkey::transport::PivTransport>
|
||||
impl rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect() -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>::connect_reader(&str) -> core::result::Result<Self, rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::attest_key(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::authenticate_management_key(&mut self, &[u8]) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::change_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::device_type(&self) -> rns_ratkey::detect::DeviceType
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::firmware(&self) -> core::option::Option<&str>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_ed25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::generate_x25519(&mut self, u8, core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_ed25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::import_x25519(&mut self, u8, &[u8; 32], core::option::Option<u8>, core::option::Option<u8>) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::new(T, rns_ratkey::session::DeviceMeta) -> Self
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_attestation_cert(&mut self) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_certificate(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_metadata(&mut self, u8) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_public_key(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::reset_piv(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::serial(&self) -> core::option::Option<u32>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::unblock_pin(&mut self, &str, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::verify_pin(&mut self, &str) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub struct rns_ratkey::ProvisionConfig
|
||||
pub rns_ratkey::ProvisionConfig::identities_dir: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::ProvisionConfig::nickname: alloc::string::String
|
||||
pub rns_ratkey::ProvisionConfig::pin: alloc::string::String
|
||||
pub rns_ratkey::ProvisionConfig::touch_encryption: rns_ratkey::mock::TouchPolicy
|
||||
pub rns_ratkey::ProvisionConfig::touch_signing: rns_ratkey::mock::TouchPolicy
|
||||
impl core::default::Default for rns_ratkey::provision::ProvisionConfig
|
||||
pub fn rns_ratkey::provision::ProvisionConfig::default() -> Self
|
||||
pub struct rns_ratkey::ProvisionResult
|
||||
pub rns_ratkey::ProvisionResult::config: rns_ratkey::hwid::HwidConfig
|
||||
pub rns_ratkey::ProvisionResult::ed25519_pub: [u8; 32]
|
||||
pub rns_ratkey::ProvisionResult::hwid_path: core::option::Option<std::path::PathBuf>
|
||||
pub rns_ratkey::ProvisionResult::identity_hash: [u8; 16]
|
||||
pub rns_ratkey::ProvisionResult::identity_hash_hex: alloc::string::String
|
||||
pub rns_ratkey::ProvisionResult::x25519_pub: [u8; 32]
|
||||
pub trait rns_ratkey::IdentityBackend
|
||||
pub fn rns_ratkey::IdentityBackend::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::IdentityBackend::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::IdentityBackend::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::hardware::IdentityBackend for rns_ratkey::mock::MockPivSession
|
||||
pub fn rns_ratkey::mock::MockPivSession::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::mock::MockPivSession::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::mock::MockPivSession::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
impl<T: rns_ratkey::transport::PivTransport> rns_ratkey::hardware::IdentityBackend for rns_ratkey::session::PivSession<T>
|
||||
pub fn rns_ratkey::session::PivSession<T>::ecdh_x25519(&mut self, u8, &[u8; 32]) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::session::PivSession<T>::lock(&mut self) -> core::result::Result<(), rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_ed25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::read_x25519_public(&mut self, u8) -> core::result::Result<[u8; 32], rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::session::PivSession<T>::sign_ed25519(&mut self, u8, &[u8]) -> core::result::Result<[u8; 64], rns_ratkey::error::RatkeyError>
|
||||
pub trait rns_ratkey::PivTransport
|
||||
pub fn rns_ratkey::PivTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PivTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
impl rns_ratkey::transport::PivTransport for rns_ratkey::PcscTransport
|
||||
pub fn rns_ratkey::PcscTransport::is_connected(&self) -> bool
|
||||
pub fn rns_ratkey::PcscTransport::transmit(&mut self, &[u8]) -> core::result::Result<alloc::vec::Vec<u8>, rns_ratkey::error::RatkeyError>
|
||||
pub fn rns_ratkey::load_hardware_identity(&rns_ratkey::hwid::HwidConfig, &str) -> core::result::Result<rns_identity::identity::Identity, rns_ratkey::error::RatkeyError>
|
||||
pub type rns_ratkey::PcscPivSession = rns_ratkey::session::PivSession<rns_ratkey::PcscTransport>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,137 @@
|
||||
pub mod rns_tools
|
||||
pub mod rns_tools::format
|
||||
pub enum rns_tools::format::PyNum
|
||||
pub rns_tools::format::PyNum::Float(f64)
|
||||
pub rns_tools::format::PyNum::Int(i64)
|
||||
impl rns_tools::format::PyNum
|
||||
pub fn rns_tools::format::PyNum::f(self) -> f64
|
||||
pub fn rns_tools::format::PyNum::i(self) -> i64
|
||||
pub fn rns_tools::format::PyNum::py_str(self) -> alloc::string::String
|
||||
pub fn rns_tools::format::hex_rep(&[u8]) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_cost(core::option::Option<f64>) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_frequency(f64) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_hex_rep(&[u8]) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_size(u64) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_speed(u64) -> alloc::string::String
|
||||
pub fn rns_tools::format::pretty_time(f64) -> alloc::string::String
|
||||
pub fn rns_tools::format::prettyfrequency(rns_tools::format::PyNum, &str, usize, bool) -> alloc::string::String
|
||||
pub fn rns_tools::format::prettyshorttime(f64) -> alloc::string::String
|
||||
pub fn rns_tools::format::prettysize(f64, &str) -> alloc::string::String
|
||||
pub fn rns_tools::format::prettyspeed(f64) -> alloc::string::String
|
||||
pub fn rns_tools::format::prettytime(rns_tools::format::PyNum, bool) -> alloc::string::String
|
||||
pub fn rns_tools::format::py_float_repr(f64) -> alloc::string::String
|
||||
pub fn rns_tools::format::py_round(f64, usize) -> f64
|
||||
pub mod rns_tools::hash
|
||||
pub fn rns_tools::hash::format_dest_hash(&[u8; 16]) -> alloc::string::String
|
||||
pub fn rns_tools::hash::parse_dest_hash(&str) -> core::result::Result<[u8; 16], alloc::string::String>
|
||||
pub mod rns_tools::rnx
|
||||
pub enum rns_tools::rnx::ResponseKind
|
||||
pub rns_tools::rnx::ResponseKind::Invalid
|
||||
pub rns_tools::rnx::ResponseKind::Missing
|
||||
pub rns_tools::rnx::ResponseKind::Result(rns_tools::rnx::Response)
|
||||
impl rns_tools::rnx::ResponseKind
|
||||
pub fn rns_tools::rnx::ResponseKind::from_value(&rmpv::Value) -> Self
|
||||
pub enum rns_tools::rnx::Timeout
|
||||
pub rns_tools::rnx::Timeout::Default
|
||||
pub rns_tools::rnx::Timeout::Given(f64)
|
||||
impl rns_tools::rnx::Timeout
|
||||
pub fn rns_tools::rnx::Timeout::seconds(self) -> f64
|
||||
pub struct rns_tools::rnx::CommandRequest
|
||||
pub rns_tools::rnx::CommandRequest::command: alloc::string::String
|
||||
pub rns_tools::rnx::CommandRequest::stderr_limit: core::option::Option<i64>
|
||||
pub rns_tools::rnx::CommandRequest::stdin: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_tools::rnx::CommandRequest::stdout_limit: core::option::Option<i64>
|
||||
pub rns_tools::rnx::CommandRequest::timeout: core::option::Option<f64>
|
||||
impl rns_tools::rnx::CommandRequest
|
||||
pub fn rns_tools::rnx::CommandRequest::from_value(&rmpv::Value) -> core::option::Option<Self>
|
||||
pub struct rns_tools::rnx::CommandResult
|
||||
pub rns_tools::rnx::CommandResult::concluded: core::option::Option<f64>
|
||||
pub rns_tools::rnx::CommandResult::executed: bool
|
||||
pub rns_tools::rnx::CommandResult::retcode: core::option::Option<i64>
|
||||
pub rns_tools::rnx::CommandResult::started: f64
|
||||
pub rns_tools::rnx::CommandResult::stderr: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_tools::rnx::CommandResult::stderr_len: core::option::Option<u64>
|
||||
pub rns_tools::rnx::CommandResult::stdout: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_tools::rnx::CommandResult::stdout_len: core::option::Option<u64>
|
||||
impl rns_tools::rnx::CommandResult
|
||||
pub fn rns_tools::rnx::CommandResult::into_msgpack_within(self, usize) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_tools::rnx::CommandResult::to_msgpack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_tools::rnx::CommandResult::to_value(&self) -> rmpv::Value
|
||||
pub struct rns_tools::rnx::Rendered
|
||||
pub rns_tools::rnx::Rendered::stderr: alloc::vec::Vec<u8>
|
||||
pub rns_tools::rnx::Rendered::stdout: alloc::vec::Vec<u8>
|
||||
pub struct rns_tools::rnx::Response
|
||||
pub rns_tools::rnx::Response::concluded: core::option::Option<f64>
|
||||
pub rns_tools::rnx::Response::executed: bool
|
||||
pub rns_tools::rnx::Response::retcode: core::option::Option<i64>
|
||||
pub rns_tools::rnx::Response::started: core::option::Option<f64>
|
||||
pub rns_tools::rnx::Response::stderr: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_tools::rnx::Response::stderr_len: core::option::Option<u64>
|
||||
pub rns_tools::rnx::Response::stdout: core::option::Option<alloc::vec::Vec<u8>>
|
||||
pub rns_tools::rnx::Response::stdout_len: core::option::Option<u64>
|
||||
pub struct rns_tools::rnx::TransferStats
|
||||
pub rns_tools::rnx::TransferStats::elapsed: f64
|
||||
pub rns_tools::rnx::TransferStats::request_size: core::option::Option<u64>
|
||||
pub rns_tools::rnx::TransferStats::response_size: u64
|
||||
pub const rns_tools::rnx::APP_NAME: &str
|
||||
pub const rns_tools::rnx::COMMAND_PATH: &str
|
||||
pub const rns_tools::rnx::DEFAULT_TIMEOUT: i64
|
||||
pub const rns_tools::rnx::REMOTE_EXEC_GRACE: f64
|
||||
pub fn rns_tools::rnx::allowed_identity_files(core::option::Option<&std::path::Path>) -> alloc::vec::Vec<std::path::PathBuf>
|
||||
pub fn rns_tools::rnx::client_result(&rmpv::Value, bool, bool, core::option::Option<i64>, core::option::Option<i64>, core::option::Option<rns_tools::rnx::TransferStats>) -> (rns_tools::rnx::Rendered, core::option::Option<rns_tools::rnx::Response>, i32)
|
||||
pub async fn rns_tools::rnx::execute(&rns_tools::rnx::CommandRequest) -> rns_tools::rnx::CommandResult
|
||||
pub fn rns_tools::rnx::mirrored_exit_code(core::option::Option<i64>) -> i32
|
||||
pub fn rns_tools::rnx::parse_allowed_identities(&str) -> core::result::Result<alloc::vec::Vec<[u8; 16]>, alloc::string::String>
|
||||
pub fn rns_tools::rnx::parse_hash_arg(&str) -> core::result::Result<[u8; 16], alloc::string::String>
|
||||
pub fn rns_tools::rnx::pretty_time(f64) -> alloc::string::String
|
||||
pub fn rns_tools::rnx::py_float(f64) -> alloc::string::String
|
||||
pub fn rns_tools::rnx::render(&rns_tools::rnx::Response, bool, core::option::Option<i64>, core::option::Option<i64>, core::option::Option<rns_tools::rnx::TransferStats>) -> rns_tools::rnx::Rendered
|
||||
pub fn rns_tools::rnx::request_value(&str, rns_tools::rnx::Timeout, core::option::Option<i64>, core::option::Option<i64>, core::option::Option<&str>) -> rmpv::Value
|
||||
pub fn rns_tools::rnx::size_str(f64, char) -> alloc::string::String
|
||||
pub fn rns_tools::rnx::truncate(&[u8], core::option::Option<i64>) -> alloc::vec::Vec<u8>
|
||||
pub enum rns_tools::LogLevel
|
||||
pub rns_tools::LogLevel::Critical = 0
|
||||
pub rns_tools::LogLevel::Debug = 6
|
||||
pub rns_tools::LogLevel::Error = 1
|
||||
pub rns_tools::LogLevel::Extreme = 8
|
||||
pub rns_tools::LogLevel::Info = 4
|
||||
pub rns_tools::LogLevel::Notice = 3
|
||||
pub rns_tools::LogLevel::Pathing = 7
|
||||
pub rns_tools::LogLevel::Verbose = 5
|
||||
pub rns_tools::LogLevel::Warning = 2
|
||||
impl rns_tools::LogLevel
|
||||
pub fn rns_tools::LogLevel::clamped(i64) -> Self
|
||||
pub fn rns_tools::LogLevel::filter(self) -> tracing_subscriber::filter::targets::Targets
|
||||
pub fn rns_tools::LogLevel::name(self) -> &'static str
|
||||
pub fn rns_tools::LogLevel::number(self) -> i32
|
||||
pub enum rns_tools::Utility
|
||||
pub rns_tools::Utility::Lxmd
|
||||
pub rns_tools::Utility::Rncp
|
||||
pub rns_tools::Utility::Rnid
|
||||
pub rns_tools::Utility::Rnir
|
||||
pub rns_tools::Utility::Rnpath
|
||||
pub rns_tools::Utility::Rnpkg
|
||||
pub rns_tools::Utility::Rnprobe
|
||||
pub rns_tools::Utility::Rnsd
|
||||
pub rns_tools::Utility::Rnsh
|
||||
pub rns_tools::Utility::Rnstatus
|
||||
pub rns_tools::Utility::Rnx
|
||||
impl rns_tools::Utility
|
||||
pub fn rns_tools::Utility::loglevel(self, core::option::Option<i64>, u8, u8, bool) -> rns_tools::LogLevel
|
||||
pub struct rns_tools::RpcRegistration
|
||||
impl rns_tools::RpcRegistration
|
||||
pub async fn rns_tools::RpcRegistration::release(self)
|
||||
pub async fn rns_tools::RpcRegistration::want(rns_runtime::reticulum::SharedInstanceRpcEndpoint, alloc::vec::Vec<u8>, &[&str], core::time::Duration) -> Self
|
||||
pub const rns_tools::NOTICE_TARGET: &str
|
||||
pub const rns_tools::PATHING_TARGET: &str
|
||||
pub const rns_tools::RETICULUM_COMPAT_VERSION: &str
|
||||
pub const rns_tools::RS_RETICULUM_VERSION: &str
|
||||
pub fn rns_tools::config_log_timestamps(&std::path::Path) -> bool
|
||||
pub async fn rns_tools::exit(&rns_runtime::reticulum::ReticulumHandle, i32) -> never
|
||||
pub async fn rns_tools::has_local_path(&rns_runtime::reticulum::ReticulumHandle, [u8; 16]) -> bool
|
||||
pub fn rns_tools::init_tracing<W>(rns_tools::LogLevel, bool, bool, W) where W: for<'a> tracing_subscriber::fmt::writer::MakeWriter<'a> + core::marker::Send + core::marker::Sync + 'static
|
||||
pub fn rns_tools::link_closed_text(core::option::Option<rns_link::link::CloseReason>) -> core::option::Option<&'static str>
|
||||
pub async fn rns_tools::medium_path_timeout(&rns_runtime::reticulum::ReticulumHandle) -> f64
|
||||
pub async fn rns_tools::shut_down(&rns_runtime::reticulum::ReticulumHandle)
|
||||
pub fn rns_tools::version_line(&str, &str, &[(&str, &str)]) -> alloc::string::String
|
||||
pub fn rns_tools::warn_deprecated_spellings(&str, &[(&str, &str)])
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,402 @@
|
||||
pub mod rns_wire
|
||||
pub mod rns_wire::constants
|
||||
pub const rns_wire::constants::AES128_BLOCKSIZE: usize
|
||||
pub const rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT: f64
|
||||
pub const rns_wire::constants::ENCRYPTED_MDU: usize
|
||||
pub const rns_wire::constants::EXPL_LENGTH: usize
|
||||
pub const rns_wire::constants::HASHLENGTH: usize
|
||||
pub const rns_wire::constants::HEADER_MAXSIZE: usize
|
||||
pub const rns_wire::constants::HEADER_MINSIZE: usize
|
||||
pub const rns_wire::constants::IMPL_LENGTH: usize
|
||||
pub const rns_wire::constants::KEYSIZE: usize
|
||||
pub const rns_wire::constants::LINK_MDU: usize
|
||||
pub const rns_wire::constants::MDU: usize
|
||||
pub const rns_wire::constants::MTU: usize
|
||||
pub const rns_wire::constants::NAME_HASH_LENGTH: usize
|
||||
pub const rns_wire::constants::PLAIN_MDU: usize
|
||||
pub const rns_wire::constants::RATCHETSIZE: usize
|
||||
pub const rns_wire::constants::RATCHET_COUNT: usize
|
||||
pub const rns_wire::constants::RATCHET_EXPIRY: u64
|
||||
pub const rns_wire::constants::RATCHET_INTERVAL: u64
|
||||
pub const rns_wire::constants::SIGLENGTH: usize
|
||||
pub const rns_wire::constants::SINGLE_PACKET_ENCRYPTED_MDU: usize
|
||||
pub const rns_wire::constants::TOKEN_OVERHEAD: usize
|
||||
pub const rns_wire::constants::TRUNCATED_HASHLENGTH: usize
|
||||
pub mod rns_wire::context
|
||||
pub enum rns_wire::context::PacketContext
|
||||
pub rns_wire::context::PacketContext::CacheRequest
|
||||
pub rns_wire::context::PacketContext::Channel
|
||||
pub rns_wire::context::PacketContext::Command
|
||||
pub rns_wire::context::PacketContext::CommandStatus
|
||||
pub rns_wire::context::PacketContext::Keepalive
|
||||
pub rns_wire::context::PacketContext::LinkClose
|
||||
pub rns_wire::context::PacketContext::LinkIdentify
|
||||
pub rns_wire::context::PacketContext::LinkProof
|
||||
pub rns_wire::context::PacketContext::Lrproof
|
||||
pub rns_wire::context::PacketContext::Lrrtt
|
||||
pub rns_wire::context::PacketContext::None
|
||||
pub rns_wire::context::PacketContext::PathResponse
|
||||
pub rns_wire::context::PacketContext::Request
|
||||
pub rns_wire::context::PacketContext::Resource
|
||||
pub rns_wire::context::PacketContext::ResourceAdv
|
||||
pub rns_wire::context::PacketContext::ResourceHmu
|
||||
pub rns_wire::context::PacketContext::ResourceIcl
|
||||
pub rns_wire::context::PacketContext::ResourcePrf
|
||||
pub rns_wire::context::PacketContext::ResourceRcl
|
||||
pub rns_wire::context::PacketContext::ResourceReq
|
||||
pub rns_wire::context::PacketContext::Response
|
||||
pub rns_wire::context::PacketContext::Unknown(u8)
|
||||
impl rns_wire::context::PacketContext
|
||||
pub fn rns_wire::context::PacketContext::from_byte(u8) -> Self
|
||||
pub fn rns_wire::context::PacketContext::is_plaintext_context(self) -> bool
|
||||
pub fn rns_wire::context::PacketContext::to_byte(self) -> u8
|
||||
pub mod rns_wire::flags
|
||||
#[repr(u8)] pub enum rns_wire::flags::DestinationType
|
||||
pub rns_wire::flags::DestinationType::Group = 1
|
||||
pub rns_wire::flags::DestinationType::Link = 3
|
||||
pub rns_wire::flags::DestinationType::Plain = 2
|
||||
pub rns_wire::flags::DestinationType::Single = 0
|
||||
#[repr(u8)] pub enum rns_wire::flags::HeaderType
|
||||
pub rns_wire::flags::HeaderType::Header1 = 0
|
||||
pub rns_wire::flags::HeaderType::Header2 = 1
|
||||
#[repr(u8)] pub enum rns_wire::flags::PacketType
|
||||
pub rns_wire::flags::PacketType::Announce = 1
|
||||
pub rns_wire::flags::PacketType::Data = 0
|
||||
pub rns_wire::flags::PacketType::LinkRequest = 2
|
||||
pub rns_wire::flags::PacketType::Proof = 3
|
||||
#[repr(u8)] pub enum rns_wire::flags::TransportType
|
||||
pub rns_wire::flags::TransportType::Broadcast = 0
|
||||
pub rns_wire::flags::TransportType::Transport = 1
|
||||
pub struct rns_wire::flags::PacketFlags
|
||||
pub rns_wire::flags::PacketFlags::context_flag: bool
|
||||
pub rns_wire::flags::PacketFlags::destination_type: rns_wire::flags::DestinationType
|
||||
pub rns_wire::flags::PacketFlags::header_type: rns_wire::flags::HeaderType
|
||||
pub rns_wire::flags::PacketFlags::packet_type: rns_wire::flags::PacketType
|
||||
pub rns_wire::flags::PacketFlags::transport_type: rns_wire::flags::TransportType
|
||||
impl rns_wire::flags::PacketFlags
|
||||
pub fn rns_wire::flags::PacketFlags::pack(&self) -> u8
|
||||
pub fn rns_wire::flags::PacketFlags::unpack(u8) -> core::option::Option<Self>
|
||||
pub mod rns_wire::hash
|
||||
pub fn rns_wire::hash::get_hashable_part(&[u8], rns_wire::flags::HeaderType) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_wire::hash::link_id_from_raw(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
|
||||
pub fn rns_wire::hash::packet_hash(&[u8], rns_wire::flags::HeaderType) -> [u8; 32]
|
||||
pub fn rns_wire::hash::packet_hash_pair(&[u8], rns_wire::flags::HeaderType) -> ([u8; 32], [u8; 16])
|
||||
pub fn rns_wire::hash::truncated_packet_hash(&[u8], rns_wire::flags::HeaderType) -> [u8; 16]
|
||||
pub mod rns_wire::header
|
||||
pub enum rns_wire::header::HeaderError
|
||||
pub rns_wire::header::HeaderError::TooShort(usize)
|
||||
pub struct rns_wire::header::PacketHeader
|
||||
pub rns_wire::header::PacketHeader::context: rns_wire::context::PacketContext
|
||||
pub rns_wire::header::PacketHeader::destination_hash: [u8; 16]
|
||||
pub rns_wire::header::PacketHeader::flags: rns_wire::flags::PacketFlags
|
||||
pub rns_wire::header::PacketHeader::hops: u8
|
||||
pub rns_wire::header::PacketHeader::transport_id: core::option::Option<[u8; 16]>
|
||||
impl rns_wire::header::PacketHeader
|
||||
pub fn rns_wire::header::PacketHeader::pack(&self) -> alloc::vec::Vec<u8>
|
||||
pub fn rns_wire::header::PacketHeader::size(&self) -> usize
|
||||
pub fn rns_wire::header::PacketHeader::unpack(&[u8]) -> core::result::Result<(Self, usize), rns_wire::header::HeaderError>
|
||||
pub mod rns_wire::link_signalling
|
||||
pub enum rns_wire::link_signalling::LinkSignallingError
|
||||
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength
|
||||
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::actual: usize
|
||||
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::legacy: usize
|
||||
pub rns_wire::link_signalling::LinkSignallingError::InvalidLength::modern: usize
|
||||
pub rns_wire::link_signalling::LinkSignallingError::InvalidMode(u8)
|
||||
pub rns_wire::link_signalling::LinkSignallingError::InvalidMtu(u32)
|
||||
pub rns_wire::link_signalling::LinkSignallingError::MduUnavailable
|
||||
pub struct rns_wire::link_signalling::LinkMtu(_)
|
||||
impl rns_wire::link_signalling::LinkMtu
|
||||
pub const rns_wire::link_signalling::LinkMtu::BASE: Self
|
||||
pub fn rns_wire::link_signalling::LinkMtu::checked_mdu(self) -> core::result::Result<usize, rns_wire::link_signalling::LinkSignallingError>
|
||||
pub const fn rns_wire::link_signalling::LinkMtu::get(self) -> u32
|
||||
pub fn rns_wire::link_signalling::LinkMtu::try_from_signal(core::option::Option<u32>) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
|
||||
pub struct rns_wire::link_signalling::LinkSignalling
|
||||
pub rns_wire::link_signalling::LinkSignalling::mode: u8
|
||||
pub rns_wire::link_signalling::LinkSignalling::mtu: rns_wire::link_signalling::LinkMtu
|
||||
pub rns_wire::link_signalling::LinkSignalling::signalling_present: bool
|
||||
pub struct rns_wire::link_signalling::SignallingData
|
||||
pub rns_wire::link_signalling::SignallingData::mode: u8
|
||||
pub rns_wire::link_signalling::SignallingData::mtu: u32
|
||||
impl rns_wire::link_signalling::SignallingData
|
||||
pub fn rns_wire::link_signalling::SignallingData::new(u8, u32) -> Self
|
||||
pub fn rns_wire::link_signalling::SignallingData::pack(&self) -> [u8; 3]
|
||||
pub fn rns_wire::link_signalling::SignallingData::try_new(u8, u32) -> core::result::Result<Self, rns_wire::link_signalling::LinkSignallingError>
|
||||
pub fn rns_wire::link_signalling::SignallingData::unpack(&[u8]) -> core::option::Option<Self>
|
||||
pub const rns_wire::link_signalling::BASE_LINK_MTU: u32
|
||||
pub const rns_wire::link_signalling::DEFAULT_LINK_MODE: u8
|
||||
pub const rns_wire::link_signalling::MAX_SIGNALLED_LINK_MTU: u32
|
||||
pub fn rns_wire::link_signalling::parse_proof_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
|
||||
pub fn rns_wire::link_signalling::parse_request_signalling(&[u8]) -> core::result::Result<rns_wire::link_signalling::LinkSignalling, rns_wire::link_signalling::LinkSignallingError>
|
||||
pub mod rns_wire::packet
|
||||
pub enum rns_wire::packet::PacketError
|
||||
pub rns_wire::packet::PacketError::ExceedsMtu(usize)
|
||||
pub rns_wire::packet::PacketError::Header(rns_wire::header::HeaderError)
|
||||
pub rns_wire::packet::PacketError::TooShort
|
||||
pub struct rns_wire::packet::Packet
|
||||
pub rns_wire::packet::Packet::header: rns_wire::header::PacketHeader
|
||||
pub rns_wire::packet::Packet::packet_hash: [u8; 32]
|
||||
pub rns_wire::packet::Packet::raw: alloc::vec::Vec<u8>
|
||||
pub rns_wire::packet::Packet::truncated_hash: [u8; 16]
|
||||
impl rns_wire::packet::Packet
|
||||
pub fn rns_wire::packet::Packet::data(&self) -> &[u8]
|
||||
pub fn rns_wire::packet::Packet::from_raw(&[u8]) -> core::result::Result<Self, rns_wire::packet::PacketError>
|
||||
pub fn rns_wire::packet::Packet::from_raw_owned(alloc::vec::Vec<u8>) -> core::result::Result<Self, rns_wire::packet::PacketError>
|
||||
pub fn rns_wire::packet::Packet::increment_hops(&mut self)
|
||||
pub fn rns_wire::packet::Packet::new(rns_wire::header::PacketHeader, alloc::vec::Vec<u8>) -> core::result::Result<Self, rns_wire::packet::PacketError>
|
||||
pub mod rns_wire::proof
|
||||
pub enum rns_wire::proof::ProofData
|
||||
pub rns_wire::proof::ProofData::Explicit
|
||||
pub rns_wire::proof::ProofData::Explicit::packet_hash: [u8; 32]
|
||||
pub rns_wire::proof::ProofData::Explicit::signature: [u8; 64]
|
||||
pub rns_wire::proof::ProofData::Implicit
|
||||
pub rns_wire::proof::ProofData::Implicit::signature: [u8; 64]
|
||||
impl rns_wire::proof::ProofData
|
||||
pub fn rns_wire::proof::ProofData::from_bytes(&[u8]) -> core::option::Option<Self>
|
||||
pub fn rns_wire::proof::ProofData::signature(&self) -> &[u8; 64]
|
||||
pub fn rns_wire::proof::ProofData::to_bytes(&self) -> alloc::vec::Vec<u8>
|
||||
pub mod rns_wire::receipt
|
||||
#[repr(u8)] pub enum rns_wire::receipt::ReceiptStatus
|
||||
pub rns_wire::receipt::ReceiptStatus::Culled = 255
|
||||
pub rns_wire::receipt::ReceiptStatus::Delivered = 2
|
||||
pub rns_wire::receipt::ReceiptStatus::Failed = 0
|
||||
pub rns_wire::receipt::ReceiptStatus::Receiving = 6
|
||||
pub rns_wire::receipt::ReceiptStatus::Sent = 1
|
||||
pub struct rns_wire::receipt::PacketReceipt
|
||||
pub rns_wire::receipt::PacketReceipt::callbacks: rns_wire::receipt::ReceiptCallbacks
|
||||
pub rns_wire::receipt::PacketReceipt::concluded_at: core::option::Option<std::time::Instant>
|
||||
pub rns_wire::receipt::PacketReceipt::destination_hash: core::option::Option<[u8; 16]>
|
||||
pub rns_wire::receipt::PacketReceipt::destination_public_key: core::option::Option<[u8; 64]>
|
||||
pub rns_wire::receipt::PacketReceipt::hash: [u8; 32]
|
||||
pub rns_wire::receipt::PacketReceipt::sent_at: std::time::Instant
|
||||
pub rns_wire::receipt::PacketReceipt::status: rns_wire::receipt::ReceiptStatus
|
||||
pub rns_wire::receipt::PacketReceipt::timeout: core::option::Option<core::time::Duration>
|
||||
pub rns_wire::receipt::PacketReceipt::truncated_hash: [u8; 16]
|
||||
impl rns_wire::receipt::PacketReceipt
|
||||
pub fn rns_wire::receipt::PacketReceipt::check_timeout(&mut self) -> bool
|
||||
pub fn rns_wire::receipt::PacketReceipt::cull(&mut self)
|
||||
pub fn rns_wire::receipt::PacketReceipt::deliver(&mut self)
|
||||
pub fn rns_wire::receipt::PacketReceipt::fail(&mut self)
|
||||
pub fn rns_wire::receipt::PacketReceipt::get_rtt(&self) -> core::option::Option<core::time::Duration>
|
||||
pub fn rns_wire::receipt::PacketReceipt::is_timed_out(&self) -> bool
|
||||
pub fn rns_wire::receipt::PacketReceipt::new([u8; 32], [u8; 16], core::option::Option<core::time::Duration>) -> Self
|
||||
pub fn rns_wire::receipt::PacketReceipt::set_delivery_callback(&mut self, impl core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_wire::receipt::PacketReceipt::set_destination_identity(&mut self, [u8; 16], core::option::Option<[u8; 64]>)
|
||||
pub fn rns_wire::receipt::PacketReceipt::set_timeout_callback(&mut self, impl core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send + 'static)
|
||||
pub fn rns_wire::receipt::PacketReceipt::validate_proof<F>(&mut self, &[u8], F) -> bool where F: core::ops::function::FnOnce(&[u8], &[u8]) -> bool
|
||||
pub fn rns_wire::receipt::PacketReceipt::validate_proof_from_destination(&mut self, &[u8]) -> bool
|
||||
pub struct rns_wire::receipt::ReceiptCallbacks
|
||||
pub rns_wire::receipt::ReceiptCallbacks::delivery: core::option::Option<rns_wire::receipt::ReceiptCallback>
|
||||
pub rns_wire::receipt::ReceiptCallbacks::timeout: core::option::Option<rns_wire::receipt::ReceiptCallback>
|
||||
pub const rns_wire::receipt::EXPL_LENGTH: usize
|
||||
pub const rns_wire::receipt::IMPL_LENGTH: usize
|
||||
pub fn rns_wire::receipt::receipt_timeout_for_route(core::time::Duration, u8) -> core::time::Duration
|
||||
pub type rns_wire::receipt::ReceiptCallback = alloc::boxed::Box<(dyn core::ops::function::FnOnce(&rns_wire::receipt::PacketReceipt) + core::marker::Send)>
|
||||
pub mod rns_wire::types
|
||||
#[repr(transparent)] pub struct rns_wire::types::DestHash(_)
|
||||
impl rns_wire::types::DestHash
|
||||
pub const rns_wire::types::DestHash::LEN: usize
|
||||
pub const fn rns_wire::types::DestHash::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::DestHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::DestHash::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::DestHash::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::DestHash> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::DestHash) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::DestHash
|
||||
pub fn rns_wire::types::DestHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::DestHash
|
||||
pub type rns_wire::types::DestHash::Target = [u8; 16]
|
||||
pub fn rns_wire::types::DestHash::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::FullHash(_)
|
||||
impl rns_wire::types::FullHash
|
||||
pub const rns_wire::types::FullHash::LEN: usize
|
||||
pub const fn rns_wire::types::FullHash::as_bytes(&self) -> &[u8; 32]
|
||||
pub fn rns_wire::types::FullHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::FullHash::into_bytes(self) -> [u8; 32]
|
||||
pub const fn rns_wire::types::FullHash::new([u8; 32]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::borrow(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::as_ref(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::from(&[u8; 32]) -> Self
|
||||
impl core::convert::From<[u8; 32]> for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::from([u8; 32]) -> Self
|
||||
impl core::convert::From<rns_wire::types::FullHash> for [u8; 32]
|
||||
pub fn [u8; 32]::from(rns_wire::types::FullHash) -> [u8; 32]
|
||||
impl core::fmt::Debug for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::FullHash
|
||||
pub fn rns_wire::types::FullHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::FullHash
|
||||
pub type rns_wire::types::FullHash::Target = [u8; 32]
|
||||
pub fn rns_wire::types::FullHash::deref(&self) -> &[u8; 32]
|
||||
#[repr(transparent)] pub struct rns_wire::types::IdentityHash(_)
|
||||
impl rns_wire::types::IdentityHash
|
||||
pub const rns_wire::types::IdentityHash::LEN: usize
|
||||
pub const fn rns_wire::types::IdentityHash::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::IdentityHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::IdentityHash::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::IdentityHash::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::IdentityHash> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::IdentityHash) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::IdentityHash
|
||||
pub fn rns_wire::types::IdentityHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::IdentityHash
|
||||
pub type rns_wire::types::IdentityHash::Target = [u8; 16]
|
||||
pub fn rns_wire::types::IdentityHash::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::LinkId(_)
|
||||
impl rns_wire::types::LinkId
|
||||
pub const rns_wire::types::LinkId::LEN: usize
|
||||
pub const fn rns_wire::types::LinkId::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::LinkId::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::LinkId::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::LinkId::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::LinkId> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::LinkId) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::LinkId
|
||||
pub fn rns_wire::types::LinkId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::LinkId
|
||||
pub type rns_wire::types::LinkId::Target = [u8; 16]
|
||||
pub fn rns_wire::types::LinkId::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::MessageHash(_)
|
||||
impl rns_wire::types::MessageHash
|
||||
pub const rns_wire::types::MessageHash::LEN: usize
|
||||
pub const fn rns_wire::types::MessageHash::as_bytes(&self) -> &[u8; 32]
|
||||
pub fn rns_wire::types::MessageHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::MessageHash::into_bytes(self) -> [u8; 32]
|
||||
pub const fn rns_wire::types::MessageHash::new([u8; 32]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::borrow(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::as_ref(&self) -> &[u8; 32]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::from(&[u8; 32]) -> Self
|
||||
impl core::convert::From<[u8; 32]> for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::from([u8; 32]) -> Self
|
||||
impl core::convert::From<rns_wire::types::MessageHash> for [u8; 32]
|
||||
pub fn [u8; 32]::from(rns_wire::types::MessageHash) -> [u8; 32]
|
||||
impl core::fmt::Debug for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::MessageHash
|
||||
pub fn rns_wire::types::MessageHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::MessageHash
|
||||
pub type rns_wire::types::MessageHash::Target = [u8; 32]
|
||||
pub fn rns_wire::types::MessageHash::deref(&self) -> &[u8; 32]
|
||||
#[repr(transparent)] pub struct rns_wire::types::NameHash(_)
|
||||
impl rns_wire::types::NameHash
|
||||
pub const rns_wire::types::NameHash::LEN: usize
|
||||
pub const fn rns_wire::types::NameHash::as_bytes(&self) -> &[u8; 10]
|
||||
pub fn rns_wire::types::NameHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::NameHash::into_bytes(self) -> [u8; 10]
|
||||
pub const fn rns_wire::types::NameHash::new([u8; 10]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::borrow(&self) -> &[u8; 10]
|
||||
impl core::convert::AsRef<[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::as_ref(&self) -> &[u8; 10]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::from(&[u8; 10]) -> Self
|
||||
impl core::convert::From<[u8; 10]> for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::from([u8; 10]) -> Self
|
||||
impl core::convert::From<rns_wire::types::NameHash> for [u8; 10]
|
||||
pub fn [u8; 10]::from(rns_wire::types::NameHash) -> [u8; 10]
|
||||
impl core::fmt::Debug for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::NameHash
|
||||
pub fn rns_wire::types::NameHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::NameHash
|
||||
pub type rns_wire::types::NameHash::Target = [u8; 10]
|
||||
pub fn rns_wire::types::NameHash::deref(&self) -> &[u8; 10]
|
||||
#[repr(transparent)] pub struct rns_wire::types::TransportId(_)
|
||||
impl rns_wire::types::TransportId
|
||||
pub const rns_wire::types::TransportId::LEN: usize
|
||||
pub const fn rns_wire::types::TransportId::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::TransportId::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::TransportId::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::TransportId::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::TransportId> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::TransportId) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::TransportId
|
||||
pub fn rns_wire::types::TransportId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::TransportId
|
||||
pub type rns_wire::types::TransportId::Target = [u8; 16]
|
||||
pub fn rns_wire::types::TransportId::deref(&self) -> &[u8; 16]
|
||||
#[repr(transparent)] pub struct rns_wire::types::TruncatedHash(_)
|
||||
impl rns_wire::types::TruncatedHash
|
||||
pub const rns_wire::types::TruncatedHash::LEN: usize
|
||||
pub const fn rns_wire::types::TruncatedHash::as_bytes(&self) -> &[u8; 16]
|
||||
pub fn rns_wire::types::TruncatedHash::from_slice(&[u8]) -> core::option::Option<Self>
|
||||
pub const fn rns_wire::types::TruncatedHash::into_bytes(self) -> [u8; 16]
|
||||
pub const fn rns_wire::types::TruncatedHash::new([u8; 16]) -> Self
|
||||
impl core::borrow::Borrow<[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::borrow(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::as_ref(&self) -> &[u8; 16]
|
||||
impl core::convert::AsRef<[u8]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::as_ref(&self) -> &[u8]
|
||||
impl core::convert::From<&[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::from(&[u8; 16]) -> Self
|
||||
impl core::convert::From<[u8; 16]> for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::from([u8; 16]) -> Self
|
||||
impl core::convert::From<rns_wire::types::TruncatedHash> for [u8; 16]
|
||||
pub fn [u8; 16]::from(rns_wire::types::TruncatedHash) -> [u8; 16]
|
||||
impl core::fmt::Debug for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::fmt::Display for rns_wire::types::TruncatedHash
|
||||
pub fn rns_wire::types::TruncatedHash::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
|
||||
impl core::ops::deref::Deref for rns_wire::types::TruncatedHash
|
||||
pub type rns_wire::types::TruncatedHash::Target = [u8; 16]
|
||||
pub fn rns_wire::types::TruncatedHash::deref(&self) -> &[u8; 16]
|
||||
@@ -0,0 +1,623 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"tool": {
|
||||
"name": "cargo-public-api",
|
||||
"version": "0.52.0",
|
||||
"rustdocToolchain": "nightly-2026-08-01",
|
||||
"target": "aarch64-apple-darwin",
|
||||
"arguments": [
|
||||
"--all-features",
|
||||
"-sss"
|
||||
]
|
||||
},
|
||||
"baseline": {
|
||||
"commit": "47dbbf1febc0a9d3259f179a0512d9b56bb2320d"
|
||||
},
|
||||
"compatibilityFloor": {
|
||||
"evidenceCommit": "14241a383910e6ee7665303eff1e7c8d98957cc0",
|
||||
"sourceCommit": "14241a383910e6ee7665303eff1e7c8d98957cc0"
|
||||
},
|
||||
"packages": [
|
||||
{
|
||||
"name": "rns-crypto",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-crypto.txt",
|
||||
"itemCount": 94,
|
||||
"sha256": "4c209368875ca6624cbdb58635b486c9fea7579c831386b60ed1a38738773387"
|
||||
},
|
||||
{
|
||||
"name": "rns-wire",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-wire.txt",
|
||||
"itemCount": 402,
|
||||
"sha256": "47f17ed4b47f0fc9ccaccc42d00b7635b07083c4eae6782a4f5de7e1452e4688"
|
||||
},
|
||||
{
|
||||
"name": "rns-identity",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-identity.txt",
|
||||
"itemCount": 537,
|
||||
"sha256": "f525e1b3f59c1092454ad4e36bc8cd7a5294ed97a33707891780748fa21286c4"
|
||||
},
|
||||
{
|
||||
"name": "rns-transport",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-transport.txt",
|
||||
"itemCount": 2273,
|
||||
"sha256": "7894fdab76428a6fd8cd7097e60058409a6a593d8c4970c01c5d440e98613fa1"
|
||||
},
|
||||
{
|
||||
"name": "rns-link",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-link.txt",
|
||||
"itemCount": 440,
|
||||
"sha256": "d1c84fa2090ecb50afc746344017a8d82b50e2733b572fdcec79f212a20c5944"
|
||||
},
|
||||
{
|
||||
"name": "rns-protocol",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-protocol.txt",
|
||||
"itemCount": 673,
|
||||
"sha256": "cac91c8ac80f6706f0d2a4257da740f8188846ffc7da61a8ff2a8a293ad6dee3"
|
||||
},
|
||||
{
|
||||
"name": "rns-interface",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "candidate-stable",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-interface.txt",
|
||||
"itemCount": 1589,
|
||||
"sha256": "d62d9d2d0825bbc56ea00c440fabe45d056447f316cd78761c1001118a3fc23c"
|
||||
},
|
||||
{
|
||||
"name": "rns-runtime",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "provisional",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-runtime.txt",
|
||||
"itemCount": 2501,
|
||||
"sha256": "485e4b02fd9c45b681c6b7d928d4d068aa50a3419b3a49175c144491bf22b63d"
|
||||
},
|
||||
{
|
||||
"name": "rns-tools",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "tool-internal",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-tools.txt",
|
||||
"itemCount": 137,
|
||||
"sha256": "064dd502544660e246ff7ffe49e11783bbc369213955c09b03af80819ffef88d"
|
||||
},
|
||||
{
|
||||
"name": "rns-git",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "tool-internal",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-git.txt",
|
||||
"itemCount": 605,
|
||||
"sha256": "b4bee5c983267ce1db8229af30fa2ceca00d0fccceb70fbdffc810524779b0e2"
|
||||
},
|
||||
{
|
||||
"name": "rns-ratkey",
|
||||
"manifestPath": "Cargo.toml",
|
||||
"tier": "experimental",
|
||||
"compatibility": "reviewed-snapshot",
|
||||
"snapshot": "api/snapshots/rns-ratkey.txt",
|
||||
"itemCount": 618,
|
||||
"sha256": "f2ab796d37f18d7d5d7a515e4b6c28900f6f1c214aec4142fed069275793fdfd"
|
||||
}
|
||||
],
|
||||
"approvedBreakingChanges": {
|
||||
"releaseLine": "1.5",
|
||||
"migrationGuide": "api/migrations/1.5.md",
|
||||
"removed": {
|
||||
"rns-crypto": [
|
||||
"pub fn rns_crypto::x25519::X25519PrivateKey::exchange(&self, &rns_crypto::x25519::X25519PublicKey) -> [u8; 32]",
|
||||
"pub rns_crypto::hkdf::HkdfError::OutputTooLong(usize)"
|
||||
],
|
||||
"rns-identity": [
|
||||
"impl core::default::Default for rns_identity::ratchet::ReceivedRatchetStore",
|
||||
"impl rns_identity::ratchet::ReceivedRatchetStore",
|
||||
"pub enum rns_identity::destination::DestinationError",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::clean_expired(&mut self)",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::current_ratchet_id(&mut self, &[u8; 16]) -> core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::default() -> Self",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::get(&mut self, &[u8; 16]) -> core::option::Option<[u8; 32]>",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::get_at(&mut self, &[u8; 16], f64) -> core::option::Option<[u8; 32]>",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::is_empty(&self) -> bool",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::len(&self) -> usize",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::new() -> Self",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::remember(&mut self, [u8; 16], [u8; 32])",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::remember_at(&mut self, [u8; 16], [u8; 32], f64)",
|
||||
"pub fn rns_identity::ratchet::ReceivedRatchetStore::with_storage(std::path::PathBuf) -> Self",
|
||||
"pub struct rns_identity::ratchet::ReceivedRatchetStore"
|
||||
],
|
||||
"rns-transport": [
|
||||
"impl core::convert::From<&rns_transport::link_table::LinkEntry> for rns_transport::link_table::ExpiredLink",
|
||||
"impl core::default::Default for rns_transport::announce::AnnounceTable",
|
||||
"impl core::default::Default for rns_transport::link_table::LinkTable",
|
||||
"impl core::default::Default for rns_transport::rate_limit::RateTable",
|
||||
"impl core::default::Default for rns_transport::reverse_table::ReverseTable",
|
||||
"impl core::default::Default for rns_transport::traffic::TrafficCounter",
|
||||
"impl rns_transport::announce::AnnounceTable",
|
||||
"impl rns_transport::link_table::LinkTable",
|
||||
"impl rns_transport::rate_limit::RateTable",
|
||||
"impl rns_transport::reverse_table::ReverseTable",
|
||||
"impl rns_transport::traffic::TrafficCounter",
|
||||
"pub const rns_transport::constants::ANNOUNCE_CACHE_SWEEP_GRACE_SECS: u64",
|
||||
"pub const rns_transport::constants::IC_BURST_MIN_SAMPLES: usize",
|
||||
"pub const rns_transport::constants::LINKS_CHECK_INTERVAL: f64",
|
||||
"pub const rns_transport::discovery::ANNOUNCE_JOB_INTERVAL_SECS: u64",
|
||||
"pub const rns_transport::discovery::APP_NAME: &str",
|
||||
"pub const rns_transport::discovery::AUTOCONNECT_INTERFACE_TYPES: &[&str]",
|
||||
"pub const rns_transport::discovery::AUTOCONNECT_MINIMUM_VERSIONS: &[(&str, core::option::Option<&str>)]",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_ASPECTS: &[&str]",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_ASPECT_FILTER: &str",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_INITIAL_WAIT: core::time::Duration",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_INITIAL_WAIT_SECS: u64",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_JOB_INTERVAL: core::time::Duration",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_JOB_INTERVAL_SECS: u64",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_SOURCE_TIMEOUT: core::time::Duration",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_SOURCE_TIMEOUT_SECS: u64",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_UPDATE_INTERVAL: core::time::Duration",
|
||||
"pub const rns_transport::discovery::BLACKHOLE_UPDATE_INTERVAL_SECS: u64",
|
||||
"pub const rns_transport::discovery::DEFAULT_STAMP_VALUE: u8",
|
||||
"pub const rns_transport::discovery::DETACH_THRESHOLD_TICKS: u64",
|
||||
"pub const rns_transport::discovery::DISCOVERABLE_INTERFACE_TYPES: &[&str]",
|
||||
"pub const rns_transport::discovery::DISCOVERED_INTERFACE_TYPES: &[&str]",
|
||||
"pub const rns_transport::discovery::DISCOVERY_ASPECTS: &[&str]",
|
||||
"pub const rns_transport::discovery::DISCOVERY_ASPECT_FILTER: &str",
|
||||
"pub const rns_transport::discovery::FLAG_ENCRYPTED: u8",
|
||||
"pub const rns_transport::discovery::FLAG_SIGNED: u8",
|
||||
"pub const rns_transport::discovery::IMPLEMENTATION_NAME: &str",
|
||||
"pub const rns_transport::discovery::IMPLEMENTATION_VERSION: &str",
|
||||
"pub const rns_transport::discovery::MONITOR_INTERVAL_SECS: u64",
|
||||
"pub const rns_transport::discovery::STAMP_SIZE: usize",
|
||||
"pub const rns_transport::discovery::THRESHOLD_REMOVE_SECS: u64",
|
||||
"pub const rns_transport::discovery::THRESHOLD_STALE_SECS: u64",
|
||||
"pub const rns_transport::discovery::THRESHOLD_UNKNOWN_SECS: u64",
|
||||
"pub const rns_transport::discovery::WORKBLOCK_EXPAND_ROUNDS: u32",
|
||||
"pub const rns_transport::discovery::blackhole_subscriber::INITIAL_WAIT: core::time::Duration",
|
||||
"pub const rns_transport::discovery::blackhole_subscriber::JOB_INTERVAL: core::time::Duration",
|
||||
"pub const rns_transport::discovery::blackhole_subscriber::SOURCE_TIMEOUT: core::time::Duration",
|
||||
"pub const rns_transport::discovery::blackhole_subscriber::UPDATE_INTERVAL: core::time::Duration",
|
||||
"pub const rns_transport::discovery::constants::BLACKHOLE_INITIAL_WAIT_SECS: u64",
|
||||
"pub const rns_transport::discovery::constants::BLACKHOLE_JOB_INTERVAL_SECS: u64",
|
||||
"pub const rns_transport::discovery::constants::BLACKHOLE_SOURCE_TIMEOUT_SECS: u64",
|
||||
"pub const rns_transport::discovery::constants::BLACKHOLE_UPDATE_INTERVAL_SECS: u64",
|
||||
"pub const rns_transport::discovery::constants::DEFAULT_STAMP_VALUE: u8",
|
||||
"pub const rns_transport::discovery::constants::WORKBLOCK_EXPAND_ROUNDS: u32",
|
||||
"pub const rns_transport::discovery::key::BANDWIDTH: u8",
|
||||
"pub const rns_transport::discovery::key::CHANNEL: u8",
|
||||
"pub const rns_transport::discovery::key::CODING_RATE: u8",
|
||||
"pub const rns_transport::discovery::key::FREQUENCY: u8",
|
||||
"pub const rns_transport::discovery::key::HEIGHT: u8",
|
||||
"pub const rns_transport::discovery::key::IFAC_NETKEY: u8",
|
||||
"pub const rns_transport::discovery::key::IFAC_NETNAME: u8",
|
||||
"pub const rns_transport::discovery::key::INTERFACE_TYPE: u8",
|
||||
"pub const rns_transport::discovery::key::LATITUDE: u8",
|
||||
"pub const rns_transport::discovery::key::LONGITUDE: u8",
|
||||
"pub const rns_transport::discovery::key::MODULATION: u8",
|
||||
"pub const rns_transport::discovery::key::NAME: u8",
|
||||
"pub const rns_transport::discovery::key::PORT: u8",
|
||||
"pub const rns_transport::discovery::key::REACHABLE_ON: u8",
|
||||
"pub const rns_transport::discovery::key::SPREADING_FACTOR: u8",
|
||||
"pub const rns_transport::discovery::key::TRANSPORT: u8",
|
||||
"pub const rns_transport::discovery::key::TRANSPORT_ID: u8",
|
||||
"pub const rns_transport::discovery::key::TRANSPORT_IMPL: u8",
|
||||
"pub const rns_transport::discovery::key::TRANSPORT_VERS: u8",
|
||||
"pub const rns_transport::ifac::MAX_IFAC_WIRE_BYTES: usize",
|
||||
"pub const rns_transport::rate_limit::RATE_PENALTY_BASE: f64",
|
||||
"pub const rns_transport::rate_limit::RATE_PENALTY_MAX: f64",
|
||||
"pub const rns_transport::rate_limit::RATE_VIOLATIONS_BEFORE_PENALTY: u32",
|
||||
"pub const rns_transport::rate_limit::RATE_VIOLATION_THRESHOLD: f64",
|
||||
"pub enum rns_transport::messages::TransportMessage",
|
||||
"pub enum rns_transport::messages::TransportQuery",
|
||||
"pub enum rns_transport::messages::TransportQueryResponse",
|
||||
"pub fn rns_transport::announce::AnnounceTable::cull_exhausted(&mut self, u8) -> usize",
|
||||
"pub fn rns_transport::announce::AnnounceTable::default() -> Self",
|
||||
"pub fn rns_transport::announce::AnnounceTable::due_for_retransmit(&self, f64) -> alloc::vec::Vec<rns_wire::types::DestHash>",
|
||||
"pub fn rns_transport::announce::AnnounceTable::get(&self, &[u8; 16]) -> core::option::Option<&rns_transport::announce::AnnounceEntry>",
|
||||
"pub fn rns_transport::announce::AnnounceTable::get_mut(&mut self, &[u8; 16]) -> core::option::Option<&mut rns_transport::announce::AnnounceEntry>",
|
||||
"pub fn rns_transport::announce::AnnounceTable::insert(&mut self, impl core::convert::Into<rns_wire::types::DestHash>, rns_transport::announce::AnnounceEntry)",
|
||||
"pub fn rns_transport::announce::AnnounceTable::is_empty(&self) -> bool",
|
||||
"pub fn rns_transport::announce::AnnounceTable::iter(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&rns_wire::types::DestHash, &rns_transport::announce::AnnounceEntry)>",
|
||||
"pub fn rns_transport::announce::AnnounceTable::len(&self) -> usize",
|
||||
"pub fn rns_transport::announce::AnnounceTable::new() -> Self",
|
||||
"pub fn rns_transport::announce::AnnounceTable::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_transport::announce::AnnounceEntry>",
|
||||
"pub fn rns_transport::discovery::DiscoveryStamper::generate(&self, &[u8; 32], u8) -> core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub fn rns_transport::discovery::DiscoveryStamper::valid(&self, &[u8; 32], &[u8], u8) -> bool",
|
||||
"pub fn rns_transport::discovery::DiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> u8",
|
||||
"pub fn rns_transport::discovery::announcer::DiscoveryInterfaceConfig::backbone(alloc::string::String, alloc::string::String, u16) -> Self",
|
||||
"pub fn rns_transport::discovery::blackhole_manifest::build_local_manifest(&rns_transport::blackhole::BlackholeTable, rns_wire::types::IdentityHash, core::option::Option<&std::collections::hash::set::HashSet<[u8; 16]>>) -> core::result::Result<alloc::vec::Vec<u8>, rns_transport::discovery::blackhole_manifest::ManifestError>",
|
||||
"pub fn rns_transport::discovery::build_local_manifest(&rns_transport::blackhole::BlackholeTable, rns_wire::types::IdentityHash, core::option::Option<&std::collections::hash::set::HashSet<[u8; 16]>>) -> core::result::Result<alloc::vec::Vec<u8>, rns_transport::discovery::blackhole_manifest::ManifestError>",
|
||||
"pub fn rns_transport::discovery::stamper::DiscoveryStamper::generate(&self, &[u8; 32], u8) -> core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub fn rns_transport::discovery::stamper::DiscoveryStamper::valid(&self, &[u8; 32], &[u8], u8) -> bool",
|
||||
"pub fn rns_transport::discovery::stamper::DiscoveryStamper::value(&self, &[u8; 32], &[u8]) -> u8",
|
||||
"pub fn rns_transport::discovery::stamper::NullStamper::generate(&self, &[u8; 32], u8) -> core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub fn rns_transport::discovery::stamper::NullStamper::valid(&self, &[u8; 32], &[u8], u8) -> bool",
|
||||
"pub fn rns_transport::discovery::stamper::NullStamper::value(&self, &[u8; 32], &[u8]) -> u8",
|
||||
"pub fn rns_transport::discovery::storage::classify(u64) -> rns_transport::discovery::storage::DiscoveryStatus",
|
||||
"pub fn rns_transport::ingress::IngressController::hold_announce(&mut self, rns_transport::ingress::HeldAnnounce)",
|
||||
"pub fn rns_transport::ingress::IngressController::incoming_announce_frequency(&self) -> f64",
|
||||
"pub fn rns_transport::ingress::IngressController::incoming_pr_frequency(&self) -> f64",
|
||||
"pub fn rns_transport::ingress::IngressController::outgoing_announce_frequency(&self) -> f64",
|
||||
"pub fn rns_transport::ingress::IngressController::outgoing_pr_frequency(&self) -> f64",
|
||||
"pub fn rns_transport::link_table::ExpiredLink::from(&rns_transport::link_table::LinkEntry) -> Self",
|
||||
"pub fn rns_transport::link_table::LinkTable::contains(&self, &[u8; 16]) -> bool",
|
||||
"pub fn rns_transport::link_table::LinkTable::cull_dead_interfaces(&mut self, &std::collections::hash::set::HashSet<rns_transport::messages::InterfaceId>) -> usize",
|
||||
"pub fn rns_transport::link_table::LinkTable::cull_stale(&mut self, f64) -> (usize, alloc::vec::Vec<rns_transport::link_table::ExpiredLink>)",
|
||||
"pub fn rns_transport::link_table::LinkTable::default() -> Self",
|
||||
"pub fn rns_transport::link_table::LinkTable::get(&self, &[u8; 16]) -> core::option::Option<&rns_transport::link_table::LinkEntry>",
|
||||
"pub fn rns_transport::link_table::LinkTable::get_mut(&mut self, &[u8; 16]) -> core::option::Option<&mut rns_transport::link_table::LinkEntry>",
|
||||
"pub fn rns_transport::link_table::LinkTable::insert(&mut self, impl core::convert::Into<rns_wire::types::LinkId>, rns_transport::link_table::LinkEntry)",
|
||||
"pub fn rns_transport::link_table::LinkTable::is_empty(&self) -> bool",
|
||||
"pub fn rns_transport::link_table::LinkTable::iter(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&rns_wire::types::LinkId, &rns_transport::link_table::LinkEntry)>",
|
||||
"pub fn rns_transport::link_table::LinkTable::len(&self) -> usize",
|
||||
"pub fn rns_transport::link_table::LinkTable::new() -> Self",
|
||||
"pub fn rns_transport::link_table::LinkTable::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_transport::link_table::LinkEntry>",
|
||||
"pub fn rns_transport::link_table::LinkTable::remove_interface(&mut self, rns_transport::messages::InterfaceId)",
|
||||
"pub fn rns_transport::path_table::PathEntry::touch(&mut self)",
|
||||
"pub fn rns_transport::persistence::load_announce_cache(&std::path::Path) -> core::result::Result<alloc::vec::Vec<rns_transport::persistence::PersistedAnnounceEntry>, rns_transport::persistence::PersistenceError>",
|
||||
"pub fn rns_transport::persistence::load_announce_cache_legacy_v5(&std::path::Path) -> core::result::Result<alloc::vec::Vec<rns_transport::persistence::LegacyPersistedAnnounceEntryV5>, rns_transport::persistence::PersistenceError>",
|
||||
"pub fn rns_transport::persistence::migrate_legacy_announce_entries(alloc::vec::Vec<rns_transport::persistence::LegacyPersistedAnnounceEntryV5>, &std::path::Path) -> alloc::vec::Vec<rns_transport::persistence::PersistedAnnounceEntry>",
|
||||
"pub fn rns_transport::persistence::save_announce_cache<'a, I>(I, &std::path::Path) -> core::result::Result<(), rns_transport::persistence::PersistenceError> where I: core::iter::traits::collect::IntoIterator<Item = &'a rns_transport::actor::RecentAnnounce>",
|
||||
"pub fn rns_transport::persistence::sweep_announce_cache(&std::path::Path, &std::collections::hash::set::HashSet<[u8; 32]>, core::time::Duration) -> (usize, usize)",
|
||||
"pub fn rns_transport::rate_limit::RateTable::check_interface_rate(&mut self, impl core::convert::Into<rns_wire::types::DestHash>, f64, u32, f64) -> bool",
|
||||
"pub fn rns_transport::rate_limit::RateTable::cull(&mut self, f64)",
|
||||
"pub fn rns_transport::rate_limit::RateTable::default() -> Self",
|
||||
"pub fn rns_transport::rate_limit::RateTable::get_rate(&self, &[u8; 16]) -> f64",
|
||||
"pub fn rns_transport::rate_limit::RateTable::is_blocked(&self, &[u8; 16]) -> bool",
|
||||
"pub fn rns_transport::rate_limit::RateTable::is_empty(&self) -> bool",
|
||||
"pub fn rns_transport::rate_limit::RateTable::iter(&self) -> impl core::iter::traits::iterator::Iterator<Item = (&rns_wire::types::DestHash, &rns_transport::rate_limit::RateEntry)>",
|
||||
"pub fn rns_transport::rate_limit::RateTable::last_announce(&self, &[u8; 16]) -> core::option::Option<f64>",
|
||||
"pub fn rns_transport::rate_limit::RateTable::len(&self) -> usize",
|
||||
"pub fn rns_transport::rate_limit::RateTable::new() -> Self",
|
||||
"pub fn rns_transport::rate_limit::RateTable::record(&mut self, impl core::convert::Into<rns_wire::types::DestHash>) -> f64",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::cull_dead_interfaces(&mut self, &std::collections::hash::set::HashSet<rns_transport::messages::InterfaceId>) -> usize",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::cull_expired(&mut self) -> usize",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::cull_expired_batch(&mut self, usize) -> usize",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::default() -> Self",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::get(&self, &[u8; 16]) -> core::option::Option<&rns_transport::reverse_table::ReverseEntry>",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::insert(&mut self, impl core::convert::Into<rns_wire::types::TruncatedHash>, rns_transport::messages::InterfaceId, u8)",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::insert_with_outbound(&mut self, impl core::convert::Into<rns_wire::types::TruncatedHash>, rns_transport::messages::InterfaceId, u8, core::option::Option<rns_transport::messages::InterfaceId>)",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::is_empty(&self) -> bool",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::len(&self) -> usize",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::new() -> Self",
|
||||
"pub fn rns_transport::reverse_table::ReverseTable::remove(&mut self, &[u8; 16]) -> core::option::Option<rns_transport::reverse_table::ReverseEntry>",
|
||||
"pub fn rns_transport::traffic::TrafficCounter::all(&self) -> &std::collections::hash::map::HashMap<rns_transport::messages::InterfaceId, rns_transport::traffic::InterfaceTraffic>",
|
||||
"pub fn rns_transport::traffic::TrafficCounter::default() -> Self",
|
||||
"pub fn rns_transport::traffic::TrafficCounter::get(&self, &rns_transport::messages::InterfaceId) -> core::option::Option<&rns_transport::traffic::InterfaceTraffic>",
|
||||
"pub fn rns_transport::traffic::TrafficCounter::new() -> Self",
|
||||
"pub fn rns_transport::traffic::TrafficCounter::record_rx(&mut self, rns_transport::messages::InterfaceId, u64)",
|
||||
"pub fn rns_transport::traffic::TrafficCounter::record_tx(&mut self, rns_transport::messages::InterfaceId, u64)",
|
||||
"pub fn rns_transport::traffic::TrafficCounter::update_speeds(&mut self)",
|
||||
"pub mod rns_transport::announce",
|
||||
"pub mod rns_transport::discovery::key",
|
||||
"pub mod rns_transport::link_table",
|
||||
"pub mod rns_transport::rate_limit",
|
||||
"pub mod rns_transport::reverse_table",
|
||||
"pub mod rns_transport::traffic",
|
||||
"pub rns_transport::actor::TransportActor::announce_sweep_in_flight: alloc::sync::Arc<core::sync::atomic::AtomicBool>",
|
||||
"pub rns_transport::actor::TransportActor::announce_table: rns_transport::announce::AnnounceTable",
|
||||
"pub rns_transport::actor::TransportActor::blackhole_sources: alloc::vec::Vec<[u8; 16]>",
|
||||
"pub rns_transport::actor::TransportActor::blackhole_table: rns_transport::blackhole::BlackholeTable",
|
||||
"pub rns_transport::actor::TransportActor::blackholed_snapshot: alloc::sync::Arc<std::sync::poison::rwlock::RwLock<std::collections::hash::set::HashSet<[u8; 16]>>>",
|
||||
"pub rns_transport::actor::TransportActor::channel_drops: u64",
|
||||
"pub rns_transport::actor::TransportActor::destination_channels: std::collections::hash::map::HashMap<[u8; 16], tokio::sync::mpsc::bounded::Sender<rns_transport::link_messages::DestinationEvent>>",
|
||||
"pub rns_transport::actor::TransportActor::discovery_pr_tags: std::collections::hash::map::HashMap<alloc::vec::Vec<u8>, f64>",
|
||||
"pub rns_transport::actor::TransportActor::ephemeral_identity_hash: core::option::Option<[u8; 16]>",
|
||||
"pub rns_transport::actor::TransportActor::hashlist_save_in_flight: alloc::sync::Arc<core::sync::atomic::AtomicBool>",
|
||||
"pub rns_transport::actor::TransportActor::held_announces: std::collections::hash::map::HashMap<[u8; 16], rns_transport::announce::AnnounceEntry>",
|
||||
"pub rns_transport::actor::TransportActor::interfaces: std::collections::hash::map::HashMap<rns_transport::messages::InterfaceId, rns_transport::messages::InterfaceEntry>",
|
||||
"pub rns_transport::actor::TransportActor::internal_identity_hash: core::option::Option<[u8; 16]>",
|
||||
"pub rns_transport::actor::TransportActor::is_foreground: alloc::sync::Arc<core::sync::atomic::AtomicBool>",
|
||||
"pub rns_transport::actor::TransportActor::is_shared_instance: bool",
|
||||
"pub rns_transport::actor::TransportActor::is_transport_enabled: bool",
|
||||
"pub rns_transport::actor::TransportActor::last_state_save: f64",
|
||||
"pub rns_transport::actor::TransportActor::link_table: rns_transport::link_table::LinkTable",
|
||||
"pub rns_transport::actor::TransportActor::local_destinations: std::collections::hash::set::HashSet<[u8; 16]>",
|
||||
"pub rns_transport::actor::TransportActor::local_hops_delta: u8",
|
||||
"pub rns_transport::actor::TransportActor::packet_hashlist: rns_transport::hashlist::PacketHashlist",
|
||||
"pub rns_transport::actor::TransportActor::packet_metrics: std::collections::hash::map::HashMap<[u8; 32], rns_transport::link_messages::PacketMetrics>",
|
||||
"pub rns_transport::actor::TransportActor::packet_metrics_order: alloc::collections::vec_deque::VecDeque<[u8; 32]>",
|
||||
"pub rns_transport::actor::TransportActor::path_interface_suppressions: std::collections::hash::map::HashMap<([u8; 16], rns_transport::messages::InterfaceId), f64>",
|
||||
"pub rns_transport::actor::TransportActor::path_requests: std::collections::hash::map::HashMap<[u8; 16], f64>",
|
||||
"pub rns_transport::actor::TransportActor::path_states: std::collections::hash::map::HashMap<[u8; 16], rns_transport::constants::PathState>",
|
||||
"pub rns_transport::actor::TransportActor::path_table: rns_transport::path_table::PathTable",
|
||||
"pub rns_transport::actor::TransportActor::path_waiters: std::collections::hash::map::HashMap<[u8; 16], alloc::vec::Vec<(tokio::sync::oneshot::Sender<bool>, f64)>>",
|
||||
"pub rns_transport::actor::TransportActor::pending_discovery_prs: alloc::collections::vec_deque::VecDeque<rns_transport::actor::PendingDiscoveryPathRequest>",
|
||||
"pub rns_transport::actor::TransportActor::pending_local_path_requests: std::collections::hash::map::HashMap<[u8; 16], rns_transport::messages::InterfaceId>",
|
||||
"pub rns_transport::actor::TransportActor::pending_path_entries: alloc::vec::Vec<rns_transport::persistence::PersistedPathEntry>",
|
||||
"pub rns_transport::actor::TransportActor::rate_table: rns_transport::rate_limit::RateTable",
|
||||
"pub rns_transport::actor::TransportActor::receipt_msg_ids: std::collections::hash::map::HashMap<[u8; 16], alloc::string::String>",
|
||||
"pub rns_transport::actor::TransportActor::receipt_proof_txs: std::collections::hash::map::HashMap<[u8; 16], tokio::sync::mpsc::unbounded::UnboundedSender<rns_transport::link_messages::DestinationEvent>>",
|
||||
"pub rns_transport::actor::TransportActor::receipt_table: std::collections::hash::map::HashMap<[u8; 16], rns_wire::receipt::PacketReceipt>",
|
||||
"pub rns_transport::actor::TransportActor::receipt_updates: std::collections::hash::map::HashMap<[u8; 16], tokio::sync::watch::Sender<rns_transport::messages::ReceiptUpdate>>",
|
||||
"pub rns_transport::actor::TransportActor::recent_announces: std::collections::hash::map::HashMap<[u8; 16], rns_transport::actor::RecentAnnounce>",
|
||||
"pub rns_transport::actor::TransportActor::reverse_table: rns_transport::reverse_table::ReverseTable",
|
||||
"pub rns_transport::actor::TransportActor::routing_save_generation: alloc::sync::Arc<core::sync::atomic::AtomicU64>",
|
||||
"pub rns_transport::actor::TransportActor::routing_save_in_flight: alloc::sync::Arc<core::sync::atomic::AtomicBool>",
|
||||
"pub rns_transport::actor::TransportActor::routing_save_lock: alloc::sync::Arc<std::sync::poison::mutex::Mutex<()>>",
|
||||
"pub rns_transport::actor::TransportActor::shared_instance_client_mode: bool",
|
||||
"pub rns_transport::actor::TransportActor::state_dirty: bool",
|
||||
"pub rns_transport::actor::TransportActor::static_transport_identity: bool",
|
||||
"pub rns_transport::actor::TransportActor::storage_dir: core::option::Option<std::path::PathBuf>",
|
||||
"pub rns_transport::actor::TransportActor::traffic: rns_transport::traffic::TrafficCounter",
|
||||
"pub rns_transport::actor::TransportActor::transport_identity_hash: core::option::Option<[u8; 16]>",
|
||||
"pub rns_transport::actor::TransportActor::tunnel_table: rns_transport::tunnel::TunnelTable",
|
||||
"pub rns_transport::announce::AnnounceEntry::attached_interface: core::option::Option<rns_transport::messages::InterfaceId>",
|
||||
"pub rns_transport::announce::AnnounceEntry::block_rebroadcast: bool",
|
||||
"pub rns_transport::announce::AnnounceEntry::hops: u8",
|
||||
"pub rns_transport::announce::AnnounceEntry::local_rebroadcasts: u32",
|
||||
"pub rns_transport::announce::AnnounceEntry::packet_raw: alloc::vec::Vec<u8>",
|
||||
"pub rns_transport::announce::AnnounceEntry::received_from: [u8; 16]",
|
||||
"pub rns_transport::announce::AnnounceEntry::retransmit_timeout: f64",
|
||||
"pub rns_transport::announce::AnnounceEntry::retries: u8",
|
||||
"pub rns_transport::announce::AnnounceEntry::source_interface: core::option::Option<rns_transport::messages::InterfaceId>",
|
||||
"pub rns_transport::announce::AnnounceEntry::timestamp: f64",
|
||||
"pub rns_transport::discovery::AnnounceRequest::stamp_value: u8",
|
||||
"pub rns_transport::discovery::DiscoveredInterface::discovered: u64",
|
||||
"pub rns_transport::discovery::DiscoveredInterface::last_heard: u64",
|
||||
"pub rns_transport::discovery::DiscoveredInterface::stamp_value: u8",
|
||||
"pub rns_transport::discovery::DiscoveryInterfaceConfig::modulation: core::option::Option<alloc::string::String>",
|
||||
"pub rns_transport::discovery::DiscoveryInterfaceConfig::name: alloc::string::String",
|
||||
"pub rns_transport::discovery::DiscoveryInterfaceConfig::stamp_value: u8",
|
||||
"pub rns_transport::discovery::ReceiverConfig::required_value: u8",
|
||||
"pub rns_transport::discovery::announcer::AnnounceRequest::stamp_value: u8",
|
||||
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::modulation: core::option::Option<alloc::string::String>",
|
||||
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::name: alloc::string::String",
|
||||
"pub rns_transport::discovery::announcer::DiscoveryInterfaceConfig::stamp_value: u8",
|
||||
"pub rns_transport::discovery::app_data::DiscoveryInfo::modulation: core::option::Option<alloc::string::String>",
|
||||
"pub rns_transport::discovery::receiver::ReceiverConfig::required_value: u8",
|
||||
"pub rns_transport::discovery::storage::DiscoveredInterface::discovered: u64",
|
||||
"pub rns_transport::discovery::storage::DiscoveredInterface::last_heard: u64",
|
||||
"pub rns_transport::discovery::storage::DiscoveredInterface::stamp_value: u8",
|
||||
"pub rns_transport::ifac::IfacSignError::PacketTooLarge",
|
||||
"pub rns_transport::link_table::ExpiredLink::destination_hash: [u8; 16]",
|
||||
"pub rns_transport::link_table::ExpiredLink::interface_id: rns_transport::messages::InterfaceId",
|
||||
"pub rns_transport::link_table::ExpiredLink::next_hop: core::option::Option<[u8; 16]>",
|
||||
"pub rns_transport::link_table::ExpiredLink::receiving_interface: rns_transport::messages::InterfaceId",
|
||||
"pub rns_transport::link_table::ExpiredLink::remaining_hops: u8",
|
||||
"pub rns_transport::link_table::ExpiredLink::taken_hops: u8",
|
||||
"pub rns_transport::link_table::LinkEntry::accepted_mtu_ceiling: u32",
|
||||
"pub rns_transport::link_table::LinkEntry::destination_hash: [u8; 16]",
|
||||
"pub rns_transport::link_table::LinkEntry::established: bool",
|
||||
"pub rns_transport::link_table::LinkEntry::interface_id: rns_transport::messages::InterfaceId",
|
||||
"pub rns_transport::link_table::LinkEntry::interface_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwner>",
|
||||
"pub rns_transport::link_table::LinkEntry::next_hop: core::option::Option<[u8; 16]>",
|
||||
"pub rns_transport::link_table::LinkEntry::proof_timeout: f64",
|
||||
"pub rns_transport::link_table::LinkEntry::receiving_interface: rns_transport::messages::InterfaceId",
|
||||
"pub rns_transport::link_table::LinkEntry::receiving_owner: core::option::Option<rns_transport::interface_ownership::InterfaceOwner>",
|
||||
"pub rns_transport::link_table::LinkEntry::remaining_hops: u8",
|
||||
"pub rns_transport::link_table::LinkEntry::requested_mode: u8",
|
||||
"pub rns_transport::link_table::LinkEntry::taken_hops: u8",
|
||||
"pub rns_transport::link_table::LinkEntry::timestamp: f64",
|
||||
"pub rns_transport::link_table::LinkEntry::validated: bool",
|
||||
"pub rns_transport::messages::InterfaceStatRpcEntry::ifac_size: usize",
|
||||
"pub rns_transport::messages::TimerTick::timestamp: f64",
|
||||
"pub rns_transport::messages::TransportMessage::SynthesizeTunnel::raw_packet: bytes::bytes::Bytes",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::app_data: core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::destination_hash: alloc::vec::Vec<u8>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::hops: u8",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::name_hash: alloc::vec::Vec<u8>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::public_key: core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::ratchet: core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::raw_packet: alloc::vec::Vec<u8>",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::retained: bool",
|
||||
"pub rns_transport::persistence::LegacyPersistedAnnounceEntryV5::timestamp: f64",
|
||||
"pub rns_transport::rate_limit::RateEntry::blocked_until: f64",
|
||||
"pub rns_transport::rate_limit::RateEntry::last: f64",
|
||||
"pub rns_transport::rate_limit::RateEntry::rate: f64",
|
||||
"pub rns_transport::rate_limit::RateEntry::timestamps: alloc::vec::Vec<f64>",
|
||||
"pub rns_transport::rate_limit::RateEntry::violations: u32",
|
||||
"pub rns_transport::reverse_table::ReverseEntry::outbound_interface: core::option::Option<rns_transport::messages::InterfaceId>",
|
||||
"pub rns_transport::reverse_table::ReverseEntry::receiving_interface: rns_transport::messages::InterfaceId",
|
||||
"pub rns_transport::reverse_table::ReverseEntry::remaining_hops: u8",
|
||||
"pub rns_transport::reverse_table::ReverseEntry::timestamp: f64",
|
||||
"pub rns_transport::traffic::InterfaceTraffic::rx_bytes: u64",
|
||||
"pub rns_transport::traffic::InterfaceTraffic::rx_bytes_prev: u64",
|
||||
"pub rns_transport::traffic::InterfaceTraffic::rx_speed: f64",
|
||||
"pub rns_transport::traffic::InterfaceTraffic::tx_bytes: u64",
|
||||
"pub rns_transport::traffic::InterfaceTraffic::tx_bytes_prev: u64",
|
||||
"pub rns_transport::traffic::InterfaceTraffic::tx_speed: f64",
|
||||
"pub struct rns_transport::announce::AnnounceEntry",
|
||||
"pub struct rns_transport::announce::AnnounceTable",
|
||||
"pub struct rns_transport::link_table::ExpiredLink",
|
||||
"pub struct rns_transport::link_table::LinkEntry",
|
||||
"pub struct rns_transport::link_table::LinkTable",
|
||||
"pub struct rns_transport::messages::AnnounceRpcEntry",
|
||||
"pub struct rns_transport::messages::BlackholeRpcEntry",
|
||||
"pub struct rns_transport::messages::InterfaceEntry",
|
||||
"pub struct rns_transport::messages::InterfaceStatRpcEntry",
|
||||
"pub struct rns_transport::messages::PathTableRpcEntry",
|
||||
"pub struct rns_transport::messages::RateTableRpcEntry",
|
||||
"pub struct rns_transport::messages::RecalledDestinationRpcEntry",
|
||||
"pub struct rns_transport::persistence::LegacyPersistedAnnounceEntryV5",
|
||||
"pub struct rns_transport::rate_limit::RateEntry",
|
||||
"pub struct rns_transport::rate_limit::RateTable",
|
||||
"pub struct rns_transport::reverse_table::ReverseEntry",
|
||||
"pub struct rns_transport::reverse_table::ReverseTable",
|
||||
"pub struct rns_transport::traffic::InterfaceTraffic",
|
||||
"pub struct rns_transport::traffic::TrafficCounter"
|
||||
],
|
||||
"rns-link": [
|
||||
"pub enum rns_link::link::CloseReason"
|
||||
],
|
||||
"rns-protocol": [
|
||||
"pub const rns_protocol::rnsh::STREAM_DATA_OVERHEAD: usize",
|
||||
"pub fn rns_protocol::resource::MultiSegmentOutbound::with_options(alloc::vec::Vec<u8>, bool, core::option::Option<alloc::vec::Vec<u8>>, core::option::Option<alloc::vec::Vec<u8>>, bool, core::option::Option<&rns_protocol::resource::ResourceEncryptor<'_>>) -> core::result::Result<Self, rns_protocol::resource::ResourceError>",
|
||||
"pub fn rns_protocol::resource::WindowState::grow(&mut self, usize)"
|
||||
],
|
||||
"rns-interface": [
|
||||
"impl rns_interface::traits::TunnelIdentity",
|
||||
"pub async fn rns_interface::auto::spawn_auto_interface(rns_interface::auto::AutoInterfaceConfig, rns_interface::traits::InterfaceId, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>, alloc::sync::Arc<core::sync::atomic::AtomicBool>) -> core::result::Result<rns_interface::traits::InterfaceHandle, rns_interface::traits::InterfaceError>",
|
||||
"pub const rns_interface::backbone::CHILD_BITRATE_GUESS: u64",
|
||||
"pub const rns_interface::i2p::RECONNECT_WAIT_MAX: u64",
|
||||
"pub const rns_interface::tcp::RECONNECT_WAIT_INITIAL: u64",
|
||||
"pub const rns_interface::tcp::RECONNECT_WAIT_MAX: u64",
|
||||
"pub const rns_interface::traits::IC_BURST_MIN_SAMPLES: usize",
|
||||
"pub fn rns_interface::rnode::process_rnode_response(u8, &[u8], rns_interface::traits::InterfaceId, &mut core::option::Option<f32>, &mut core::option::Option<f32>) -> rns_interface::rnode::RNodeResponse",
|
||||
"pub fn rns_interface::traits::TunnelIdentity::synthesis(&self, &str) -> core::option::Option<bytes::bytes::Bytes>",
|
||||
"pub rns_interface::backbone::BackboneServerConfig::listen_ip: alloc::string::String",
|
||||
"pub rns_interface::ble_rnode::BleRNodeConfig::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_interface::ble_rnode::BleRNodeConfig::st_alock: core::option::Option<f32>",
|
||||
"pub rns_interface::rnode::RNodeConfig::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_interface::rnode::RNodeConfig::st_alock: core::option::Option<f32>",
|
||||
"pub rns_interface::rnode::RNodeConfigValidationError::NonFinite::value: f32",
|
||||
"pub rns_interface::rnode::RNodeResponse::Ready(bool)",
|
||||
"pub rns_interface::rnode_multi::RNodeMultiConfig::flow_control: bool",
|
||||
"pub rns_interface::rnode_multi::SubInterfaceConfig::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_interface::rnode_multi::SubInterfaceConfig::mode: rns_interface::traits::InterfaceMode",
|
||||
"pub rns_interface::rnode_multi::SubInterfaceConfig::st_alock: core::option::Option<f32>",
|
||||
"pub rns_interface::rnode_multi::SubInterfaceConfig::tx_power: u8",
|
||||
"pub rns_interface::tcp::TcpServerConfig::listen_ip: alloc::string::String",
|
||||
"pub type rns_interface::auto::McastAddrType::Err = alloc::string::String"
|
||||
],
|
||||
"rns-runtime": [
|
||||
"impl core::ops::drop::Drop for rns_runtime::buffer_stream::LinkSessionBufferReader",
|
||||
"impl rns_runtime::buffer_stream::LinkSessionBuffer",
|
||||
"impl rns_runtime::buffer_stream::LinkSessionBufferReader",
|
||||
"impl rns_runtime::buffer_stream::LinkSessionBufferWriter",
|
||||
"impl tokio::io::async_read::AsyncRead for rns_runtime::buffer_stream::LinkSessionBuffer",
|
||||
"impl tokio::io::async_read::AsyncRead for rns_runtime::buffer_stream::LinkSessionBufferReader",
|
||||
"impl tokio::io::async_write::AsyncWrite for rns_runtime::buffer_stream::LinkSessionBuffer",
|
||||
"impl tokio::io::async_write::AsyncWrite for rns_runtime::buffer_stream::LinkSessionBufferWriter",
|
||||
"pub async fn rns_runtime::buffer_stream::LinkSessionBuffer::close_reader(&mut self) -> core::result::Result<(), rns_runtime::buffer_stream::LinkSessionBufferError>",
|
||||
"pub async fn rns_runtime::buffer_stream::LinkSessionBufferReader::close(&mut self) -> core::result::Result<(), rns_runtime::buffer_stream::LinkSessionBufferError>",
|
||||
"pub async fn rns_runtime::destination_runtime::DestinationHandle::register_request_handler<F>(&self, impl core::convert::Into<alloc::string::String>, rns_identity::destination::AllowPolicy, alloc::vec::Vec<[u8; 16]>, bool, F) -> core::result::Result<bool, rns_runtime::destination_runtime::DestinationRuntimeError> where F: core::ops::function::Fn(rns_runtime::link_manager::DestinationRequest) -> rns_runtime::link_manager::RequestOutcome + core::marker::Send + 'static",
|
||||
"pub async fn rns_runtime::link_session::LinkSessionChannelHandle::create_bidirectional_buffer(&self, u16, u16) -> core::result::Result<rns_runtime::buffer_stream::LinkSessionBuffer, rns_runtime::buffer_stream::LinkSessionBufferError>",
|
||||
"pub async fn rns_runtime::link_session::LinkSessionChannelHandle::create_reader(&self, u16) -> core::result::Result<rns_runtime::buffer_stream::LinkSessionBufferReader, rns_runtime::buffer_stream::LinkSessionBufferError>",
|
||||
"pub async fn rns_runtime::link_session::LinkSessionChannelHandle::create_reader_with_capacity(&self, u16, usize) -> core::result::Result<rns_runtime::buffer_stream::LinkSessionBufferReader, rns_runtime::buffer_stream::LinkSessionBufferError>",
|
||||
"pub const rns_runtime::buffer_stream::DEFAULT_CLOSE_TIMEOUT: core::time::Duration",
|
||||
"pub const rns_runtime::buffer_stream::DEFAULT_READER_CAPACITY: usize",
|
||||
"pub const rns_runtime::constants::ANNOUNCE_CAP: f64",
|
||||
"pub const rns_runtime::constants::GRACIOUS_PERSIST_INTERVAL: u64",
|
||||
"pub const rns_runtime::constants::MAX_QUEUED_ANNOUNCES: usize",
|
||||
"pub const rns_runtime::constants::QUEUED_ANNOUNCE_LIFE: u64",
|
||||
"pub enum rns_runtime::buffer_stream::LinkSessionBufferError",
|
||||
"pub enum rns_runtime::link_manager::LinkManagerCommand",
|
||||
"pub enum rns_runtime::rnsh::RnshError",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBuffer::into_split(self) -> (rns_runtime::buffer_stream::LinkSessionBufferReader, rns_runtime::buffer_stream::LinkSessionBufferWriter)",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBuffer::poll_flush(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>) -> core::task::poll::Poll<core::io::error::Result<()>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBuffer::poll_read(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>, &mut tokio::io::read_buf::ReadBuf<'_>) -> core::task::poll::Poll<core::io::error::Result<()>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBuffer::poll_shutdown(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>) -> core::task::poll::Poll<core::io::error::Result<()>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBuffer::poll_write(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>, &[u8]) -> core::task::poll::Poll<core::io::error::Result<usize>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBuffer::reader(&self) -> &rns_runtime::buffer_stream::LinkSessionBufferReader",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBuffer::writer(&self) -> &rns_runtime::buffer_stream::LinkSessionBufferWriter",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferReader::available(&self) -> usize",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferReader::drop(&mut self)",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferReader::is_eof(&self) -> bool",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferReader::poll_read(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>, &mut tokio::io::read_buf::ReadBuf<'_>) -> core::task::poll::Poll<core::io::error::Result<()>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferReader::stream_id(&self) -> u16",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferWriter::is_closed(&self) -> bool",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferWriter::poll_flush(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>) -> core::task::poll::Poll<core::io::error::Result<()>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferWriter::poll_shutdown(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>) -> core::task::poll::Poll<core::io::error::Result<()>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferWriter::poll_write(core::pin::Pin<&mut Self>, &mut core::task::wake::Context<'_>, &[u8]) -> core::task::poll::Poll<core::io::error::Result<usize>>",
|
||||
"pub fn rns_runtime::buffer_stream::LinkSessionBufferWriter::with_close_timeout(self, core::time::Duration) -> Self",
|
||||
"pub fn rns_runtime::jobs::JobScheduler::request_persist(&mut self)",
|
||||
"pub fn rns_runtime::link_manager::LinkManager::register_deferred_request_handler<F>(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool, usize, F) -> bool where F: core::ops::function::Fn(rns_runtime::link_manager::DestinationRequest, rns_runtime::link_manager::DeferredRequestResponder) + core::marker::Send + 'static",
|
||||
"pub fn rns_runtime::link_manager::LinkManager::register_request_handler<F>(&mut self, &str, rns_identity::destination::AllowPolicy, core::option::Option<alloc::vec::Vec<[u8; 16]>>, bool, F) -> bool where F: core::ops::function::Fn(rns_runtime::link_manager::DestinationRequest) -> rns_runtime::link_manager::RequestOutcome + core::marker::Send + 'static",
|
||||
"pub fn rns_runtime::link_session::LinkSessionChannelHandle::create_writer(&self, u16) -> core::result::Result<rns_runtime::buffer_stream::LinkSessionBufferWriter, rns_runtime::buffer_stream::LinkSessionBufferError>",
|
||||
"pub rns_runtime::buffer_stream::LinkSessionBufferError::Channel(rns_runtime::link_session::LinkSessionChannelError)",
|
||||
"pub rns_runtime::buffer_stream::LinkSessionBufferError::ChannelMduTooSmall(usize)",
|
||||
"pub rns_runtime::buffer_stream::LinkSessionBufferError::InvalidReaderCapacity",
|
||||
"pub rns_runtime::buffer_stream::LinkSessionBufferError::InvalidStreamId(u16)",
|
||||
"pub rns_runtime::interface_factory::BleRNodeInterfaceConfig::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::interface_factory::BleRNodeInterfaceConfig::st_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::interface_factory::PipeInterfaceConfig::respawn_delay: u64",
|
||||
"pub rns_runtime::interface_factory::RNodeInterfaceConfig::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::interface_factory::RNodeInterfaceConfig::st_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::interface_factory::RNodeMultiInterfaceConfig::flow_control: bool",
|
||||
"pub rns_runtime::interface_factory::RNodeSubInterfaceConfig::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::interface_factory::RNodeSubInterfaceConfig::mode: rns_interface::traits::InterfaceMode",
|
||||
"pub rns_runtime::interface_factory::RNodeSubInterfaceConfig::st_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::interface_factory::RNodeSubInterfaceConfig::tx_power: u8",
|
||||
"pub rns_runtime::link_manager::LinkManagerCommand::RegisterRequestHandler::auto_compress: bool",
|
||||
"pub rns_runtime::link_manager::RequestOutcome::Reply(alloc::vec::Vec<u8>)",
|
||||
"pub rns_runtime::link_manager::RequestOutcome::ReplyWithResource::data: alloc::vec::Vec<u8>",
|
||||
"pub rns_runtime::prelude::RequestOutcome::Reply(alloc::vec::Vec<u8>)",
|
||||
"pub rns_runtime::prelude::RequestOutcome::ReplyWithResource::data: alloc::vec::Vec<u8>",
|
||||
"pub rns_runtime::reticulum::BleRnodeRuntimeArgs::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::reticulum::BleRnodeRuntimeArgs::st_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::reticulum::ReticulumConfig::discover_interfaces_required_value: u8",
|
||||
"pub rns_runtime::reticulum::RnodeRuntimeArgs::lt_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::reticulum::RnodeRuntimeArgs::st_alock: core::option::Option<f32>",
|
||||
"pub rns_runtime::rncp::RncpFetchRequest::overall_timeout: core::time::Duration",
|
||||
"pub rns_runtime::rncp::RncpFetchRequest::path_wait: core::time::Duration",
|
||||
"pub rns_runtime::rncp::RncpFetchRequest::progress_tx: core::option::Option<tokio::sync::mpsc::bounded::Sender<f32>>",
|
||||
"pub rns_runtime::rncp::RncpSendRequest::data: alloc::vec::Vec<u8>",
|
||||
"pub rns_runtime::rncp::RncpSendRequest::overall_timeout: core::time::Duration",
|
||||
"pub rns_runtime::rncp::RncpSendRequest::path_wait: core::time::Duration",
|
||||
"pub rns_runtime::rncp::RncpSendRequest::progress_tx: core::option::Option<tokio::sync::mpsc::bounded::Sender<f32>>",
|
||||
"pub rns_runtime::rnsh::RnshError::Denied",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::announce_cap: f64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::announce_queue: core::option::Option<u64>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_grace: core::option::Option<u32>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_penalty: core::option::Option<f64>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::announce_rate_target: core::option::Option<f64>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::announces_received: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::announces_sent: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::autoconnect_source: core::option::Option<alloc::string::String>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::bitrate: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::blocked_ips: core::option::Option<u64>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::burst_activated: f64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::burst_active: bool",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::clients: core::option::Option<u64>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::held_announces: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::id: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::ifac_netname: core::option::Option<alloc::string::String>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::ifac_signature: core::option::Option<alloc::vec::Vec<u8>>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::ifac_size: core::option::Option<usize>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::ifac_violations: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::incoming_announce_frequency: f64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::incoming_pr_frequency: f64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::mode: alloc::string::String",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::mtu: u32",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::name: alloc::string::String",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::online: bool",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::outgoing_announce_frequency: f64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::outgoing_pr_frequency: f64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::packet_filter_hits: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::parent_interface_name: core::option::Option<alloc::string::String>",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::path_requests_received: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::path_requests_sent: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::pr_burst_activated: f64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::pr_burst_active: bool",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::protocol_violations: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::role: alloc::string::String",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::rx_bytes: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::rx_rate: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::tx_bytes: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::tx_dropped_bytes: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::tx_drops: u64",
|
||||
"pub rns_runtime::rpc::InterfaceStatEntry::tx_rate: u64",
|
||||
"pub rns_runtime::rpc::RpcResponse::InterfaceStats(alloc::vec::Vec<rns_runtime::rpc::InterfaceStatEntry>)",
|
||||
"pub struct rns_runtime::buffer_stream::LinkSessionBuffer",
|
||||
"pub struct rns_runtime::buffer_stream::LinkSessionBufferReader",
|
||||
"pub struct rns_runtime::buffer_stream::LinkSessionBufferWriter",
|
||||
"pub struct rns_runtime::prelude::InitOptions",
|
||||
"pub struct rns_runtime::reticulum::InitOptions",
|
||||
"pub struct rns_runtime::reticulum::ReticulumConfig",
|
||||
"pub struct rns_runtime::rpc::InterfaceStatEntry"
|
||||
],
|
||||
"rns-tools": [
|
||||
"pub fn rns_tools::init_tracing<W>(tracing_core::metadata::Level, bool, bool, W) where W: for<'a> tracing_subscriber::fmt::writer::MakeWriter<'a> + core::marker::Send + core::marker::Sync + 'static"
|
||||
]
|
||||
}
|
||||
},
|
||||
"newPackages": [
|
||||
"rns-git"
|
||||
]
|
||||
}
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
# Keep Clippy suggestions aligned with the public MSRV in Cargo.toml.
|
||||
msrv = "1.85"
|
||||
msrv = "1.89"
|
||||
@@ -1,9 +1,11 @@
|
||||
[package]
|
||||
name = "rns-crypto"
|
||||
description = "Cryptographic primitives for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
//! AES-CBC, no padding (callers use [`crate::pkcs7`]). Key length selects:
|
||||
//! 16 → AES-128, 32 → AES-256. Wire negotiates AES-256; AES-128 kept for
|
||||
//! legacy Token material.
|
||||
//! 16 → AES-128, 32 → AES-256. AES-128 supports legacy Token material.
|
||||
//! These primitives do not negotiate a cipher or authenticate ciphertext;
|
||||
//! [`crate::token`] supplies the authenticated Token format.
|
||||
|
||||
use aes::{Aes128, Aes256};
|
||||
use alloc::vec::Vec;
|
||||
use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
|
||||
use cbc::{Decryptor, Encryptor};
|
||||
use thiserror::Error;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const AES_BLOCK_SIZE: usize = 16;
|
||||
|
||||
/// Rust 1.85-compatible block alignment check. Newer Clippy suggests
|
||||
/// `usize::is_multiple_of`, but that API is not available on our MSRV.
|
||||
/// Block alignment check kept explicit at this cryptographic boundary.
|
||||
#[inline]
|
||||
pub(crate) fn is_nonzero_block_aligned(len: usize) -> bool {
|
||||
len != 0 && len % AES_BLOCK_SIZE == 0
|
||||
len != 0 && len.is_multiple_of(AES_BLOCK_SIZE)
|
||||
}
|
||||
|
||||
/// Errors surfaced by [`encrypt`] and [`decrypt`].
|
||||
@@ -47,7 +48,8 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
|
||||
return Err(AesCbcError::NotBlockAligned);
|
||||
}
|
||||
|
||||
let mut buf = plaintext.to_vec();
|
||||
// Wiped if an error leaves this plaintext copy unencrypted.
|
||||
let mut buf = Zeroizing::new(plaintext.to_vec());
|
||||
match key.len() {
|
||||
16 => {
|
||||
let enc = Encryptor::<Aes128>::new_from_slices(key, iv)
|
||||
@@ -69,10 +71,13 @@ pub fn encrypt(key: &[u8], iv: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, AesCb
|
||||
}
|
||||
n => return Err(AesCbcError::InvalidKeyLength(n)),
|
||||
}
|
||||
Ok(buf)
|
||||
Ok(core::mem::take(&mut *buf))
|
||||
}
|
||||
|
||||
/// AES-CBC decrypt. Output is still PKCS7-padded; caller strips it.
|
||||
/// AES-CBC decrypt without checking authentication or removing padding.
|
||||
/// If the sender applied PKCS7 padding, the caller must validate and strip it.
|
||||
/// The key must be 16 or 32 bytes, the IV 16 bytes, and the ciphertext a
|
||||
/// non-zero multiple of 16 bytes.
|
||||
pub fn decrypt(key: &[u8], iv: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, AesCbcError> {
|
||||
if iv.len() != AES_BLOCK_SIZE {
|
||||
return Err(AesCbcError::InvalidIvLength(iv.len()));
|
||||
@@ -175,6 +180,15 @@ mod tests {
|
||||
assert_eq!(&pt[..], &plaintext[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cipher_state_is_wiped_on_drop() {
|
||||
fn wiped_on_drop<T: zeroize::ZeroizeOnDrop>() {}
|
||||
wiped_on_drop::<Encryptor<Aes128>>();
|
||||
wiped_on_drop::<Encryptor<Aes256>>();
|
||||
wiped_on_drop::<Decryptor<Aes128>>();
|
||||
wiped_on_drop::<Decryptor<Aes256>>();
|
||||
}
|
||||
|
||||
/// Different key sizes must produce different ciphertexts for the same input.
|
||||
#[test]
|
||||
fn test_aes128_vs_aes256_distinct_ciphertexts() {
|
||||
|
||||
@@ -14,7 +14,9 @@ pub enum Ed25519Error {
|
||||
/// Public key bytes were not a valid Ed25519 point.
|
||||
#[error("invalid public key bytes")]
|
||||
InvalidPublicKey,
|
||||
/// Signature bytes could not be decoded as an Ed25519 signature.
|
||||
/// Retained signature-decoding error variant. The current `verify` method
|
||||
/// accepts a fixed 64-byte signature and returns `VerificationFailed` on
|
||||
/// verification failure.
|
||||
#[error("invalid signature bytes")]
|
||||
InvalidSignature,
|
||||
}
|
||||
|
||||
@@ -3,18 +3,23 @@
|
||||
use alloc::vec;
|
||||
use alloc::vec::Vec;
|
||||
use hkdf::Hkdf;
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
use thiserror::Error;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const HASH_LEN: usize = 32;
|
||||
/// Per RFC 5869, HKDF-SHA256 can emit at most 255 * HashLen = 8160 bytes.
|
||||
const MAX_OUTPUT_LENGTH: usize = 255 * 32;
|
||||
const RFC_MAX_OUTPUT_LENGTH: usize = 255 * HASH_LEN;
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
/// Errors surfaced by [`hkdf_sha256`].
|
||||
#[derive(Debug, Error)]
|
||||
pub enum HkdfError {
|
||||
/// Requested output length exceeds the RFC 5869 cap (8160 bytes).
|
||||
#[error("requested length {0} exceeds maximum HKDF output of {MAX_OUTPUT_LENGTH} bytes")]
|
||||
OutputTooLong(usize),
|
||||
/// Requested output length is zero.
|
||||
#[error("invalid HKDF output length 0")]
|
||||
InvalidLength,
|
||||
/// Underlying HKDF expand call returned an error.
|
||||
#[error("HKDF expansion failed")]
|
||||
ExpansionFailed,
|
||||
@@ -22,32 +27,56 @@ pub enum HkdfError {
|
||||
|
||||
/// HKDF-SHA256 key derivation (RFC 5869).
|
||||
///
|
||||
/// `length` is capped at 8160 bytes. `salt = None` uses 32 zero bytes as
|
||||
/// specified by the RFC; `info = None` uses an empty context string.
|
||||
/// `salt = None` uses 32 zero bytes as specified by the RFC; `info = None`
|
||||
/// uses an empty context string. The output is wiped when it is dropped.
|
||||
/// Lengths above the RFC's 255-block bound are accepted: the reference
|
||||
/// implementation wraps its one-byte block counter, and IFAC masks for large
|
||||
/// frames depend on that.
|
||||
pub fn hkdf_sha256(
|
||||
length: usize,
|
||||
ikm: &[u8],
|
||||
salt: Option<&[u8]>,
|
||||
info: Option<&[u8]>,
|
||||
) -> Result<Vec<u8>, HkdfError> {
|
||||
if length > MAX_OUTPUT_LENGTH {
|
||||
return Err(HkdfError::OutputTooLong(length));
|
||||
) -> Result<Zeroizing<Vec<u8>>, HkdfError> {
|
||||
if length == 0 {
|
||||
return Err(HkdfError::InvalidLength);
|
||||
}
|
||||
let info = info.unwrap_or(b"");
|
||||
let mut okm = Zeroizing::new(vec![0u8; length]);
|
||||
if length <= RFC_MAX_OUTPUT_LENGTH {
|
||||
Hkdf::<Sha256>::new(salt, ikm)
|
||||
.expand(info, &mut okm)
|
||||
.map_err(|_| HkdfError::ExpansionFailed)?;
|
||||
return Ok(okm);
|
||||
}
|
||||
|
||||
let hk = Hkdf::<Sha256>::new(salt, ikm);
|
||||
let mut okm = vec![0u8; length];
|
||||
hk.expand(info.unwrap_or(b""), &mut okm)
|
||||
.map_err(|_| HkdfError::ExpansionFailed)?;
|
||||
let (prk, _) = Hkdf::<Sha256>::extract(salt, ikm);
|
||||
let keyed = HmacSha256::new_from_slice(&prk).map_err(|_| HkdfError::ExpansionFailed)?;
|
||||
let mut previous = Zeroizing::new([0u8; HASH_LEN]);
|
||||
for (index, chunk) in okm.chunks_mut(HASH_LEN).enumerate() {
|
||||
let mut mac = keyed.clone();
|
||||
if index > 0 {
|
||||
mac.update(&previous[..]);
|
||||
}
|
||||
mac.update(info);
|
||||
mac.update(&[(index as u8).wrapping_add(1)]);
|
||||
previous.copy_from_slice(&mac.finalize().into_bytes());
|
||||
chunk.copy_from_slice(&previous[..chunk.len()]);
|
||||
}
|
||||
Ok(okm)
|
||||
}
|
||||
|
||||
/// Derive the 64-byte session key used for RNS link encryption:
|
||||
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=identity_hash, info=None)`.
|
||||
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<[u8; 64], HkdfError> {
|
||||
let okm = hkdf_sha256(64, shared_secret, Some(salt), None)?;
|
||||
let mut out = [0u8; 64];
|
||||
out.copy_from_slice(&okm);
|
||||
Ok(out)
|
||||
/// Derive 64 key bytes with the caller-provided salt:
|
||||
/// `HKDF-SHA256(length=64, ikm=shared_secret, salt=salt, info=None)`.
|
||||
/// Identity encryption passes the identity hash. Link key derivation instead
|
||||
/// selects its key length by mode and uses the Link ID as salt.
|
||||
/// The key is expanded straight into its return buffer, which is wiped on drop.
|
||||
pub fn derive_key_64(shared_secret: &[u8], salt: &[u8]) -> Result<Zeroizing<[u8; 64]>, HkdfError> {
|
||||
let mut okm = Zeroizing::new([0u8; 64]);
|
||||
Hkdf::<Sha256>::new(Some(salt), shared_secret)
|
||||
.expand(b"", &mut okm[..])
|
||||
.map_err(|_| HkdfError::ExpansionFailed)?;
|
||||
Ok(okm)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -68,9 +97,11 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hkdf_max_length_exceeded() {
|
||||
let result = hkdf_sha256(MAX_OUTPUT_LENGTH + 1, b"test", None, None);
|
||||
assert!(result.is_err());
|
||||
fn test_hkdf_rejects_zero_length() {
|
||||
assert!(matches!(
|
||||
hkdf_sha256(0, b"test", None, None),
|
||||
Err(HkdfError::InvalidLength)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -84,5 +115,12 @@ mod tests {
|
||||
fn test_derive_key_64() {
|
||||
let key = derive_key_64(b"shared_secret", b"salt_value").unwrap();
|
||||
assert_eq!(key.len(), 64);
|
||||
let cases: [(&[u8], &[u8]); 2] = [(b"shared_secret", b"salt_value"), (&[7; 32], &[9; 16])];
|
||||
for (ikm, salt) in cases {
|
||||
assert_eq!(
|
||||
&derive_key_64(ikm, salt).unwrap()[..],
|
||||
&hkdf_sha256(64, ikm, Some(salt), None).unwrap()[..]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
//! Cryptographic primitives for Reticulum. Constants, derivation inputs, and
|
||||
//! wire-visible byte layouts match the Python reference (`RNS/Cryptography/`)
|
||||
//! exactly — downstream interop depends on it. `no_std + alloc` when `std` is off.
|
||||
//! Cryptographic primitives used by Reticulum identities, Links and Tokens.
|
||||
//! This crate exposes low-level ciphers, hashes, key derivation and key types;
|
||||
//! callers supply the protocol-specific salts, authentication and key lifecycle.
|
||||
//!
|
||||
//! Disabling this crate's `std` feature selects `no_std + alloc` for its code.
|
||||
//! Workspace dependencies retain their own default features, and random/key
|
||||
//! generation still requires an operating-system entropy source. This setting
|
||||
//! alone does not make the crate a bare-metal cryptographic backend.
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![warn(missing_docs)]
|
||||
extern crate alloc;
|
||||
@@ -16,6 +21,10 @@ pub mod token;
|
||||
pub mod x25519;
|
||||
|
||||
pub use token::TOKEN_OVERHEAD;
|
||||
/// The wiping types in this crate's API, such as the output of
|
||||
/// [`hkdf::hkdf_sha256`], for crates that hold secrets without depending on
|
||||
/// `zeroize` themselves.
|
||||
pub use zeroize;
|
||||
|
||||
use alloc::string::String;
|
||||
use core::fmt::Write;
|
||||
|
||||
@@ -8,7 +8,8 @@ const BLOCK_SIZE: usize = 16;
|
||||
/// Errors surfaced by [`unpad`].
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Pkcs7Error {
|
||||
/// Trailing byte is zero or greater than the 16-byte block size.
|
||||
/// Trailing byte is zero, greater than the 16-byte block size, or greater
|
||||
/// than the input length.
|
||||
#[error("invalid padding: padding byte value {0} exceeds block size {BLOCK_SIZE}")]
|
||||
InvalidPaddingValue(u8),
|
||||
/// The declared padding length doesn't match the trailing bytes.
|
||||
@@ -33,7 +34,8 @@ pub fn pad(data: &[u8]) -> Vec<u8> {
|
||||
|
||||
/// Strip PKCS7 padding for a 16-byte block size.
|
||||
///
|
||||
/// All padding bytes are validated; a mismatch returns an error.
|
||||
/// All padding bytes are validated; a mismatch returns an error. This helper
|
||||
/// checks the trailing padding only, not the input's total block alignment.
|
||||
pub fn unpad(data: &[u8]) -> Result<&[u8], Pkcs7Error> {
|
||||
if data.is_empty() {
|
||||
return Err(Pkcs7Error::EmptyInput);
|
||||
|
||||
@@ -1,15 +1,27 @@
|
||||
//! RNS encryption token: AES-256-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
|
||||
//! RNS encryption token: AES-CBC + HMAC-SHA256 over an IV-prefixed ciphertext.
|
||||
//! A 64-byte key selects AES-256; a legacy 32-byte key selects AES-128.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use thiserror::Error;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::aes_cbc;
|
||||
use crate::hmac::{hmac_sha256, hmac_verify};
|
||||
use crate::pkcs7;
|
||||
use crate::random::random_16;
|
||||
use crate::random::{random_16, random_bytes};
|
||||
|
||||
/// IV (16) + HMAC (32). A token is this plus the PKCS7-padded ciphertext.
|
||||
pub const TOKEN_OVERHEAD: usize = 48;
|
||||
/// AES block size used by legacy AES-128 tokens.
|
||||
pub const AES128_BLOCKSIZE: usize = 16;
|
||||
/// AES block size used by current AES-256 tokens.
|
||||
pub const AES256_BLOCKSIZE: usize = 16;
|
||||
/// AES-256 token key size: 32-byte HMAC key + 32-byte encryption key.
|
||||
pub const KEY_LENGTH: usize = 64;
|
||||
/// Legacy AES-128 token key size: 16-byte HMAC key + 16-byte encryption key.
|
||||
pub const LEGACY_KEY_LENGTH: usize = 32;
|
||||
/// Python `Identity.DERIVED_KEY_LENGTH_LEGACY`.
|
||||
pub const DERIVED_KEY_LENGTH_LEGACY: usize = LEGACY_KEY_LENGTH;
|
||||
|
||||
/// Errors surfaced by [`encrypt`] and [`decrypt`].
|
||||
#[derive(Debug, Error)]
|
||||
@@ -17,13 +29,15 @@ pub enum TokenError {
|
||||
/// Key must be 32 or 64 bytes.
|
||||
#[error("invalid key length: expected 32 or 64, got {0}")]
|
||||
InvalidKeyLength(usize),
|
||||
/// Token is shorter than [`TOKEN_OVERHEAD`] so cannot contain IV + HMAC.
|
||||
/// Retained short-token error variant. The current `decrypt` method maps
|
||||
/// every token shorter than 64 bytes to `AuthenticationFailed`.
|
||||
#[error("token too short for decryption")]
|
||||
TooShort,
|
||||
/// HMAC tag did not validate.
|
||||
/// Token length, authentication, block alignment, decryption or padding failed.
|
||||
#[error("authentication failed")]
|
||||
AuthenticationFailed,
|
||||
/// Underlying AES-CBC decrypt returned an error.
|
||||
/// Retained decryption error variant. The current `decrypt` method maps
|
||||
/// underlying cipher failures to `AuthenticationFailed`.
|
||||
#[error("decryption failed")]
|
||||
DecryptionFailed,
|
||||
/// Underlying AES-CBC encrypt returned an error.
|
||||
@@ -35,24 +49,29 @@ pub enum TokenError {
|
||||
/// 64 → 32/32 (AES-256 + HMAC-SHA256); 32 → 16/16 (AES-128, legacy).
|
||||
fn split_key(key: &[u8]) -> Result<(&[u8], &[u8]), TokenError> {
|
||||
match key.len() {
|
||||
64 => Ok((&key[..32], &key[32..])),
|
||||
32 => Ok((&key[..16], &key[16..])),
|
||||
KEY_LENGTH => Ok((&key[..32], &key[32..])),
|
||||
LEGACY_KEY_LENGTH => Ok((&key[..16], &key[16..])),
|
||||
n => Err(TokenError::InvalidKeyLength(n)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a fresh AES-256 token key with the operating-system CSPRNG.
|
||||
pub fn generate_key() -> Zeroizing<Vec<u8>> {
|
||||
Zeroizing::new(random_bytes(KEY_LENGTH))
|
||||
}
|
||||
|
||||
/// Token encrypt (Modified Fernet — no version byte, no timestamp).
|
||||
/// Wire: `IV(16) || AES-CBC(PKCS7(plaintext)) || HMAC-SHA256(IV || ciphertext)(32)`.
|
||||
pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
let (signing_key, encryption_key) = split_key(key)?;
|
||||
|
||||
let iv = random_16();
|
||||
let padded = pkcs7::pad(plaintext);
|
||||
let padded = Zeroizing::new(pkcs7::pad(plaintext));
|
||||
|
||||
let ciphertext =
|
||||
aes_cbc::encrypt(encryption_key, &iv, &padded).map_err(|_| TokenError::EncryptionFailed)?;
|
||||
|
||||
let mut signed_parts = Vec::with_capacity(16 + ciphertext.len());
|
||||
let mut signed_parts = Vec::with_capacity(16 + ciphertext.len() + 32);
|
||||
signed_parts.extend_from_slice(&iv);
|
||||
signed_parts.extend_from_slice(&ciphertext);
|
||||
|
||||
@@ -64,8 +83,13 @@ pub fn encrypt(plaintext: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Token decrypt. All failure modes collapse to `AuthenticationFailed`
|
||||
/// (padding-oracle defence). HMAC comparison is constant-time.
|
||||
/// Authenticate and decrypt a Token. An invalid key length returns
|
||||
/// `InvalidKeyLength`; malformed-token, authentication, cipher and padding
|
||||
/// failures return `AuthenticationFailed`. HMAC comparison is constant-time.
|
||||
///
|
||||
/// The plaintext is returned in the buffer it was decrypted into, and a failed
|
||||
/// decryption wipes that buffer. Callers wrap a secret plaintext in
|
||||
/// [`Zeroizing`] so it is wiped when dropped.
|
||||
pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
let (signing_key, encryption_key) = split_key(key)?;
|
||||
|
||||
@@ -89,12 +113,17 @@ pub fn decrypt(token: &[u8], key: &[u8]) -> Result<Vec<u8>, TokenError> {
|
||||
return Err(TokenError::AuthenticationFailed);
|
||||
}
|
||||
|
||||
let padded = aes_cbc::decrypt(encryption_key, iv, ciphertext)
|
||||
.map_err(|_| TokenError::AuthenticationFailed)?;
|
||||
let mut padded = Zeroizing::new(
|
||||
aes_cbc::decrypt(encryption_key, iv, ciphertext)
|
||||
.map_err(|_| TokenError::AuthenticationFailed)?,
|
||||
);
|
||||
|
||||
let plaintext = pkcs7::unpad(&padded).map_err(|_| TokenError::AuthenticationFailed)?;
|
||||
let len = pkcs7::unpad(&padded)
|
||||
.map_err(|_| TokenError::AuthenticationFailed)?
|
||||
.len();
|
||||
padded.truncate(len);
|
||||
|
||||
Ok(plaintext.to_vec())
|
||||
Ok(core::mem::take(&mut *padded))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -112,6 +141,20 @@ mod tests {
|
||||
assert_eq!(&decrypted, plaintext);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_key_is_valid_and_unique() {
|
||||
let first = generate_key();
|
||||
let second = generate_key();
|
||||
|
||||
assert_eq!(first.len(), KEY_LENGTH);
|
||||
assert_eq!(second.len(), KEY_LENGTH);
|
||||
assert_ne!(&*first, &*second);
|
||||
assert_eq!(
|
||||
decrypt(&encrypt(b"generated", &first).unwrap(), &first).unwrap(),
|
||||
b"generated"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encrypt_produces_correct_structure() {
|
||||
let key = [0x42u8; 64];
|
||||
@@ -207,7 +250,7 @@ mod tests {
|
||||
assert_ne!(t1, t2);
|
||||
}
|
||||
|
||||
/// Legacy AES-128 round-trip via 32-byte key (Python `Token.py:62-65`).
|
||||
/// Legacy AES-128 round-trip via 32-byte key (Python `Token.py`).
|
||||
#[test]
|
||||
fn test_encrypt_decrypt_roundtrip_aes128() {
|
||||
let key = [0x42u8; 32];
|
||||
|
||||
@@ -4,7 +4,8 @@ use rand_core::OsRng;
|
||||
use x25519_dalek::{PublicKey, StaticSecret};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
/// X25519 private key (32 bytes, clamped scalar).
|
||||
/// X25519 private key material (32 bytes). Scalar clamping occurs during
|
||||
/// public-key derivation and Diffie-Hellman, not when these bytes are stored.
|
||||
///
|
||||
/// Key material is zeroized on drop.
|
||||
pub struct X25519PrivateKey {
|
||||
@@ -24,6 +25,14 @@ impl Drop for X25519PrivateKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors surfaced by [`X25519PrivateKey::exchange`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum X25519Error {
|
||||
/// The peer key is a low-order point, so the shared secret is all zero.
|
||||
#[error("X25519 peer key is a low-order point")]
|
||||
LowOrderPoint,
|
||||
}
|
||||
|
||||
/// X25519 public key (32 bytes, u-coordinate).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct X25519PublicKey {
|
||||
@@ -38,14 +47,14 @@ impl X25519PrivateKey {
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct from a 32-byte scalar.
|
||||
/// Store 32 bytes of private key material without changing their encoding.
|
||||
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
|
||||
Self {
|
||||
secret: StaticSecret::from(*bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the 32-byte scalar.
|
||||
/// Return the stored 32-byte private key material.
|
||||
pub fn to_bytes(&self) -> [u8; 32] {
|
||||
self.secret.to_bytes()
|
||||
}
|
||||
@@ -58,13 +67,19 @@ impl X25519PrivateKey {
|
||||
}
|
||||
|
||||
/// Compute the shared secret with `peer` via X25519 Diffie-Hellman.
|
||||
pub fn exchange(&self, peer: &X25519PublicKey) -> [u8; 32] {
|
||||
self.secret.diffie_hellman(&peer.key).to_bytes()
|
||||
/// An all-zero result (a low-order peer key) is rejected, as the
|
||||
/// reference implementation's default backend does.
|
||||
pub fn exchange(&self, peer: &X25519PublicKey) -> Result<[u8; 32], X25519Error> {
|
||||
let shared = self.secret.diffie_hellman(&peer.key);
|
||||
if !shared.was_contributory() {
|
||||
return Err(X25519Error::LowOrderPoint);
|
||||
}
|
||||
Ok(shared.to_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
impl X25519PublicKey {
|
||||
/// Parse a 32-byte u-coordinate.
|
||||
/// Store a 32-byte u-coordinate without rejecting low-order public inputs.
|
||||
pub fn from_bytes(bytes: &[u8; 32]) -> Self {
|
||||
Self {
|
||||
key: PublicKey::from(*bytes),
|
||||
@@ -104,8 +119,8 @@ mod tests {
|
||||
let bob_prv = X25519PrivateKey::generate();
|
||||
let bob_pub = bob_prv.public_key();
|
||||
|
||||
let alice_shared = alice_prv.exchange(&bob_pub);
|
||||
let bob_shared = bob_prv.exchange(&alice_pub);
|
||||
let alice_shared = alice_prv.exchange(&bob_pub).unwrap();
|
||||
let bob_shared = bob_prv.exchange(&alice_pub).unwrap();
|
||||
|
||||
assert_eq!(alice_shared, bob_shared);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Shared by the secret-residue test binaries. A recording allocator copies
|
||||
//! every block the calling thread frees while a check runs; each check then
|
||||
//! searches those copies for its secrets.
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::cell::{Cell, UnsafeCell};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, MutexGuard};
|
||||
|
||||
const RECORD_CAPACITY: usize = 8 << 20;
|
||||
|
||||
struct Recording(UnsafeCell<[u8; RECORD_CAPACITY]>);
|
||||
|
||||
// Written only by the armed thread while armed, read only after disarming.
|
||||
unsafe impl Sync for Recording {}
|
||||
|
||||
static RECORDING: Recording = Recording(UnsafeCell::new([0; RECORD_CAPACITY]));
|
||||
static RECORDED: AtomicUsize = AtomicUsize::new(0);
|
||||
static OVERFLOWED: AtomicBool = AtomicBool::new(false);
|
||||
static PEAK: AtomicUsize = AtomicUsize::new(0);
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
thread_local! {
|
||||
static ARMED: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
struct RecordingAllocator;
|
||||
|
||||
fn armed() -> bool {
|
||||
ARMED.try_with(Cell::get).unwrap_or(false)
|
||||
}
|
||||
|
||||
unsafe impl GlobalAlloc for RecordingAllocator {
|
||||
// Blocks handed out while armed start zeroed, so a recorded block holds
|
||||
// only what was written during the check, never a reused block's old bytes.
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
if !armed() {
|
||||
return unsafe { System.alloc(layout) };
|
||||
}
|
||||
PEAK.fetch_max(layout.size(), Ordering::Relaxed);
|
||||
unsafe { System.alloc_zeroed(layout) }
|
||||
}
|
||||
|
||||
// The default `realloc` frees the old block through `dealloc`, so blocks
|
||||
// left behind by growth are recorded too.
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
if armed() {
|
||||
let start = RECORDED.load(Ordering::Relaxed);
|
||||
let end = start + 4 + layout.size();
|
||||
if end <= RECORD_CAPACITY {
|
||||
let base = RECORDING.0.get().cast::<u8>();
|
||||
unsafe {
|
||||
base.add(start)
|
||||
.cast::<[u8; 4]>()
|
||||
.write_unaligned((layout.size() as u32).to_le_bytes());
|
||||
std::ptr::copy_nonoverlapping(ptr, base.add(start + 4), layout.size());
|
||||
}
|
||||
RECORDED.store(end, Ordering::Relaxed);
|
||||
} else {
|
||||
OVERFLOWED.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
unsafe { System.dealloc(ptr, layout) }
|
||||
}
|
||||
}
|
||||
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: RecordingAllocator = RecordingAllocator;
|
||||
|
||||
pub fn serial() -> MutexGuard<'static, ()> {
|
||||
SERIAL
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
pub struct Freed {
|
||||
pub blocks: Vec<Vec<u8>>,
|
||||
pub peak_allocation: usize,
|
||||
}
|
||||
|
||||
/// Run `f` and return its result with a copy of every block it freed.
|
||||
pub fn freed_by<R>(f: impl FnOnce() -> R) -> (R, Freed) {
|
||||
RECORDED.store(0, Ordering::Relaxed);
|
||||
OVERFLOWED.store(false, Ordering::Relaxed);
|
||||
PEAK.store(0, Ordering::Relaxed);
|
||||
ARMED.with(|armed| armed.set(true));
|
||||
let result = f();
|
||||
ARMED.with(|armed| armed.set(false));
|
||||
assert!(
|
||||
!OVERFLOWED.load(Ordering::Relaxed),
|
||||
"freed blocks exceeded the recording buffer"
|
||||
);
|
||||
let len = RECORDED.load(Ordering::Relaxed);
|
||||
let recorded = unsafe { std::slice::from_raw_parts(RECORDING.0.get().cast::<u8>(), len) };
|
||||
let mut blocks = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < len {
|
||||
let size = u32::from_le_bytes(recorded[at..at + 4].try_into().unwrap()) as usize;
|
||||
blocks.push(recorded[at + 4..at + 4 + size].to_vec());
|
||||
at += 4 + size;
|
||||
}
|
||||
let freed = Freed {
|
||||
blocks,
|
||||
peak_allocation: PEAK.load(Ordering::Relaxed),
|
||||
};
|
||||
(result, freed)
|
||||
}
|
||||
|
||||
/// Whether `block` holds 16 consecutive bytes of `secret`.
|
||||
pub fn holds(block: &[u8], secret: &[u8]) -> bool {
|
||||
!find(&[block.to_vec()], &[secret]).is_empty()
|
||||
}
|
||||
|
||||
/// For each block holding 16 consecutive bytes of any of `secrets`: its
|
||||
/// length and the indexes of the secrets it holds.
|
||||
pub fn find(blocks: &[Vec<u8>], secrets: &[&[u8]]) -> Vec<(usize, Vec<usize>)> {
|
||||
let mut windows: HashMap<&[u8], Vec<usize>> = HashMap::new();
|
||||
for (index, secret) in secrets.iter().enumerate() {
|
||||
assert!(secret.len() >= 16, "secret is too short to search for");
|
||||
for window in secret.windows(16) {
|
||||
let owners = windows.entry(window).or_default();
|
||||
if owners.last() != Some(&index) {
|
||||
owners.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
for block in blocks {
|
||||
let mut held: Vec<usize> = block
|
||||
.windows(16)
|
||||
.filter_map(|window| windows.get(window))
|
||||
.flatten()
|
||||
.copied()
|
||||
.collect();
|
||||
held.sort_unstable();
|
||||
held.dedup();
|
||||
if !held.is_empty() {
|
||||
found.push((block.len(), held));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Fail if any freed block holds part of a secret.
|
||||
pub fn assert_no_residue(freed: &Freed, secrets: &[(&str, &[u8])]) {
|
||||
let values: Vec<&[u8]> = secrets.iter().map(|(_, secret)| *secret).collect();
|
||||
let mut found = Vec::new();
|
||||
for (len, held) in find(&freed.blocks, &values) {
|
||||
for index in held {
|
||||
found.push(format!("{} in a freed {len}-byte block", secrets[index].0));
|
||||
}
|
||||
}
|
||||
assert!(found.is_empty(), "secret residue: {found:?}");
|
||||
}
|
||||
|
||||
pub fn pseudo_random<const N: usize>(seed: u64) -> [u8; N] {
|
||||
let mut state = seed;
|
||||
let mut out = [0u8; N];
|
||||
for byte in &mut out {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
*byte = (state >> 24) as u8;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Plaintext and key material must not survive in freed heap memory.
|
||||
|
||||
mod residue;
|
||||
|
||||
use residue::{assert_no_residue, freed_by, holds, pseudo_random, serial};
|
||||
use rns_crypto::{aes_cbc, hkdf, hmac, token};
|
||||
use std::hint::black_box;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
#[test]
|
||||
fn the_harness_finds_unwiped_copies() {
|
||||
let _serial = serial();
|
||||
let secret: [u8; 64] = pseudo_random(12);
|
||||
|
||||
let ((), dropped) = freed_by(|| drop(black_box(secret.to_vec())));
|
||||
// A wiped buffer that grew still frees its first block unwiped.
|
||||
let ((), grown) = freed_by(|| {
|
||||
let mut copy = Zeroizing::new(Vec::with_capacity(32));
|
||||
copy.extend_from_slice(&secret[..32]);
|
||||
copy.extend_from_slice(&secret[32..]);
|
||||
black_box(©);
|
||||
});
|
||||
|
||||
for (case, freed) in [("dropped", dropped), ("grown", grown)] {
|
||||
assert!(
|
||||
freed.blocks.iter().any(|block| holds(block, &secret)),
|
||||
"{case}: copy not found"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_harness_ignores_bytes_freed_before_the_check() {
|
||||
let _serial = serial();
|
||||
let secret: [u8; 64] = pseudo_random(13);
|
||||
// Large enough that the allocator hands the same block straight back.
|
||||
drop(black_box(secret.repeat(1024)));
|
||||
|
||||
let ((), freed) = freed_by(|| drop(black_box(Vec::<u8>::with_capacity(64 * 1024))));
|
||||
|
||||
assert_no_residue(&freed, &[("secret", &secret)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_encrypt_frees_no_plaintext() {
|
||||
let _serial = serial();
|
||||
let key: [u8; 64] = pseudo_random(1);
|
||||
let plaintext: [u8; 100] = pseudo_random(2);
|
||||
|
||||
let (token, freed) = freed_by(|| token::encrypt(&plaintext, &key).unwrap());
|
||||
|
||||
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
|
||||
assert_eq!(
|
||||
&Zeroizing::new(token::decrypt(&token, &key).unwrap())[..],
|
||||
&plaintext[..]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_decrypt_frees_no_plaintext() {
|
||||
let _serial = serial();
|
||||
let key: [u8; 64] = pseudo_random(3);
|
||||
let plaintext: [u8; 100] = pseudo_random(4);
|
||||
let token = token::encrypt(&plaintext, &key).unwrap();
|
||||
|
||||
let ((), freed) = freed_by(|| {
|
||||
let decrypted = Zeroizing::new(token::decrypt(&token, &key).unwrap());
|
||||
assert_eq!(&decrypted[..], &plaintext[..]);
|
||||
});
|
||||
|
||||
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_decrypt_wipes_an_authenticated_plaintext_with_bad_padding() {
|
||||
let _serial = serial();
|
||||
let key: [u8; 64] = pseudo_random(5);
|
||||
let mut plaintext: [u8; 64] = pseudo_random(6);
|
||||
plaintext[63] = 0;
|
||||
let iv = [0x24u8; 16];
|
||||
let mut token = iv.to_vec();
|
||||
token.extend_from_slice(&aes_cbc::encrypt(&key[32..], &iv, &plaintext).unwrap());
|
||||
let mac = hmac::hmac_sha256(&key[..32], &token);
|
||||
token.extend_from_slice(&mac);
|
||||
|
||||
let (result, freed) = freed_by(|| token::decrypt(&token, &key));
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(token::TokenError::AuthenticationFailed)
|
||||
));
|
||||
assert_no_residue(&freed, &[("plaintext", &plaintext[..63])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aes_cbc_encrypt_with_a_bad_key_frees_no_plaintext() {
|
||||
let _serial = serial();
|
||||
let plaintext: [u8; 64] = pseudo_random(7);
|
||||
|
||||
let (result, freed) = freed_by(|| aes_cbc::encrypt(&[0x11; 24], &[0x22; 16], &plaintext));
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(aes_cbc::AesCbcError::InvalidKeyLength(24))
|
||||
));
|
||||
assert_no_residue(&freed, &[("plaintext", &plaintext)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn derive_key_64_frees_no_key() {
|
||||
let _serial = serial();
|
||||
let shared: [u8; 32] = pseudo_random(8);
|
||||
let salt: [u8; 16] = pseudo_random(9);
|
||||
let expected = hkdf::hkdf_sha256(64, &shared, Some(&salt), None).unwrap();
|
||||
|
||||
let ((), freed) = freed_by(|| {
|
||||
let derived = hkdf::derive_key_64(&shared, &salt).unwrap();
|
||||
assert_eq!(&derived[..], &expected[..]);
|
||||
});
|
||||
|
||||
assert_no_residue(&freed, &[("derived key", &expected)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hkdf_output_is_wiped_when_dropped() {
|
||||
let _serial = serial();
|
||||
let ikm: [u8; 32] = pseudo_random(10);
|
||||
let salt: [u8; 16] = pseudo_random(11);
|
||||
let expected = hkdf::derive_key_64(&ikm, &salt).unwrap();
|
||||
|
||||
let ((), freed) = freed_by(|| {
|
||||
let okm: Zeroizing<Vec<u8>> = hkdf::hkdf_sha256(64, &ikm, Some(&salt), None).unwrap();
|
||||
assert_eq!(&okm[..], &expected[..]);
|
||||
});
|
||||
|
||||
assert_no_residue(&freed, &[("HKDF output", &expected[..])]);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
[package]
|
||||
name = "rns-git"
|
||||
description = "Git over Reticulum: rngit-rs and the rngcs-rs commit signer"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
autobins = false
|
||||
|
||||
[dependencies]
|
||||
rns-tools = { path = "../rns-tools", default-features = false }
|
||||
rns-identity = { workspace = true }
|
||||
rns-runtime = { workspace = true }
|
||||
rns-transport = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
nix = { workspace = true }
|
||||
rmpv = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
rns-wire = { workspace = true, features = ["std"] }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[[bin]]
|
||||
name = "rngcs-rs"
|
||||
path = "src/bin/rngcs-rs.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "rngit-rs"
|
||||
path = "src/bin/rngit-rs.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "git-remote-rns"
|
||||
path = "src/bin/git-remote-rns.rs"
|
||||
@@ -0,0 +1,332 @@
|
||||
//! `git-remote-rns`: the git remote helper for `rns://` URLs
|
||||
//! (`RNS/Utilities/rngit/client.py`).
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rns_git::remote_helper::{
|
||||
Abort, ClientConfig, ClientConfigError, PATH_TIMEOUT, REQUEST_TIMEOUT, RemoteHelper, Response,
|
||||
Transport, load_or_create_identity, parse_args, resolve_config_dir,
|
||||
};
|
||||
use rns_git::server::APP_NAME;
|
||||
use rns_runtime::lifecycle::ShutdownSignal;
|
||||
use rns_runtime::link_session::{LinkSessionHandle, RequestOptions};
|
||||
use rns_runtime::reticulum::{LinkConnectOptions, ReticulumHandle};
|
||||
use rns_tools::rsg::pyfmt::py_fromhex;
|
||||
use rns_transport::messages::PathRequestOptions;
|
||||
|
||||
/// `RNS.LOG_MAXSIZE` (`RNS/__init__.py`).
|
||||
const LOG_MAXSIZE: u64 = 5 * 1024 * 1024;
|
||||
|
||||
/// `client_log`, appended per line and rotated to `.1` past `LOG_MAXSIZE`
|
||||
/// as `RNS.log` does with `LOG_FILE` (`RNS/__init__.py`).
|
||||
#[derive(Clone)]
|
||||
struct ClientLog(PathBuf);
|
||||
|
||||
impl Write for ClientLog {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let appended = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&self.0)
|
||||
.and_then(|mut file| file.write_all(buf).map(|()| file.metadata()));
|
||||
if let Ok(Ok(meta)) = appended
|
||||
&& meta.len() > LOG_MAXSIZE
|
||||
{
|
||||
let mut rotated = self.0.clone().into_os_string();
|
||||
rotated.push(".1");
|
||||
let _ = std::fs::remove_file(&rotated);
|
||||
let _ = std::fs::rename(&self.0, &rotated);
|
||||
}
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn status(text: &str) {
|
||||
let mut stderr = std::io::stderr();
|
||||
let _ = stderr.write_all(text.as_bytes());
|
||||
let _ = stderr.flush();
|
||||
}
|
||||
|
||||
fn prettyhex(hash: &[u8]) -> String {
|
||||
format!("<{}>", hex::encode(hash))
|
||||
}
|
||||
|
||||
/// Requests on the established link, made from the blocking command loop.
|
||||
struct LinkTransport {
|
||||
runtime: tokio::runtime::Handle,
|
||||
link: LinkSessionHandle,
|
||||
spool: PathBuf,
|
||||
}
|
||||
|
||||
impl Transport for LinkTransport {
|
||||
fn request(&mut self, path: &str, data: rmpv::Value) -> Option<Response> {
|
||||
tracing::debug!("Sending request: {path}");
|
||||
let options = RequestOptions {
|
||||
timeout: Some(Duration::from_secs_f64(REQUEST_TIMEOUT)),
|
||||
spool_dir: Some(self.spool.clone()),
|
||||
..RequestOptions::default()
|
||||
};
|
||||
let request = self.link.request_with_options(path, data, options);
|
||||
let response = self
|
||||
.runtime
|
||||
.block_on(async {
|
||||
tokio::time::timeout(Duration::from_secs_f64(REQUEST_TIMEOUT), request).await
|
||||
})
|
||||
.ok()?
|
||||
.map_err(|e| tracing::debug!("Request {path} failed: {e}"))
|
||||
.ok()?;
|
||||
tracing::debug!("Got response for: {path}");
|
||||
match (response.metadata, response.file) {
|
||||
(Some(metadata), Some(file)) => Some(Response::File {
|
||||
path: file,
|
||||
metadata: rmpv::decode::read_value(&mut metadata.as_slice())
|
||||
.unwrap_or(rmpv::Value::Nil),
|
||||
}),
|
||||
// A spooled Resource response without metadata: the value itself.
|
||||
(None, Some(file)) => {
|
||||
let data = std::fs::read(&file).ok();
|
||||
let _ = std::fs::remove_file(&file);
|
||||
let value = rmpv::decode::read_value(&mut data?.as_slice()).ok()?;
|
||||
Some(response_value(value))
|
||||
}
|
||||
_ => Some(response_value(response.value)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn response_value(value: rmpv::Value) -> Response {
|
||||
match value {
|
||||
rmpv::Value::Binary(bytes) => Response::Bytes(bytes),
|
||||
other => Response::Other(other),
|
||||
}
|
||||
}
|
||||
|
||||
/// `abort()`; `sys.exit` also runs Reticulum's exit handler (Reticulum.py).
|
||||
fn abort(
|
||||
reason: Abort,
|
||||
link: Option<&LinkSessionHandle>,
|
||||
handle: &ReticulumHandle,
|
||||
runtime: &tokio::runtime::Runtime,
|
||||
) -> ! {
|
||||
eprintln!("{}", reason.message());
|
||||
runtime.block_on(async {
|
||||
if let Some(link) = link {
|
||||
link.close().await;
|
||||
}
|
||||
rns_tools::exit(handle, reason.code).await
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether this process's own path table has the path and its identity is
|
||||
/// known, as `RNS.Transport.has_path` in `client.py`. Known destinations loaded
|
||||
/// over RPC give the identity before any path of our own.
|
||||
async fn path_ready(handle: &ReticulumHandle, hash: [u8; 16]) -> bool {
|
||||
rns_tools::has_local_path(handle, hash).await
|
||||
&& matches!(handle.recall_without_use(hash).await, Ok(Some(_)))
|
||||
}
|
||||
|
||||
/// `Transport.await_path` with `medium_path_timeout(PATH_TIMEOUT)` (`client.py`).
|
||||
async fn await_path(handle: &ReticulumHandle, hash: [u8; 16]) -> bool {
|
||||
if path_ready(handle, hash).await {
|
||||
return true;
|
||||
}
|
||||
let _ = handle
|
||||
.request_path(hash, PathRequestOptions::default())
|
||||
.await;
|
||||
let wait = PATH_TIMEOUT.max(rns_tools::medium_path_timeout(handle).await);
|
||||
let deadline = Instant::now() + Duration::from_secs_f64(wait);
|
||||
while Instant::now() < deadline {
|
||||
if path_ready(handle, hash).await {
|
||||
return true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
rns_tools::has_local_path(handle, hash).await
|
||||
}
|
||||
|
||||
fn init_logging(configdir: &Path, rnsconfig: Option<&str>, level: Option<i64>) {
|
||||
let rns_dir = rns_runtime::platform::resolve_config_dir(rnsconfig);
|
||||
// Reticulum applies its own config loglevel first; the client config overrides it.
|
||||
let level = level.or_else(|| {
|
||||
rns_runtime::config::Config::from_file(&rns_dir.join("config"))
|
||||
.ok()
|
||||
.and_then(|c| c.section("logging")?.get_int("loglevel"))
|
||||
.or(Some(rns_tools::LogLevel::Notice as i64))
|
||||
});
|
||||
let Some(level) = level.filter(|l| *l >= 0) else {
|
||||
return;
|
||||
};
|
||||
let log = ClientLog(configdir.join("client_log"));
|
||||
rns_tools::init_tracing(
|
||||
rns_tools::LogLevel::clamped(level),
|
||||
rns_tools::config_log_timestamps(&rns_dir),
|
||||
false,
|
||||
move || log.clone(),
|
||||
);
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let url = match parse_args(&args) {
|
||||
Ok(url) => url,
|
||||
Err((message, code)) => {
|
||||
eprintln!("{message}");
|
||||
std::process::exit(code);
|
||||
}
|
||||
};
|
||||
let configdir = std::env::var_os("RNGIT_CONFIG").map(PathBuf::from);
|
||||
let rnsconfig = std::env::var("RNS_CONFIG").ok();
|
||||
let home = rns_runtime::platform::home_dir().unwrap_or_default();
|
||||
let configdir = resolve_config_dir(configdir.as_deref(), &home);
|
||||
|
||||
let config = match ClientConfig::load(&configdir) {
|
||||
Ok(config) => config,
|
||||
Err(e @ ClientConfigError::Parse(..)) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
init_logging(&configdir, rnsconfig.as_deref(), config.loglevel);
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("tokio runtime");
|
||||
let handle = match runtime.block_on(rns_runtime::reticulum::init(
|
||||
rnsconfig.as_deref(),
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
Arc::new(AtomicBool::new(false)),
|
||||
)) {
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
eprintln!("Failed to initialize Reticulum: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
runtime.block_on(handle.wants_destination_type(APP_NAME));
|
||||
|
||||
let identitypath = configdir.join("client_identity");
|
||||
let existed = identitypath.is_file();
|
||||
let Some(identity) = load_or_create_identity(&identitypath) else {
|
||||
tracing::error!("Could not initialize client identity.");
|
||||
std::process::exit(1);
|
||||
};
|
||||
if existed {
|
||||
tracing::debug!("Client identity loaded from {}", identitypath.display());
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"Client identity generated and persisted to {}",
|
||||
identitypath.display()
|
||||
);
|
||||
}
|
||||
let destination = config.resolve_destination(&url.destination);
|
||||
|
||||
// connect_server (client.py)
|
||||
let hash = match py_fromhex(&destination) {
|
||||
Ok(hash) => hash,
|
||||
Err(e) => abort(
|
||||
Abort::new(format!("Invalid destination hash: {e}")),
|
||||
None,
|
||||
&handle,
|
||||
&runtime,
|
||||
),
|
||||
};
|
||||
tracing::debug!("Requesting path to {}", prettyhex(&hash));
|
||||
status("Requesting path...");
|
||||
let hash16: Option<[u8; 16]> = hash.as_slice().try_into().ok();
|
||||
let found = match hash16 {
|
||||
Some(h) => runtime.block_on(await_path(&handle, h)),
|
||||
None => false,
|
||||
};
|
||||
let Some(hash16) = hash16.filter(|_| found) else {
|
||||
status("\n");
|
||||
abort(
|
||||
Abort::new(format!("Could not resolve path to {}", prettyhex(&hash))),
|
||||
None,
|
||||
&handle,
|
||||
&runtime,
|
||||
);
|
||||
};
|
||||
tracing::debug!("Path to {} resolved", prettyhex(&hash));
|
||||
status("\rPath resolved ");
|
||||
let recalled = runtime.block_on(handle.recall(hash16)).ok().flatten();
|
||||
if recalled.is_none() {
|
||||
abort(
|
||||
Abort::new("Could not recall remote identity. Is the server announcing?"),
|
||||
None,
|
||||
&handle,
|
||||
&runtime,
|
||||
);
|
||||
}
|
||||
status("\rEstablishing link...");
|
||||
|
||||
// The Link fails at its own establishment timeout, which ends run()'s
|
||||
// max(15, establishment_timeout) wait (client.py).
|
||||
let options = LinkConnectOptions {
|
||||
client_label: "git-remote-rns".to_string(),
|
||||
identify: true,
|
||||
..LinkConnectOptions::default()
|
||||
};
|
||||
let session = runtime.block_on(handle.connect_link(hash16, identity, options));
|
||||
let mut session = match session {
|
||||
Ok(session) => session,
|
||||
Err(e) => {
|
||||
tracing::debug!("Link establishment failed: {e}");
|
||||
abort(
|
||||
Abort::new("Failed to establish link"),
|
||||
None,
|
||||
&handle,
|
||||
&runtime,
|
||||
);
|
||||
}
|
||||
};
|
||||
tracing::debug!("Link established, identifying...");
|
||||
status("\rLink established with remote\n");
|
||||
let link = session.handle.clone();
|
||||
let events = std::mem::replace(&mut session.events, tokio::sync::mpsc::channel(1).1);
|
||||
runtime.spawn(async move {
|
||||
let mut events = events;
|
||||
while events.recv().await.is_some() {}
|
||||
});
|
||||
|
||||
let spool = match tempfile::tempdir() {
|
||||
Ok(dir) => dir,
|
||||
Err(e) => abort(Abort::new(e.to_string()), Some(&link), &handle, &runtime),
|
||||
};
|
||||
let transport = LinkTransport {
|
||||
runtime: runtime.handle().clone(),
|
||||
link: link.clone(),
|
||||
spool: spool.path().to_path_buf(),
|
||||
};
|
||||
let git_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
|
||||
let mut helper = RemoteHelper::new(transport, url.repo_path(), config.ref_batch_size, git_dir);
|
||||
let result = {
|
||||
let stdin = std::io::stdin();
|
||||
let mut stdin = stdin.lock();
|
||||
let mut stdout = std::io::stdout();
|
||||
let mut stderr = std::io::stderr();
|
||||
helper.run(&mut stdin, &mut stdout, &mut stderr)
|
||||
};
|
||||
drop(helper);
|
||||
if let Err(reason) = result {
|
||||
drop(spool);
|
||||
abort(reason, Some(&link), &handle, &runtime);
|
||||
}
|
||||
runtime.block_on(link.close());
|
||||
drop(spool);
|
||||
runtime.block_on(rns_tools::shut_down(&handle));
|
||||
std::process::exit(0);
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
//! `rngcs-rs`: the command line of `RNS/Utilities/rngit/commitsigs.py@1.6.0`.
|
||||
//! git drives it as its `gpg.ssh.program`.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use rmpv::Value;
|
||||
use rns_git::commitsigs::{
|
||||
HASH_ALGORITHM, HeaderEmail, NAMESPACE_GIT, RESERVED_EMPTY, SshSignature, armor_ssh_signature,
|
||||
create_ssh_signature, extract_commit_author, extract_commit_committer, extract_commit_tagger,
|
||||
get_pubkey_wire_format, parse_ssh_signature, unarmor_ssh_signature,
|
||||
};
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_tools::rsg::pyfmt::{py_bytes_repr, py_os_error, py_str_repr, py_utf8_error};
|
||||
use rns_tools::rsg::{self, Message, Valid};
|
||||
|
||||
const PROG: &str = "rngcs-rs";
|
||||
const HELP: &str = include_str!("../commitsigs/help.txt");
|
||||
const OPERATIONS: [&str; 4] = ["sign", "find-principals", "check-novalidate", "verify"];
|
||||
|
||||
/// `RNS.hexrep(value, delimit=False)` for an unpacked value; `Err` is the
|
||||
/// exception upstream raises.
|
||||
fn hexrep_value(value: &Value) -> Result<String, String> {
|
||||
fn byte(value: &Value) -> Result<String, String> {
|
||||
match value {
|
||||
Value::Integer(i) => Ok(match i.as_i64() {
|
||||
Some(n) if n < 0 => format!("-{:x}", n.unsigned_abs()),
|
||||
_ => format!("{:02x}", i.as_u64().unwrap_or_default()),
|
||||
}),
|
||||
Value::Boolean(b) => Ok(format!("{:02x}", u8::from(*b))),
|
||||
Value::Nil => Err(
|
||||
"TypeError: unsupported format string passed to NoneType.__format__".to_string(),
|
||||
),
|
||||
other => Err(format!(
|
||||
"ValueError: Unknown format code 'x' for object of type '{}'",
|
||||
rsg::py_type_name(other)
|
||||
)),
|
||||
}
|
||||
}
|
||||
match value {
|
||||
Value::Binary(b) => Ok(hex::encode(b)),
|
||||
Value::String(s) if s.as_str().is_some_and(|s| !s.is_empty()) => {
|
||||
Err("ValueError: Unknown format code 'x' for object of type 'str'".to_string())
|
||||
}
|
||||
Value::String(_) => Ok(String::new()),
|
||||
Value::Array(items) => items.iter().map(byte).collect(),
|
||||
Value::Map(entries) => entries.iter().map(|(k, _)| byte(k)).collect(),
|
||||
other => byte(other),
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Command line, as upstream's argparse parser with parse_known_args
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Opt {
|
||||
Help,
|
||||
Op,
|
||||
Namespace,
|
||||
Keyfile,
|
||||
Principal,
|
||||
Sigfile,
|
||||
SshOption,
|
||||
}
|
||||
|
||||
const OPTION_STRINGS: [(&str, Opt); 8] = [
|
||||
("-h", Opt::Help),
|
||||
("--help", Opt::Help),
|
||||
("-Y", Opt::Op),
|
||||
("-n", Opt::Namespace),
|
||||
("-f", Opt::Keyfile),
|
||||
("-I", Opt::Principal),
|
||||
("-s", Opt::Sigfile),
|
||||
("-O", Opt::SshOption),
|
||||
];
|
||||
|
||||
impl Opt {
|
||||
fn lookup(option: &str) -> Option<Opt> {
|
||||
OPTION_STRINGS
|
||||
.iter()
|
||||
.find(|(s, _)| *s == option)
|
||||
.map(|(_, o)| *o)
|
||||
}
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Opt::Help => "-h/--help",
|
||||
Opt::Op => "-Y",
|
||||
Opt::Namespace => "-n",
|
||||
Opt::Keyfile => "-f",
|
||||
Opt::Principal => "-I",
|
||||
Opt::Sigfile => "-s",
|
||||
Opt::SshOption => "-O",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Args {
|
||||
op: Option<String>,
|
||||
keyfile: Option<String>,
|
||||
principal: Option<String>,
|
||||
sigfile: Option<String>,
|
||||
file: Option<String>,
|
||||
extras: Vec<String>,
|
||||
}
|
||||
|
||||
enum ParseExit {
|
||||
Help,
|
||||
Error(String),
|
||||
}
|
||||
|
||||
struct OptionTuple {
|
||||
action: Option<Opt>,
|
||||
option_string: String,
|
||||
sep: Option<&'static str>,
|
||||
explicit: Option<String>,
|
||||
}
|
||||
|
||||
fn tuple(
|
||||
action: Option<Opt>,
|
||||
option_string: &str,
|
||||
sep: Option<&'static str>,
|
||||
explicit: Option<&str>,
|
||||
) -> OptionTuple {
|
||||
OptionTuple {
|
||||
action,
|
||||
option_string: option_string.to_string(),
|
||||
sep,
|
||||
explicit: explicit.map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
fn partition(arg: &str) -> (&str, Option<&'static str>, Option<&str>) {
|
||||
match arg.split_once('=') {
|
||||
Some((prefix, rest)) => (prefix, Some("="), Some(rest)),
|
||||
None => (arg, None, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// `ArgumentParser._parse_optional`; `None` is a positional.
|
||||
fn parse_optional(arg: &str) -> Option<Vec<OptionTuple>> {
|
||||
if !arg.starts_with('-') {
|
||||
return None;
|
||||
}
|
||||
if let Some(action) = Opt::lookup(arg) {
|
||||
return Some(vec![tuple(Some(action), arg, None, None)]);
|
||||
}
|
||||
if arg.chars().count() == 1 {
|
||||
return None;
|
||||
}
|
||||
let (prefix, sep, explicit) = partition(arg);
|
||||
if sep.is_some()
|
||||
&& let Some(action) = Opt::lookup(prefix)
|
||||
{
|
||||
return Some(vec![tuple(Some(action), prefix, sep, explicit)]);
|
||||
}
|
||||
let mut result = Vec::new();
|
||||
if arg.starts_with("--") {
|
||||
for (option, action) in OPTION_STRINGS {
|
||||
if option.starts_with(prefix) {
|
||||
result.push(tuple(Some(action), option, sep, explicit));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let split = arg.char_indices().nth(2).map_or(arg.len(), |(i, _)| i);
|
||||
let (short_prefix, short_explicit) = arg.split_at(split);
|
||||
for (option, action) in OPTION_STRINGS {
|
||||
if option == short_prefix {
|
||||
result.push(tuple(Some(action), option, Some(""), Some(short_explicit)));
|
||||
} else if option.starts_with(prefix) {
|
||||
result.push(tuple(Some(action), option, sep, explicit));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !result.is_empty() {
|
||||
return Some(result);
|
||||
}
|
||||
let digits = &arg[1..];
|
||||
let negative_number = (!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit()))
|
||||
|| digits.split_once('.').is_some_and(|(int, frac)| {
|
||||
int.chars().all(|c| c.is_ascii_digit())
|
||||
&& !frac.is_empty()
|
||||
&& frac.chars().all(|c| c.is_ascii_digit())
|
||||
});
|
||||
if negative_number || arg.contains(' ') {
|
||||
return None;
|
||||
}
|
||||
Some(vec![tuple(None, arg, None, None)])
|
||||
}
|
||||
|
||||
fn take_option(args: &mut Args, action: Opt, values: &[String]) -> Result<(), ParseExit> {
|
||||
let value = values.first().cloned();
|
||||
match action {
|
||||
Opt::Help => return Err(ParseExit::Help),
|
||||
Opt::Op => {
|
||||
let value = value.unwrap_or_default();
|
||||
if !OPERATIONS.contains(&value.as_str()) {
|
||||
return Err(ParseExit::Error(format!(
|
||||
"argument -Y: invalid choice: {} (choose from {})",
|
||||
py_str_repr(&value),
|
||||
OPERATIONS.join(", ")
|
||||
)));
|
||||
}
|
||||
args.op = Some(value);
|
||||
}
|
||||
Opt::Namespace | Opt::SshOption => {}
|
||||
Opt::Keyfile => args.keyfile = value,
|
||||
Opt::Principal => args.principal = value,
|
||||
Opt::Sigfile => args.sigfile = value,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `ArgumentParser.parse_known_args` for upstream's parser.
|
||||
fn parse_args(argv: &[String]) -> Result<Args, ParseExit> {
|
||||
let mut args = Args::default();
|
||||
let mut options: Vec<Option<Vec<OptionTuple>>> = Vec::with_capacity(argv.len());
|
||||
let mut pattern: Vec<char> = Vec::with_capacity(argv.len());
|
||||
let mut after_dashes = false;
|
||||
for arg in argv {
|
||||
if after_dashes {
|
||||
options.push(None);
|
||||
pattern.push('A');
|
||||
} else if arg == "--" {
|
||||
after_dashes = true;
|
||||
options.push(None);
|
||||
pattern.push('-');
|
||||
} else {
|
||||
let tuples = parse_optional(arg);
|
||||
pattern.push(if tuples.is_some() { 'O' } else { 'A' });
|
||||
options.push(tuples);
|
||||
}
|
||||
}
|
||||
let error = |action: Option<Opt>, message: String| {
|
||||
ParseExit::Error(match action {
|
||||
Some(action) => format!("argument {}: {message}", action.name()),
|
||||
None => message,
|
||||
})
|
||||
};
|
||||
let mut file_pending = true;
|
||||
let mut consume_positionals = |args: &mut Args, start: usize| -> usize {
|
||||
if !file_pending {
|
||||
return start;
|
||||
}
|
||||
let mut end = start;
|
||||
while pattern.get(end) == Some(&'-') {
|
||||
end += 1;
|
||||
}
|
||||
if pattern.get(end) == Some(&'A') {
|
||||
end += 1;
|
||||
}
|
||||
while pattern.get(end) == Some(&'-') {
|
||||
end += 1;
|
||||
}
|
||||
if end == start && pattern.get(end) == Some(&'O') {
|
||||
return start;
|
||||
}
|
||||
let mut values: Vec<&String> = argv[start..end].iter().collect();
|
||||
if let Some(i) = pattern[start..end].iter().position(|c| *c == '-') {
|
||||
values.remove(i);
|
||||
}
|
||||
args.file = values.first().map(|v| v.to_string());
|
||||
file_pending = false;
|
||||
end
|
||||
};
|
||||
|
||||
let max_option = pattern.iter().rposition(|c| *c == 'O');
|
||||
let mut start = 0usize;
|
||||
while max_option.is_some_and(|max| start <= max) {
|
||||
let max = max_option.expect("checked");
|
||||
let mut next_option = start;
|
||||
while next_option <= max && pattern[next_option] != 'O' {
|
||||
next_option += 1;
|
||||
}
|
||||
if start != next_option {
|
||||
let end = consume_positionals(&mut args, start);
|
||||
if end > start {
|
||||
start = end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if pattern.get(start) != Some(&'O') {
|
||||
args.extras.extend(argv[start..next_option].iter().cloned());
|
||||
start = next_option;
|
||||
}
|
||||
|
||||
let tuples = options[start].as_ref().expect("an option");
|
||||
if tuples.len() > 1 {
|
||||
let matches: Vec<&str> = tuples.iter().map(|t| t.option_string.as_str()).collect();
|
||||
return Err(error(
|
||||
None,
|
||||
format!(
|
||||
"ambiguous option: {} could match {}",
|
||||
argv[start],
|
||||
matches.join(", ")
|
||||
),
|
||||
));
|
||||
}
|
||||
let first = &tuples[0];
|
||||
let (mut action, mut option_string) = (first.action, first.option_string.clone());
|
||||
let (mut sep, mut explicit) = (first.sep, first.explicit.clone());
|
||||
let mut actions: Vec<(Opt, Vec<String>)> = Vec::new();
|
||||
let stop;
|
||||
loop {
|
||||
let Some(current) = action else {
|
||||
args.extras.push(argv[start].clone());
|
||||
stop = start + 1;
|
||||
break;
|
||||
};
|
||||
let arg_count = usize::from(current != Opt::Help);
|
||||
if let Some(value) = explicit.clone() {
|
||||
let short = !option_string[1..].starts_with('-');
|
||||
if arg_count == 0 && short && !value.is_empty() {
|
||||
if sep == Some("=") || value.starts_with('-') {
|
||||
return Err(error(
|
||||
Some(current),
|
||||
format!("ignored explicit argument {}", py_str_repr(&value)),
|
||||
));
|
||||
}
|
||||
actions.push((current, Vec::new()));
|
||||
let mut chars = value.chars();
|
||||
let flag = chars.next().expect("non-empty");
|
||||
let rest = chars.as_str();
|
||||
option_string = format!("-{flag}");
|
||||
if let Some(next) = Opt::lookup(&option_string) {
|
||||
action = Some(next);
|
||||
if rest.is_empty() {
|
||||
sep = None;
|
||||
explicit = None;
|
||||
} else if let Some(stripped) = rest.strip_prefix('=') {
|
||||
sep = Some("=");
|
||||
explicit = Some(stripped.to_string());
|
||||
} else {
|
||||
sep = Some("");
|
||||
explicit = Some(rest.to_string());
|
||||
}
|
||||
} else {
|
||||
args.extras.push(format!("-{value}"));
|
||||
stop = start + 1;
|
||||
break;
|
||||
}
|
||||
} else if arg_count == 1 {
|
||||
actions.push((current, vec![value]));
|
||||
stop = start + 1;
|
||||
break;
|
||||
} else {
|
||||
return Err(error(
|
||||
Some(current),
|
||||
format!("ignored explicit argument {}", py_str_repr(&value)),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
if arg_count == 1 && pattern.get(start + 1) != Some(&'A') {
|
||||
return Err(error(Some(current), "expected one argument".to_string()));
|
||||
}
|
||||
actions.push((current, argv[start + 1..start + 1 + arg_count].to_vec()));
|
||||
stop = start + 1 + arg_count;
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (action, values) in actions {
|
||||
take_option(&mut args, action, &values)?;
|
||||
}
|
||||
start = stop;
|
||||
}
|
||||
let stop = consume_positionals(&mut args, start);
|
||||
args.extras.extend(argv[stop..].iter().cloned());
|
||||
if args.op.is_none() {
|
||||
return Err(error(
|
||||
None,
|
||||
"the following arguments are required: -Y".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `RNS.Identity.from_file`, plus the Rust identity envelope rnid-rs reads.
|
||||
fn load_identity(path: &str) -> Option<Identity> {
|
||||
let data = std::fs::read(path).ok()?;
|
||||
if data.len() == 64 {
|
||||
return Identity::from_private_key(&data).ok();
|
||||
}
|
||||
Identity::from_file(Path::new(path)).ok()
|
||||
}
|
||||
|
||||
/// `open(path, "r").read()`: UTF-8 with universal newlines.
|
||||
fn read_text(path: &str) -> Result<String, String> {
|
||||
let data = std::fs::read(path).map_err(|e| py_os_error(&e, path))?;
|
||||
let text =
|
||||
String::from_utf8(data).map_err(|e| py_utf8_error(e.as_bytes()).unwrap_or_default())?;
|
||||
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
|
||||
}
|
||||
|
||||
fn read_stdin() -> Vec<u8> {
|
||||
let mut message = Vec::new();
|
||||
let _ = std::io::stdin().lock().read_to_end(&mut message);
|
||||
message
|
||||
}
|
||||
|
||||
fn is_file(path: Option<&str>) -> bool {
|
||||
path.is_some_and(|path| !path.is_empty() && Path::new(path).is_file())
|
||||
}
|
||||
|
||||
fn read_signature(path: &str) -> Result<SshSignature, String> {
|
||||
parse_ssh_signature(&unarmor_ssh_signature(&read_text(path)?)?)
|
||||
}
|
||||
|
||||
fn sign(args: &Args) -> u8 {
|
||||
let keyfile = args.keyfile.as_deref();
|
||||
if !is_file(keyfile) {
|
||||
eprintln!("Identity file not found: {}", keyfile.unwrap_or("None"));
|
||||
return 1;
|
||||
}
|
||||
let Some(identity) =
|
||||
load_identity(keyfile.unwrap_or_default()).filter(Identity::has_private_key)
|
||||
else {
|
||||
eprintln!("Error: Could not load identity or identity has no private key");
|
||||
return 1;
|
||||
};
|
||||
let (message, sig_file) = match args.file.as_deref() {
|
||||
Some(file) if is_file(Some(file)) => match std::fs::read(file) {
|
||||
Ok(message) => (message, Some(format!("{file}.sig"))),
|
||||
Err(e) => {
|
||||
eprintln!("{}", py_os_error(&e, file));
|
||||
return 1;
|
||||
}
|
||||
},
|
||||
_ => (read_stdin(), None),
|
||||
};
|
||||
let rsg = match rsg::create_rsg(&identity, &message[..], false, None) {
|
||||
Ok(rsg) => rsg,
|
||||
Err(e) => {
|
||||
eprintln!("Error creating signature: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let blob = create_ssh_signature(
|
||||
&get_pubkey_wire_format(&identity),
|
||||
NAMESPACE_GIT,
|
||||
RESERVED_EMPTY,
|
||||
HASH_ALGORITHM,
|
||||
&rsg,
|
||||
);
|
||||
let armored = armor_ssh_signature(&blob);
|
||||
match sig_file {
|
||||
Some(path) => {
|
||||
if let Err(e) = std::fs::write(&path, &armored) {
|
||||
eprintln!("Error writing signature file: {}", py_os_error(&e, &path));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
print!("{armored}");
|
||||
let _ = std::io::stdout().flush();
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn find_principals(args: &Args) -> u8 {
|
||||
let sigfile = args.sigfile.as_deref();
|
||||
if !is_file(sigfile) {
|
||||
eprintln!("Error: Signature file not found");
|
||||
return 1;
|
||||
}
|
||||
let armored = match read_text(sigfile.unwrap_or_default()) {
|
||||
Ok(text) => text,
|
||||
Err(e) => {
|
||||
eprintln!("Error reading signature file: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let ssh_sig = match unarmor_ssh_signature(&armored).and_then(|raw| parse_ssh_signature(&raw)) {
|
||||
Ok(sig) => sig,
|
||||
Err(e) => {
|
||||
eprintln!("Error parsing SSH signature: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
if ssh_sig.namespace != NAMESPACE_GIT {
|
||||
eprintln!(
|
||||
"Error: Namespace mismatch: {}",
|
||||
py_bytes_repr(&ssh_sig.namespace)
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
let envelope = rsg::extract_signed_rsg_data(&ssh_sig.signature_data).unwrap_or(Value::Nil);
|
||||
let signer =
|
||||
match rsg::py_index(&envelope, "meta").and_then(|meta| rsg::py_index(meta, "signer")) {
|
||||
Ok(signer) => signer,
|
||||
Err(e) => {
|
||||
eprintln!("Could not determine signer identity: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
match hexrep_value(signer) {
|
||||
Ok(hex) => {
|
||||
println!("{hex}");
|
||||
0
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_novalidate(args: &Args) -> u8 {
|
||||
if !is_file(args.sigfile.as_deref()) {
|
||||
return 1;
|
||||
}
|
||||
match read_signature(args.sigfile.as_deref().unwrap_or_default()) {
|
||||
Ok(ssh_sig) if ssh_sig.namespace == NAMESPACE_GIT => {
|
||||
match rsg::extract_signed_rsg_data(&ssh_sig.signature_data) {
|
||||
Some(signed_data) if rsg::py_truthy(&signed_data) => 0,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn verify(args: &Args) -> u8 {
|
||||
let sigfile = args.sigfile.as_deref();
|
||||
if !is_file(sigfile) {
|
||||
eprintln!("Error: Signature file not found");
|
||||
return 1;
|
||||
}
|
||||
let message = read_stdin();
|
||||
let ssh_sig = match read_signature(sigfile.unwrap_or_default()) {
|
||||
Ok(sig) => sig,
|
||||
Err(e) => {
|
||||
eprintln!("Error parsing signature: {e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let mut author = extract_commit_author(&message);
|
||||
extract_commit_committer(&message);
|
||||
let Some((tagger, is_tag)) = extract_commit_tagger(&message) else {
|
||||
eprintln!("TypeError: cannot unpack non-iterable int object");
|
||||
return 1;
|
||||
};
|
||||
if ssh_sig.namespace != NAMESPACE_GIT {
|
||||
eprintln!("Invalid commit signature namespace");
|
||||
return 1;
|
||||
}
|
||||
let message_value = Value::Binary(message);
|
||||
let valid = match rsg::validate_rsg(
|
||||
&ssh_sig.signature_data,
|
||||
Message::Unpacked(&message_value),
|
||||
None,
|
||||
) {
|
||||
Ok(valid) => valid,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
let Some(Valid { signer_hash, .. }) = valid else {
|
||||
eprintln!("Invalid signature");
|
||||
return 1;
|
||||
};
|
||||
if is_tag {
|
||||
author = HeaderEmail::Email(tagger);
|
||||
}
|
||||
let signer_hash = hex::encode(signer_hash);
|
||||
if author != HeaderEmail::Email(signer_hash.clone()) {
|
||||
println!("Commit not signed by author <{author}>");
|
||||
return 1;
|
||||
}
|
||||
if let Some(principal) = args.principal.as_deref().filter(|p| !p.is_empty())
|
||||
&& principal != signer_hash
|
||||
{
|
||||
eprintln!("Principal mismatch");
|
||||
return 1;
|
||||
}
|
||||
println!(
|
||||
"Good \"git\" signature for commit, signed with Reticulum Identity key <{signer_hash}>"
|
||||
);
|
||||
0
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let argv: Vec<String> = std::env::args().skip(1).collect();
|
||||
ExitCode::from(run(&argv))
|
||||
}
|
||||
|
||||
fn run(argv: &[String]) -> u8 {
|
||||
let args = match parse_args(argv) {
|
||||
Ok(args) => args,
|
||||
Err(ParseExit::Help) => {
|
||||
print!("{HELP}");
|
||||
return 0;
|
||||
}
|
||||
Err(ParseExit::Error(message)) => {
|
||||
let usage = HELP.split("\n\n").next().unwrap_or_default();
|
||||
eprint!("{usage}\n{PROG}: error: {message}\n");
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
if let Some(unknown) = args.extras.iter().find(|arg| !arg.starts_with("-O")) {
|
||||
eprintln!("Error: Unknown argument: {unknown}");
|
||||
return 1;
|
||||
}
|
||||
match args.op.as_deref() {
|
||||
Some("sign") => sign(&args),
|
||||
Some("find-principals") => find_principals(&args),
|
||||
Some("check-novalidate") => check_novalidate(&args),
|
||||
_ => verify(&args),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,279 @@
|
||||
//! `rngit fork`, `rngit mirror` and `rngit sync` (`fork_repository`,
|
||||
//! `mirror_repository`, `_remote_clone_operation`, `sync_repository`,
|
||||
//! `server.py`).
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_runtime::lifecycle::ShutdownSignal;
|
||||
use rns_runtime::reticulum::ReticulumHandle;
|
||||
|
||||
use crate::server::client::{ClientConfig, client_config_dir};
|
||||
use crate::server::{
|
||||
APP_NAME, IDX_REPOSITORY, PATH_FORK, PATH_MIRROR, PATH_SYNC, RES_DISALLOWED, RES_INVALID_REQ,
|
||||
RES_NOT_FOUND, RES_OK,
|
||||
};
|
||||
|
||||
/// The three subcommands.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Operation {
|
||||
Fork,
|
||||
Mirror,
|
||||
Sync,
|
||||
}
|
||||
|
||||
impl Operation {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Operation::Fork => "fork",
|
||||
Operation::Mirror => "mirror",
|
||||
Operation::Sync => "sync",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the subcommand was given on the command line.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ClientArgs {
|
||||
pub config: Option<String>,
|
||||
pub rnsconfig: Option<String>,
|
||||
pub identity: Option<String>,
|
||||
/// `fork`/`mirror`: the source URL; `sync`: unused.
|
||||
pub source: Option<String>,
|
||||
/// `fork`/`mirror`: the target URL; `sync`: the repository URL.
|
||||
pub target: String,
|
||||
pub verbose: u8,
|
||||
pub quiet: u8,
|
||||
}
|
||||
|
||||
/// The decoded status text, or `fallback` for a lone status byte.
|
||||
fn reply_text(response: &[u8], fallback: &str) -> String {
|
||||
if response.len() > 1 {
|
||||
response[1..].utf8_chunks().map(|c| c.valid()).collect()
|
||||
} else {
|
||||
fallback.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// What `_remote_clone_operation` and `sync_repository` print for a reply
|
||||
/// (`server.py`): `Ok` on success, `Err` for the abort text.
|
||||
pub fn outcome(op: Operation, repo_path: &str, response: Option<&[u8]>) -> Result<String, String> {
|
||||
let Some(response) = response.filter(|r| !r.is_empty()) else {
|
||||
return Err("No response from remote".into());
|
||||
};
|
||||
match response[0] {
|
||||
RES_OK => Ok(match op {
|
||||
Operation::Sync => "Repository synced".to_string(),
|
||||
_ => format!("Repository {}ed to {repo_path}", op.name()),
|
||||
}),
|
||||
RES_NOT_FOUND => Err(reply_text(response, "Not found")),
|
||||
RES_INVALID_REQ => Err(reply_text(response, "Invalid request")),
|
||||
RES_DISALLOWED => Err(reply_text(response, "Not allowed")),
|
||||
_ => Err(format!(
|
||||
"Server error: {}",
|
||||
reply_text(response, "Unknown error")
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn prettyhex(hash: &[u8]) -> String {
|
||||
format!("<{}>", hex::encode(hash))
|
||||
}
|
||||
|
||||
/// `ReticulumGitClient.abort` (`server.py`).
|
||||
async fn abort(handle: &ReticulumHandle, message: &str) -> ! {
|
||||
println!("{message}");
|
||||
rns_tools::exit(handle, 1).await
|
||||
}
|
||||
|
||||
/// Run `rngit fork`, `rngit mirror` or `rngit sync`; never returns.
|
||||
pub async fn run(op: Operation, args: ClientArgs) -> ! {
|
||||
let non_empty = |v: Option<String>| v.filter(|v| !v.is_empty());
|
||||
let configdir = client_config_dir(non_empty(args.config).map(PathBuf::from).as_deref());
|
||||
let rnsconfig = non_empty(args.rnsconfig);
|
||||
let rns_dir = rns_runtime::platform::resolve_config_dir(rnsconfig.as_deref());
|
||||
let configured = rns_runtime::config::Config::from_file(&rns_dir.join("config"))
|
||||
.ok()
|
||||
.and_then(|c| c.section("logging")?.get_int("loglevel"));
|
||||
let level = rns_tools::Utility::Rnir.loglevel(configured, args.verbose, args.quiet, false);
|
||||
rns_tools::init_tracing(
|
||||
level,
|
||||
rns_tools::config_log_timestamps(&rns_dir),
|
||||
true,
|
||||
std::io::stdout,
|
||||
);
|
||||
let handle = match rns_runtime::reticulum::init(
|
||||
rnsconfig.as_deref(),
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
eprintln!("failed to start reticulum: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
handle.wants_destination_type(APP_NAME).await;
|
||||
if let Err(e) = std::fs::create_dir_all(&configdir) {
|
||||
abort(
|
||||
&handle,
|
||||
&format!("Could not create {}: {e}", configdir.display()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
let identity_path = non_empty(args.identity)
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| configdir.join("client_identity"));
|
||||
let identity = if identity_path.is_file() {
|
||||
Identity::from_file(&identity_path).ok()
|
||||
} else {
|
||||
let id = Identity::new();
|
||||
id.to_file(&identity_path).ok().map(|_| id)
|
||||
};
|
||||
let Some(identity) = identity else {
|
||||
abort(&handle, "Could not initialize client identity").await;
|
||||
};
|
||||
let config = match ClientConfig::load_or_create(&configdir) {
|
||||
Ok(config) => config,
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Could not parse the configuration at {}",
|
||||
configdir.join("client_config").display()
|
||||
);
|
||||
tracing::error!("Check your configuration file for errors! ({e})");
|
||||
rns_tools::exit(&handle, 255).await;
|
||||
}
|
||||
};
|
||||
|
||||
// fork_repository / mirror_repository, then _resolve_aliased_url (server.py).
|
||||
let mut source = None;
|
||||
if op != Operation::Sync {
|
||||
let Some(src) = non_empty(args.source) else {
|
||||
abort(&handle, "No source specified").await;
|
||||
};
|
||||
if args.target.is_empty() {
|
||||
abort(&handle, "No target specified").await;
|
||||
}
|
||||
let resolved = if src.to_lowercase().starts_with("rns://") {
|
||||
match config.parse_remote_url(&src) {
|
||||
Ok((hash, group, repo)) if !group.is_empty() && !repo.is_empty() => {
|
||||
format!("rns://{}/{group}/{repo}", hex::encode(hash))
|
||||
}
|
||||
Ok(_) => abort(&handle, "Invalid source URL").await,
|
||||
Err(message) => abort(&handle, &message).await,
|
||||
}
|
||||
} else {
|
||||
src
|
||||
};
|
||||
source = Some(resolved);
|
||||
} else if args.target.is_empty() {
|
||||
abort(&handle, "No remote specified").await;
|
||||
}
|
||||
|
||||
// connect_remote (server.py).
|
||||
let remote = args.target;
|
||||
let destination = match config.parse_remote_destination_url(&remote) {
|
||||
Ok(hash) => hash,
|
||||
Err(message) => abort(&handle, &message).await,
|
||||
};
|
||||
let Ok(destination) = <[u8; 16]>::try_from(destination.as_slice()) else {
|
||||
abort(&handle, "Invalid destination hash length").await;
|
||||
};
|
||||
print!("Requesting path... ");
|
||||
let _ = std::io::stdout().flush();
|
||||
let path_timeout = rns_tools::medium_path_timeout(&handle).await.max(15.0);
|
||||
if handle
|
||||
.await_path(destination, Duration::from_secs_f64(path_timeout))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
println!();
|
||||
abort(
|
||||
&handle,
|
||||
&format!("Could not resolve path to {}", prettyhex(&destination)),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
print!("\rPath resolved ");
|
||||
print!("\rEstablishing link... ");
|
||||
let _ = std::io::stdout().flush();
|
||||
let hops = handle.hops_to(destination).await.unwrap_or(1);
|
||||
let first_hop = handle
|
||||
.first_hop_timeout(destination)
|
||||
.await
|
||||
.map_or(rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT, |d| {
|
||||
d.as_secs_f64()
|
||||
});
|
||||
let establishment =
|
||||
first_hop + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT * f64::from(hops.max(1));
|
||||
let options = rns_runtime::reticulum::LinkConnectOptions {
|
||||
path_timeout: Duration::from_secs_f64(path_timeout),
|
||||
establishment_timeout: Some(Duration::from_secs_f64(establishment.max(15.0))),
|
||||
client_label: "rngit".to_string(),
|
||||
identify: true,
|
||||
..Default::default()
|
||||
};
|
||||
let session = match handle.connect_link(destination, identity, options).await {
|
||||
Ok(session) => session,
|
||||
Err(_) => abort(&handle, "Link establishment failed").await,
|
||||
};
|
||||
print!("\rLink established ");
|
||||
print!("\r \r");
|
||||
let _ = std::io::stdout().flush();
|
||||
|
||||
let result = match config.parse_remote_url(&remote) {
|
||||
Err(message) => Err(message),
|
||||
Ok((_, group, repo)) => {
|
||||
let repo_path = format!("{group}/{repo}");
|
||||
let mut request = vec![(
|
||||
rmpv::Value::from(IDX_REPOSITORY),
|
||||
rmpv::Value::from(repo_path.as_str()),
|
||||
)];
|
||||
let path = match op {
|
||||
Operation::Fork => PATH_FORK,
|
||||
Operation::Mirror => PATH_MIRROR,
|
||||
Operation::Sync => PATH_SYNC,
|
||||
};
|
||||
match &source {
|
||||
Some(source) => {
|
||||
request.push((
|
||||
rmpv::Value::from("source"),
|
||||
rmpv::Value::from(source.as_str()),
|
||||
));
|
||||
println!("Remote is {}ing repository to {repo_path}...", op.name());
|
||||
}
|
||||
None => println!("Remote is syncing repository..."),
|
||||
}
|
||||
let options = rns_runtime::link_session::RequestOptions {
|
||||
timeout: Some(Duration::from_secs(7200)),
|
||||
..Default::default()
|
||||
};
|
||||
match session
|
||||
.handle
|
||||
.request_with_options(path, rmpv::Value::Map(request), options)
|
||||
.await
|
||||
{
|
||||
Ok(response) if matches!(response.value, rmpv::Value::Binary(_)) => {
|
||||
outcome(op, &repo_path, Some(&response.data))
|
||||
}
|
||||
Ok(_) => outcome(op, &repo_path, None),
|
||||
Err(_) => Err("Request failed or timed out".to_string()),
|
||||
}
|
||||
}
|
||||
};
|
||||
session.handle.close().await;
|
||||
match result {
|
||||
Ok(message) => {
|
||||
println!("{message}");
|
||||
rns_tools::exit(&handle, 0).await;
|
||||
}
|
||||
Err(message) => abort(&handle, &message).await,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! `rngit` client subcommands (`ReticulumGitClient`, `server.py`).
|
||||
|
||||
pub mod forks;
|
||||
pub mod perms;
|
||||
pub mod releases;
|
||||
pub mod work;
|
||||
@@ -0,0 +1,84 @@
|
||||
//! `rngit perms` (`group_permissions` and `repository_permissions`,
|
||||
//! `server.py`).
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
use super::releases::{Connect, Fail};
|
||||
use super::work::edit_remote_permissions;
|
||||
use crate::server::client::ClientConfig;
|
||||
use crate::server::{IDX_GROUP, IDX_REPOSITORY};
|
||||
|
||||
/// Which file a `perms` URL names: 4 components a group, 5 a repository.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PermsTarget {
|
||||
Group,
|
||||
Repository,
|
||||
}
|
||||
|
||||
/// `args.remote.rstrip("/")` and the component count (`server.py`);
|
||||
/// `None` is "Invalid URL".
|
||||
pub fn perms_target(remote: &str) -> Option<(String, PermsTarget)> {
|
||||
let remote = remote.trim_end_matches('/').to_string();
|
||||
match remote.split('/').count() {
|
||||
5 => Some((remote, PermsTarget::Repository)),
|
||||
4 => Some((remote, PermsTarget::Group)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn map(entries: Vec<(Value, Value)>) -> Value {
|
||||
Value::Map(entries)
|
||||
}
|
||||
|
||||
/// `rngit perms <url>` once Reticulum is up. `Ok` is the exit code.
|
||||
pub fn run_perms(
|
||||
out: &mut dyn Write,
|
||||
config: &ClientConfig,
|
||||
connect: &mut Connect<'_>,
|
||||
remote: &str,
|
||||
target: PermsTarget,
|
||||
) -> Result<i32, Fail> {
|
||||
let mut link = connect(remote, "Failed to establish link")?;
|
||||
let _ = write!(out, "\r \r");
|
||||
let (key, name, operation) = match target {
|
||||
PermsTarget::Group => (
|
||||
Value::from(IDX_GROUP),
|
||||
config
|
||||
.parse_remote_group_url(remote)
|
||||
.map_err(Fail::Abort)?
|
||||
.1,
|
||||
"gperms",
|
||||
),
|
||||
PermsTarget::Repository => {
|
||||
let (_, group, repo) = config.parse_remote_url(remote).map_err(Fail::Abort)?;
|
||||
(
|
||||
Value::from(IDX_REPOSITORY),
|
||||
format!("{group}/{repo}"),
|
||||
"rperms",
|
||||
)
|
||||
}
|
||||
};
|
||||
let get = map(vec![
|
||||
(key.clone(), Value::from(name.as_str())),
|
||||
(Value::from("operation"), Value::from(operation)),
|
||||
(Value::from("step"), Value::from("get")),
|
||||
]);
|
||||
let set = |content: String| {
|
||||
map(vec![
|
||||
(key.clone(), Value::from(name.as_str())),
|
||||
(Value::from("operation"), Value::from(operation)),
|
||||
(Value::from("step"), Value::from("set")),
|
||||
(Value::from("content"), Value::from(content)),
|
||||
])
|
||||
};
|
||||
if edit_remote_permissions(out, link.as_mut(), get, set)? {
|
||||
match target {
|
||||
PermsTarget::Group => writeln!(out, "Permissions updated for group {name}"),
|
||||
PermsTarget::Repository => writeln!(out, "Permissions updated for {name}"),
|
||||
}
|
||||
.ok();
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,987 @@
|
||||
//! `rngit work` (`ReticulumGitClient.work_*` and the editor helpers,
|
||||
//! `server.py`).
|
||||
|
||||
use std::io::{BufRead, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::time::Duration;
|
||||
|
||||
use rmpv::Value;
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_runtime::lifecycle::ShutdownSignal;
|
||||
|
||||
use super::releases::{Connect, Fail, Remote, Response};
|
||||
use crate::server::client::{ClientConfig, client_config_dir};
|
||||
use crate::server::{APP_NAME, IDX_REPOSITORY};
|
||||
|
||||
/// `COMMENT_TEMPLATE`, `CREATE_DOC_TEMPLATE` and `PERMISSIONS_TEMPLATE` (`server.py`).
|
||||
pub const COMMENT_TEMPLATE: &str = "# Remove this line and enter your update. Save and exit when done, or save an empty document to abort abort.";
|
||||
pub const CREATE_DOC_TEMPLATE: &str = "# Remove this line and enter your document content. Save and exit when done, or save an empty document to abort abort.";
|
||||
pub const PERMISSIONS_TEMPLATE: &str = "# No permissions are currently defined for this entity. Add them below, and save and exit when you are done.";
|
||||
|
||||
/// The `rngit work` operations (`server.py`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WorkOp {
|
||||
List,
|
||||
View,
|
||||
Create,
|
||||
Propose,
|
||||
Edit,
|
||||
Delete,
|
||||
Update,
|
||||
Complete,
|
||||
Activate,
|
||||
Perms,
|
||||
}
|
||||
|
||||
impl WorkOp {
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
Some(match name {
|
||||
"list" => WorkOp::List,
|
||||
"view" => WorkOp::View,
|
||||
"create" => WorkOp::Create,
|
||||
"propose" => WorkOp::Propose,
|
||||
"edit" => WorkOp::Edit,
|
||||
"delete" => WorkOp::Delete,
|
||||
"update" => WorkOp::Update,
|
||||
"complete" => WorkOp::Complete,
|
||||
"activate" => WorkOp::Activate,
|
||||
"perms" => WorkOp::Perms,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What `rngit work` was given on the command line.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct WorkArgs {
|
||||
pub remote: Option<String>,
|
||||
pub scope: String,
|
||||
pub doc_id: Option<i64>,
|
||||
pub title: Option<String>,
|
||||
}
|
||||
|
||||
fn abort<T>(message: impl Into<String>) -> Result<T, Fail> {
|
||||
Err(Fail::Abort(message.into()))
|
||||
}
|
||||
|
||||
fn s(v: &str) -> Value {
|
||||
Value::from(v)
|
||||
}
|
||||
|
||||
pub(crate) fn field<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
|
||||
match value {
|
||||
Value::Map(entries) => entries
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some(key))
|
||||
.map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn py_str(value: &Value) -> String {
|
||||
rns_tools::rsg::pyfmt::py_str(value)
|
||||
}
|
||||
|
||||
/// `send_request` and the shared reply checks: the body after a zero status.
|
||||
pub(crate) fn exchange(
|
||||
remote: &mut dyn Remote,
|
||||
data: Value,
|
||||
timeout: u64,
|
||||
prefix: &str,
|
||||
) -> Result<Vec<u8>, Fail> {
|
||||
let Some(response) = remote.request(data, Duration::from_secs(timeout)) else {
|
||||
return abort("Request failed or timed out");
|
||||
};
|
||||
let Response::Bytes(bytes) = response else {
|
||||
return abort("No response from remote");
|
||||
};
|
||||
if bytes.is_empty() {
|
||||
return abort("No response from remote");
|
||||
}
|
||||
if bytes[0] != 0 {
|
||||
let text: String = bytes[1..].utf8_chunks().map(|c| c.valid()).collect();
|
||||
return abort(format!("{prefix}{text}"));
|
||||
}
|
||||
Ok(bytes[1..].to_vec())
|
||||
}
|
||||
|
||||
pub(crate) fn unpack(body: &[u8], context: &str) -> Result<Value, Fail> {
|
||||
rmpv::decode::read_value(&mut &body[..]).map_err(|e| Fail::Abort(format!("{context}: {e}")))
|
||||
}
|
||||
|
||||
/// Python `str.capitalize()`.
|
||||
fn capitalize(text: &str) -> String {
|
||||
let mut chars = text.chars();
|
||||
match chars.next() {
|
||||
Some(first) => first
|
||||
.to_uppercase()
|
||||
.chain(chars.flat_map(char::to_lowercase))
|
||||
.collect(),
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `f"{text:<width}"`.
|
||||
fn pad(text: &str, width: usize) -> String {
|
||||
format!(
|
||||
"{text}{}",
|
||||
" ".repeat(width.saturating_sub(text.chars().count()))
|
||||
)
|
||||
}
|
||||
|
||||
fn timestamp(value: Option<&Value>) -> f64 {
|
||||
match value {
|
||||
Some(Value::F64(f)) => *f,
|
||||
Some(Value::F32(f)) => f64::from(*f),
|
||||
Some(Value::Integer(i)) => i.as_f64().unwrap_or(0.0),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `time.strftime("%Y-%m-%d %H:%M[:%S]", time.localtime(ts))`.
|
||||
fn strftime(ts: f64, seconds: bool) -> String {
|
||||
let Some(tm) = crate::platform::localtime(ts.floor() as i64) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut out = format!(
|
||||
"{:04}-{:02}-{:02} {:02}:{:02}",
|
||||
tm.year, tm.month, tm.day, tm.hour, tm.minute
|
||||
);
|
||||
if seconds {
|
||||
out.push_str(&format!(":{:02}", tm.second));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The editor `_edit_work_content` and `_edit_permissions` run: `$EDITOR`,
|
||||
/// else the first of nano, vim and vi that `which` finds.
|
||||
fn find_editor(out: &mut dyn Write) -> Option<String> {
|
||||
let editor = std::env::var("EDITOR").unwrap_or_default();
|
||||
if !editor.is_empty() {
|
||||
return Some(editor);
|
||||
}
|
||||
let found = ["nano", "vim", "vi"].into_iter().find(|fallback| {
|
||||
std::process::Command::new("which")
|
||||
.arg(fallback)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.status()
|
||||
.is_ok_and(|s| s.success())
|
||||
});
|
||||
if found.is_none() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"No editor found. Please set $EDITOR environment variable."
|
||||
);
|
||||
}
|
||||
found.map(str::to_string)
|
||||
}
|
||||
|
||||
/// Write `template` to a kept temporary file, run `[editor, path]` and read
|
||||
/// the file back. A file the editor could not be started on is left behind.
|
||||
fn run_editor(
|
||||
out: &mut dyn Write,
|
||||
editor: &str,
|
||||
template: &str,
|
||||
suffix: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
let file = tempfile::Builder::new()
|
||||
.prefix("tmp")
|
||||
.suffix(suffix)
|
||||
.tempfile()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let (mut file, path) = file.keep().map_err(|e| e.to_string())?;
|
||||
file.write_all(template.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
drop(file);
|
||||
let _ = out.flush();
|
||||
let status = std::process::Command::new(editor)
|
||||
.arg(&path)
|
||||
.status()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if !status.success() {
|
||||
let code = crate::platform::return_code(status);
|
||||
let _ = writeln!(out, "Editor exited with error code {code}");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return Ok(None);
|
||||
}
|
||||
let edited = crate::server::work::read_text(&path).map_err(|e| e.to_string())?;
|
||||
let _ = std::fs::remove_file(&path);
|
||||
Ok(Some(edited))
|
||||
}
|
||||
|
||||
fn py_strip(s: &str) -> &str {
|
||||
s.trim_matches(|c: char| c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c))
|
||||
}
|
||||
|
||||
/// `_edit_work_content` (`server.py`): template lines are dropped,
|
||||
/// the rest stripped; empty is None.
|
||||
pub fn edit_work_content(out: &mut dyn Write, content: &str, is_comment: bool) -> Option<String> {
|
||||
let editor = find_editor(out)?;
|
||||
let template = if !content.is_empty() {
|
||||
content
|
||||
} else if is_comment {
|
||||
COMMENT_TEMPLATE
|
||||
} else {
|
||||
CREATE_DOC_TEMPLATE
|
||||
};
|
||||
match run_editor(out, &editor, template, ".md") {
|
||||
Ok(edited) => {
|
||||
let edited = edited?;
|
||||
let lines: Vec<&str> = edited
|
||||
.split('\n')
|
||||
.filter(|line| {
|
||||
let line = py_strip(line);
|
||||
!(line.starts_with(COMMENT_TEMPLATE) || line.starts_with(CREATE_DOC_TEMPLATE))
|
||||
})
|
||||
.collect();
|
||||
let result = py_strip(&lines.join("\n")).to_string();
|
||||
(!result.is_empty()).then_some(result)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Error editing work content: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_edit_permissions` (`server.py`): the file as saved, even empty.
|
||||
pub fn edit_permissions(out: &mut dyn Write, content: &str) -> Option<String> {
|
||||
let editor = find_editor(out)?;
|
||||
let template = if content.is_empty() {
|
||||
PERMISSIONS_TEMPLATE
|
||||
} else {
|
||||
content
|
||||
};
|
||||
match run_editor(out, &editor, template, ".txt") {
|
||||
Ok(edited) => edited,
|
||||
Err(e) => {
|
||||
tracing::error!("Error editing permissions: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn request(repo_path: &str, fields: Vec<(&str, Value)>) -> Value {
|
||||
let mut map = vec![(Value::from(IDX_REPOSITORY), s(repo_path))];
|
||||
map.extend(fields.into_iter().map(|(k, v)| (s(k), v)));
|
||||
Value::Map(map)
|
||||
}
|
||||
|
||||
const CLEAR: &str = "\r \r";
|
||||
|
||||
/// `work_list` after the Link is up (`server.py`).
|
||||
fn work_list(
|
||||
out: &mut dyn Write,
|
||||
remote: &mut dyn Remote,
|
||||
repo_path: &str,
|
||||
scope: &str,
|
||||
) -> Result<(), Fail> {
|
||||
let data = request(
|
||||
repo_path,
|
||||
vec![("operation", s("list")), ("scope", s(scope))],
|
||||
);
|
||||
let sent = exchange(remote, data, 120, "Remote error: ");
|
||||
let _ = write!(out, "{CLEAR}");
|
||||
let body = sent?;
|
||||
let result = if body.is_empty() {
|
||||
Value::Map(vec![
|
||||
(s("active"), Value::Array(vec![])),
|
||||
(s("completed"), Value::Array(vec![])),
|
||||
])
|
||||
} else {
|
||||
unpack(&body, "Error listing work documents")?
|
||||
};
|
||||
let docs_of = |name: &str| -> Vec<Value> {
|
||||
match field(&result, name) {
|
||||
Some(Value::Array(items)) => items.clone(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
};
|
||||
let shown: Vec<&str> = if scope == "all" {
|
||||
vec!["active", "completed", "proposed"]
|
||||
} else {
|
||||
vec![scope]
|
||||
};
|
||||
for name in shown {
|
||||
let docs = docs_of(name);
|
||||
if docs.is_empty() {
|
||||
if scope != "all" {
|
||||
let _ = writeln!(out, "No {name} work documents found.");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let header = format!("\n{} documents", capitalize(name));
|
||||
let _ = writeln!(out, "{header}");
|
||||
let _ = writeln!(out, "{}\n", "=".repeat(header.chars().count()));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{} {} {} {} Comments",
|
||||
pad("ID", 4),
|
||||
pad("Title", 30),
|
||||
pad("Author", 17),
|
||||
pad("Created", 18)
|
||||
);
|
||||
let _ = writeln!(out, "{}", "-".repeat(80));
|
||||
for doc in &docs {
|
||||
let id = field(doc, "id").map_or("?".to_string(), py_str);
|
||||
let mut title = field(doc, "title").map_or("Untitled".to_string(), py_str);
|
||||
if title.chars().count() > 29 {
|
||||
title = format!("{}…", title.chars().take(29).collect::<String>());
|
||||
}
|
||||
let author: String = field(doc, "author")
|
||||
.map(py_str)
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.take(16)
|
||||
.collect();
|
||||
let created_ts = timestamp(field(doc, "created"));
|
||||
let created = if created_ts != 0.0 {
|
||||
strftime(created_ts, false)
|
||||
} else {
|
||||
"unknown".into()
|
||||
};
|
||||
let comments = field(doc, "comments").map_or("0".to_string(), py_str);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{} {} {} {} {comments}",
|
||||
pad(&id, 4),
|
||||
pad(&title, 30),
|
||||
pad(&format!("{author}…"), 17),
|
||||
pad(&created, 18)
|
||||
);
|
||||
}
|
||||
let _ = writeln!(out);
|
||||
}
|
||||
if scope == "all"
|
||||
&& ["active", "completed", "proposed"]
|
||||
.iter()
|
||||
.all(|n| docs_of(n).is_empty())
|
||||
{
|
||||
let _ = writeln!(out, "No work documents found.");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `work_view` after the Link is up (`server.py`).
|
||||
fn work_view(
|
||||
out: &mut dyn Write,
|
||||
remote: &mut dyn Remote,
|
||||
repo_path: &str,
|
||||
doc_id: i64,
|
||||
scope: &str,
|
||||
) -> Result<(), Fail> {
|
||||
let data = request(
|
||||
repo_path,
|
||||
vec![
|
||||
("operation", s("view")),
|
||||
("doc_id", Value::from(doc_id)),
|
||||
("scope", s(scope)),
|
||||
],
|
||||
);
|
||||
let sent = exchange(remote, data, 120, "Remote error: ");
|
||||
let _ = write!(out, "{CLEAR}");
|
||||
let body = sent?;
|
||||
if body.is_empty() {
|
||||
return abort("Empty response from remote");
|
||||
}
|
||||
let doc = unpack(&body, "Error viewing work document")?;
|
||||
let missing = |key: &str| Fail::Abort(format!("Error viewing work document: '{key}'"));
|
||||
let meta = field(&doc, "meta").ok_or_else(|| missing("meta"))?;
|
||||
let meta_field = |key: &str| field(meta, key).ok_or_else(|| missing(key));
|
||||
let content = field(&doc, "content").map(py_str).unwrap_or_default();
|
||||
let mut author = format!("{} (not locally validated)", py_str(meta_field("author")?));
|
||||
let mut signature_text = "Document not signed";
|
||||
if let (Some(Value::Binary(sig)), Some(Value::Binary(key))) =
|
||||
(field(meta, "signature"), field(meta, "identity"))
|
||||
&& sig.len() == 64
|
||||
&& key.len() == 64
|
||||
{
|
||||
signature_text = "Not valid";
|
||||
if let (Ok(identity), Ok(sig)) = (
|
||||
Identity::from_public_key(key),
|
||||
<[u8; 64]>::try_from(sig.as_slice()),
|
||||
) && identity.verify(content.as_bytes(), &sig)
|
||||
{
|
||||
signature_text = "Valid";
|
||||
author = format!("<{}>", hex::encode(identity.hash));
|
||||
}
|
||||
}
|
||||
let heading = format!(
|
||||
"{} (#{})",
|
||||
py_str(meta_field("title")?),
|
||||
py_str(field(&doc, "id").ok_or_else(|| missing("id"))?)
|
||||
);
|
||||
let comments = match field(&doc, "comments") {
|
||||
Some(Value::Array(items)) => items.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let _ = writeln!(out, "{heading}");
|
||||
let _ = writeln!(out, "{}", "=".repeat(heading.chars().count()));
|
||||
let _ = writeln!(out, "Author : {author}");
|
||||
let _ = writeln!(out, "Signature : {signature_text}");
|
||||
let _ = writeln!(out, "Status : {}", capitalize(scope));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Created : {}",
|
||||
strftime(timestamp(Some(meta_field("created")?)), true)
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Edited : {}",
|
||||
strftime(timestamp(Some(meta_field("edited")?)), true)
|
||||
);
|
||||
let _ = writeln!(out, "Format : {}", py_str(meta_field("format")?));
|
||||
let _ = writeln!(out, "Updates : {}", comments.len());
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
py_str(field(&doc, "content").ok_or_else(|| missing("content"))?)
|
||||
);
|
||||
if !comments.is_empty() {
|
||||
let _ = writeln!(out, "\nUpdates\n=======");
|
||||
for c in &comments {
|
||||
let get = |key: &str| field(c, key).ok_or_else(|| missing(key));
|
||||
let line = format!(
|
||||
"#{} by {} at {}",
|
||||
py_str(get("id")?),
|
||||
py_str(get("author")?),
|
||||
strftime(timestamp(Some(get("created")?)), true)
|
||||
);
|
||||
let _ = writeln!(out, "\n{line}");
|
||||
let _ = writeln!(out, "{}", "-".repeat(line.chars().count()));
|
||||
let _ = writeln!(out, "{}", py_str(get("content")?));
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sign(identity: &Identity, content: &str) -> Result<Value, Fail> {
|
||||
match identity.sign(content.as_bytes()) {
|
||||
Some(sig) => Ok(Value::Binary(sig.to_vec())),
|
||||
None => abort("Could not sign work document"),
|
||||
}
|
||||
}
|
||||
|
||||
fn result_field(body: &[u8], key: &str, context: &str) -> Result<String, Fail> {
|
||||
let value = unpack(body, context)?;
|
||||
field(&value, key)
|
||||
.map(py_str)
|
||||
.ok_or_else(|| Fail::Abort(format!("{context}: '{key}'")))
|
||||
}
|
||||
|
||||
/// `work_create` and `work_propose` after the Link is up (`server.py`).
|
||||
fn work_new(
|
||||
out: &mut dyn Write,
|
||||
remote: &mut dyn Remote,
|
||||
identity: &Identity,
|
||||
repo_path: &str,
|
||||
title: &str,
|
||||
propose: bool,
|
||||
) -> Result<(), Fail> {
|
||||
let Some(content) = edit_work_content(out, "", false) else {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
if propose {
|
||||
"Proposal cancelled"
|
||||
} else {
|
||||
"Creation cancelled"
|
||||
}
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
let signature = sign(identity, &content)?;
|
||||
let operation = if propose { "propose" } else { "create" };
|
||||
let data = request(
|
||||
repo_path,
|
||||
vec![
|
||||
("operation", s(operation)),
|
||||
("title", s(title)),
|
||||
("content", s(&content)),
|
||||
("format", s("markdown")),
|
||||
("signature", signature),
|
||||
],
|
||||
);
|
||||
let body = exchange(remote, data, 600, "Server error: ")?;
|
||||
if body.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
if propose {
|
||||
"Work document proposed"
|
||||
} else {
|
||||
"Work document created"
|
||||
}
|
||||
);
|
||||
} else {
|
||||
let context = "Error creating work document";
|
||||
let scope = result_field(&body, "scope", context)?;
|
||||
let id = result_field(&body, "id", context)?;
|
||||
let _ = writeln!(out, "Work document created as {scope} #{id}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `work_edit` after the Link is up (`server.py`).
|
||||
fn work_edit(
|
||||
out: &mut dyn Write,
|
||||
remote: &mut dyn Remote,
|
||||
identity: &Identity,
|
||||
repo_path: &str,
|
||||
args: &WorkArgs,
|
||||
doc_id: i64,
|
||||
) -> Result<(), Fail> {
|
||||
let scope = args.scope.as_str();
|
||||
let view = request(
|
||||
repo_path,
|
||||
vec![
|
||||
("operation", s("view")),
|
||||
("doc_id", Value::from(doc_id)),
|
||||
("scope", s(scope)),
|
||||
],
|
||||
);
|
||||
let body = exchange(remote, view, 600, "Remote error: ")?;
|
||||
let doc = unpack(&body, "Error editing work document")?;
|
||||
let missing = |key: &str| Fail::Abort(format!("Error editing work document: '{key}'"));
|
||||
let current_content = py_str(field(&doc, "content").ok_or_else(|| missing("content"))?);
|
||||
let meta = field(&doc, "meta").ok_or_else(|| missing("meta"))?;
|
||||
let current_title = field(meta, "title")
|
||||
.ok_or_else(|| missing("title"))?
|
||||
.clone();
|
||||
let Some(content) = edit_work_content(out, ¤t_content, false) else {
|
||||
let _ = writeln!(out, "Edit cancelled");
|
||||
return Ok(());
|
||||
};
|
||||
let signature = sign(identity, &content)?;
|
||||
let title = match args.title.as_deref().filter(|t| !t.is_empty()) {
|
||||
Some(title) => s(title),
|
||||
None => current_title,
|
||||
};
|
||||
let data = request(
|
||||
repo_path,
|
||||
vec![
|
||||
("operation", s("edit")),
|
||||
("doc_id", Value::from(doc_id)),
|
||||
("scope", s(scope)),
|
||||
("content", s(&content)),
|
||||
("title", title),
|
||||
("signature", signature),
|
||||
],
|
||||
);
|
||||
exchange(remote, data, 600, "Remote error: ")?;
|
||||
let _ = writeln!(out, "Work document {scope} #{doc_id} updated");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `work_delete` after the Link is up (`server.py`).
|
||||
fn work_delete(
|
||||
out: &mut dyn Write,
|
||||
input: &mut dyn BufRead,
|
||||
remote: &mut dyn Remote,
|
||||
repo_path: &str,
|
||||
doc_id: i64,
|
||||
scope: &str,
|
||||
) -> Result<(), Fail> {
|
||||
let _ = write!(
|
||||
out,
|
||||
"Are you sure you want to delete {scope} work document #{doc_id}? [y/N]: "
|
||||
);
|
||||
let _ = out.flush();
|
||||
let mut line = String::new();
|
||||
let confirm = match input.read_line(&mut line) {
|
||||
Ok(0) | Err(_) => "n".to_string(),
|
||||
Ok(_) => py_strip(line.trim_end_matches('\n')).to_lowercase(),
|
||||
};
|
||||
if confirm != "y" {
|
||||
let _ = writeln!(out, "Deletion cancelled");
|
||||
return Ok(());
|
||||
}
|
||||
let data = request(
|
||||
repo_path,
|
||||
vec![
|
||||
("operation", s("delete")),
|
||||
("doc_id", Value::from(doc_id)),
|
||||
("scope", s(scope)),
|
||||
],
|
||||
);
|
||||
exchange(remote, data, 120, "Remote error: ")?;
|
||||
let _ = writeln!(out, "Work document {scope} #{doc_id} deleted");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `work_comment` after the Link is up (`server.py`).
|
||||
fn work_comment(
|
||||
out: &mut dyn Write,
|
||||
remote: &mut dyn Remote,
|
||||
repo_path: &str,
|
||||
doc_id: i64,
|
||||
scope: &str,
|
||||
) -> Result<(), Fail> {
|
||||
let Some(content) = edit_work_content(out, "", true) else {
|
||||
let _ = writeln!(out, "Update cancelled");
|
||||
return Ok(());
|
||||
};
|
||||
let data = request(
|
||||
repo_path,
|
||||
vec![
|
||||
("operation", s("comment")),
|
||||
("doc_id", Value::from(doc_id)),
|
||||
("scope", s(scope)),
|
||||
("content", s(&content)),
|
||||
("format", s("markdown")),
|
||||
],
|
||||
);
|
||||
let body = exchange(remote, data, 600, "Remote error: ")?;
|
||||
if body.is_empty() {
|
||||
let _ = writeln!(out, "Update added");
|
||||
} else {
|
||||
let id = result_field(&body, "id", "Error adding comment")?;
|
||||
let _ = writeln!(out, "Update #{id} added to {scope} document #{doc_id}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `work_complete` and `work_activate` after the Link is up (`server.py`).
|
||||
fn work_move(
|
||||
out: &mut dyn Write,
|
||||
remote: &mut dyn Remote,
|
||||
repo_path: &str,
|
||||
doc_id: i64,
|
||||
activate: bool,
|
||||
) -> Result<(), Fail> {
|
||||
let (operation, done, context) = if activate {
|
||||
("activate", "activated", "Error activating work document")
|
||||
} else {
|
||||
("complete", "completed", "Error completing work document")
|
||||
};
|
||||
let data = request(
|
||||
repo_path,
|
||||
vec![("operation", s(operation)), ("doc_id", Value::from(doc_id))],
|
||||
);
|
||||
let body = exchange(remote, data, 120, "Remote error: ")?;
|
||||
if body.is_empty() {
|
||||
let _ = writeln!(out, "Work document {done}");
|
||||
} else {
|
||||
let id = result_field(&body, "id", context)?;
|
||||
let _ = writeln!(out, "Work document #{id} {done}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The get, edit and set round of every permissions command
|
||||
/// (`server.py`).
|
||||
pub(crate) fn edit_remote_permissions(
|
||||
out: &mut dyn Write,
|
||||
remote: &mut dyn Remote,
|
||||
get: Value,
|
||||
set: impl FnOnce(String) -> Value,
|
||||
) -> Result<bool, Fail> {
|
||||
let body = exchange(remote, get, 120, "Remote error: ")?;
|
||||
let current = if body.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
let result = unpack(&body, "Error editing permissions")?;
|
||||
field(&result, "content").map(py_str).unwrap_or_default()
|
||||
};
|
||||
let Some(content) = edit_permissions(out, ¤t) else {
|
||||
let _ = writeln!(out, "Edit cancelled");
|
||||
return Ok(false);
|
||||
};
|
||||
exchange(remote, set(content), 120, "Remote error: ")?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `rngit work <repository> <operation>` once Reticulum is up
|
||||
/// (`server.py`). `Ok` is the exit code.
|
||||
pub fn run_work(
|
||||
out: &mut dyn Write,
|
||||
input: &mut dyn BufRead,
|
||||
config: &ClientConfig,
|
||||
connect: &mut Connect<'_>,
|
||||
identity: &Identity,
|
||||
operation: Option<&str>,
|
||||
args: &WorkArgs,
|
||||
) -> Result<i32, Fail> {
|
||||
let Some(op) = operation.and_then(WorkOp::parse) else {
|
||||
let _ = writeln!(out, "Invalid operation");
|
||||
return Ok(1);
|
||||
};
|
||||
let Some(remote) = args.remote.as_deref().filter(|r| !r.is_empty()) else {
|
||||
return abort("No remote specified");
|
||||
};
|
||||
let needs_id = !matches!(op, WorkOp::List | WorkOp::Create | WorkOp::Propose);
|
||||
if needs_id && args.doc_id.is_none() {
|
||||
return abort("No document ID specified");
|
||||
}
|
||||
let title = args.title.as_deref().filter(|t| !t.is_empty());
|
||||
if matches!(op, WorkOp::Create | WorkOp::Propose) && title.is_none() {
|
||||
return abort("No title specified");
|
||||
}
|
||||
let failed = if matches!(op, WorkOp::List | WorkOp::View) {
|
||||
"Link establishment failed"
|
||||
} else {
|
||||
"Failed to establish link"
|
||||
};
|
||||
let mut link = connect(remote, failed)?;
|
||||
if !matches!(op, WorkOp::List | WorkOp::View) {
|
||||
let _ = write!(out, "{CLEAR}");
|
||||
}
|
||||
let (_, group, repo) = config.parse_remote_url(remote).map_err(Fail::Abort)?;
|
||||
let repo_path = format!("{group}/{repo}");
|
||||
let remote = link.as_mut();
|
||||
let doc_id = args.doc_id.unwrap_or_default();
|
||||
let scope = args.scope.as_str();
|
||||
match op {
|
||||
WorkOp::List => work_list(out, remote, &repo_path, scope)?,
|
||||
WorkOp::View => work_view(out, remote, &repo_path, doc_id, scope)?,
|
||||
WorkOp::Create => work_new(
|
||||
out,
|
||||
remote,
|
||||
identity,
|
||||
&repo_path,
|
||||
title.unwrap_or_default(),
|
||||
false,
|
||||
)?,
|
||||
WorkOp::Propose => work_new(
|
||||
out,
|
||||
remote,
|
||||
identity,
|
||||
&repo_path,
|
||||
title.unwrap_or_default(),
|
||||
true,
|
||||
)?,
|
||||
WorkOp::Edit => work_edit(out, remote, identity, &repo_path, args, doc_id)?,
|
||||
WorkOp::Delete => work_delete(out, input, remote, &repo_path, doc_id, scope)?,
|
||||
WorkOp::Update => work_comment(out, remote, &repo_path, doc_id, scope)?,
|
||||
WorkOp::Complete => work_move(out, remote, &repo_path, doc_id, false)?,
|
||||
WorkOp::Activate => work_move(out, remote, &repo_path, doc_id, true)?,
|
||||
WorkOp::Perms => {
|
||||
let get = request(
|
||||
&repo_path,
|
||||
vec![
|
||||
("operation", s("perms")),
|
||||
("doc_id", Value::from(doc_id)),
|
||||
("step", s("get")),
|
||||
],
|
||||
);
|
||||
let set = |content: String| {
|
||||
request(
|
||||
&repo_path,
|
||||
vec![
|
||||
("operation", s("perms")),
|
||||
("doc_id", Value::from(doc_id)),
|
||||
("step", s("set")),
|
||||
("content", s(&content)),
|
||||
],
|
||||
)
|
||||
};
|
||||
if edit_remote_permissions(out, remote, get, set)? {
|
||||
let _ = writeln!(out, "Permissions updated for work document #{doc_id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// Requests over an established Link; the Link closes when this is dropped,
|
||||
/// as upstream's `finally: link.teardown()`.
|
||||
struct SessionRemote {
|
||||
runtime: tokio::runtime::Handle,
|
||||
session: rns_runtime::link_session::LinkSessionHandle,
|
||||
path: &'static str,
|
||||
}
|
||||
|
||||
impl Remote for SessionRemote {
|
||||
fn request(&mut self, data: Value, timeout: Duration) -> Option<Response> {
|
||||
let options = rns_runtime::link_session::RequestOptions {
|
||||
timeout: Some(timeout),
|
||||
..Default::default()
|
||||
};
|
||||
let request = self.session.request_with_options(self.path, data, options);
|
||||
let response = self
|
||||
.runtime
|
||||
.block_on(async {
|
||||
tokio::time::timeout(timeout + Duration::from_secs(30), request).await
|
||||
})
|
||||
.ok()?
|
||||
.ok()?;
|
||||
Some(match response.value {
|
||||
Value::Binary(bytes) => Response::Bytes(bytes),
|
||||
other => Response::Other(other),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SessionRemote {
|
||||
fn drop(&mut self) {
|
||||
self.runtime.block_on(self.session.close());
|
||||
}
|
||||
}
|
||||
|
||||
/// The options every `rngit` client subcommand shares.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CommonArgs {
|
||||
pub config: Option<String>,
|
||||
pub rnsconfig: Option<String>,
|
||||
pub identity: Option<String>,
|
||||
pub verbose: u8,
|
||||
pub quiet: u8,
|
||||
}
|
||||
|
||||
/// The body of a client subcommand, run on the blocking pool once Reticulum,
|
||||
/// the identity and the client config are ready.
|
||||
pub type ClientBody = Box<
|
||||
dyn FnOnce(
|
||||
&mut dyn Write,
|
||||
&mut dyn BufRead,
|
||||
&ClientConfig,
|
||||
&mut Connect<'_>,
|
||||
&Identity,
|
||||
) -> Result<i32, Fail>
|
||||
+ Send,
|
||||
>;
|
||||
|
||||
/// `program_setup` and `ReticulumGitClient.__init__` for a client task, then
|
||||
/// `body` with a `connect_remote` whose requests go to `path`; never returns.
|
||||
pub async fn run_client(common: CommonArgs, path: &'static str, body: ClientBody) -> ! {
|
||||
let non_empty = |v: Option<String>| v.filter(|v| !v.is_empty());
|
||||
let configdir = client_config_dir(non_empty(common.config).map(PathBuf::from).as_deref());
|
||||
let rnsconfig = non_empty(common.rnsconfig);
|
||||
let rns_dir = rns_runtime::platform::resolve_config_dir(rnsconfig.as_deref());
|
||||
let configured = rns_runtime::config::Config::from_file(&rns_dir.join("config"))
|
||||
.ok()
|
||||
.and_then(|c| c.section("logging")?.get_int("loglevel"));
|
||||
let level = rns_tools::Utility::Rnir.loglevel(configured, common.verbose, common.quiet, false);
|
||||
rns_tools::init_tracing(
|
||||
level,
|
||||
rns_tools::config_log_timestamps(&rns_dir),
|
||||
true,
|
||||
std::io::stdout,
|
||||
);
|
||||
let handle = match rns_runtime::reticulum::init(
|
||||
rnsconfig.as_deref(),
|
||||
None,
|
||||
ShutdownSignal::new(),
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(handle) => handle,
|
||||
Err(e) => {
|
||||
eprintln!("failed to start reticulum: {e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
handle.wants_destination_type(APP_NAME).await;
|
||||
if let Err(e) = std::fs::create_dir_all(&configdir) {
|
||||
println!("Could not create {}: {e}", configdir.display());
|
||||
rns_tools::exit(&handle, 1).await;
|
||||
}
|
||||
let identity_path = non_empty(common.identity)
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| configdir.join("client_identity"));
|
||||
let identity = if identity_path.is_file() {
|
||||
Identity::from_file(&identity_path).ok()
|
||||
} else {
|
||||
let id = Identity::new();
|
||||
id.to_file(&identity_path).ok().map(|_| id)
|
||||
};
|
||||
let Some(identity) = identity else {
|
||||
println!("Could not initialize client identity");
|
||||
rns_tools::exit(&handle, 1).await;
|
||||
};
|
||||
let config = match ClientConfig::load_or_create(&configdir) {
|
||||
Ok(config) => config,
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Could not parse the configuration at {}",
|
||||
configdir.join("client_config").display()
|
||||
);
|
||||
tracing::error!("Check your configuration file for errors! ({e})");
|
||||
rns_tools::exit(&handle, 255).await;
|
||||
}
|
||||
};
|
||||
let runtime = tokio::runtime::Handle::current();
|
||||
let link_handle = handle.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let mut out = std::io::stdout();
|
||||
let mut input = std::io::stdin().lock();
|
||||
let link_identity = identity.clone();
|
||||
let mut connect = |remote: &str, failure: &str| -> Result<Box<dyn Remote>, Fail> {
|
||||
let destination = config
|
||||
.parse_remote_destination_url(remote)
|
||||
.map_err(Fail::Abort)?;
|
||||
let Ok(destination) = <[u8; 16]>::try_from(destination.as_slice()) else {
|
||||
return abort("Invalid destination hash length");
|
||||
};
|
||||
let path_timeout = runtime
|
||||
.block_on(rns_tools::medium_path_timeout(&link_handle))
|
||||
.max(15.0);
|
||||
print!("Requesting path... ");
|
||||
let _ = std::io::stdout().flush();
|
||||
if runtime
|
||||
.block_on(
|
||||
link_handle.await_path(destination, Duration::from_secs_f64(path_timeout)),
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
println!();
|
||||
return abort(format!(
|
||||
"Could not resolve path to <{}>",
|
||||
hex::encode(destination)
|
||||
));
|
||||
}
|
||||
print!("\rPath resolved ");
|
||||
print!("\rEstablishing link... ");
|
||||
let _ = std::io::stdout().flush();
|
||||
let hops = runtime
|
||||
.block_on(link_handle.hops_to(destination))
|
||||
.unwrap_or(1);
|
||||
let first_hop = runtime
|
||||
.block_on(link_handle.first_hop_timeout(destination))
|
||||
.map_or(rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT, |d| {
|
||||
d.as_secs_f64()
|
||||
});
|
||||
let establishment =
|
||||
first_hop + rns_wire::constants::DEFAULT_PER_HOP_TIMEOUT * f64::from(hops.max(1));
|
||||
let options = rns_runtime::reticulum::LinkConnectOptions {
|
||||
path_timeout: Duration::from_secs_f64(path_timeout),
|
||||
establishment_timeout: Some(Duration::from_secs_f64(establishment.max(15.0))),
|
||||
client_label: "rngit".to_string(),
|
||||
identify: true,
|
||||
..Default::default()
|
||||
};
|
||||
let session = runtime
|
||||
.block_on(link_handle.connect_link(destination, link_identity.clone(), options))
|
||||
.map_err(|_| Fail::Abort(failure.to_string()))?;
|
||||
print!("\rLink established ");
|
||||
let _ = std::io::stdout().flush();
|
||||
Ok(Box::new(SessionRemote {
|
||||
runtime: runtime.clone(),
|
||||
session: session.handle,
|
||||
path,
|
||||
}))
|
||||
};
|
||||
let result = body(&mut out, &mut input, &config, &mut connect, &identity);
|
||||
let _ = out.flush();
|
||||
result
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| Err(Fail::Raised(format!("client task failed: {e}"))));
|
||||
match result {
|
||||
Ok(code) => rns_tools::exit(&handle, code).await,
|
||||
Err(Fail::Abort(message)) => {
|
||||
println!("{message}");
|
||||
rns_tools::exit(&handle, 1).await
|
||||
}
|
||||
Err(Fail::Raised(message)) => {
|
||||
eprintln!("{message}");
|
||||
rns_tools::exit(&handle, 1).await
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
# This is the default rngit client config file.
|
||||
|
||||
[client]
|
||||
|
||||
# You can control the batch size of ref transfers
|
||||
# using the ref_batch_size directive:
|
||||
|
||||
ref_batch_size = 25
|
||||
|
||||
|
||||
[aliases]
|
||||
|
||||
# You can define aliases for commonly used destination
|
||||
# hashes in this section. Each line must be in the format
|
||||
# aliased_name = DESTINATION_HASH
|
||||
#
|
||||
# These hashes are used for resolving remote destinations.
|
||||
# For rngit node permissions and identity resolution,
|
||||
# aliases must be defined in ~/.rngit/config.
|
||||
|
||||
# my_node = 063d38912bffc850af4a1b8a270a9d85
|
||||
# bobs_node = 714981d03e41deda0e4468cb274414cc
|
||||
|
||||
|
||||
[logging]
|
||||
# Valid log levels are 0 through 7:
|
||||
# 0: Log only critical information
|
||||
# 1: Log errors and lower log levels
|
||||
# 2: Log warnings and lower log levels
|
||||
# 3: Log notices and lower log levels
|
||||
# 4: Log info and lower (this is the default)
|
||||
# 5: Verbose logging
|
||||
# 6: Debug logging
|
||||
# 7: Extreme logging
|
||||
|
||||
loglevel = 4
|
||||
@@ -0,0 +1,304 @@
|
||||
//! `rngcs` signatures: git commit signing with Reticulum identities, a port
|
||||
//! of `RNS/Utilities/rngit/commitsigs.py@1.6.0`. The signature is an rsg
|
||||
//! envelope inside an SSHSIG container, so only rngcs (not `ssh-keygen`) can
|
||||
//! verify it. The command line is in the `rngcs-rs` binary.
|
||||
|
||||
use rns_identity::identity::Identity;
|
||||
|
||||
pub const SSHSIG_MAGIC: &[u8] = b"SSHSIG";
|
||||
pub const SSHSIG_VERSION: u32 = 1;
|
||||
pub const NAMESPACE_GIT: &[u8] = b"git";
|
||||
pub const RESERVED_EMPTY: &[u8] = b"";
|
||||
pub const HASH_ALGORITHM: &[u8] = b"sha256";
|
||||
|
||||
/// `ssh_string`: a big-endian u32 length, then the bytes.
|
||||
pub fn ssh_string(data: &[u8]) -> Vec<u8> {
|
||||
let mut out = (data.len() as u32).to_be_bytes().to_vec();
|
||||
out.extend_from_slice(data);
|
||||
out
|
||||
}
|
||||
|
||||
fn read_ssh_string(data: &[u8], offset: usize) -> Result<(&[u8], usize), String> {
|
||||
if offset + 4 > data.len() {
|
||||
return Err("Not enough data for string length".to_string());
|
||||
}
|
||||
let length = u32::from_be_bytes(data[offset..offset + 4].try_into().expect("4 bytes")) as usize;
|
||||
if offset + 4 + length > data.len() {
|
||||
return Err("Not enough data for string content".to_string());
|
||||
}
|
||||
Ok((&data[offset + 4..offset + 4 + length], offset + 4 + length))
|
||||
}
|
||||
|
||||
/// `create_ssh_signature`.
|
||||
pub fn create_ssh_signature(
|
||||
public_key_wire: &[u8],
|
||||
namespace: &[u8],
|
||||
reserved: &[u8],
|
||||
hash_algorithm: &[u8],
|
||||
signature_data: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let mut blob = SSHSIG_MAGIC.to_vec();
|
||||
blob.extend_from_slice(&SSHSIG_VERSION.to_be_bytes());
|
||||
for field in [
|
||||
public_key_wire,
|
||||
namespace,
|
||||
reserved,
|
||||
hash_algorithm,
|
||||
signature_data,
|
||||
] {
|
||||
blob.extend_from_slice(&ssh_string(field));
|
||||
}
|
||||
blob
|
||||
}
|
||||
|
||||
/// The fields `parse_ssh_signature` returns.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SshSignature {
|
||||
pub version: u32,
|
||||
pub public_key: Vec<u8>,
|
||||
pub namespace: Vec<u8>,
|
||||
pub reserved: Vec<u8>,
|
||||
pub hash_algorithm: Vec<u8>,
|
||||
pub signature_data: Vec<u8>,
|
||||
}
|
||||
|
||||
/// `parse_ssh_signature`; trailing bytes are ignored as upstream does.
|
||||
pub fn parse_ssh_signature(sig_data: &[u8]) -> Result<SshSignature, String> {
|
||||
if !sig_data.starts_with(SSHSIG_MAGIC) {
|
||||
return Err("Invalid SSH signature: missing SSHSIG magic".to_string());
|
||||
}
|
||||
let mut offset = SSHSIG_MAGIC.len();
|
||||
if offset + 4 > sig_data.len() {
|
||||
return Err("Invalid SSH signature: truncated".to_string());
|
||||
}
|
||||
let version = u32::from_be_bytes(sig_data[offset..offset + 4].try_into().expect("4 bytes"));
|
||||
if version != SSHSIG_VERSION {
|
||||
return Err(format!("Unsupported SSH signature version: {version}"));
|
||||
}
|
||||
offset += 4;
|
||||
let mut fields = Vec::with_capacity(5);
|
||||
for _ in 0..5 {
|
||||
let (field, next) = read_ssh_string(sig_data, offset)?;
|
||||
fields.push(field.to_vec());
|
||||
offset = next;
|
||||
}
|
||||
let mut fields = fields.into_iter();
|
||||
let mut next = || fields.next().expect("five fields");
|
||||
Ok(SshSignature {
|
||||
version,
|
||||
public_key: next(),
|
||||
namespace: next(),
|
||||
reserved: next(),
|
||||
hash_algorithm: next(),
|
||||
signature_data: next(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `armor_ssh_signature`: standard base64 in 70-character lines.
|
||||
pub fn armor_ssh_signature(sig_blob: &[u8]) -> String {
|
||||
use base64::Engine;
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(sig_blob);
|
||||
let lines: Vec<&str> = b64
|
||||
.as_bytes()
|
||||
.chunks(70)
|
||||
.map(|chunk| std::str::from_utf8(chunk).expect("base64 is ASCII"))
|
||||
.collect();
|
||||
format!(
|
||||
"-----BEGIN SSH SIGNATURE-----\n{}\n-----END SSH SIGNATURE-----\n",
|
||||
lines.join("\n")
|
||||
)
|
||||
}
|
||||
|
||||
fn is_py_space(c: char) -> bool {
|
||||
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
|
||||
}
|
||||
|
||||
/// `unarmor_ssh_signature`: collects the stripped lines between the markers,
|
||||
/// so the indentation git adds in a `gpgsig` header is tolerated.
|
||||
pub fn unarmor_ssh_signature(armored: &str) -> Result<Vec<u8>, String> {
|
||||
let mut b64 = String::new();
|
||||
let mut in_sig = false;
|
||||
for line in armored.trim_matches(is_py_space).split('\n') {
|
||||
if line.contains("BEGIN SSH SIGNATURE") {
|
||||
in_sig = true;
|
||||
continue;
|
||||
}
|
||||
if line.contains("END SSH SIGNATURE") {
|
||||
break;
|
||||
}
|
||||
if in_sig {
|
||||
b64.push_str(line.trim_matches(is_py_space));
|
||||
}
|
||||
}
|
||||
if b64.is_empty() {
|
||||
return Err("No signature data found in armored input".to_string());
|
||||
}
|
||||
py_b64decode(&b64)
|
||||
}
|
||||
|
||||
/// Python `base64.b64decode` without `validate`: characters outside the
|
||||
/// alphabet are skipped and padding is checked as `binascii` does.
|
||||
fn py_b64decode(text: &str) -> Result<Vec<u8>, String> {
|
||||
if !text.is_ascii() {
|
||||
return Err("string argument should contain only ASCII characters".to_string());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let (mut quad, mut left, mut pads) = (0, 0u8, 0);
|
||||
for c in text.bytes() {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
b'=' => {
|
||||
pads += 1;
|
||||
continue;
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
pads = 0;
|
||||
match quad {
|
||||
0 => {
|
||||
left = v;
|
||||
quad = 1;
|
||||
}
|
||||
1 => {
|
||||
out.push((left << 2) | (v >> 4));
|
||||
left = v & 0x0f;
|
||||
quad = 2;
|
||||
}
|
||||
2 => {
|
||||
out.push((left << 4) | (v >> 2));
|
||||
left = v & 0x03;
|
||||
quad = 3;
|
||||
}
|
||||
_ => {
|
||||
out.push((left << 6) | v);
|
||||
quad = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
match quad {
|
||||
1 => Err(format!(
|
||||
"Invalid base64-encoded string: number of data characters ({}) cannot be 1 more than a multiple of 4",
|
||||
out.len() / 3 * 4 + 1
|
||||
)),
|
||||
2 | 3 if quad + pads < 4 => Err("Incorrect padding".to_string()),
|
||||
_ => Ok(out),
|
||||
}
|
||||
}
|
||||
|
||||
/// `get_pubkey_wire_format`: the OpenSSH `ssh-ed25519` public key blob.
|
||||
pub fn get_pubkey_wire_format(identity: &Identity) -> Vec<u8> {
|
||||
let mut wire = ssh_string(b"ssh-ed25519");
|
||||
wire.extend_from_slice(&ssh_string(&identity.get_public_key()[32..]));
|
||||
wire
|
||||
}
|
||||
|
||||
/// An email taken from a commit header. `DecodeError` is the int 1 upstream
|
||||
/// returns after failing to decode it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HeaderEmail {
|
||||
Email(String),
|
||||
DecodeError,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for HeaderEmail {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
HeaderEmail::Email(email) => f.write_str(email),
|
||||
HeaderEmail::DecodeError => f.write_str("1"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `bytes.splitlines()`.
|
||||
fn bytes_splitlines(data: &[u8]) -> Vec<&[u8]> {
|
||||
let mut lines = Vec::new();
|
||||
let (mut start, mut i) = (0, 0);
|
||||
while i < data.len() {
|
||||
match data[i] {
|
||||
b'\n' => {
|
||||
lines.push(&data[start..i]);
|
||||
start = i + 1;
|
||||
}
|
||||
b'\r' => {
|
||||
lines.push(&data[start..i]);
|
||||
if data.get(i + 1) == Some(&b'\n') {
|
||||
i += 1;
|
||||
}
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if start < data.len() {
|
||||
lines.push(&data[start..]);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// The `<email>` of a header line, under upstream's bounds.
|
||||
fn header_email(line: &[u8], target: &[u8]) -> Option<Result<String, ()>> {
|
||||
let spos = line.iter().position(|b| *b == b'<')?;
|
||||
let epos = line.iter().position(|b| *b == b'>')?;
|
||||
if spos > target.len() && epos > spos && epos + 1 < line.len() {
|
||||
Some(String::from_utf8(line[spos + 1..epos].to_vec()).map_err(|_| ()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_header(message: &[u8], target: &[u8], what: &str) -> HeaderEmail {
|
||||
for line in bytes_splitlines(message) {
|
||||
if line.is_empty() {
|
||||
break;
|
||||
}
|
||||
if line.starts_with(target) {
|
||||
match header_email(line, target) {
|
||||
Some(Ok(email)) => return HeaderEmail::Email(email),
|
||||
Some(Err(())) => {
|
||||
println!("Error while determining {what} from signed commit");
|
||||
return HeaderEmail::DecodeError;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
HeaderEmail::Email(String::new())
|
||||
}
|
||||
|
||||
/// `extract_commit_author`.
|
||||
pub fn extract_commit_author(message: &[u8]) -> HeaderEmail {
|
||||
extract_header(message, b"author ", "author")
|
||||
}
|
||||
|
||||
/// `extract_commit_committer`.
|
||||
pub fn extract_commit_committer(message: &[u8]) -> HeaderEmail {
|
||||
extract_header(message, b"committer ", "committer")
|
||||
}
|
||||
|
||||
/// `extract_commit_tagger`: `(tagger, is_tag)`, or `None` where upstream
|
||||
/// returns the int 1 after a decode failure.
|
||||
pub fn extract_commit_tagger(message: &[u8]) -> Option<(String, bool)> {
|
||||
let mut is_tag = false;
|
||||
for line in bytes_splitlines(message) {
|
||||
if line.is_empty() {
|
||||
break;
|
||||
} else if line.starts_with(b"tag ") {
|
||||
is_tag = true;
|
||||
} else if line.starts_with(b"tagger ") && is_tag {
|
||||
match header_email(line, b"tagger ") {
|
||||
Some(Ok(email)) => return Some((email, is_tag)),
|
||||
Some(Err(())) => {
|
||||
println!("Error while determining tagger from signed commit");
|
||||
return None;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some((String::new(), is_tag))
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
usage: rngcs-rs [-h] -Y {sign,find-principals,check-novalidate,verify}
|
||||
[-n NAMESPACE] [-f KEYFILE] [-I PRINCIPAL] [-s SIGFILE]
|
||||
[-O SSH_OPTIONS]
|
||||
[file]
|
||||
|
||||
Git commit signer and validator
|
||||
|
||||
positional arguments:
|
||||
file File to sign (for signing)
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
-Y {sign,find-principals,check-novalidate,verify}
|
||||
Operation to perform
|
||||
-n NAMESPACE Namespace
|
||||
-f KEYFILE Key file (for signing) or allowed signers file (for
|
||||
verification)
|
||||
-I PRINCIPAL Principal identity (for verification)
|
||||
-s SIGFILE Signature file
|
||||
-O SSH_OPTIONS SSH options (for git compatibility, ignored)
|
||||
@@ -0,0 +1,351 @@
|
||||
//! Micron syntax highlighting: a port of `RNS/Utilities/rngit/highlight.py`.
|
||||
//!
|
||||
//! Upstream colours code only when the optional Pygments package is
|
||||
//! installed (`highlight.py`). This port has no lexer and
|
||||
//! always takes upstream's path without Pygments (`highlight.py`):
|
||||
//! a Micron literal block. [`MicronFormatter`] is ported for token streams
|
||||
//! from any lexer that names its tokens the way Pygments does.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Theme key to `rrggbb` colour; `None` means no colour tag.
|
||||
pub type Theme = HashMap<String, Option<String>>;
|
||||
|
||||
/// Python `SyntaxHighlighter._get_default_theme` (`highlight.py`).
|
||||
pub fn default_theme() -> Theme {
|
||||
DEFAULT_THEME
|
||||
.iter()
|
||||
.map(|(k, v)| (k.to_string(), v.map(str::to_string)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Python `SyntaxHighlighter` (`highlight.py`) without Pygments.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SyntaxHighlighter {
|
||||
pub theme: Theme,
|
||||
}
|
||||
|
||||
impl Default for SyntaxHighlighter {
|
||||
fn default() -> Self {
|
||||
Self::new(None)
|
||||
}
|
||||
}
|
||||
|
||||
impl SyntaxHighlighter {
|
||||
pub fn new(theme: Option<Theme>) -> Self {
|
||||
Self {
|
||||
theme: theme.unwrap_or_else(default_theme),
|
||||
}
|
||||
}
|
||||
|
||||
/// Always false: no Pygments-compatible lexer is built in.
|
||||
pub fn pygments_available(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Python `highlight` (`highlight.py`). Upstream doubles
|
||||
/// backslashes on every path except empty content.
|
||||
pub fn highlight(
|
||||
&self,
|
||||
content: &str,
|
||||
_filename: Option<&str>,
|
||||
_language: Option<&str>,
|
||||
) -> String {
|
||||
if content.is_empty() {
|
||||
return plain_text(content);
|
||||
}
|
||||
plain_text(content).replace('\\', "\\\\")
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `highlight_code` (`highlight.py`).
|
||||
pub fn highlight_code(
|
||||
content: &str,
|
||||
filename: Option<&str>,
|
||||
language: Option<&str>,
|
||||
theme: Option<Theme>,
|
||||
) -> String {
|
||||
SyntaxHighlighter::new(theme).highlight(content, filename, language)
|
||||
}
|
||||
|
||||
/// Python `_plain_text` (`highlight.py`).
|
||||
fn plain_text(content: &str) -> String {
|
||||
format!("`=\n{}\n`=", content.replace('`', "\\`"))
|
||||
}
|
||||
|
||||
/// Python `MicronFormatter` (`highlight.py`).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MicronFormatter {
|
||||
pub theme: Theme,
|
||||
}
|
||||
|
||||
impl MicronFormatter {
|
||||
pub fn new(theme: Theme) -> Self {
|
||||
Self { theme }
|
||||
}
|
||||
|
||||
/// Python `format` (`highlight.py`). A token type is its dotted
|
||||
/// Pygments name, such as `Token.Name.Function`.
|
||||
pub fn format<'a>(&self, tokens: impl IntoIterator<Item = (&'a str, &'a str)>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut prev_was_dot = false;
|
||||
let mut last_ended_with_break = true;
|
||||
for (ttype, value) in tokens {
|
||||
let is_dot = ttype == "Token.Operator" && value == ".";
|
||||
let ends_with_break = value.ends_with('\n');
|
||||
let escaped = escape_value(value);
|
||||
if prev_was_dot && ttype.starts_with("Token.Name") && !value.is_empty() {
|
||||
match self.color_from_key(Some("attribute_call")) {
|
||||
Some(color) => out.push_str(&format!("`FT{color}{escaped}`f")),
|
||||
None => out.push_str(&escaped),
|
||||
}
|
||||
} else if let Some(color) = self
|
||||
.color_from_key(color_key_for_token(ttype))
|
||||
.filter(|_| !value.is_empty())
|
||||
{
|
||||
let mut inner = escaped.as_str();
|
||||
let ilb = if let Some(s) = inner.strip_prefix('\n') {
|
||||
inner = s;
|
||||
"\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let tlb = if let Some(s) = inner.strip_suffix('\n') {
|
||||
inner = s;
|
||||
"\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
if inner.is_empty() {
|
||||
out.push_str(&format!("{ilb}{tlb}"));
|
||||
} else {
|
||||
out.push_str(&format!("{ilb}`FT{color}{inner}`f{tlb}"));
|
||||
}
|
||||
} else if escaped.contains('\n') {
|
||||
let lines = py_splitlines(&escaped);
|
||||
if lines.len() > 1 {
|
||||
let parts: Vec<String> = lines.iter().map(|l| escape_line_start(l)).collect();
|
||||
out.push_str(&parts.join("\n"));
|
||||
if escaped.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
} else {
|
||||
out.push_str(&escaped);
|
||||
}
|
||||
} else if last_ended_with_break {
|
||||
out.push_str(&escape_line_start(&escaped));
|
||||
} else {
|
||||
out.push_str(&escaped);
|
||||
}
|
||||
prev_was_dot = is_dot;
|
||||
last_ended_with_break = ends_with_break;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn color_from_key(&self, key: Option<&str>) -> Option<&str> {
|
||||
self.theme.get(key?)?.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `_get_color_key_for_token` (`highlight.py`): the nearest
|
||||
/// mapped ancestor of the token type.
|
||||
fn color_key_for_token(ttype: &str) -> Option<&'static str> {
|
||||
let mut current = Some(ttype);
|
||||
while let Some(t) = current {
|
||||
if let Some((_, key)) = GRANULAR_TOKEN_MAP.iter().find(|(name, _)| *name == t) {
|
||||
return Some(key);
|
||||
}
|
||||
current = t.rsplit_once('.').map(|(parent, _)| parent);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Python `_escape_value` (`highlight.py`).
|
||||
fn escape_value(value: &str) -> String {
|
||||
value.replace('\\', "\\\\").replace('`', "\\`")
|
||||
}
|
||||
|
||||
fn escape_line_start(line: &str) -> String {
|
||||
if line.starts_with(['-', '>', '<']) {
|
||||
format!("\\{line}")
|
||||
} else {
|
||||
line.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `str.splitlines()`.
|
||||
fn py_splitlines(s: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut it = s.char_indices().peekable();
|
||||
while let Some((i, c)) = it.next() {
|
||||
let boundary = matches!(
|
||||
c,
|
||||
'\n' | '\r'
|
||||
| '\x0b'
|
||||
| '\x0c'
|
||||
| '\x1c'
|
||||
| '\x1d'
|
||||
| '\x1e'
|
||||
| '\u{85}'
|
||||
| '\u{2028}'
|
||||
| '\u{2029}'
|
||||
);
|
||||
if boundary {
|
||||
lines.push(&s[start..i]);
|
||||
let mut end = i + c.len_utf8();
|
||||
if c == '\r' && it.peek().map(|p| p.1) == Some('\n') {
|
||||
it.next();
|
||||
end += 1;
|
||||
}
|
||||
start = end;
|
||||
}
|
||||
}
|
||||
if start < s.len() {
|
||||
lines.push(&s[start..]);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
const DEFAULT_THEME: [(&str, Option<&str>); 58] = [
|
||||
("keyword", Some("ff7b72")),
|
||||
("keyword_constant", Some("ff7b72")),
|
||||
("keyword_control", Some("ff7b72")),
|
||||
("keyword_declaration", Some("ff7b72")),
|
||||
("function_def", Some("79c0ff")),
|
||||
("function_magic", Some("ff7b72")),
|
||||
("function_call", Some("d2a8ff")),
|
||||
("function_builtin", Some("ffa657")),
|
||||
("class_def", Some("7ee787")),
|
||||
("class_ref", Some("56d364")),
|
||||
("self", Some("ff9bce")),
|
||||
("cls", Some("ff9bce")),
|
||||
("string", Some("a5d6ff")),
|
||||
("string_quoted", Some("a5d6ff")),
|
||||
("string_doc", Some("8b949e")),
|
||||
("string_interpol", Some("ffd700")),
|
||||
("string_escape", Some("ffea00")),
|
||||
("number", Some("79c0ff")),
|
||||
("number_float", Some("79c0ff")),
|
||||
("number_integer", Some("79c0ff")),
|
||||
("number_hex", Some("79c0ff")),
|
||||
("comment", Some("8b949e")),
|
||||
("comment_doc", Some("8b949e")),
|
||||
("comment_preproc", Some("ff7b72")),
|
||||
("operator", Some("ff7b72")),
|
||||
("operator_arithmetic", Some("ff7b72")),
|
||||
("operator_comparison", Some("ff7b72")),
|
||||
("operator_assignment", Some("ff7b72")),
|
||||
("operator_word", Some("ff7b72")),
|
||||
("operator_dot", Some("c9d1d9")),
|
||||
("punctuation", Some("b4b4b4")),
|
||||
("punctuation_brace", Some("b4b4b4")),
|
||||
("punctuation_paren", Some("b4b4b4")),
|
||||
("punctuation_colon", Some("b4b4b4")),
|
||||
("punctuation_comma", Some("8b949e")),
|
||||
("decorator", Some("f0883e")),
|
||||
("constant", Some("ff7b72")),
|
||||
("constant_builtin", Some("ff7b72")),
|
||||
("type_hint", Some("ffa657")),
|
||||
("type_builtin", Some("ffa657")),
|
||||
("exception", Some("f85149")),
|
||||
("exception_builtin", Some("f85149")),
|
||||
("name", Some("e6edf3")),
|
||||
("attribute", Some("e6edf3")),
|
||||
("attribute_call", Some("d2a8ff")),
|
||||
("variable", Some("e6edf3")),
|
||||
("parameter", Some("e6edf3")),
|
||||
("namespace", Some("7ee787")),
|
||||
("module", Some("a5d6ff")),
|
||||
("generic_heading", Some("c9d1d9")),
|
||||
("generic_subheading", Some("c9d1d9")),
|
||||
("generic_prompt", Some("8b949e")),
|
||||
("generic_error", Some("f85149")),
|
||||
("generic_deleted", Some("f85149")),
|
||||
("generic_inserted", Some("7ee787")),
|
||||
("generic_output", Some("e6edf3")),
|
||||
("text", None),
|
||||
("whitespace", None),
|
||||
];
|
||||
|
||||
const GRANULAR_TOKEN_MAP: [(&str, &str); 78] = [
|
||||
("Token.Keyword", "keyword"),
|
||||
("Token.Keyword.Constant", "keyword_constant"),
|
||||
("Token.Keyword.Declaration", "keyword_declaration"),
|
||||
("Token.Keyword.Namespace", "keyword_control"),
|
||||
("Token.Keyword.Pseudo", "keyword_control"),
|
||||
("Token.Keyword.Reserved", "keyword_control"),
|
||||
("Token.Keyword.Type", "type_builtin"),
|
||||
("Token.Name.Function", "function_call"),
|
||||
("Token.Name.Function.Magic", "function_magic"),
|
||||
("Token.Name.Class", "class_ref"),
|
||||
("Token.Name.Builtin", "function_builtin"),
|
||||
("Token.Name.Builtin.Pseudo", "constant_builtin"),
|
||||
("Token.Name.Exception", "exception_builtin"),
|
||||
("Token.Name.Decorator", "decorator"),
|
||||
("Token.Name.Namespace", "namespace"),
|
||||
("Token.Name.Attribute", "attribute"),
|
||||
("Token.Name.Variable", "variable"),
|
||||
("Token.Name.Variable.Magic", "function_magic"),
|
||||
("Token.Name.Other", "name"),
|
||||
("Token.Name", "name"),
|
||||
("Token.Name.Tag", "keyword"),
|
||||
("Token.Name.Constant", "constant"),
|
||||
("Token.Name.Label", "name"),
|
||||
("Token.Name.Entity", "name"),
|
||||
("Token.Literal.String", "string"),
|
||||
("Token.Literal.String.Affix", "string"),
|
||||
("Token.Literal.String.Backtick", "string"),
|
||||
("Token.Literal.String.Char", "string"),
|
||||
("Token.Literal.String.Delimiter", "string"),
|
||||
("Token.Literal.String.Doc", "string_doc"),
|
||||
("Token.Literal.String.Double", "string_quoted"),
|
||||
("Token.Literal.String.Escape", "string_escape"),
|
||||
("Token.Literal.String.Heredoc", "string"),
|
||||
("Token.Literal.String.Interpol", "string_interpol"),
|
||||
("Token.Literal.String.Other", "string"),
|
||||
("Token.Literal.String.Regex", "string"),
|
||||
("Token.Literal.String.Single", "string_quoted"),
|
||||
("Token.Literal.String.Symbol", "string"),
|
||||
("Token.Literal.Number", "number"),
|
||||
("Token.Literal.Number.Bin", "number"),
|
||||
("Token.Literal.Number.Float", "number_float"),
|
||||
("Token.Literal.Number.Hex", "number_hex"),
|
||||
("Token.Literal.Number.Integer", "number_integer"),
|
||||
("Token.Literal.Number.Integer.Long", "number_integer"),
|
||||
("Token.Literal.Number.Oct", "number"),
|
||||
("Token.Literal", "string"),
|
||||
("Token.Literal.Date", "string"),
|
||||
("Token.Operator", "operator"),
|
||||
("Token.Operator.Word", "operator_word"),
|
||||
("Token.Operator.Comparison", "operator_comparison"),
|
||||
("Token.Operator.Assignment", "operator_assignment"),
|
||||
("Token.Operator.Arithmetic", "operator_arithmetic"),
|
||||
("Token.Punctuation", "punctuation"),
|
||||
("Token.Punctuation.Marker", "punctuation"),
|
||||
("Token.Punctuation.Brace", "punctuation_brace"),
|
||||
("Token.Punctuation.Bracket", "punctuation_brace"),
|
||||
("Token.Punctuation.Parenthesis", "punctuation_paren"),
|
||||
("Token.Punctuation.Colon", "punctuation_colon"),
|
||||
("Token.Punctuation.Comma", "punctuation_comma"),
|
||||
("Token.Comment", "comment"),
|
||||
("Token.Comment.Hashbang", "comment"),
|
||||
("Token.Comment.Multiline", "comment_doc"),
|
||||
("Token.Comment.Preproc", "comment_preproc"),
|
||||
("Token.Comment.Single", "comment"),
|
||||
("Token.Comment.Special", "comment"),
|
||||
("Token.Generic.Deleted", "generic_deleted"),
|
||||
("Token.Generic.Emph", "text"),
|
||||
("Token.Generic.Error", "generic_error"),
|
||||
("Token.Generic.Heading", "generic_heading"),
|
||||
("Token.Generic.Inserted", "generic_inserted"),
|
||||
("Token.Generic.Output", "generic_output"),
|
||||
("Token.Generic.Prompt", "generic_prompt"),
|
||||
("Token.Generic.Strong", "text"),
|
||||
("Token.Generic.Subheading", "generic_subheading"),
|
||||
("Token.Generic.Traceback", "generic_error"),
|
||||
("Token.Generic", "text"),
|
||||
("Token.Text", "text"),
|
||||
("Token.Text.Whitespace", "whitespace"),
|
||||
];
|
||||
@@ -0,0 +1,12 @@
|
||||
//! Git over Reticulum: a port of `RNS/Utilities/rngit` from Reticulum 1.6.0.
|
||||
|
||||
pub mod client;
|
||||
pub mod commitsigs;
|
||||
pub mod highlight;
|
||||
pub mod md2micron;
|
||||
pub mod media;
|
||||
pub mod pages;
|
||||
mod platform;
|
||||
pub mod remote_helper;
|
||||
pub mod server;
|
||||
pub mod util;
|
||||
@@ -0,0 +1,966 @@
|
||||
//! Markdown to Micron conversion: a port of `MarkdownToMicron` and
|
||||
//! `convert_markdown_to_micron` from `RNS/Utilities/rngit/util.py`
|
||||
//! (`:79-816`).
|
||||
//!
|
||||
//! Upstream's regular expressions are matched by hand with the same Python
|
||||
//! `re` semantics: `\s` is Python's Unicode whitespace, `\d` any Unicode
|
||||
//! decimal digit. Display width is the character count, which is what
|
||||
//! upstream uses when the optional `wcwidth` module is absent
|
||||
//! (`util.py`). Input lines never contain `\n`: `format_block`
|
||||
//! splits on it first, as upstream does.
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::fmt;
|
||||
|
||||
use crate::highlight::SyntaxHighlighter;
|
||||
|
||||
/// A Python exception upstream raises while converting.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MarkdownError {
|
||||
/// Python `IndexError`: the input holds a `\0LINKn\0` or `\0CODEn\0`
|
||||
/// placeholder naming a link or code span that does not exist.
|
||||
PlaceholderIndex,
|
||||
/// Python `ValueError`: a placeholder index longer than the 4300 digits
|
||||
/// Python `int()` accepts.
|
||||
PlaceholderDigits,
|
||||
}
|
||||
|
||||
impl fmt::Display for MarkdownError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::PlaceholderIndex => f.write_str("placeholder index out of range"),
|
||||
Self::PlaceholderDigits => f.write_str("placeholder index has too many digits"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for MarkdownError {}
|
||||
|
||||
/// Column alignment parsed from a table separator row.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Align {
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
}
|
||||
|
||||
/// Python `MarkdownToMicron` (`util.py`).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MarkdownToMicron {
|
||||
pub max_width: usize,
|
||||
pub local_url_scope: String,
|
||||
initial_url_scope: String,
|
||||
pub syntax_highlighter: Option<SyntaxHighlighter>,
|
||||
pub bold_links: bool,
|
||||
pub underline_links: bool,
|
||||
pub link_color: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for MarkdownToMicron {
|
||||
fn default() -> Self {
|
||||
Self::new(100, None, None)
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `convert_markdown_to_micron` (`util.py`).
|
||||
pub fn convert_markdown_to_micron(text: &str) -> Result<String, MarkdownError> {
|
||||
MarkdownToMicron::default().format_block(text)
|
||||
}
|
||||
|
||||
impl MarkdownToMicron {
|
||||
pub const BOLD: &'static str = "`!";
|
||||
pub const BOLD_END: &'static str = "`!";
|
||||
pub const ITALIC: &'static str = "`*";
|
||||
pub const ITALIC_END: &'static str = "`*";
|
||||
pub const UNDERLINE: &'static str = "`_";
|
||||
pub const UNDERLINE_END: &'static str = "`_";
|
||||
pub const CODE_BG: &'static str = "`BT282828";
|
||||
pub const CODE_BG_INLINE: &'static str = "`BT383838";
|
||||
pub const CODE_FG: &'static str = "`Fddd";
|
||||
pub const CODE_RESET: &'static str = "`f`b";
|
||||
pub const LITERAL_START: &'static str = "`=";
|
||||
pub const LITERAL_END: &'static str = "`=";
|
||||
pub const BULLET: &'static str = "•";
|
||||
pub const TABLE_H: char = '─';
|
||||
pub const TABLE_V: char = '│';
|
||||
pub const TABLE_TL: char = '┌';
|
||||
pub const TABLE_TR: char = '┐';
|
||||
pub const TABLE_BL: char = '└';
|
||||
pub const TABLE_BR: char = '┘';
|
||||
pub const TABLE_ML: char = '├';
|
||||
pub const TABLE_MR: char = '┤';
|
||||
pub const TABLE_TM: char = '┬';
|
||||
pub const TABLE_BM: char = '┴';
|
||||
pub const TABLE_MM: char = '┼';
|
||||
pub const TABLE_MIN_COL_WIDTH: usize = 3;
|
||||
|
||||
/// An empty or absent `url_scope` selects `:/page/`, as upstream's
|
||||
/// `url_scope or ":/page/"` does (`util.py`).
|
||||
pub fn new(
|
||||
max_width: usize,
|
||||
syntax_highlighter: Option<SyntaxHighlighter>,
|
||||
url_scope: Option<&str>,
|
||||
) -> Self {
|
||||
let scope = match url_scope {
|
||||
Some(s) if !s.is_empty() => s,
|
||||
_ => ":/page/",
|
||||
};
|
||||
Self {
|
||||
max_width,
|
||||
local_url_scope: scope.to_string(),
|
||||
initial_url_scope: scope.to_string(),
|
||||
syntax_highlighter,
|
||||
bold_links: true,
|
||||
underline_links: true,
|
||||
link_color: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_url_scope(&mut self, url_scope: &str) {
|
||||
self.local_url_scope = url_scope.to_string();
|
||||
}
|
||||
|
||||
/// Back to the scope given at construction (`util.py`).
|
||||
pub fn restore_url_scope(&mut self) {
|
||||
self.local_url_scope = self.initial_url_scope.clone();
|
||||
}
|
||||
|
||||
pub fn display_width(&self, text: &[char]) -> usize {
|
||||
text.len()
|
||||
}
|
||||
|
||||
/// Python `format_block` (`util.py`).
|
||||
pub fn format_block(&self, text: &str) -> Result<String, MarkdownError> {
|
||||
let mut st = BlockState::default();
|
||||
for line in text.split('\n') {
|
||||
if let Some(lang_hint) = detect_code_fence(line) {
|
||||
st.flush_quote(self)?;
|
||||
st.flush_table(self)?;
|
||||
if !st.in_code_block {
|
||||
st.in_code_block = true;
|
||||
st.code_block_lang =
|
||||
(!lang_hint.is_empty()).then(|| py_strip(lang_hint).to_string());
|
||||
st.code_buffer.clear();
|
||||
} else {
|
||||
st.flush_code(self);
|
||||
st.in_code_block = false;
|
||||
st.code_block_lang = None;
|
||||
}
|
||||
} else if st.in_code_block {
|
||||
st.code_buffer.push(line.to_string());
|
||||
} else if let Some(quoted) = quote_match(line) {
|
||||
if !st.in_quote {
|
||||
st.flush_table(self)?;
|
||||
st.in_quote = true;
|
||||
st.quote_buffer.clear();
|
||||
}
|
||||
st.quote_buffer.push(quoted.to_string());
|
||||
} else if st.in_quote {
|
||||
st.flush_quote(self)?;
|
||||
if !py_strip(line).is_empty() {
|
||||
if is_table_row(line) {
|
||||
st.in_table = true;
|
||||
st.table_buffer = vec![line.to_string()];
|
||||
} else {
|
||||
st.out.push(self.format_line(line)?);
|
||||
}
|
||||
} else {
|
||||
st.out.push(String::new());
|
||||
}
|
||||
} else if is_table_row(line) {
|
||||
if !st.in_table {
|
||||
st.in_table = true;
|
||||
st.table_buffer = vec![line.to_string()];
|
||||
} else {
|
||||
st.table_buffer.push(line.to_string());
|
||||
}
|
||||
} else {
|
||||
if st.in_table {
|
||||
st.flush_table(self)?;
|
||||
}
|
||||
st.out.push(self.format_line(line)?);
|
||||
}
|
||||
}
|
||||
if st.in_quote {
|
||||
st.flush_quote(self)?;
|
||||
}
|
||||
if st.in_table {
|
||||
st.flush_table(self)?;
|
||||
}
|
||||
if st.in_code_block {
|
||||
st.flush_code(self);
|
||||
}
|
||||
Ok(st.out.join("\n"))
|
||||
}
|
||||
|
||||
/// Python `format_line(line)` (`util.py`).
|
||||
pub fn format_line(&self, line: &str) -> Result<String, MarkdownError> {
|
||||
let mut line = line.replace('\\', "\\\\");
|
||||
if line.starts_with('-') && !line.starts_with("---") && !line.starts_with("- ") {
|
||||
line = format!("\\{line}");
|
||||
}
|
||||
if line.starts_with('<') {
|
||||
line = format!("\\{line}");
|
||||
}
|
||||
let c: Vec<char> = line.chars().collect();
|
||||
if is_horizontal_rule(&c) {
|
||||
return Ok("-".to_string());
|
||||
}
|
||||
if let Some((level, content)) = match_header(&c) {
|
||||
let content: String = content.iter().collect();
|
||||
return Ok(format!(
|
||||
"{}{}",
|
||||
">".repeat(level.min(6)),
|
||||
self.format_inline(&content)?
|
||||
));
|
||||
}
|
||||
if let Some((indent, content)) = match_list_item(&c) {
|
||||
let indent: String = indent.iter().collect();
|
||||
let content: String = content.iter().collect();
|
||||
return Ok(format!(
|
||||
"{indent} {} {}",
|
||||
Self::BULLET,
|
||||
self.format_inline(&content)?
|
||||
));
|
||||
}
|
||||
self.format_inline(&line)
|
||||
}
|
||||
|
||||
/// Python `format_line(line, mode="codeblock")` (`util.py`).
|
||||
pub fn format_codeblock_line(&self, line: &str) -> String {
|
||||
escape_literals(line)
|
||||
}
|
||||
|
||||
/// Python `_format_inline` (`util.py`).
|
||||
pub fn format_inline(&self, text: &str) -> Result<String, MarkdownError> {
|
||||
let mut links: Vec<(String, String)> = Vec::new();
|
||||
let mut codes: Vec<String> = Vec::new();
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
let text = sub_links(&c, &mut links);
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
let text = sub_inline_code(&c, &mut codes);
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
let text = sub_emphasis(&c, '*', 2, Self::BOLD, Self::BOLD_END);
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
let text = sub_emphasis(&c, '*', 1, Self::ITALIC, Self::ITALIC_END);
|
||||
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
let text = sub_placeholders(&c, "LINK", |idx| {
|
||||
let (text, url) = links.get(idx).ok_or(MarkdownError::PlaceholderIndex)?;
|
||||
Ok(self.restore_link(text, url))
|
||||
})?;
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
sub_placeholders(&c, "CODE", |idx| {
|
||||
let content = codes.get(idx).ok_or(MarkdownError::PlaceholderIndex)?;
|
||||
Ok(format!(
|
||||
"{}{}{}{}",
|
||||
Self::CODE_BG_INLINE,
|
||||
Self::CODE_FG,
|
||||
content.replace('`', "\\`"),
|
||||
Self::CODE_RESET
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
fn restore_link(&self, text: &str, url: &str) -> String {
|
||||
let mut components = url.split('#');
|
||||
let mut url = components.next().unwrap_or("").to_string();
|
||||
let anchor = components.next().unwrap_or("");
|
||||
if !url.contains(":/") {
|
||||
url = format!("{}{url}", self.local_url_scope);
|
||||
if !anchor.is_empty() {
|
||||
url = format!("{url}|anchor={anchor}");
|
||||
}
|
||||
}
|
||||
let undl = if self.underline_links { "`_" } else { "" };
|
||||
let bold = if self.bold_links { "`!" } else { "" };
|
||||
let text = text.replace('`', "");
|
||||
let link = format!("{undl}{bold}`[{text}`{url}]{bold}{undl}");
|
||||
match self.link_color.as_deref() {
|
||||
Some(c) if c.chars().count() == 3 => format!("`F{c}{link}`f"),
|
||||
Some(c) if c.chars().count() == 6 => format!("`FT{c}{link}`f"),
|
||||
_ => link,
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `format_table` (`util.py`); `align` empty means none.
|
||||
pub fn format_table(&self, rows: &[String], align: &str) -> Result<Vec<String>, MarkdownError> {
|
||||
self.table(rows, align, false, |cell| self.format_inline(cell))
|
||||
}
|
||||
|
||||
/// Python `format_table_raw` (`util.py`): cells are not formatted
|
||||
/// and the header row is not escaped.
|
||||
pub fn format_table_raw(&self, rows: &[String], align: &str) -> Vec<String> {
|
||||
let Ok(lines) = self.table(rows, align, true, |cell| {
|
||||
Ok::<_, Infallible>(cell.to_string())
|
||||
});
|
||||
lines
|
||||
}
|
||||
|
||||
fn table<E>(
|
||||
&self,
|
||||
rows: &[String],
|
||||
align: &str,
|
||||
raw: bool,
|
||||
fmt: impl Fn(&str) -> Result<String, E>,
|
||||
) -> Result<Vec<String>, E> {
|
||||
if rows.len() < 2 {
|
||||
return Ok(rows.to_vec());
|
||||
}
|
||||
let header_cells = parse_table_row(&rows[0]);
|
||||
let num_cols = header_cells.len();
|
||||
let mut alignments = parse_table_alignments(&rows[1]);
|
||||
alignments.resize(num_cols, Align::Left);
|
||||
let data_rows: Vec<Vec<String>> = rows[2..]
|
||||
.iter()
|
||||
.map(|row| {
|
||||
let mut cells = parse_table_row(row);
|
||||
cells.resize(num_cols, String::new());
|
||||
cells
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut col_widths = vec![0usize; num_cols];
|
||||
for row in std::iter::once(&header_cells).chain(data_rows.iter()) {
|
||||
for (i, cell) in row.iter().enumerate() {
|
||||
let formatted: Vec<char> = fmt(cell)?.chars().collect();
|
||||
col_widths[i] = col_widths[i].max(self.visible_width(&formatted));
|
||||
}
|
||||
}
|
||||
for w in &mut col_widths {
|
||||
*w = (*w).max(Self::TABLE_MIN_COL_WIDTH);
|
||||
}
|
||||
|
||||
let total_width = col_widths.iter().sum::<usize>() + num_cols * 3 + 1;
|
||||
if total_width > self.max_width {
|
||||
let mut excess = total_width - self.max_width;
|
||||
let mut indexed: Vec<(usize, usize)> = col_widths.iter().copied().enumerate().collect();
|
||||
indexed.sort_by_key(|&(_, w)| std::cmp::Reverse(w));
|
||||
for (i, w) in indexed {
|
||||
if excess == 0 {
|
||||
break;
|
||||
}
|
||||
let reduction = excess.min(w - Self::TABLE_MIN_COL_WIDTH);
|
||||
col_widths[i] -= reduction;
|
||||
excess -= reduction;
|
||||
}
|
||||
}
|
||||
|
||||
let border = |left: char, mid: char, right: char| {
|
||||
let mut s = String::from(left);
|
||||
for (i, w) in col_widths.iter().enumerate() {
|
||||
s.extend(std::iter::repeat_n(Self::TABLE_H, w + 2));
|
||||
s.push(if i < num_cols - 1 { mid } else { right });
|
||||
}
|
||||
escape_literals(&s)
|
||||
};
|
||||
|
||||
let mut result = Vec::new();
|
||||
if !align.is_empty() {
|
||||
result.push(format!("`{align}"));
|
||||
}
|
||||
result.push(border(Self::TABLE_TL, Self::TABLE_TM, Self::TABLE_TR));
|
||||
|
||||
let mut header_line = String::from(Self::TABLE_V);
|
||||
for (i, cell) in header_cells.iter().enumerate() {
|
||||
let padded = self.pad_cell(&fmt(cell)?, col_widths[i], Align::Left);
|
||||
header_line.push_str(&format!(" {padded} {}", Self::TABLE_V));
|
||||
}
|
||||
result.push(if raw {
|
||||
header_line
|
||||
} else {
|
||||
escape_literals(&header_line)
|
||||
});
|
||||
|
||||
result.push(border(Self::TABLE_ML, Self::TABLE_MM, Self::TABLE_MR));
|
||||
|
||||
for row in &data_rows {
|
||||
let mut row_line = String::from(Self::TABLE_V);
|
||||
for (i, cell) in row.iter().enumerate() {
|
||||
let padded = self.pad_cell(&fmt(cell)?, col_widths[i], alignments[i]);
|
||||
row_line.push_str(&format!(" {padded} {}", Self::TABLE_V));
|
||||
}
|
||||
result.push(row_line);
|
||||
}
|
||||
|
||||
result.push(border(Self::TABLE_BL, Self::TABLE_BM, Self::TABLE_BR));
|
||||
if !align.is_empty() {
|
||||
result.push("`a".to_string());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Python `_visible_width` (`util.py`): the six tag patterns are
|
||||
/// removed one pass each, in upstream's order.
|
||||
fn visible_width(&self, text: &[char]) -> usize {
|
||||
let hex = |c: &[char], from: usize, n: usize| {
|
||||
c.len() >= from + n && c[from..from + n].iter().all(|x| x.is_ascii_hexdigit())
|
||||
};
|
||||
let is = |c: &[char], i: usize, s: &str| {
|
||||
s.chars().enumerate().all(|(k, x)| c.get(i + k) == Some(&x))
|
||||
};
|
||||
let mut s = remove_matches(text, |c, i| {
|
||||
(c[i] == '`' && matches!(c.get(i + 1), Some('F' | 'B')) && hex(c, i + 2, 3))
|
||||
.then_some(5)
|
||||
});
|
||||
s = remove_matches(&s, |c, i| {
|
||||
(c[i] == '`'
|
||||
&& matches!(c.get(i + 1), Some('F' | 'B'))
|
||||
&& c.get(i + 2) == Some(&'T')
|
||||
&& hex(c, i + 3, 6))
|
||||
.then_some(9)
|
||||
});
|
||||
s = remove_matches(&s, |c, i| {
|
||||
(c[i] == '`' && matches!(c.get(i + 1), Some('!' | '*' | '_' | '='))).then_some(2)
|
||||
});
|
||||
s = remove_matches(&s, |c, i| is(c, i, "`f`b").then_some(4));
|
||||
s = remove_matches(&s, |c, i| is(c, i, "`f").then_some(2));
|
||||
s = remove_matches(&s, |c, i| is(c, i, "`b").then_some(2));
|
||||
self.display_width(&s)
|
||||
}
|
||||
|
||||
/// Python `_pad_cell` (`util.py`).
|
||||
fn pad_cell(&self, text: &str, width: usize, align: Align) -> String {
|
||||
let text = self.truncate_cell(text, width);
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
let padding = width.saturating_sub(self.visible_width(&c));
|
||||
match align {
|
||||
Align::Right => format!("{}{text}", " ".repeat(padding)),
|
||||
Align::Center => {
|
||||
let left = padding / 2;
|
||||
format!("{}{text}{}", " ".repeat(left), " ".repeat(padding - left))
|
||||
}
|
||||
Align::Left => format!("{text}{}", " ".repeat(padding)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `_truncate_cell` (`util.py`). Upstream appends the open
|
||||
/// toggle closers in `set` order, which varies per process; this emits
|
||||
/// them in `!*_=` order, one of upstream's possible outputs.
|
||||
fn truncate_cell(&self, text: &str, width: usize) -> String {
|
||||
let c: Vec<char> = text.chars().collect();
|
||||
if self.visible_width(&c) <= width {
|
||||
return text.to_string();
|
||||
}
|
||||
let mut point = c.len();
|
||||
while point > 0 && self.visible_width(&c[..point]) >= width {
|
||||
point -= 1;
|
||||
}
|
||||
let t = &c[..point];
|
||||
|
||||
const TOGGLES: [char; 4] = ['!', '*', '_', '='];
|
||||
let mut active = [false; 4];
|
||||
let mut fg_active = false;
|
||||
let mut bg_active = false;
|
||||
let mut i = 0;
|
||||
while i < t.len() {
|
||||
if t[i] == '`' && i + 1 < t.len() {
|
||||
let tag = t[i + 1];
|
||||
if let Some(k) = TOGGLES.iter().position(|&x| x == tag) {
|
||||
active[k] = !active[k];
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
match tag {
|
||||
'f' | 'b' => {
|
||||
if tag == 'f' {
|
||||
fg_active = false;
|
||||
} else {
|
||||
bg_active = false;
|
||||
}
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
'F' | 'B' => {
|
||||
if tag == 'F' {
|
||||
fg_active = true;
|
||||
} else {
|
||||
bg_active = true;
|
||||
}
|
||||
i += if t.get(i + 2) == Some(&'T') { 8 } else { 5 };
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
let mut out: String = t.iter().collect();
|
||||
if fg_active {
|
||||
out.push_str("`f");
|
||||
}
|
||||
if bg_active {
|
||||
out.push_str("`b");
|
||||
}
|
||||
for (k, on) in active.iter().enumerate() {
|
||||
if *on {
|
||||
out.push('`');
|
||||
out.push(TOGGLES[k]);
|
||||
}
|
||||
}
|
||||
out.push('…');
|
||||
out
|
||||
}
|
||||
|
||||
/// Python `_wrap_text` (`util.py`).
|
||||
fn wrap_text(&self, text: &str, width: usize) -> Vec<String> {
|
||||
if text.is_empty() {
|
||||
return vec![String::new()];
|
||||
}
|
||||
let mut lines = Vec::new();
|
||||
let mut current_line = String::new();
|
||||
let mut current_width = 0;
|
||||
for word in text.split(' ') {
|
||||
if word.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let wc: Vec<char> = word.chars().collect();
|
||||
let word_width = self.visible_width(&wc);
|
||||
if word_width > width {
|
||||
if !current_line.is_empty() {
|
||||
lines.push(std::mem::take(&mut current_line));
|
||||
current_width = 0;
|
||||
}
|
||||
let mut remaining: &[char] = &wc;
|
||||
while !remaining.is_empty() {
|
||||
let (mut low, mut high) = (1usize, remaining.len());
|
||||
let mut fit = 0;
|
||||
while low <= high {
|
||||
let mid = (low + high) / 2;
|
||||
if self.visible_width(&remaining[..mid]) <= width {
|
||||
fit = mid;
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid - 1;
|
||||
}
|
||||
}
|
||||
if fit == 0 {
|
||||
fit = 1;
|
||||
}
|
||||
lines.push(remaining[..fit].iter().collect());
|
||||
remaining = &remaining[fit..];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let space_width = usize::from(!current_line.is_empty());
|
||||
if current_width + space_width + word_width <= width {
|
||||
if !current_line.is_empty() {
|
||||
current_line.push(' ');
|
||||
current_line.push_str(word);
|
||||
current_width += space_width + word_width;
|
||||
} else {
|
||||
current_line = word.to_string();
|
||||
current_width = word_width;
|
||||
}
|
||||
} else {
|
||||
lines.push(std::mem::replace(&mut current_line, word.to_string()));
|
||||
current_width = word_width;
|
||||
}
|
||||
}
|
||||
if !current_line.is_empty() {
|
||||
lines.push(current_line);
|
||||
}
|
||||
if lines.is_empty() {
|
||||
vec![String::new()]
|
||||
} else {
|
||||
lines
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BlockState {
|
||||
out: Vec<String>,
|
||||
in_code_block: bool,
|
||||
code_block_lang: Option<String>,
|
||||
code_buffer: Vec<String>,
|
||||
in_table: bool,
|
||||
table_buffer: Vec<String>,
|
||||
in_quote: bool,
|
||||
quote_buffer: Vec<String>,
|
||||
}
|
||||
|
||||
impl BlockState {
|
||||
fn flush_quote(&mut self, m: &MarkdownToMicron) -> Result<(), MarkdownError> {
|
||||
if self.quote_buffer.is_empty() {
|
||||
self.in_quote = false;
|
||||
return Ok(());
|
||||
}
|
||||
let formatted = m.format_inline(&self.quote_buffer.join(" "))?;
|
||||
let width = m.max_width.saturating_sub(3).max(1);
|
||||
for line in m.wrap_text(&formatted, width) {
|
||||
self.out.push(format!(" │ {line}"));
|
||||
}
|
||||
self.quote_buffer.clear();
|
||||
self.in_quote = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flush_table(&mut self, m: &MarkdownToMicron) -> Result<(), MarkdownError> {
|
||||
if self.table_buffer.is_empty() {
|
||||
self.in_table = false;
|
||||
return Ok(());
|
||||
}
|
||||
let rows = std::mem::take(&mut self.table_buffer);
|
||||
if rows.len() >= 2 && is_table_separator(&rows[1]) {
|
||||
self.out.extend(m.format_table(&rows, "c")?);
|
||||
} else {
|
||||
for line in &rows {
|
||||
self.out.push(m.format_line(line)?);
|
||||
}
|
||||
}
|
||||
self.in_table = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Upstream's `except Exception` fallback (`util.py`) has no
|
||||
/// counterpart: the highlighter here cannot fail.
|
||||
fn flush_code(&mut self, m: &MarkdownToMicron) {
|
||||
if self.code_buffer.is_empty() {
|
||||
return;
|
||||
}
|
||||
let code = self.code_buffer.join("\n");
|
||||
let lang = self.code_block_lang.as_deref().filter(|l| !l.is_empty());
|
||||
match (&m.syntax_highlighter, lang) {
|
||||
(Some(_), Some(lang)) if lang.to_lowercase() == "rawmu" => self.out.push(code),
|
||||
(Some(hl), Some(lang)) => {
|
||||
self.out.push(format!(
|
||||
"{}{}",
|
||||
MarkdownToMicron::CODE_BG,
|
||||
MarkdownToMicron::CODE_FG
|
||||
));
|
||||
self.out.push(hl.highlight(&code, None, Some(lang)));
|
||||
self.out.push(MarkdownToMicron::CODE_RESET.to_string());
|
||||
}
|
||||
_ => {
|
||||
self.out.push(format!(
|
||||
"{}{}",
|
||||
MarkdownToMicron::CODE_BG,
|
||||
MarkdownToMicron::CODE_FG
|
||||
));
|
||||
self.out.push(MarkdownToMicron::LITERAL_START.to_string());
|
||||
self.out.push(escape_literals(&code));
|
||||
self.out.push(MarkdownToMicron::LITERAL_END.to_string());
|
||||
self.out.push(MarkdownToMicron::CODE_RESET.to_string());
|
||||
}
|
||||
}
|
||||
self.code_buffer.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `re` `\s` and `str.isspace()`: Unicode White_Space plus U+001C..U+001F.
|
||||
fn py_space(c: char) -> bool {
|
||||
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
|
||||
}
|
||||
|
||||
fn py_strip(s: &str) -> &str {
|
||||
s.trim_matches(py_space)
|
||||
}
|
||||
|
||||
fn escape_literals(text: &str) -> String {
|
||||
text.replace('`', "\\`")
|
||||
}
|
||||
|
||||
fn leading_space(c: &[char]) -> usize {
|
||||
c.iter().take_while(|x| py_space(**x)).count()
|
||||
}
|
||||
|
||||
/// `\s+(.+)$` on `rest`: the `(.+)` group.
|
||||
fn spaced_tail(rest: &[char]) -> Option<&[char]> {
|
||||
let k = leading_space(rest);
|
||||
if k == 0 || rest.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
Some(&rest[k.min(rest.len() - 1)..])
|
||||
}
|
||||
|
||||
/// `HEADER_RE = ^(#{1,6})\s+(.+)$`.
|
||||
fn match_header(c: &[char]) -> Option<(usize, &[char])> {
|
||||
let n = c.iter().take_while(|x| **x == '#').count();
|
||||
if n == 0 || n > 6 {
|
||||
return None;
|
||||
}
|
||||
spaced_tail(&c[n..]).map(|t| (n, t))
|
||||
}
|
||||
|
||||
/// `UNORDERED_LIST_RE = ^(\s*)([-*+])\s+(.+)$`.
|
||||
fn match_list_item(c: &[char]) -> Option<(&[char], &[char])> {
|
||||
let w = leading_space(c);
|
||||
if !matches!(c.get(w), Some('-' | '*' | '+')) {
|
||||
return None;
|
||||
}
|
||||
spaced_tail(&c[w + 1..]).map(|t| (&c[..w], t))
|
||||
}
|
||||
|
||||
/// `HORIZONTAL_RULE_RE = ^(\s*)(---+|===+|\*\*\*+|___+)\s*$`.
|
||||
fn is_horizontal_rule(c: &[char]) -> bool {
|
||||
let w = leading_space(c);
|
||||
let Some(&ch) = c.get(w) else { return false };
|
||||
if !matches!(ch, '-' | '=' | '*' | '_') {
|
||||
return false;
|
||||
}
|
||||
let run = c[w..].iter().take_while(|x| **x == ch).count();
|
||||
run >= 3 && c[w + run..].iter().all(|x| py_space(*x))
|
||||
}
|
||||
|
||||
/// `CODE_FENCE_RE = ^(\s*)```(.*)$`: the language hint (group 2).
|
||||
fn detect_code_fence(line: &str) -> Option<&str> {
|
||||
line.trim_start_matches(py_space).strip_prefix("```")
|
||||
}
|
||||
|
||||
/// `QUOTE_RE = ^>\s?(.*)$`: group 1.
|
||||
fn quote_match(line: &str) -> Option<&str> {
|
||||
let rest = line.strip_prefix('>')?;
|
||||
let mut chars = rest.chars();
|
||||
match chars.next() {
|
||||
Some(c) if py_space(c) => Some(chars.as_str()),
|
||||
_ => Some(rest),
|
||||
}
|
||||
}
|
||||
|
||||
/// Group 1 of `TABLE_ROW_RE = ^\s*\|?(.+?)\|?\s*$`.
|
||||
fn table_row_group(c: &[char]) -> Option<&[char]> {
|
||||
let trail = c.len() - c.iter().rev().take_while(|x| py_space(**x)).count();
|
||||
let suffix_from = if trail > 0 && c[trail - 1] == '|' {
|
||||
trail - 1
|
||||
} else {
|
||||
trail
|
||||
};
|
||||
let w = leading_space(c);
|
||||
for ws in (0..=w).rev() {
|
||||
let pipe = c.get(ws) == Some(&'|');
|
||||
for start in [ws + usize::from(pipe), ws] {
|
||||
if start < c.len() {
|
||||
return Some(&c[start..(start + 1).max(suffix_from)]);
|
||||
}
|
||||
if !pipe {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Python `_is_table_row` (`util.py`).
|
||||
fn is_table_row(line: &str) -> bool {
|
||||
if !line.contains('|') {
|
||||
return false;
|
||||
}
|
||||
let c: Vec<char> = line.chars().collect();
|
||||
let Some(content) = table_row_group(&c) else {
|
||||
return false;
|
||||
};
|
||||
content.contains(&'|') || py_strip(line).starts_with('|')
|
||||
}
|
||||
|
||||
/// `TABLE_SEP_RE = ^\s*\|?(?:\s*:?-+:?\s*\|)+\s*$`.
|
||||
fn is_table_separator(line: &str) -> bool {
|
||||
let c: Vec<char> = line.chars().collect();
|
||||
let mut i = leading_space(&c);
|
||||
if c.get(i) == Some(&'|') {
|
||||
i += 1;
|
||||
}
|
||||
let group = |mut j: usize| -> Option<usize> {
|
||||
j += leading_space(&c[j..]);
|
||||
if c.get(j) == Some(&':') {
|
||||
j += 1;
|
||||
}
|
||||
let dashes = c[j..].iter().take_while(|x| **x == '-').count();
|
||||
if dashes == 0 {
|
||||
return None;
|
||||
}
|
||||
j += dashes;
|
||||
if c.get(j) == Some(&':') {
|
||||
j += 1;
|
||||
}
|
||||
j += leading_space(&c[j..]);
|
||||
(c.get(j) == Some(&'|')).then_some(j + 1)
|
||||
};
|
||||
let Some(mut j) = group(i) else { return false };
|
||||
while let Some(next) = group(j) {
|
||||
j = next;
|
||||
}
|
||||
c[j..].iter().all(|x| py_space(*x))
|
||||
}
|
||||
|
||||
/// Python `_parse_table_row` (`util.py`).
|
||||
fn parse_table_row(line: &str) -> Vec<String> {
|
||||
let line = py_strip(line);
|
||||
let line = line.strip_prefix('|').unwrap_or(line);
|
||||
let line = line.strip_suffix('|').unwrap_or(line);
|
||||
let mut cells = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut escaped = false;
|
||||
for ch in line.chars() {
|
||||
if escaped {
|
||||
current.push(ch);
|
||||
escaped = false;
|
||||
} else if ch == '\\' {
|
||||
escaped = true;
|
||||
} else if ch == '|' {
|
||||
cells.push(py_strip(¤t).to_string());
|
||||
current.clear();
|
||||
} else {
|
||||
current.push(ch);
|
||||
}
|
||||
}
|
||||
cells.push(py_strip(¤t).to_string());
|
||||
cells
|
||||
}
|
||||
|
||||
/// Python `_parse_table_alignments` (`util.py`).
|
||||
fn parse_table_alignments(line: &str) -> Vec<Align> {
|
||||
parse_table_row(line)
|
||||
.iter()
|
||||
.map(|cell| {
|
||||
let cell = py_strip(cell);
|
||||
if cell.starts_with(':') && cell.ends_with(':') {
|
||||
Align::Center
|
||||
} else if cell.ends_with(':') {
|
||||
Align::Right
|
||||
} else {
|
||||
Align::Left
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One left-to-right `re.sub(pattern, '', text)` pass.
|
||||
fn remove_matches(c: &[char], matcher: impl Fn(&[char], usize) -> Option<usize>) -> Vec<char> {
|
||||
let mut out = Vec::with_capacity(c.len());
|
||||
let mut i = 0;
|
||||
while i < c.len() {
|
||||
if let Some(n) = matcher(c, i) {
|
||||
i += n;
|
||||
} else {
|
||||
out.push(c[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `LINK_RE = \[([^\]]+)\]\(([^)]+)\)` replaced by `\0LINKn\0`.
|
||||
fn sub_links(c: &[char], links: &mut Vec<(String, String)>) -> String {
|
||||
let find = |from: usize, ch: char| c[from..].iter().position(|x| *x == ch).map(|p| from + p);
|
||||
let mut out = String::new();
|
||||
let mut i = 0;
|
||||
while i < c.len() {
|
||||
if c[i] == '[' {
|
||||
let m = find(i + 1, ']')
|
||||
.filter(|&j| j > i + 1 && c.get(j + 1) == Some(&'('))
|
||||
.and_then(|j| find(j + 2, ')').filter(|&k| k > j + 2).map(|k| (j, k)));
|
||||
if let Some((j, k)) = m {
|
||||
links.push((c[i + 1..j].iter().collect(), c[j + 2..k].iter().collect()));
|
||||
out.push_str(&format!("\0LINK{}\0", links.len() - 1));
|
||||
i = k + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(c[i]);
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `INLINE_CODE_RE = `([^`]+)`` replaced by `\0CODEn\0`.
|
||||
fn sub_inline_code(c: &[char], codes: &mut Vec<String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut i = 0;
|
||||
while i < c.len() {
|
||||
if c[i] == '`'
|
||||
&& let Some(p) = c[i + 1..].iter().position(|x| *x == '`')
|
||||
&& p > 0
|
||||
{
|
||||
codes.push(c[i + 1..i + 1 + p].iter().collect());
|
||||
out.push_str(&format!("\0CODE{}\0", codes.len() - 1));
|
||||
i += p + 2;
|
||||
continue;
|
||||
}
|
||||
out.push(c[i]);
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `BOLD_RE = \*\*(.+?)\*\*|__(.+?)__` (`n == 2`) and
|
||||
/// `ITALIC_RE = \*(.+?)\*|_(.+?)_` (`n == 1`).
|
||||
fn sub_emphasis(c: &[char], star: char, n: usize, open: &str, close: &str) -> String {
|
||||
let delim_at = |i: usize, d: char| c.len() >= i + n && c[i..i + n].iter().all(|x| *x == d);
|
||||
let mut out = String::new();
|
||||
let mut i = 0;
|
||||
while i < c.len() {
|
||||
let delim = [star, '_'].into_iter().find(|&d| delim_at(i, d));
|
||||
if let Some(d) = delim {
|
||||
let end = (i + n + 1..c.len())
|
||||
.take_while(|&j| c[j - 1] != '\n')
|
||||
.find(|&j| delim_at(j, d));
|
||||
if let Some(j) = end {
|
||||
out.push_str(open);
|
||||
out.extend(&c[i + n..j]);
|
||||
out.push_str(close);
|
||||
i = j + n;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(c[i]);
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `re.sub(r'\x00TAG(\d+)\x00', f, text)`; the index goes through Python
|
||||
/// `int()`, which accepts any Unicode decimal digit and at most 4300 of them.
|
||||
fn sub_placeholders(
|
||||
c: &[char],
|
||||
tag: &str,
|
||||
mut f: impl FnMut(usize) -> Result<String, MarkdownError>,
|
||||
) -> Result<String, MarkdownError> {
|
||||
let tag: Vec<char> = tag.chars().collect();
|
||||
let mut out = String::new();
|
||||
let mut i = 0;
|
||||
while i < c.len() {
|
||||
if c[i] == '\0' && c[i + 1..].starts_with(&tag) {
|
||||
let d0 = i + 1 + tag.len();
|
||||
let digits = c[d0..]
|
||||
.iter()
|
||||
.take_while(|x| py_decimal(**x).is_some())
|
||||
.count();
|
||||
if digits > 0 && c.get(d0 + digits) == Some(&'\0') {
|
||||
if digits > 4300 {
|
||||
return Err(MarkdownError::PlaceholderDigits);
|
||||
}
|
||||
let idx = c[d0..d0 + digits].iter().try_fold(0usize, |acc, x| {
|
||||
acc.checked_mul(10)?.checked_add(py_decimal(*x)? as usize)
|
||||
});
|
||||
out.push_str(&f(idx.unwrap_or(usize::MAX))?);
|
||||
i = d0 + digits + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(c[i]);
|
||||
i += 1;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Digit zeros of every Unicode decimal-digit run in Python 3.13's Unicode
|
||||
/// 15.1 database; each run holds the ten digits zero..nine.
|
||||
const DECIMAL_ZEROS: [u32; 68] = [
|
||||
0x30, 0x660, 0x6F0, 0x7C0, 0x966, 0x9E6, 0xA66, 0xAE6, 0xB66, 0xBE6, 0xC66, 0xCE6, 0xD66,
|
||||
0xDE6, 0xE50, 0xED0, 0xF20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80, 0x1A90,
|
||||
0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, 0xFF10,
|
||||
0x104A0, 0x10D30, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0, 0x11650,
|
||||
0x116C0, 0x11730, 0x118E0, 0x11950, 0x11C50, 0x11D50, 0x11DA0, 0x11F50, 0x16A60, 0x16AC0,
|
||||
0x16B50, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E4F0, 0x1E950,
|
||||
0x1FBF0,
|
||||
];
|
||||
|
||||
fn py_decimal(c: char) -> Option<u32> {
|
||||
let c = c as u32;
|
||||
DECIMAL_ZEROS
|
||||
.iter()
|
||||
.find(|&&z| (z..=z + 9).contains(&c))
|
||||
.map(|z| c - z)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! WebP conversion through external encoders (`RNS/Utilities/rngit/media.py@1.6.0`).
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `CONVERSION_TIMEOUT`: one deadline across the input and encoder processes.
|
||||
pub const CONVERSION_TIMEOUT: Duration = Duration::from_secs(8);
|
||||
|
||||
/// `BACKENDS`, in preference order.
|
||||
pub const BACKENDS: [(&str, &[&str]); 5] = [
|
||||
("magick", &["magick", "-", "webp:-"]),
|
||||
("convert", &["convert", "-", "webp:-"]),
|
||||
("gm", &["gm", "convert", "-", "webp:-"]),
|
||||
(
|
||||
"ffmpeg",
|
||||
&[
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-i",
|
||||
"-",
|
||||
"-f",
|
||||
"webp",
|
||||
"pipe:1",
|
||||
],
|
||||
),
|
||||
(
|
||||
"avconv",
|
||||
&[
|
||||
"avconv",
|
||||
"-y",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-i",
|
||||
"-",
|
||||
"-f",
|
||||
"webp",
|
||||
"pipe:1",
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
/// The encoder argv for a source of this extension, with the input format
|
||||
/// named. Upstream lets the encoder guess the format from the content, so a
|
||||
/// file with an image name could be read as SVG, PostScript or a playlist;
|
||||
/// here only the decoder for the extension runs.
|
||||
pub fn encoder_argv(backend_argv: &[&str], source_ext: &str) -> Option<Vec<String>> {
|
||||
let (coder, demuxer) = match source_ext.to_ascii_lowercase().as_str() {
|
||||
".png" => ("png", "png_pipe"),
|
||||
".jpg" | ".jpeg" => ("jpeg", "jpeg_pipe"),
|
||||
".gif" => ("gif", "gif"),
|
||||
".tiff" | ".tif" => ("tiff", "tiff_pipe"),
|
||||
".bmp" => ("bmp", "bmp_pipe"),
|
||||
_ => return None,
|
||||
};
|
||||
let mut argv = Vec::with_capacity(backend_argv.len() + 2);
|
||||
for arg in backend_argv {
|
||||
match (backend_argv[0], *arg) {
|
||||
("ffmpeg" | "avconv", "-i") => {
|
||||
argv.extend(["-f".to_string(), demuxer.to_string(), "-i".to_string()])
|
||||
}
|
||||
("magick" | "convert" | "gm", "-") => argv.push(format!("{coder}:-")),
|
||||
_ => argv.push(arg.to_string()),
|
||||
}
|
||||
}
|
||||
Some(argv)
|
||||
}
|
||||
|
||||
/// `_ENV_BACKEND`, read once as upstream reads it at import.
|
||||
fn env_backend() -> Option<&'static str> {
|
||||
static ENV: OnceLock<Option<String>> = OnceLock::new();
|
||||
ENV.get_or_init(|| {
|
||||
std::env::var("RNGIT_MEDIA_BACKEND")
|
||||
.ok()
|
||||
.filter(|v| !v.is_empty())
|
||||
})
|
||||
.as_deref()
|
||||
}
|
||||
|
||||
static WINNER: Mutex<Option<&'static str>> = Mutex::new(None);
|
||||
static NO_BACKEND_LOGGED: Mutex<bool> = Mutex::new(false);
|
||||
|
||||
/// `shutil.which`: an executable file of that name on `PATH`.
|
||||
#[cfg(unix)]
|
||||
pub fn which(tool: &str) -> bool {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
};
|
||||
std::env::split_paths(&path).any(|dir| {
|
||||
std::fs::metadata(dir.join(tool))
|
||||
.is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
|
||||
})
|
||||
}
|
||||
|
||||
/// `shutil.which` on Windows: a file of that name on `PATH`, tried with each
|
||||
/// `PATHEXT` extension unless it already ends in one.
|
||||
#[cfg(not(unix))]
|
||||
pub fn which(tool: &str) -> bool {
|
||||
let Some(path) = std::env::var_os("PATH") else {
|
||||
return false;
|
||||
};
|
||||
let pathext = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into());
|
||||
let extensions: Vec<&str> = pathext.split(';').filter(|e| !e.is_empty()).collect();
|
||||
let lower = tool.to_ascii_lowercase();
|
||||
let names: Vec<String> = if extensions
|
||||
.iter()
|
||||
.any(|e| lower.ends_with(&e.to_ascii_lowercase()))
|
||||
{
|
||||
vec![tool.to_string()]
|
||||
} else {
|
||||
extensions.iter().map(|e| format!("{tool}{e}")).collect()
|
||||
};
|
||||
std::env::split_paths(&path).any(|dir| names.iter().any(|name| dir.join(name).is_file()))
|
||||
}
|
||||
|
||||
/// `_selected_backend` for a forced name, a tool lookup and the previous
|
||||
/// winner. A forced name whose tool is absent selects nothing.
|
||||
pub fn select_backend(
|
||||
forced: Option<&str>,
|
||||
present: &dyn Fn(&str) -> bool,
|
||||
winner: Option<&str>,
|
||||
) -> Option<(&'static str, &'static [&'static str])> {
|
||||
if let Some(forced) = forced {
|
||||
return BACKENDS
|
||||
.iter()
|
||||
.find(|(name, argv)| *name == forced && present(argv[0]))
|
||||
.copied();
|
||||
}
|
||||
let mut order: Vec<_> = BACKENDS.to_vec();
|
||||
if let Some(winner) = winner {
|
||||
order.sort_by_key(|(name, _)| *name != winner);
|
||||
}
|
||||
order.into_iter().find(|(_, argv)| present(argv[0]))
|
||||
}
|
||||
|
||||
/// `_configured_backend` without quality or size options, as the page node calls it.
|
||||
fn configured_backend() -> Option<(&'static str, &'static [&'static str])> {
|
||||
let mut winner = WINNER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let selected = select_backend(env_backend(), &which, *winner);
|
||||
let mut logged = NO_BACKEND_LOGGED.lock().unwrap_or_else(|e| e.into_inner());
|
||||
match selected {
|
||||
None => {
|
||||
if !*logged {
|
||||
*logged = true;
|
||||
tracing::warn!(
|
||||
"No WebP encoding backend available for media conversion. You can Install ImageMagick or ffmpeg to enable image conversion."
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
Some(backend) => {
|
||||
if env_backend().is_none() {
|
||||
*winner = Some(backend.0);
|
||||
}
|
||||
*logged = false;
|
||||
Some(backend)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_webp_info`: the image size from a WebP header of at least 30 bytes.
|
||||
pub fn webp_info(data: &[u8]) -> Option<(u32, u32)> {
|
||||
if data.len() < 30 || &data[..4] != b"RIFF" || &data[8..12] != b"WEBP" {
|
||||
return None;
|
||||
}
|
||||
let le = |b: &[u8]| {
|
||||
b.iter()
|
||||
.rev()
|
||||
.fold(0u32, |acc, &x| (acc << 8) | u32::from(x))
|
||||
};
|
||||
let (width, height) = match &data[12..16] {
|
||||
b"VP8X" => (le(&data[24..27]) + 1, le(&data[27..30]) + 1),
|
||||
b"VP8 " => (le(&data[26..28]) & 0x3FFF, le(&data[28..30]) & 0x3FFF),
|
||||
b"VP8L" => {
|
||||
let bits = le(&data[21..25]);
|
||||
((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
(width > 0 && height > 0).then_some((width, height))
|
||||
}
|
||||
|
||||
fn valid_webp(path: &Path) -> bool {
|
||||
let mut header = Vec::with_capacity(30);
|
||||
std::fs::File::open(path)
|
||||
.and_then(|f| f.take(30).read_to_end(&mut header))
|
||||
.is_ok_and(|_| webp_info(&header).is_some())
|
||||
}
|
||||
|
||||
fn terminate(child: &mut Child) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
fn stderr_tail(child: &mut Child) -> String {
|
||||
let mut data = Vec::new();
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
let _ = stderr.take(1024).read_to_end(&mut data);
|
||||
}
|
||||
String::from_utf8_lossy(&data).trim().to_string()
|
||||
}
|
||||
|
||||
/// `convert_to_webp`: `input_argv` writes the source image to stdout and the
|
||||
/// encoder writes WebP to `output_path`. Both run by argv, never through a shell.
|
||||
pub fn convert_to_webp(
|
||||
input_argv: &[&str],
|
||||
output_path: &Path,
|
||||
cwd: Option<&Path>,
|
||||
source_ext: &str,
|
||||
) -> bool {
|
||||
let Some((backend, backend_argv)) = configured_backend() else {
|
||||
return false;
|
||||
};
|
||||
let Some(encoder_argv) = encoder_argv(backend_argv, source_ext) else {
|
||||
return false;
|
||||
};
|
||||
let result = (|| -> std::io::Result<bool> {
|
||||
let output = std::fs::File::create(output_path)?;
|
||||
let mut input_cmd = Command::new(input_argv[0]);
|
||||
input_cmd
|
||||
.args(&input_argv[1..])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
if let Some(cwd) = cwd {
|
||||
input_cmd.current_dir(cwd);
|
||||
}
|
||||
let mut input = input_cmd.spawn()?;
|
||||
let pipe = input.stdout.take().expect("piped stdout");
|
||||
let encoder = Command::new(&encoder_argv[0])
|
||||
.args(&encoder_argv[1..])
|
||||
.stdin(pipe)
|
||||
.stdout(output)
|
||||
.stderr(Stdio::piped())
|
||||
.spawn();
|
||||
let mut encoder = match encoder {
|
||||
Ok(child) => child,
|
||||
Err(e) => {
|
||||
terminate(&mut input);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let deadline = Instant::now() + CONVERSION_TIMEOUT;
|
||||
let mut encoder_status = None;
|
||||
let mut input_done = false;
|
||||
loop {
|
||||
if encoder_status.is_none() {
|
||||
encoder_status = encoder.try_wait()?;
|
||||
}
|
||||
if encoder_status.is_some() && !input_done {
|
||||
input_done = input.try_wait()?.is_some();
|
||||
}
|
||||
if encoder_status.is_some() && input_done {
|
||||
break;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate(&mut input);
|
||||
terminate(&mut encoder);
|
||||
tracing::warn!(
|
||||
"Media conversion via {backend} timed out after {} seconds",
|
||||
CONVERSION_TIMEOUT.as_secs()
|
||||
);
|
||||
return Ok(false);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
if !encoder_status.is_some_and(|s| s.success()) {
|
||||
let mut detail = String::new();
|
||||
let encoder_tail = stderr_tail(&mut encoder);
|
||||
let input_tail = stderr_tail(&mut input);
|
||||
if !encoder_tail.is_empty() {
|
||||
detail.push_str(&format!(" Encoder: {encoder_tail}"));
|
||||
}
|
||||
if !input_tail.is_empty() {
|
||||
detail.push_str(&format!(" Input: {input_tail}"));
|
||||
}
|
||||
tracing::warn!("Media conversion via {backend} failed.{detail}");
|
||||
return Ok(false);
|
||||
}
|
||||
if !valid_webp(output_path) {
|
||||
tracing::warn!("Media conversion via {backend} produced invalid WebP output");
|
||||
return Ok(false);
|
||||
}
|
||||
tracing::debug!("Media converted to WebP with {backend}");
|
||||
Ok(true)
|
||||
})();
|
||||
result.unwrap_or_else(|e| {
|
||||
tracing::warn!("Error during media conversion: {e}");
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn encoder_is_told_the_input_format() {
|
||||
let argv = |backend: &str, ext: &str| {
|
||||
let (_, base) = BACKENDS.iter().find(|(name, _)| *name == backend).unwrap();
|
||||
encoder_argv(base, ext).map(|a| a.join(" "))
|
||||
};
|
||||
assert_eq!(argv("magick", ".PNG").unwrap(), "magick png:- webp:-");
|
||||
assert_eq!(argv("convert", ".jpg").unwrap(), "convert jpeg:- webp:-");
|
||||
assert_eq!(argv("gm", ".tif").unwrap(), "gm convert tiff:- webp:-");
|
||||
assert_eq!(
|
||||
argv("ffmpeg", ".gif").unwrap(),
|
||||
"ffmpeg -y -loglevel error -f gif -i - -f webp pipe:1"
|
||||
);
|
||||
assert_eq!(
|
||||
argv("avconv", ".bmp").unwrap(),
|
||||
"avconv -y -loglevel error -f bmp_pipe -i - -f webp pipe:1"
|
||||
);
|
||||
// No decoder is named for anything else, so nothing is converted.
|
||||
assert_eq!(argv("magick", ".svg"), None);
|
||||
assert_eq!(argv("ffmpeg", ".webp"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! The stats page charts (`render_chart_halfblock`, `render_combined_chart`, `pages.py`).
|
||||
|
||||
use super::{CLR_DIM, RCLR_DOWNLOAD, RCLR_FETCH, RCLR_PUSH, RCLR_VIEW};
|
||||
|
||||
fn expand(c: &str) -> String {
|
||||
if c.chars().count() == 3 {
|
||||
c.chars().flat_map(|ch| [ch, ch]).collect()
|
||||
} else {
|
||||
c.chars().take(6).collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn rgb(h: &str) -> [f64; 3] {
|
||||
let part = |i: usize| f64::from(u8::from_str_radix(&h[i..i + 2], 16).unwrap_or(0));
|
||||
[part(0), part(2), part(4)]
|
||||
}
|
||||
|
||||
/// `int(g + (c - g) * min(1, t * f))` per channel, as two hex digits each.
|
||||
fn blend(c: [f64; 3], g: [f64; 3], t: f64, f: f64) -> String {
|
||||
let m = (t * f).min(1.0);
|
||||
(0..3)
|
||||
.map(|i| format!("{:02x}", (g[i] + (c[i] - g[i]) * m) as i64))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn pad_left(s: &str, width: usize) -> String {
|
||||
let n = s.chars().count();
|
||||
format!("{s}{}", " ".repeat(width.saturating_sub(n)))
|
||||
}
|
||||
|
||||
fn pad_right(s: &str, width: usize) -> String {
|
||||
let n = s.chars().count();
|
||||
format!("{}{s}", " ".repeat(width.saturating_sub(n)))
|
||||
}
|
||||
|
||||
fn first12(s: &str) -> String {
|
||||
s.chars().take(12).collect()
|
||||
}
|
||||
|
||||
/// `render_chart` (the half-block renderer, height 10).
|
||||
pub fn render_chart(
|
||||
data: &[i64],
|
||||
labels: &[String],
|
||||
color: &str,
|
||||
secondary_color: Option<&str>,
|
||||
gradient_factor: Option<f64>,
|
||||
) -> String {
|
||||
let height = 10i64;
|
||||
let gradient_factor = gradient_factor.filter(|g| *g != 0.0).unwrap_or(1.3);
|
||||
if data.iter().all(|d| *d == 0) {
|
||||
return "No data available\n".to_string();
|
||||
}
|
||||
let max_val = (*data.iter().max().unwrap_or(&1)).max(1) as f64;
|
||||
let max_label = *data.iter().max().unwrap_or(&1);
|
||||
let primary = expand(color);
|
||||
let secondary = match secondary_color {
|
||||
Some(c) => expand(c),
|
||||
None => (0..3)
|
||||
.map(|i| {
|
||||
let v = i64::from_str_radix(&primary[i * 2..i * 2 + 2], 16).unwrap_or(0);
|
||||
format!("{:02x}", (v as f64 * 0.42) as i64)
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
let (p, s) = (rgb(&primary), rgb(&secondary));
|
||||
let gradient = |t: f64| blend(p, s, t, gradient_factor);
|
||||
let mut out = format!("`FT{primary}Peak: {max_label}`f\n");
|
||||
for row in (1..=height).rev() {
|
||||
let h = height as f64;
|
||||
let r = row as f64;
|
||||
let row_top = (r / h) * max_val;
|
||||
let row_bottom = ((r - 1.0) / h) * max_val;
|
||||
let row_mid = (row_top + row_bottom) / 2.0;
|
||||
let grad_top = r / h;
|
||||
let grad_mid = (r - 0.5) / h;
|
||||
let mut line = String::from("│");
|
||||
for &val in data {
|
||||
let v = val as f64;
|
||||
let upper = v >= row_top;
|
||||
let lower = v >= row_mid || (row == 1 && val > 0);
|
||||
if !upper && !lower {
|
||||
line.push(' ');
|
||||
} else if upper {
|
||||
line.push_str(&format!(
|
||||
"`FT{}`BT{}▀`f`b",
|
||||
gradient(grad_top),
|
||||
gradient(grad_mid)
|
||||
));
|
||||
} else {
|
||||
line.push_str(&format!("`FT{}▄`f", gradient(grad_mid)));
|
||||
}
|
||||
}
|
||||
out.push_str(&line);
|
||||
out.push('\n');
|
||||
}
|
||||
let bottom = format!("└{}┘", "─".repeat(data.len()));
|
||||
out.push_str(&bottom);
|
||||
out.push('\n');
|
||||
let width = data.len() as i64 + 2;
|
||||
let first = pad_left(&first12(&labels[0]), 12);
|
||||
let last = pad_right(&first12(&labels[labels.len() - 1]), 12);
|
||||
let middle = (width - first.chars().count() as i64 - last.chars().count() as i64).max(0);
|
||||
out.push_str(&format!(
|
||||
"{CLR_DIM}{first}`f{}{CLR_DIM}{last}`f\n",
|
||||
" ".repeat(middle as usize)
|
||||
));
|
||||
out
|
||||
}
|
||||
|
||||
/// `render_combined_chart` with its default height 6 and dim 0.87.
|
||||
pub fn render_combined_chart(
|
||||
views: &[i64],
|
||||
fetches: &[i64],
|
||||
pushes: &[i64],
|
||||
downloads: &[i64],
|
||||
labels: &[String],
|
||||
) -> String {
|
||||
let height = 6i64;
|
||||
let dim = 0.87;
|
||||
if views.is_empty() || fetches.is_empty() || pushes.is_empty() || downloads.is_empty() {
|
||||
return "No data available\n".to_string();
|
||||
}
|
||||
let color = |c: &str| blend(rgb(&expand(c)), [0.0; 3], dim, 1.0);
|
||||
let categories = ["pushes", "fetches", "views", "downloads"];
|
||||
let colors = [
|
||||
color(RCLR_PUSH),
|
||||
color(RCLR_FETCH),
|
||||
color(RCLR_VIEW),
|
||||
color(RCLR_DOWNLOAD),
|
||||
];
|
||||
let series = [pushes, fetches, views, downloads];
|
||||
let legend: Vec<String> = categories
|
||||
.iter()
|
||||
.zip(&colors)
|
||||
.map(|(cat, col)| {
|
||||
let mut name = cat.to_string();
|
||||
name[..1].make_ascii_uppercase();
|
||||
format!("`FT{col}`BT{col}██`f`b {name}")
|
||||
})
|
||||
.collect();
|
||||
let mut out = format!("{}\n\n", legend.join(" "));
|
||||
let n = views.len();
|
||||
for row in (1..=height).rev() {
|
||||
let (h, r) = (height as f64, row as f64);
|
||||
let (lower_min, lower_max) = ((r - 1.0) / h, (r - 0.5) / h);
|
||||
let (upper_min, upper_max) = ((r - 0.5) / h, r / h);
|
||||
let mut line = String::from("│");
|
||||
for i in 0..n {
|
||||
let total: i64 = series.iter().map(|d| d[i]).sum();
|
||||
if total == 0 {
|
||||
line.push(' ');
|
||||
continue;
|
||||
}
|
||||
let mut cumsum = 0i64;
|
||||
let mut ranges = [(0.0f64, 0.0f64); 4];
|
||||
for (k, d) in series.iter().enumerate() {
|
||||
let start = cumsum as f64 / total as f64;
|
||||
cumsum += d[i];
|
||||
ranges[k] = (start, cumsum as f64 / total as f64);
|
||||
}
|
||||
let pixel =
|
||||
|pmin: f64, pmax: f64| (0..4).find(|&k| pmin < ranges[k].1 && pmax > ranges[k].0);
|
||||
match (pixel(upper_min, upper_max), pixel(lower_min, lower_max)) {
|
||||
(None, None) => line.push(' '),
|
||||
(Some(u), Some(l)) if u == l => {
|
||||
line.push_str(&format!("`FT{0}`BT{0}█`f`b", colors[u]));
|
||||
}
|
||||
(Some(u), Some(l)) => {
|
||||
line.push_str(&format!("`FT{}`BT{}▀`f`b", colors[u], colors[l]));
|
||||
}
|
||||
(Some(u), None) => line.push_str(&format!("`FT{}▀`f", colors[u])),
|
||||
(None, Some(l)) => line.push_str(&format!("`FT{}▄`f", colors[l])),
|
||||
}
|
||||
}
|
||||
out.push_str(&line);
|
||||
out.push('\n');
|
||||
}
|
||||
let bottom = format!("└{}┘", "─".repeat(n));
|
||||
out.push_str(&bottom);
|
||||
out.push('\n');
|
||||
if !labels.is_empty() {
|
||||
let first = first12(&labels[0]);
|
||||
let last = first12(&labels[labels.len() - 1]);
|
||||
let mid =
|
||||
(n as i64 + 2 - first.chars().count() as i64 - last.chars().count() as i64).max(0);
|
||||
out.push_str(&format!(
|
||||
"{CLR_DIM}{first}{}{last}`f\n",
|
||||
" ".repeat(mid as usize)
|
||||
));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! `/media` and the `/file/*` handlers (`pages.py`).
|
||||
|
||||
use std::io::{Read, Seek, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
use super::git;
|
||||
use super::views::{doc_dir, doc_id_of};
|
||||
use super::*;
|
||||
use crate::server::perms::Perm;
|
||||
|
||||
fn packed(value: &Value) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
rmpv::encode::write_value(&mut out, value).expect("writing to a Vec");
|
||||
out
|
||||
}
|
||||
|
||||
fn false_reply() -> PageReply {
|
||||
PageReply::Value(packed(&Value::Boolean(false)))
|
||||
}
|
||||
|
||||
impl PageNode {
|
||||
pub(crate) fn serve_artifact(&self, req: &PageRequest<'_>) -> PageReply {
|
||||
let data = Data::of(req.data);
|
||||
let group = data.text("var_g", "");
|
||||
let name = data.text("var_r", "");
|
||||
let mut tag = data.text("var_t", "");
|
||||
let artifact = unquote_plus(&data.text("var_a", ""));
|
||||
if artifact.contains('/') {
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let Some(repo) = self.accessible_repository(req.identity, &group, &name) else {
|
||||
tracing::debug!(
|
||||
"Repository not found or no access for artifact request {group}/{name}/{tag}/{artifact}"
|
||||
);
|
||||
return PageReply::Drop;
|
||||
};
|
||||
let releases_path = PathBuf::from(format!("{}.releases", repo.path.to_string_lossy()));
|
||||
if tag == "latest" {
|
||||
let Some((releases, latest)) = crate::server::releases::list_for_pages(&releases_path)
|
||||
.filter(|(r, _)| !r.is_empty())
|
||||
else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
tag = latest.unwrap_or_else(|| field_str_or(&releases[0], "tag", ""));
|
||||
}
|
||||
// Upstream joins the tag and name unchecked; only plain names stay inside the release.
|
||||
if !plain_name(&tag) || !plain_name(&artifact) {
|
||||
tracing::warn!("Refused artifact request {group}/{name}/{tag}/{artifact}");
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let release_dir = releases_path.join(&tag);
|
||||
let artifacts_dir = release_dir.join("artifacts");
|
||||
let artifact_path = artifacts_dir.join(&artifact);
|
||||
let Some(info) = crate::server::releases::data_for_pages(&release_dir, &tag) else {
|
||||
tracing::warn!(
|
||||
"Could not resolve release info for artifact request {group}/{name}/{tag}/{artifact}"
|
||||
);
|
||||
return PageReply::Drop;
|
||||
};
|
||||
if field(&info, "status").and_then(Value::as_str) != Some("published") {
|
||||
tracing::warn!("Attempt to fetch unpublished artifact {group}/{name}/{tag}/{artifact}");
|
||||
return PageReply::Drop;
|
||||
}
|
||||
if !release_dir.is_dir() || !artifacts_dir.is_dir() || !artifact_path.is_file() {
|
||||
tracing::warn!(
|
||||
"Artifact not found for artifact request {group}/{name}/{tag}/{artifact}"
|
||||
);
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let Ok(file) = std::fs::File::open(&artifact_path) else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
self.stats
|
||||
.release_download_succeeded(&group, &name, req.identity.as_ref());
|
||||
PageReply::File {
|
||||
file,
|
||||
name: artifact,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn serve_media(&self, req: &PageRequest<'_>) -> PageReply {
|
||||
let data = Data::of(req.data);
|
||||
if !data.has("key") {
|
||||
tracing::debug!("Missing request key in media request");
|
||||
return false_reply();
|
||||
}
|
||||
let media_path = data.text("path", "");
|
||||
if !data.truthy("path") {
|
||||
tracing::debug!("Missing path in media request");
|
||||
return false_reply();
|
||||
}
|
||||
let rest = media_path.strip_prefix("/media").unwrap_or(&media_path);
|
||||
let comps: Vec<&str> = rest.trim_start_matches('/').split('/').collect();
|
||||
if comps.len() < 4 {
|
||||
tracing::debug!("Insufficient path components in media request");
|
||||
return false_reply();
|
||||
}
|
||||
let (group, name, reference) = (comps[0], comps[1], comps[2]);
|
||||
let file_path = unquote_plus(&comps[3..].join("/"));
|
||||
let file_name = basename(&file_path).to_string();
|
||||
let Some(repo) = self.accessible_repository(req.identity, group, name) else {
|
||||
tracing::debug!(
|
||||
"Repository not found or no access for media request {group}/{name}/{reference}/{file_path}"
|
||||
);
|
||||
return false_reply();
|
||||
};
|
||||
let Some(resolved) = git::resolve_ref(&repo.path, reference) else {
|
||||
tracing::warn!(
|
||||
"Ref not found for media request {group}/{name}/{reference}/{file_path}"
|
||||
);
|
||||
return false_reply();
|
||||
};
|
||||
if file_path.is_empty() {
|
||||
return false_reply();
|
||||
}
|
||||
if git::blob_info(&repo.path, &resolved, &file_path).is_none() {
|
||||
tracing::warn!(
|
||||
"File not found at ref for media request {group}/{name}/{reference}/{file_path}"
|
||||
);
|
||||
return false_reply();
|
||||
}
|
||||
let ext = extension(&file_path).to_lowercase();
|
||||
if self.options.media_conversion
|
||||
&& IMAGE_EXTS.contains(&ext.as_str())
|
||||
&& ext != ".webp"
|
||||
&& let Some(file) = self.webp_stream(&repo.path, &resolved, &file_path)
|
||||
{
|
||||
let response_name = format!("{}.webp", stem(basename(file_path.trim_matches('/'))));
|
||||
return PageReply::File {
|
||||
file,
|
||||
name: response_name,
|
||||
};
|
||||
}
|
||||
match git::blob_stream(&repo.path, &resolved, &file_path) {
|
||||
Some(file) => PageReply::File {
|
||||
file,
|
||||
name: file_name,
|
||||
},
|
||||
None => PageReply::Drop,
|
||||
}
|
||||
}
|
||||
|
||||
/// `get_webp_stream`: the converted image, opened before its spool directory goes.
|
||||
fn webp_stream(
|
||||
&self,
|
||||
repo_path: &std::path::Path,
|
||||
resolved: &str,
|
||||
file_path: &str,
|
||||
) -> Option<std::fs::File> {
|
||||
let file_path = file_path.trim_matches('/');
|
||||
let tmpdir = tempfile::TempDir::new().ok()?;
|
||||
let stem = stem(basename(file_path)).to_string();
|
||||
let spool = tempfile::Builder::new()
|
||||
.prefix(&format!("{stem}."))
|
||||
.suffix(".webp")
|
||||
.tempfile_in(tmpdir.path())
|
||||
.ok()?;
|
||||
let spool_path = spool.path().to_path_buf();
|
||||
let spec = format!("{resolved}:{file_path}");
|
||||
if !crate::media::convert_to_webp(
|
||||
&["git", "show", &spec],
|
||||
&spool_path,
|
||||
Some(repo_path),
|
||||
extension(file_path),
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
std::fs::File::open(&spool_path).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn serve_download(&self, req: &PageRequest<'_>) -> PageReply {
|
||||
let data = Data::of(req.data);
|
||||
let group = data.text("var_g", "");
|
||||
let name = data.text("var_r", "");
|
||||
let reference = data.text("var_ref", "HEAD");
|
||||
let fmt = data.text("var_fmt", "");
|
||||
let fmt_set = data.truthy("var_fmt");
|
||||
let file_path = unquote_plus(&data.text("var_path", ""));
|
||||
let file_name = basename(&file_path).to_string();
|
||||
let ext = extension(&file_path).to_lowercase();
|
||||
if fmt_set && !CONVERTABLE_EXTS.contains(&ext.as_str()) {
|
||||
tracing::debug!("Download conversion request for non-convertable file");
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let Some(repo) = self.accessible_repository(req.identity, &group, &name) else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
let Some(resolved) = git::resolve_ref(&repo.path, &reference) else {
|
||||
tracing::warn!(
|
||||
"Ref not found for download request {group}/{name}/{reference}/{file_path}"
|
||||
);
|
||||
return PageReply::Drop;
|
||||
};
|
||||
let info = (!file_path.is_empty())
|
||||
.then(|| git::blob_info(&repo.path, &resolved, &file_path))
|
||||
.flatten();
|
||||
let Some(info) = info else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
// The conversion holds the file in memory; upstream converts any size.
|
||||
if fmt_set && info.size > CONVERT_SIZE_LIMIT {
|
||||
tracing::warn!("Refused conversion of {file_path}: {} bytes", info.size);
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let Some(mut stream) = git::blob_stream(&repo.path, &resolved, &file_path) else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
self.stats
|
||||
.download_succeeded(&group, &name, req.identity.as_ref());
|
||||
if !fmt_set {
|
||||
return PageReply::File {
|
||||
file: stream,
|
||||
name: file_name,
|
||||
};
|
||||
}
|
||||
if fmt != "mu" {
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let converted = (|| -> Option<std::fs::File> {
|
||||
let mut raw = Vec::new();
|
||||
stream.read_to_end(&mut raw).ok()?;
|
||||
let text = String::from_utf8(raw).ok()?;
|
||||
let components: Vec<&str> = file_path.trim_matches('/').split('/').collect();
|
||||
let dir = if components.len() > 1 {
|
||||
format!("{}/", components[..components.len() - 1].join("/"))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let scope = format!(":/page/blob.mu`g={group}|r={name}|ref={reference}|path={dir}");
|
||||
let mu = match self.mdc_scoped(&scope).format_block(&text) {
|
||||
Ok(mu) => mu,
|
||||
Err(e) => {
|
||||
tracing::warn!("Error during file conversion of {file_path}: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let mu = mu.trim_end_matches(py_space);
|
||||
if mu.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut spool = tempfile::tempfile().ok()?;
|
||||
spool.write_all(mu.as_bytes()).ok()?;
|
||||
spool.rewind().ok()?;
|
||||
Some(spool)
|
||||
})();
|
||||
match converted {
|
||||
Some(file) => PageReply::File {
|
||||
file,
|
||||
name: format!("{}.mu", stem(&file_name)),
|
||||
},
|
||||
None => PageReply::Drop,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn serve_wd_download(&self, req: &PageRequest<'_>) -> PageReply {
|
||||
let data = Data::of(req.data);
|
||||
let group = data.text("var_g", "");
|
||||
let name = data.text("var_r", "");
|
||||
let mut scope = data.text("var_scope", "all");
|
||||
if !["active", "completed", "all"].contains(&scope.as_str()) {
|
||||
scope = "active".to_string();
|
||||
}
|
||||
if group.is_empty() || name.is_empty() || !data.truthy("var_id") {
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let Some(doc_id) = doc_id_of(data.raw("var_id")) else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
let Some(repo) = self.accessible_repository(req.identity, &group, &name) else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
if !self.resolve_doc_permission(req.identity, &group, &name, doc_id, Perm::Read) {
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let work_path = PathBuf::from(format!("{}.work", repo.path.to_string_lossy()));
|
||||
let (dir, _) = doc_dir(&work_path, doc_id, &scope);
|
||||
let root = dir.join("root");
|
||||
if !root.is_file() {
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let Some(doc) = crate::server::work::load_document(&root) else {
|
||||
return PageReply::Drop;
|
||||
};
|
||||
let empty = Value::Map(Vec::new());
|
||||
let meta = field(&doc, "meta").unwrap_or(&empty);
|
||||
let fmt = field_str_or(meta, "format", "markdown");
|
||||
let title = chars(&field_str_or(meta, "title", "Untitled"), 256);
|
||||
let content = field_str_or(&doc, "content", "");
|
||||
let content = py_strip(&content);
|
||||
if content.is_empty() {
|
||||
return PageReply::Drop;
|
||||
}
|
||||
let file_name = if fmt == "micron" {
|
||||
format!("{title}.mu")
|
||||
} else {
|
||||
format!("{title}.md")
|
||||
};
|
||||
self.stats
|
||||
.download_succeeded(&group, &name, req.identity.as_ref());
|
||||
PageReply::Value(packed(&Value::Array(vec![
|
||||
Value::from(file_name),
|
||||
Value::Binary(content.as_bytes().to_vec()),
|
||||
])))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
//! Git data extraction for the page node (`pages.py`).
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use super::py_strip;
|
||||
|
||||
/// `GIT_COMMAND_TIMEOUT`.
|
||||
pub const GIT_COMMAND_TIMEOUT: Duration = Duration::from_secs(8);
|
||||
|
||||
/// Most output kept from one command. Upstream keeps all of it; anyone who can
|
||||
/// reach the page node could otherwise make it hold a whole blob in memory.
|
||||
const CAPTURE_LIMIT: u64 = 16 * 1024 * 1024;
|
||||
|
||||
/// What `get_blob_info` looks at to tell text from binary.
|
||||
const SAMPLE_BYTES: u64 = 8192;
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub code: Option<i32>,
|
||||
pub stdout: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Output {
|
||||
pub fn ok(&self) -> bool {
|
||||
self.code == Some(0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RunError {
|
||||
/// `subprocess.TimeoutExpired`.
|
||||
Timeout,
|
||||
/// Any other exception: spawn failure or undecodable text output.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// `subprocess.run(argv, cwd=cwd, capture_output=True, timeout=timeout)`;
|
||||
/// the child is killed when the deadline passes or its output passes
|
||||
/// `CAPTURE_LIMIT`.
|
||||
pub(crate) fn run(
|
||||
argv: &[&str],
|
||||
cwd: &Path,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<Output, RunError> {
|
||||
let (out, truncated) = run_capped(argv, cwd, timeout, CAPTURE_LIMIT)?;
|
||||
if truncated {
|
||||
tracing::warn!("Output of {} is over the capture limit", argv.join(" "));
|
||||
return Err(RunError::Failed);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The first `limit` bytes of a command's output. A command cut off at the
|
||||
/// limit is killed and counts as successful.
|
||||
fn run_capped(
|
||||
argv: &[&str],
|
||||
cwd: &Path,
|
||||
timeout: Option<Duration>,
|
||||
limit: u64,
|
||||
) -> Result<(Output, bool), RunError> {
|
||||
let mut child = Command::new(argv[0])
|
||||
.args(&argv[1..])
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.map_err(|_| RunError::Failed)?;
|
||||
let mut stdout = child.stdout.take().expect("piped stdout");
|
||||
let mut stderr = child.stderr.take().expect("piped stderr");
|
||||
let full = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let reader_full = full.clone();
|
||||
let out_reader = std::thread::spawn(move || {
|
||||
let mut data = Vec::new();
|
||||
let _ = (&mut stdout).take(limit).read_to_end(&mut data);
|
||||
// One more byte tells a command that ended at the limit from one cut off by it.
|
||||
if data.len() as u64 == limit && matches!(stdout.read(&mut [0u8; 1]), Ok(1)) {
|
||||
reader_full.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
data
|
||||
});
|
||||
let err_reader = std::thread::spawn(move || {
|
||||
let _ = std::io::copy(&mut stderr, &mut std::io::sink());
|
||||
});
|
||||
let deadline = timeout.map(|t| Instant::now() + t);
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {}
|
||||
Err(_) => return Err(RunError::Failed),
|
||||
}
|
||||
if full.load(std::sync::atomic::Ordering::Acquire) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let stdout = out_reader.join().unwrap_or_default();
|
||||
let _ = err_reader.join();
|
||||
return Ok((
|
||||
Output {
|
||||
code: Some(0),
|
||||
stdout,
|
||||
},
|
||||
true,
|
||||
));
|
||||
}
|
||||
if deadline.is_some_and(|d| Instant::now() >= d) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let _ = out_reader.join();
|
||||
let _ = err_reader.join();
|
||||
return Err(RunError::Timeout);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
};
|
||||
let stdout = out_reader.join().unwrap_or_default();
|
||||
let _ = err_reader.join();
|
||||
// A command cut off at the limit may also have died writing to the closed pipe.
|
||||
let truncated = full.load(std::sync::atomic::Ordering::Acquire);
|
||||
let code = if truncated { Some(0) } else { status.code() };
|
||||
Ok((Output { code, stdout }, truncated))
|
||||
}
|
||||
|
||||
/// `text=True` decoding: strict UTF-8 with universal newlines.
|
||||
pub(crate) fn text(data: &[u8]) -> Result<String, RunError> {
|
||||
let text = std::str::from_utf8(data).map_err(|_| RunError::Failed)?;
|
||||
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
|
||||
}
|
||||
|
||||
/// `run` with text output.
|
||||
pub(crate) fn run_text(
|
||||
argv: &[&str],
|
||||
cwd: &Path,
|
||||
timeout: Option<Duration>,
|
||||
) -> Result<(bool, String), RunError> {
|
||||
let out = run(argv, cwd, timeout)?;
|
||||
Ok((out.ok(), text(&out.stdout)?))
|
||||
}
|
||||
|
||||
fn timed() -> Option<Duration> {
|
||||
Some(GIT_COMMAND_TIMEOUT)
|
||||
}
|
||||
|
||||
fn path_str(path: &Path) -> String {
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// `get_repository_description`.
|
||||
pub fn repository_description(repo_path: &Path) -> Option<String> {
|
||||
let result = (|| -> Result<Option<String>, RunError> {
|
||||
let (ok, out) = run_text(
|
||||
&["git", "config", "--get", "repository.description"],
|
||||
repo_path,
|
||||
None,
|
||||
)?;
|
||||
if ok && !py_strip(&out).is_empty() {
|
||||
return Ok(Some(py_strip(&out).to_string()));
|
||||
}
|
||||
let desc_path = format!("{}.description", path_str(repo_path));
|
||||
if Path::new(&desc_path).is_file() {
|
||||
let data = std::fs::read(&desc_path).map_err(|_| RunError::Failed)?;
|
||||
let desc = text(&data)?;
|
||||
let desc = py_strip(&desc);
|
||||
if !desc.is_empty() {
|
||||
return Ok(Some(desc.to_string()));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
})();
|
||||
result.unwrap_or_else(|e| {
|
||||
tracing::debug!("Error getting repository description: {e:?}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// `get_repository_refs`, reduced to the branch and tag counts the repository page shows.
|
||||
pub fn repository_ref_counts(repo_path: &Path) -> (usize, usize) {
|
||||
let Ok((ok, out)) = run_text(
|
||||
&[
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format",
|
||||
"%(objectname) %(refname) %(refname:short)",
|
||||
"refs/heads",
|
||||
"refs/tags",
|
||||
],
|
||||
repo_path,
|
||||
None,
|
||||
) else {
|
||||
return (0, 0);
|
||||
};
|
||||
if !ok {
|
||||
return (0, 0);
|
||||
}
|
||||
let (mut heads, mut tags) = (0, 0);
|
||||
for line in py_strip(&out).split('\n') {
|
||||
if py_strip(line).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let parts: Vec<&str> = line.splitn(3, ' ').collect();
|
||||
if parts.len() >= 2 {
|
||||
if parts[1].starts_with("refs/heads/") {
|
||||
heads += 1;
|
||||
} else if parts[1].starts_with("refs/tags/") {
|
||||
tags += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
(heads, tags)
|
||||
}
|
||||
|
||||
/// `resolve_ref`. `--end-of-options` keeps a ref from being read as an option.
|
||||
pub fn resolve_ref(repo_path: &Path, reference: &str) -> Option<String> {
|
||||
match run_text(
|
||||
&[
|
||||
"git",
|
||||
"rev-parse",
|
||||
"--verify",
|
||||
"--end-of-options",
|
||||
reference,
|
||||
],
|
||||
repo_path,
|
||||
timed(),
|
||||
) {
|
||||
Ok((true, out)) => {
|
||||
let hash = py_strip(&out).to_lowercase();
|
||||
crate::util::san_sha(&hash).map(str::to_string)
|
||||
}
|
||||
Ok(_) => None,
|
||||
Err(RunError::Timeout) => {
|
||||
tracing::warn!("Timeout resolving ref '{reference}'");
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Error resolving ref: {e:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TreeEntry {
|
||||
pub name: String,
|
||||
/// `blob`, `tree`, `commit` or `link`.
|
||||
pub kind: String,
|
||||
pub size: u64,
|
||||
pub link_target: Option<String>,
|
||||
}
|
||||
|
||||
/// `get_tree_entries`; `None` when the path is not a tree.
|
||||
pub fn tree_entries(repo_path: &Path, reference: &str, path: &str) -> Option<Vec<TreeEntry>> {
|
||||
let tree_path = path.trim_matches('/');
|
||||
let ls_tree_path = if tree_path.is_empty() {
|
||||
reference.to_string()
|
||||
} else {
|
||||
format!("{reference}:{tree_path}")
|
||||
};
|
||||
let result = (|| -> Result<Option<Vec<TreeEntry>>, RunError> {
|
||||
let (ok, out) = run_text(&["git", "ls-tree", "-l", &ls_tree_path], repo_path, timed())?;
|
||||
if !ok {
|
||||
let (ok, kind) = run_text(
|
||||
&["git", "cat-file", "-t", &ls_tree_path],
|
||||
repo_path,
|
||||
timed(),
|
||||
)?;
|
||||
if !ok || py_strip(&kind) != "tree" {
|
||||
return Ok(None);
|
||||
}
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
for line in py_strip(&out).split('\n') {
|
||||
if py_strip(line).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some((meta, name)) = line.split_once('\t') else {
|
||||
continue;
|
||||
};
|
||||
let meta: Vec<&str> = meta.split_whitespace().collect();
|
||||
if meta.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let size = meta.get(3).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
let mut entry = TreeEntry {
|
||||
name: name.to_string(),
|
||||
kind: meta[1].to_string(),
|
||||
size,
|
||||
link_target: None,
|
||||
};
|
||||
if meta[0] == "120000" {
|
||||
entry.kind = "link".to_string();
|
||||
let spec = if tree_path.is_empty() {
|
||||
format!("{reference}:{name}")
|
||||
} else {
|
||||
format!("{reference}:{tree_path}/{name}")
|
||||
};
|
||||
if let Ok((true, target)) = run_text(&["git", "show", &spec], repo_path, timed()) {
|
||||
entry.link_target = Some(py_strip(&target).to_string());
|
||||
}
|
||||
}
|
||||
entries.push(entry);
|
||||
}
|
||||
Ok(Some(entries))
|
||||
})();
|
||||
match result {
|
||||
Ok(entries) => entries,
|
||||
Err(RunError::Timeout) => {
|
||||
tracing::warn!("Timeout listing tree contents");
|
||||
None
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Error getting tree entries: {e:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BlobInfo {
|
||||
pub size: u64,
|
||||
pub is_tree: bool,
|
||||
pub is_binary: bool,
|
||||
pub is_symlink: bool,
|
||||
pub symlink_target: Option<String>,
|
||||
}
|
||||
|
||||
/// `get_blob_info`.
|
||||
pub fn blob_info(repo_path: &Path, reference: &str, path: &str) -> Option<BlobInfo> {
|
||||
let file_path = path.trim_matches('/');
|
||||
let spec = format!("{reference}:{file_path}");
|
||||
let result = (|| -> Result<Option<BlobInfo>, RunError> {
|
||||
let (ok, out) = run_text(&["git", "cat-file", "-s", &spec], repo_path, timed())?;
|
||||
if !ok {
|
||||
return Ok(None);
|
||||
}
|
||||
let size: u64 = py_strip(&out).parse().map_err(|_| RunError::Failed)?;
|
||||
let tree_spec = if file_path.is_empty() {
|
||||
reference.to_string()
|
||||
} else {
|
||||
spec.clone()
|
||||
};
|
||||
let is_tree = run(&["git", "ls-tree", &tree_spec], repo_path, timed())?.ok();
|
||||
let (parent, filename) = match file_path.rsplit_once('/') {
|
||||
Some((parent, name)) => (parent, name),
|
||||
None => ("", file_path),
|
||||
};
|
||||
let parent_spec = if parent.is_empty() {
|
||||
reference.to_string()
|
||||
} else {
|
||||
format!("{reference}:{parent}")
|
||||
};
|
||||
let (ok, listing) = run_text(&["git", "ls-tree", &parent_spec], repo_path, timed())?;
|
||||
let needle = format!("\t{filename}");
|
||||
let is_symlink = ok
|
||||
&& py_strip(&listing)
|
||||
.split('\n')
|
||||
.any(|line| line.contains(&needle) && line.starts_with("120000"));
|
||||
let mut symlink_target = None;
|
||||
if is_symlink {
|
||||
let (ok, target) = run_text(&["git", "show", &spec], repo_path, timed())?;
|
||||
if ok {
|
||||
symlink_target = Some(py_strip(&target).to_string());
|
||||
}
|
||||
}
|
||||
let mut is_binary = false;
|
||||
if !is_symlink {
|
||||
// Upstream reads the whole blob and looks at its first 8192 bytes.
|
||||
let (sample, _) =
|
||||
run_capped(&["git", "show", &spec], repo_path, timed(), SAMPLE_BYTES)?;
|
||||
if sample.ok() {
|
||||
let head = &sample.stdout[..];
|
||||
if head.contains(&0) {
|
||||
is_binary = true;
|
||||
} else {
|
||||
// Upstream's second check; `<ref>:<path>` is not a file, so it never matches.
|
||||
let out = run(
|
||||
&[
|
||||
"git",
|
||||
"diff",
|
||||
"--numstat",
|
||||
"--no-index",
|
||||
"--",
|
||||
"/dev/null",
|
||||
&spec,
|
||||
],
|
||||
repo_path,
|
||||
timed(),
|
||||
)?;
|
||||
let first = text(&out.stdout)?;
|
||||
if out.code == Some(1)
|
||||
&& py_strip(&first)
|
||||
.split('\n')
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.starts_with('-')
|
||||
{
|
||||
is_binary = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(BlobInfo {
|
||||
size,
|
||||
is_tree,
|
||||
is_binary,
|
||||
is_symlink,
|
||||
symlink_target,
|
||||
}))
|
||||
})();
|
||||
result.unwrap_or_else(|e| {
|
||||
tracing::debug!("Error getting blob info: {e:?}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// `get_blob_content`.
|
||||
pub fn blob_content(repo_path: &Path, reference: &str, path: &str) -> Option<String> {
|
||||
let spec = format!("{reference}:{}", path.trim_matches('/'));
|
||||
match run_text(&["git", "show", &spec], repo_path, timed()) {
|
||||
Ok((true, content)) => Some(content),
|
||||
Ok(_) => None,
|
||||
Err(e) => {
|
||||
tracing::warn!("Error getting blob content: {e:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `get_blob_stream`: `git show` spooled to an anonymous file, as upstream's
|
||||
/// Resource proxies a pipe into a temporary file before sending it.
|
||||
pub fn blob_stream(repo_path: &Path, reference: &str, path: &str) -> Option<std::fs::File> {
|
||||
use std::io::Seek;
|
||||
let spec = format!("{reference}:{}", path.trim_matches('/'));
|
||||
let result = (|| -> std::io::Result<std::fs::File> {
|
||||
let mut spool = tempfile::tempfile()?;
|
||||
let mut child = Command::new("git")
|
||||
.args(["show", &spec])
|
||||
.current_dir(repo_path)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(spool.try_clone()?)
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
child.wait()?;
|
||||
spool.rewind()?;
|
||||
Ok(spool)
|
||||
})();
|
||||
result
|
||||
.map_err(|e| tracing::warn!("Error getting blob content handle: {e}"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RefInfo {
|
||||
pub name: String,
|
||||
pub short_hash: String,
|
||||
pub commit_subject: String,
|
||||
pub is_default: bool,
|
||||
pub is_annotated: bool,
|
||||
pub tag_message: Option<String>,
|
||||
}
|
||||
|
||||
/// `get_refs_info`: heads and tags.
|
||||
pub fn refs_info(repo_path: &Path, default_branch: Option<&str>) -> (Vec<RefInfo>, Vec<RefInfo>) {
|
||||
let mut heads = Vec::new();
|
||||
let mut tags = Vec::new();
|
||||
let result = (|| -> Result<(), RunError> {
|
||||
let (ok, out) = run_text(
|
||||
&[
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(objectname)|%(refname)|%(refname:short)|%(subject)",
|
||||
"refs/heads",
|
||||
"refs/tags",
|
||||
],
|
||||
repo_path,
|
||||
timed(),
|
||||
)?;
|
||||
if !ok {
|
||||
return Ok(());
|
||||
}
|
||||
for line in py_strip(&out).split('\n') {
|
||||
if py_strip(line).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let parts: Vec<&str> = line.splitn(4, '|').collect();
|
||||
if parts.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let mut info = RefInfo {
|
||||
name: parts[2].to_string(),
|
||||
short_hash: parts[0].chars().take(7).collect(),
|
||||
commit_subject: parts.get(3).unwrap_or(&"").to_string(),
|
||||
is_default: Some(parts[2]) == default_branch,
|
||||
is_annotated: false,
|
||||
tag_message: None,
|
||||
};
|
||||
if parts[1].starts_with("refs/heads/") {
|
||||
heads.push(info);
|
||||
} else if parts[1].starts_with("refs/tags/") {
|
||||
if let Ok((true, tag)) = run_text(
|
||||
&[
|
||||
"git",
|
||||
"for-each-ref",
|
||||
"--format=%(objecttype)|%(contents:subject)",
|
||||
parts[1],
|
||||
],
|
||||
repo_path,
|
||||
timed(),
|
||||
) && let Some((kind, message)) = py_strip(&tag).split_once('|')
|
||||
&& kind == "tag"
|
||||
{
|
||||
info.is_annotated = true;
|
||||
info.tag_message = Some(message.to_string());
|
||||
}
|
||||
tags.push(info);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
tracing::warn!("Error getting refs info: {e:?}");
|
||||
}
|
||||
(heads, tags)
|
||||
}
|
||||
|
||||
/// `get_commit_count`.
|
||||
pub fn commit_count(repo_path: &Path, reference: &str) -> u64 {
|
||||
match run_text(
|
||||
&["git", "rev-list", "--count", reference],
|
||||
repo_path,
|
||||
timed(),
|
||||
) {
|
||||
Ok((true, out)) => py_strip(&out).parse().unwrap_or(0),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CommitEntry {
|
||||
pub hash: String,
|
||||
pub subject: String,
|
||||
pub author: String,
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
/// `get_commits`.
|
||||
pub fn commits(
|
||||
repo_path: &Path,
|
||||
reference: &str,
|
||||
file_path: &str,
|
||||
skip: u64,
|
||||
limit: u64,
|
||||
) -> Option<Vec<CommitEntry>> {
|
||||
const SEP: &str = "|_SEP_|";
|
||||
let format = format!("--format=%H{SEP}%s{SEP}%an{SEP}%ae{SEP}%at");
|
||||
let (skip, limit) = (skip.to_string(), limit.to_string());
|
||||
let mut argv = vec![
|
||||
"git", "log", &format, "--skip", &skip, "-n", &limit, reference,
|
||||
];
|
||||
if !file_path.is_empty() {
|
||||
argv.extend(["--", file_path]);
|
||||
}
|
||||
let result = (|| -> Result<Option<Vec<CommitEntry>>, RunError> {
|
||||
let (ok, out) = run_text(&argv, repo_path, timed())?;
|
||||
if !ok {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut commits = Vec::new();
|
||||
for line in py_strip(&out).split('\n') {
|
||||
if py_strip(line).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let parts: Vec<&str> = line.splitn(5, SEP).collect();
|
||||
if parts.len() >= 5 {
|
||||
commits.push(CommitEntry {
|
||||
hash: parts[0].to_string(),
|
||||
subject: parts[1].to_string(),
|
||||
author: parts[2].to_string(),
|
||||
timestamp: super::py_int(parts[4]).ok_or(RunError::Failed)? as i64,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Some(commits))
|
||||
})();
|
||||
result.unwrap_or_else(|e| {
|
||||
tracing::debug!("Error getting commits: {e:?}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ChangedFile {
|
||||
pub path: String,
|
||||
pub status: &'static str,
|
||||
pub additions: i64,
|
||||
pub deletions: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CommitInfo {
|
||||
pub parents: Vec<String>,
|
||||
pub author_name: String,
|
||||
pub author_email: String,
|
||||
pub author_date: String,
|
||||
pub committer_name: String,
|
||||
pub committer_email: String,
|
||||
pub committer_date: String,
|
||||
pub message: String,
|
||||
pub files: Vec<ChangedFile>,
|
||||
pub diff: Option<String>,
|
||||
}
|
||||
|
||||
/// `get_commit_info`.
|
||||
pub fn commit_info(repo_path: &Path, hash: &str) -> Option<CommitInfo> {
|
||||
let result = (|| -> Result<Option<CommitInfo>, RunError> {
|
||||
let (ok, out) = run_text(
|
||||
&[
|
||||
"git",
|
||||
"show",
|
||||
"--no-patch",
|
||||
"--format=%P%n%an%n%ae%n%aI%n%cn%n%ce%n%cI%n%B",
|
||||
hash,
|
||||
],
|
||||
repo_path,
|
||||
timed(),
|
||||
)?;
|
||||
if !ok {
|
||||
return Ok(None);
|
||||
}
|
||||
let lines: Vec<&str> = out.split('\n').collect();
|
||||
if lines.len() < 7 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut info = CommitInfo {
|
||||
parents: lines[0].split_whitespace().map(str::to_string).collect(),
|
||||
author_name: lines[1].to_string(),
|
||||
author_email: lines[2].to_string(),
|
||||
author_date: lines[3].to_string(),
|
||||
committer_name: lines[4].to_string(),
|
||||
committer_email: lines[5].to_string(),
|
||||
committer_date: lines[6].to_string(),
|
||||
message: py_strip(&lines[7..].join("\n")).to_string(),
|
||||
files: Vec::new(),
|
||||
diff: None,
|
||||
};
|
||||
let (ok, stats) = run_text(
|
||||
&["git", "diff-tree", "--numstat", "-r", hash],
|
||||
repo_path,
|
||||
timed(),
|
||||
)?;
|
||||
if ok {
|
||||
for line in py_strip(&stats).split('\n') {
|
||||
if py_strip(line).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let parts: Vec<&str> = line.split('\t').collect();
|
||||
if parts.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
let (mut additions, mut deletions) = (parts[0], parts[1]);
|
||||
let file_path = parts[2];
|
||||
let mut status = "M";
|
||||
if additions == "-" && deletions == "-" {
|
||||
status = "R";
|
||||
additions = "0";
|
||||
deletions = "0";
|
||||
}
|
||||
if let Some(parent) = info.parents.first() {
|
||||
let in_parent = run(
|
||||
&["git", "cat-file", "-e", &format!("{parent}:{file_path}")],
|
||||
repo_path,
|
||||
timed(),
|
||||
)?;
|
||||
if !in_parent.ok() {
|
||||
status = "A";
|
||||
} else {
|
||||
let in_current = run(
|
||||
&["git", "cat-file", "-e", &format!("{hash}:{file_path}")],
|
||||
repo_path,
|
||||
timed(),
|
||||
)?;
|
||||
if !in_current.ok() {
|
||||
status = "D";
|
||||
}
|
||||
}
|
||||
}
|
||||
let count = |s: &str| if s == "-" { Some(0) } else { super::py_int(s) };
|
||||
let (additions, deletions) = match (count(additions), count(deletions)) {
|
||||
(Some(a), Some(d)) => (a as i64, d as i64),
|
||||
_ => (0, 0),
|
||||
};
|
||||
info.files.push(ChangedFile {
|
||||
path: file_path.to_string(),
|
||||
status,
|
||||
additions,
|
||||
deletions,
|
||||
});
|
||||
}
|
||||
}
|
||||
let (ok, diff) = run_text(&["git", "show", "--format=", hash], repo_path, timed())?;
|
||||
if ok {
|
||||
info.diff = Some(diff);
|
||||
}
|
||||
Ok(Some(info))
|
||||
})();
|
||||
result.unwrap_or_else(|e| {
|
||||
tracing::warn!("Error getting commit info: {e:?}");
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
/// The `cat-file -t` check of the commit page: `Ok(true)` for a commit.
|
||||
pub fn is_commit(repo_path: &Path, hash: &str) -> Result<bool, RunError> {
|
||||
let (ok, kind) = run_text(&["git", "cat-file", "-t", hash], repo_path, timed())?;
|
||||
Ok(ok && py_strip(&kind) == "commit")
|
||||
}
|
||||
|
||||
/// The commit page's signature status (`get_commit_signature`).
|
||||
pub struct SignatureStatus {
|
||||
pub signed: bool,
|
||||
pub valid: bool,
|
||||
pub author_match: bool,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
pub fn commit_signature(repo_path: &Path, hash: &str) -> SignatureStatus {
|
||||
let status = |signed, valid, author_match, message: &str| SignatureStatus {
|
||||
signed,
|
||||
valid,
|
||||
author_match,
|
||||
message: message.to_string(),
|
||||
};
|
||||
let (ok, content) = match run_text(&["git", "cat-file", "-p", hash], repo_path, timed()) {
|
||||
Ok(result) => result,
|
||||
Err(RunError::Timeout) => return status(false, false, false, "Timeout"),
|
||||
Err(RunError::Failed) => return status(false, false, false, "Error"),
|
||||
};
|
||||
if !ok {
|
||||
return status(false, false, false, "Could not read commit object");
|
||||
}
|
||||
let mut sig_lines: Vec<&str> = Vec::new();
|
||||
let mut signed_lines: Vec<&str> = Vec::new();
|
||||
let mut in_signature = false;
|
||||
for line in content.split('\n') {
|
||||
if line.starts_with("gpgsig ") || line.starts_with("gpgsig-sha256 ") {
|
||||
in_signature = true;
|
||||
let start = line.find(' ').map_or(0, |i| i + 1);
|
||||
sig_lines.push(&line[start..]);
|
||||
} else if in_signature {
|
||||
if let Some(rest) = line.strip_prefix(' ') {
|
||||
sig_lines.push(rest);
|
||||
} else {
|
||||
in_signature = false;
|
||||
signed_lines.push(line);
|
||||
}
|
||||
} else {
|
||||
signed_lines.push(line);
|
||||
}
|
||||
}
|
||||
if sig_lines.is_empty() {
|
||||
return status(false, false, false, "Not signed");
|
||||
}
|
||||
let armored = sig_lines.join("\n");
|
||||
let signed_content = signed_lines.join("\n").into_bytes();
|
||||
let Ok(sig_data) = crate::commitsigs::unarmor_ssh_signature(&armored) else {
|
||||
return status(true, false, false, "Signature validation error");
|
||||
};
|
||||
let rsg = match crate::commitsigs::parse_ssh_signature(&sig_data) {
|
||||
Ok(sig) => sig.signature_data,
|
||||
Err(_) => return status(true, false, false, "Malformed SSH wrapping for RSG data"),
|
||||
};
|
||||
let message = rmpv::Value::Binary(signed_content.clone());
|
||||
let valid =
|
||||
match rns_tools::rsg::validate_rsg(&rsg, rns_tools::rsg::Message::Unpacked(&message), None)
|
||||
{
|
||||
Ok(Some(valid)) => valid,
|
||||
Ok(None) => return status(true, false, false, "Invalid signature"),
|
||||
Err(_) => return status(true, false, false, "Signature validation error"),
|
||||
};
|
||||
let signer = hex::encode(valid.signer_hash);
|
||||
let author = match crate::commitsigs::extract_commit_author(&signed_content) {
|
||||
crate::commitsigs::HeaderEmail::Email(email) => email,
|
||||
crate::commitsigs::HeaderEmail::DecodeError => "1".to_string(),
|
||||
};
|
||||
if author.is_empty() {
|
||||
return status(true, true, false, "Could not verify author");
|
||||
}
|
||||
if author == signer {
|
||||
status(true, true, true, &format!("Valid, signed by <{signer}>"))
|
||||
} else {
|
||||
status(
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
&format!("Invalid signer <{signer}>, author is <{author}>"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// `get_readme_content`: always read from `HEAD`, as upstream does.
|
||||
pub fn readme_content(repo_path: &Path) -> Option<(String, bool)> {
|
||||
const NAMES: [(&str, bool); 11] = [
|
||||
("README.mu", false),
|
||||
("Readme.mu", false),
|
||||
("readme.mu", false),
|
||||
("README", false),
|
||||
("readme", false),
|
||||
("README.md", true),
|
||||
("readme.md", true),
|
||||
("README.rst", false),
|
||||
("README.txt", false),
|
||||
("readme.rst", false),
|
||||
("readme.txt", false),
|
||||
];
|
||||
for (name, is_markdown) in NAMES {
|
||||
if let Ok((true, content)) =
|
||||
run_text(&["git", "show", &format!("HEAD:{name}")], repo_path, None)
|
||||
{
|
||||
return Some((content, is_markdown));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The refs page's default branch (`git symbolic-ref HEAD`).
|
||||
pub fn default_branch(repo_path: &Path) -> Option<String> {
|
||||
match run_text(&["git", "symbolic-ref", "HEAD"], repo_path, timed()) {
|
||||
Ok((true, out)) => Some(py_strip(&out).replace("refs/heads/", "")),
|
||||
Err(RunError::Timeout) => {
|
||||
tracing::warn!("Git command execution timed out");
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn captured_output_is_bounded() {
|
||||
let cwd = std::env::temp_dir();
|
||||
let endless = ["sh", "-c", "while :; do printf '%4096s' x; done"];
|
||||
// A sample takes its bytes and stops the command.
|
||||
let (sample, truncated) = run_capped(&endless, &cwd, timed(), SAMPLE_BYTES).unwrap();
|
||||
assert!(sample.ok() && truncated);
|
||||
assert_eq!(sample.stdout.len() as u64, SAMPLE_BYTES);
|
||||
// A full capture refuses instead of growing without bound.
|
||||
assert!(matches!(
|
||||
run(&endless, &cwd, timed()),
|
||||
Err(RunError::Failed)
|
||||
));
|
||||
// Output that ends exactly at the limit is whole.
|
||||
let exact = ["sh", "-c", "printf '%8192s' x"];
|
||||
let (out, truncated) = run_capped(&exact, &cwd, timed(), SAMPLE_BYTES).unwrap();
|
||||
assert!(out.ok() && !truncated && out.stdout.len() as u64 == SAMPLE_BYTES);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,835 @@
|
||||
//! The Nomad Network page node (`RNS/Utilities/rngit/pages.py`).
|
||||
|
||||
mod chart;
|
||||
mod files;
|
||||
pub mod git;
|
||||
mod views;
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
use crate::highlight::SyntaxHighlighter;
|
||||
use crate::md2micron::MarkdownToMicron;
|
||||
use crate::server::layout::Repositories;
|
||||
use crate::server::perms::Perm;
|
||||
use crate::server::stats::Stats;
|
||||
|
||||
pub use chart::{render_chart, render_combined_chart};
|
||||
|
||||
/// `NomadNetworkNode.APP_NAME` plus the aspect.
|
||||
pub const APP_NAME: &str = "nomadnetwork.node";
|
||||
/// `JOBS_INTERVAL`, seconds.
|
||||
pub const JOBS_INTERVAL: u64 = 5;
|
||||
/// What the pages render as `{VERSION}`: this crate's version, as `rngit-rs --version` prints it.
|
||||
/// Differs from `pages.py`, which renders `RNS._version.__version__`.
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub const PATH_INDEX: &str = "/page/index.mu";
|
||||
pub const PATH_GROUP: &str = "/page/group.mu";
|
||||
pub const PATH_REPO: &str = "/page/repo.mu";
|
||||
pub const PATH_TREE: &str = "/page/tree.mu";
|
||||
pub const PATH_BLOB: &str = "/page/blob.mu";
|
||||
pub const PATH_COMMITS: &str = "/page/commits.mu";
|
||||
pub const PATH_COMMIT: &str = "/page/commit.mu";
|
||||
pub const PATH_REFS: &str = "/page/refs.mu";
|
||||
pub const PATH_STATS: &str = "/page/stats.mu";
|
||||
pub const PATH_RELEASES: &str = "/page/releases.mu";
|
||||
pub const PATH_RELEASE: &str = "/page/release.mu";
|
||||
pub const PATH_WORK: &str = "/page/work.mu";
|
||||
pub const PATH_WORK_DOC: &str = "/page/work_doc.mu";
|
||||
pub const PATH_MEDIA: &str = "/media";
|
||||
pub const FILE_ARTIFACT: &str = "/file/artifact";
|
||||
pub const FILE_DOWNLOAD: &str = "/file/download";
|
||||
pub const FILE_WORKDOC: &str = "/file/workdoc";
|
||||
|
||||
/// Every request path the node registers, in upstream's order.
|
||||
pub const PATHS: [&str; 17] = [
|
||||
PATH_INDEX,
|
||||
PATH_GROUP,
|
||||
PATH_REPO,
|
||||
PATH_TREE,
|
||||
PATH_BLOB,
|
||||
PATH_COMMITS,
|
||||
PATH_COMMIT,
|
||||
PATH_REFS,
|
||||
PATH_STATS,
|
||||
PATH_RELEASES,
|
||||
PATH_RELEASE,
|
||||
PATH_WORK,
|
||||
PATH_WORK_DOC,
|
||||
PATH_MEDIA,
|
||||
FILE_ARTIFACT,
|
||||
FILE_DOWNLOAD,
|
||||
FILE_WORKDOC,
|
||||
];
|
||||
|
||||
pub(crate) const BLOB_SIZE_LIMIT: u64 = 256 * 1024;
|
||||
/// Largest file `/file/download` converts to Micron in memory.
|
||||
pub(crate) const CONVERT_SIZE_LIMIT: u64 = 4 * 1024 * 1024;
|
||||
pub(crate) const TREE_ENTRIES_PER_PAGE: usize = 1000;
|
||||
pub(crate) const COMMITS_PER_PAGE: usize = 100;
|
||||
pub(crate) const MAX_RENDER_WIDTH: usize = 100;
|
||||
pub(crate) const TAB_WIDTH: &str = " ";
|
||||
|
||||
pub(crate) const CLR_FOLDER: &str = "`Ffe6";
|
||||
pub(crate) const CLR_FILE: &str = "`F66d";
|
||||
pub(crate) const CLR_DIM: &str = "`F666";
|
||||
pub(crate) const CLR_DIM_H: &str = "`F444";
|
||||
pub(crate) const CLR_OK_DIM: &str = "`FT537855";
|
||||
pub(crate) const CLR_DIFF_A: &str = "`F0a0";
|
||||
pub(crate) const CLR_DIFF_R: &str = "`F900";
|
||||
pub(crate) const CLR_DIFF_P: &str = "`F0aa";
|
||||
|
||||
pub(crate) const RCLR_PUSH: &str = "B9A810";
|
||||
pub(crate) const RCLR_PUSH_G: &str = "791212";
|
||||
pub(crate) const RCLR_FETCH: &str = "10b981";
|
||||
pub(crate) const RCLR_FETCH_G: &str = "1c5e71";
|
||||
pub(crate) const RCLR_VIEW: &str = "3b82f6";
|
||||
pub(crate) const RCLR_VIEW_G: &str = "13428A";
|
||||
pub(crate) const RCLR_DOWNLOAD: &str = "7831E0";
|
||||
pub(crate) const RCLR_DOWNLOAD_G: &str = "c5754d";
|
||||
|
||||
pub(crate) const CONVERTABLE_EXTS: [&str; 1] = [".md"];
|
||||
pub(crate) const RENDERABLE_EXTS: [&str; 2] = [".md", ".mu"];
|
||||
pub(crate) const RENDER_DEFAULT: [&str; 2] = [".md", ".mu"];
|
||||
pub(crate) const IMAGE_EXTS: [&str; 8] = [
|
||||
".webp", ".png", ".jpg", ".jpeg", ".gif", ".tiff", ".tif", ".bmp",
|
||||
];
|
||||
|
||||
// Names `rngit-rs`, where `DEFAULT_BASE_TEMPLATE` (`pages.py`) names `rngit`.
|
||||
const DEFAULT_BASE_TEMPLATE: &str = "#!c=0\n> {NODE_NAME}\n\n{NAVIGATION}\n{PAGE_CONTENT}\n<\n-\n`a`F666`[Served by rngit-rs {VERSION}`:/page/index.mu] - {GEN_TIME}`f";
|
||||
const DEFAULT_FRONT_TEMPLATE: &str = "> Groups\n\n{PAGE_CONTENT}";
|
||||
const DEFAULT_NO_IDENT_TEMPLATE: &str =
|
||||
">>No Identity\n\nThis page requires identification, and none was received.\n";
|
||||
/// Templates whose default is the page content alone.
|
||||
const PLAIN_TEMPLATES: [&str; 12] = [
|
||||
"group", "repo", "releases", "release", "tree", "blob", "commits", "commit", "refs", "stats",
|
||||
"work", "work_doc",
|
||||
];
|
||||
|
||||
/// The `[pages]` keys `NomadNetworkNode.__init__` reads (`pages.py`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PageOptions {
|
||||
pub use_nerdfonts: bool,
|
||||
pub media_conversion: bool,
|
||||
/// Quantized; applied to the node destination only when above 0.
|
||||
pub stamp_value: Option<f64>,
|
||||
/// Quantized announced link request cost.
|
||||
pub link_cost: f64,
|
||||
}
|
||||
|
||||
impl Default for PageOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
use_nerdfonts: true,
|
||||
media_conversion: true,
|
||||
stamp_value: None,
|
||||
link_cost: crate::server::config::DEFAULT_LINK_COST,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PageOptions {
|
||||
/// Read the `[pages]` keys from the node config text; a value `as_bool`
|
||||
/// or `as_float` rejects is an error, as upstream raises.
|
||||
pub fn from_config_text(text: &str) -> Result<Self, rns_runtime::config::ConfigError> {
|
||||
let mut options = Self::default();
|
||||
let config = rns_runtime::config::Config::parse(text)?;
|
||||
let Some(section) = config.section("pages") else {
|
||||
return Ok(options);
|
||||
};
|
||||
let as_bool = |key: &str| {
|
||||
section
|
||||
.get_bool(key)
|
||||
.ok_or_else(|| rns_runtime::config::ConfigError::InvalidValue {
|
||||
section: "pages".to_string(),
|
||||
key: key.to_string(),
|
||||
message: "not a boolean".to_string(),
|
||||
})
|
||||
};
|
||||
if section.has("unicode_icons") && as_bool("unicode_icons")? {
|
||||
options.use_nerdfonts = false;
|
||||
}
|
||||
if section.has("media_conversion") {
|
||||
options.media_conversion = as_bool("media_conversion")?;
|
||||
}
|
||||
if section.has("link_cost") {
|
||||
options.link_cost = crate::server::config::as_cost(section, "pages", "link_cost")?;
|
||||
}
|
||||
if section.has("stamp_value") {
|
||||
options.stamp_value = Some(crate::server::config::as_cost(
|
||||
section,
|
||||
"pages",
|
||||
"stamp_value",
|
||||
)?);
|
||||
}
|
||||
Ok(options)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a page handler answers, as upstream's handler return values.
|
||||
pub enum PageReply {
|
||||
/// Rendered Micron bytes.
|
||||
Page(Vec<u8>),
|
||||
/// One packed MessagePack value: `False` or the work-document list.
|
||||
Value(Vec<u8>),
|
||||
/// A file response with its `{"name": bytes}` metadata.
|
||||
File { file: std::fs::File, name: String },
|
||||
/// `None`, or an exception in the handler thread: nothing is sent.
|
||||
Drop,
|
||||
}
|
||||
|
||||
/// The packed `{"name": name.encode("utf-8")}` metadata of a file response.
|
||||
pub fn file_metadata(name: &str) -> Vec<u8> {
|
||||
let value = Value::Map(vec![(
|
||||
Value::from("name"),
|
||||
Value::Binary(name.as_bytes().to_vec()),
|
||||
)]);
|
||||
let mut out = Vec::new();
|
||||
rmpv::encode::write_value(&mut out, &value).expect("writing to a Vec");
|
||||
out
|
||||
}
|
||||
|
||||
/// Identity hash of the source repository's announced node, by destination hash.
|
||||
pub type Recall = Box<dyn Fn([u8; 16]) -> Option<[u8; 16]> + Send + Sync>;
|
||||
|
||||
/// The page node's state (`NomadNetworkNode`).
|
||||
pub struct PageNode {
|
||||
pub repos: Arc<RwLock<Repositories>>,
|
||||
pub stats: Arc<Stats>,
|
||||
pub node_name: String,
|
||||
/// The repositories destination, shown in each repository's `rns://` URL.
|
||||
pub repositories_destination: [u8; 16],
|
||||
pub templates_dir: PathBuf,
|
||||
pub options: PageOptions,
|
||||
pub recall: Option<Recall>,
|
||||
null_hash: [u8; 16],
|
||||
highlighter: SyntaxHighlighter,
|
||||
mdc: MarkdownToMicron,
|
||||
thanks: Mutex<VecDeque<Vec<u8>>>,
|
||||
}
|
||||
|
||||
/// A request as the handlers see it.
|
||||
pub struct PageRequest<'a> {
|
||||
pub path: &'a str,
|
||||
pub data: &'a Value,
|
||||
pub link_id: [u8; 16],
|
||||
pub identity: Option<[u8; 16]>,
|
||||
}
|
||||
|
||||
impl PageNode {
|
||||
/// Creates `<configdir>/templates` as upstream does.
|
||||
pub fn new(
|
||||
repos: Arc<RwLock<Repositories>>,
|
||||
stats: Arc<Stats>,
|
||||
node_name: String,
|
||||
repositories_destination: [u8; 16],
|
||||
configdir: &Path,
|
||||
options: PageOptions,
|
||||
) -> Self {
|
||||
let templates_dir = configdir.join("templates");
|
||||
if !templates_dir.is_dir()
|
||||
&& let Err(e) = std::fs::create_dir_all(&templates_dir)
|
||||
{
|
||||
tracing::error!(
|
||||
"Could not create templates directory {}: {e}",
|
||||
templates_dir.display()
|
||||
);
|
||||
}
|
||||
let null_hash = rns_identity::identity::Identity::from_private_key(&[0u8; 64])
|
||||
.expect("64-byte key")
|
||||
.hash;
|
||||
let highlighter = SyntaxHighlighter::default();
|
||||
Self {
|
||||
repos,
|
||||
stats,
|
||||
node_name,
|
||||
repositories_destination,
|
||||
templates_dir,
|
||||
options,
|
||||
recall: None,
|
||||
null_hash,
|
||||
mdc: MarkdownToMicron::new(MAX_RENDER_WIDTH, Some(highlighter.clone()), None),
|
||||
highlighter,
|
||||
thanks: Mutex::new(VecDeque::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatch a request to its handler by path.
|
||||
pub fn handle(&self, request: &PageRequest<'_>) -> PageReply {
|
||||
let page = |r: Option<Vec<u8>>| r.map_or(PageReply::Drop, PageReply::Page);
|
||||
match request.path {
|
||||
PATH_INDEX => page(self.serve_front_page(request)),
|
||||
PATH_GROUP => page(self.serve_group_page(request)),
|
||||
PATH_REPO => page(self.serve_repo_page(request)),
|
||||
PATH_TREE => page(self.serve_tree_page(request)),
|
||||
PATH_BLOB => page(self.serve_blob_page(request)),
|
||||
PATH_COMMITS => page(self.serve_commits_page(request)),
|
||||
PATH_COMMIT => page(self.serve_commit_page(request)),
|
||||
PATH_REFS => page(self.serve_refs_page(request)),
|
||||
PATH_STATS => page(self.serve_stats_page(request)),
|
||||
PATH_RELEASES => page(self.serve_releases_page(request)),
|
||||
PATH_RELEASE => page(self.serve_release_page(request)),
|
||||
PATH_WORK => page(self.serve_work_page(request)),
|
||||
PATH_WORK_DOC => page(self.serve_work_doc_page(request)),
|
||||
PATH_MEDIA => self.serve_media(request),
|
||||
FILE_ARTIFACT => self.serve_artifact(request),
|
||||
FILE_DOWNLOAD => self.serve_download(request),
|
||||
FILE_WORKDOC => self.serve_wd_download(request),
|
||||
_ => PageReply::Drop,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn icon(&self, name: &str) -> &'static str {
|
||||
let nf = self.options.use_nerdfonts;
|
||||
match (name, nf) {
|
||||
("sep", _) => "\u{2022}",
|
||||
("folder", true) => "\u{F0256}",
|
||||
("file", true) => "\u{F0F6}",
|
||||
("branch", true) => "\u{F062C}",
|
||||
("commits", true) => "\u{F02DA}",
|
||||
("tag", true) => "\u{F04FC}",
|
||||
("stats", true) => "\u{F201}",
|
||||
("heart", true) => "\u{F02D1}",
|
||||
("package", true) => "\u{F03D7}",
|
||||
("work", true) => "\u{F1323}",
|
||||
("folder", false) => "\u{1F5C0}",
|
||||
("file", false) => "\u{1F5CE}",
|
||||
("branch", false) => "\u{2443}",
|
||||
("commits", false) => "\u{1F5B9}",
|
||||
("tag", false) => "\u{2306}",
|
||||
("stats", false) => "\u{1F5E0}",
|
||||
("heart", false) => "\u{2665}",
|
||||
("package", false) => "\u{25C7}",
|
||||
("work", false) => "\u{2638}",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// The caller, or the null identity when it has not identified.
|
||||
pub(crate) fn caller(&self, identity: Option<[u8; 16]>) -> [u8; 16] {
|
||||
identity.unwrap_or(self.null_hash)
|
||||
}
|
||||
|
||||
/// The no-identity check every page makes for an unidentified, blocked caller.
|
||||
pub(crate) fn blocked_unidentified(&self, identity: Option<[u8; 16]>) -> bool {
|
||||
identity.is_none()
|
||||
&& self
|
||||
.read_repos()
|
||||
.blocked
|
||||
.iter()
|
||||
.any(|b| b[..] == self.null_hash)
|
||||
}
|
||||
|
||||
pub(crate) fn read_repos(&self) -> std::sync::RwLockReadGuard<'_, Repositories> {
|
||||
self.repos.read().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_permission(
|
||||
&self,
|
||||
identity: Option<[u8; 16]>,
|
||||
group: &str,
|
||||
repo: &str,
|
||||
perm: Perm,
|
||||
) -> bool {
|
||||
self.read_repos()
|
||||
.resolve_permission(&self.caller(identity), group, repo, perm)
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_doc_permission(
|
||||
&self,
|
||||
identity: Option<[u8; 16]>,
|
||||
group: &str,
|
||||
repo: &str,
|
||||
doc_id: i128,
|
||||
perm: Perm,
|
||||
) -> bool {
|
||||
crate::server::work::resolve_doc_permission(
|
||||
&self.read_repos(),
|
||||
&self.caller(identity),
|
||||
Some((group, repo)),
|
||||
doc_id,
|
||||
perm,
|
||||
)
|
||||
}
|
||||
|
||||
/// `get_accessible_repository`: the repository's path when the caller may read it.
|
||||
pub(crate) fn accessible_repository(
|
||||
&self,
|
||||
identity: Option<[u8; 16]>,
|
||||
group: &str,
|
||||
repo: &str,
|
||||
) -> Option<crate::server::layout::Repository> {
|
||||
let repos = self.read_repos();
|
||||
let repository = repos.repository(group, repo)?.clone();
|
||||
repos
|
||||
.resolve_permission(&self.caller(identity), group, repo, Perm::Read)
|
||||
.then_some(repository)
|
||||
}
|
||||
|
||||
/// `get_template`: `<templates>/<name>.mu`, run when executable.
|
||||
fn get_template(&self, name: &str) -> Option<String> {
|
||||
let path = self.templates_dir.join(format!("{name}.mu"));
|
||||
let meta = std::fs::metadata(&path).ok().filter(|m| m.is_file())?;
|
||||
if crate::platform::mode_executable(&meta) {
|
||||
let argv = [path.to_string_lossy().into_owned()];
|
||||
let argv: Vec<&str> = argv.iter().map(String::as_str).collect();
|
||||
let output = std::process::Command::new(argv[0])
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
.output();
|
||||
match output.ok().and_then(|o| String::from_utf8(o.stdout).ok()) {
|
||||
Some(text) => Some(text.trim_end_matches(py_space).to_string()),
|
||||
None => {
|
||||
tracing::error!(
|
||||
"Could not get dynamic template content from {}",
|
||||
path.display()
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
match std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|d| String::from_utf8(d).ok())
|
||||
{
|
||||
Some(text) => Some(text.trim_end_matches(py_space).to_string()),
|
||||
None => {
|
||||
tracing::error!(
|
||||
"Could not get static template content from {}",
|
||||
path.display()
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn builtin_template(name: &str) -> Option<&'static str> {
|
||||
match name {
|
||||
"front" => Some(DEFAULT_FRONT_TEMPLATE),
|
||||
"no_ident" => Some(DEFAULT_NO_IDENT_TEMPLATE),
|
||||
n if PLAIN_TEMPLATES.contains(&n) => Some("{PAGE_CONTENT}"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `render_template` (`pages.py`).
|
||||
pub(crate) fn render(
|
||||
&self,
|
||||
page_content: &str,
|
||||
nav: Option<&str>,
|
||||
template: Option<&str>,
|
||||
started: std::time::Instant,
|
||||
) -> Vec<u8> {
|
||||
let mut content = page_content.replace('\t', TAB_WIDTH);
|
||||
if let Some(name) = template {
|
||||
let custom = self.get_template(name).filter(|t| !t.is_empty());
|
||||
if let Some(custom) = custom {
|
||||
content = custom.replace("{PAGE_CONTENT}", &content);
|
||||
} else if let Some(builtin) = Self::builtin_template(name) {
|
||||
content = builtin.replace("{PAGE_CONTENT}", &content);
|
||||
}
|
||||
}
|
||||
let base = self
|
||||
.get_template("base")
|
||||
.filter(|t| !t.is_empty())
|
||||
.unwrap_or_else(|| DEFAULT_BASE_TEMPLATE.to_string());
|
||||
let gen_time = format!(
|
||||
"Generated in {}",
|
||||
rns_tools::format::prettytime(
|
||||
rns_tools::format::PyNum::Float(started.elapsed().as_secs_f64()),
|
||||
false
|
||||
)
|
||||
);
|
||||
base.replace("{NODE_NAME}", &self.node_name)
|
||||
.replace("{VERSION}", VERSION)
|
||||
.replace("{NAVIGATION}", nav.unwrap_or(""))
|
||||
.replace("{GEN_TIME}", &gen_time)
|
||||
.replace("{PAGE_CONTENT}", &content)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
pub(crate) fn mdc_scoped(&self, url_scope: &str) -> MarkdownToMicron {
|
||||
MarkdownToMicron::new(
|
||||
MAX_RENDER_WIDTH,
|
||||
Some(self.highlighter.clone()),
|
||||
Some(url_scope),
|
||||
)
|
||||
}
|
||||
|
||||
/// `repository_thanks` and `release_thanks`: the count in `thanks_path`,
|
||||
/// once per link and path. The request that creates the file reads 0, as upstream.
|
||||
pub(crate) fn thanks(
|
||||
&self,
|
||||
key_path: &str,
|
||||
thanks_path: &Path,
|
||||
add: bool,
|
||||
link_id: [u8; 16],
|
||||
) -> i64 {
|
||||
let mut add = add;
|
||||
if add {
|
||||
let mut key = link_id.to_vec();
|
||||
key.extend_from_slice(key_path.as_bytes());
|
||||
let mut seen = self.thanks.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if seen.contains(&key) {
|
||||
add = false;
|
||||
} else {
|
||||
if seen.len() == 256 {
|
||||
seen.pop_front();
|
||||
}
|
||||
seen.push_back(key);
|
||||
}
|
||||
}
|
||||
let write = |count: i64| {
|
||||
let value = Value::Map(vec![(Value::from("count"), Value::from(count))]);
|
||||
let mut out = Vec::new();
|
||||
rmpv::encode::write_value(&mut out, &value).expect("writing to a Vec");
|
||||
std::fs::write(thanks_path, out)
|
||||
};
|
||||
let result = (|| -> Result<i64, String> {
|
||||
if !thanks_path.is_file() {
|
||||
write(i64::from(add)).map_err(|e| e.to_string())?;
|
||||
return Ok(0);
|
||||
}
|
||||
let data = std::fs::read(thanks_path).map_err(|e| e.to_string())?;
|
||||
let value = rmpv::decode::read_value(&mut &data[..]).map_err(|e| e.to_string())?;
|
||||
let count = match &value {
|
||||
Value::Map(entries) => entries
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some("count"))
|
||||
.map(|(_, v)| v.clone()),
|
||||
_ => None,
|
||||
}
|
||||
.ok_or("Invalid data in thanks file")?;
|
||||
let mut count = count.as_i64().ok_or("Invalid data in thanks file")?;
|
||||
if add {
|
||||
count += 1;
|
||||
}
|
||||
write(count).map_err(|e| e.to_string())?;
|
||||
Ok(count)
|
||||
})();
|
||||
result.unwrap_or_else(|e| {
|
||||
tracing::error!("Error while processing thanks for {key_path}: {e}");
|
||||
0
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The request map as upstream reads it: `{}` for anything that is not a map.
|
||||
pub(crate) struct Data<'a>(&'a [(Value, Value)]);
|
||||
|
||||
impl<'a> Data<'a> {
|
||||
pub fn of(value: &'a Value) -> Self {
|
||||
match value {
|
||||
Value::Map(entries) => Data(entries),
|
||||
_ => Data(&[]),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn raw(&self, key: &str) -> Option<&'a Value> {
|
||||
self.0
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some(key))
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
pub fn has(&self, key: &str) -> bool {
|
||||
self.raw(key).is_some()
|
||||
}
|
||||
|
||||
/// `data.get(key, default)` used as text.
|
||||
pub fn text(&self, key: &str, default: &str) -> String {
|
||||
match self.raw(key) {
|
||||
None => default.to_string(),
|
||||
Some(value) => rns_tools::rsg::pyfmt::py_str(value),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python truthiness of `data.get(key, "")`.
|
||||
pub fn truthy(&self, key: &str) -> bool {
|
||||
match self.raw(key) {
|
||||
None | Some(Value::Nil) => false,
|
||||
Some(Value::Boolean(b)) => *b,
|
||||
Some(Value::Integer(i)) => i.as_i64() != Some(0),
|
||||
Some(Value::F32(f)) => *f != 0.0,
|
||||
Some(Value::F64(f)) => *f != 0.0,
|
||||
Some(Value::String(s)) => !s.as_bytes().is_empty(),
|
||||
Some(Value::Binary(b)) => !b.is_empty(),
|
||||
Some(Value::Array(a)) => !a.is_empty(),
|
||||
Some(Value::Map(m)) => !m.is_empty(),
|
||||
Some(Value::Ext(..)) => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// `max(0, int(data.get(key, "0")))`, 0 where `int` raises.
|
||||
pub fn page(&self, key: &str) -> usize {
|
||||
let n = match self.raw(key) {
|
||||
None => Some(0),
|
||||
Some(Value::Integer(i)) => i.as_i64().map(i128::from),
|
||||
Some(Value::F64(f)) if f.is_finite() => Some(*f as i128),
|
||||
Some(Value::F32(f)) if f.is_finite() => Some(*f as i128),
|
||||
Some(Value::Boolean(b)) => Some(i128::from(*b)),
|
||||
Some(Value::String(s)) => s.as_str().and_then(py_int),
|
||||
_ => None,
|
||||
};
|
||||
n.map_or(0, |n| n.clamp(0, usize::MAX as i128 / 2) as usize)
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `str.isspace()` for one character.
|
||||
pub(crate) fn py_space(c: char) -> bool {
|
||||
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
|
||||
}
|
||||
|
||||
pub(crate) fn py_strip(s: &str) -> &str {
|
||||
s.trim_matches(py_space)
|
||||
}
|
||||
|
||||
/// Python `int(text)` for a decimal string; `None` where it raises.
|
||||
pub(crate) fn py_int(text: &str) -> Option<i128> {
|
||||
let t = py_strip(text);
|
||||
let (negative, digits) = match t.strip_prefix(['+', '-']) {
|
||||
Some(rest) => (t.starts_with('-'), rest),
|
||||
None => (false, t),
|
||||
};
|
||||
if digits.is_empty()
|
||||
|| digits.starts_with('_')
|
||||
|| digits.ends_with('_')
|
||||
|| digits.contains("__")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut value: i128 = 0;
|
||||
for c in digits.chars().filter(|c| *c != '_') {
|
||||
value = value
|
||||
.checked_mul(10)?
|
||||
.checked_add(i128::from(c.to_digit(10)?))?;
|
||||
}
|
||||
Some(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
/// `str[:n]` in code points.
|
||||
pub(crate) fn chars(s: &str, n: usize) -> String {
|
||||
s.chars().take(n).collect()
|
||||
}
|
||||
|
||||
/// `urllib.parse.quote_plus(str(value).encode("utf-8"))`.
|
||||
pub fn quote_plus(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len());
|
||||
for b in value.bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'.' | b'-' | b'~' => {
|
||||
out.push(b as char)
|
||||
}
|
||||
b' ' => out.push('+'),
|
||||
_ => out.push_str(&format!("%{b:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `urllib.parse.unquote_plus`: invalid UTF-8 becomes U+FFFD.
|
||||
pub fn unquote_plus(value: &str) -> String {
|
||||
let bytes = value.replace('+', " ").into_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& i + 2 < bytes.len()
|
||||
&& let (Some(h), Some(l)) = (
|
||||
(bytes[i + 1] as char).to_digit(16),
|
||||
(bytes[i + 2] as char).to_digit(16),
|
||||
)
|
||||
{
|
||||
out.push((h * 16 + l) as u8);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
fn sanitize_label(label: &str) -> String {
|
||||
label.replace(['[', ']', '`'], "")
|
||||
}
|
||||
|
||||
fn field_str(fields: &[(&str, &str)]) -> String {
|
||||
if fields.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let parts: Vec<String> = fields
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={}", quote_plus(v)))
|
||||
.collect();
|
||||
format!("`{}", parts.join("|"))
|
||||
}
|
||||
|
||||
/// `m_link`: a bold link.
|
||||
pub fn m_link(label: &str, path: &str, fields: &[(&str, &str)]) -> String {
|
||||
format!(
|
||||
"`!`[{}`:{path}{}]`!",
|
||||
sanitize_label(label),
|
||||
field_str(fields)
|
||||
)
|
||||
}
|
||||
|
||||
/// `m_link_r`: a plain link.
|
||||
pub fn m_link_r(label: &str, path: &str, fields: &[(&str, &str)]) -> String {
|
||||
format!("`[{}`:{path}{}]", sanitize_label(label), field_str(fields))
|
||||
}
|
||||
|
||||
/// `m_link_e`: a bold link to another node.
|
||||
pub fn m_link_e(label: &str, remote: &str, path: &str, fields: &[(&str, &str)]) -> String {
|
||||
format!(
|
||||
"`!`[{}`{remote}:{path}{}]`!",
|
||||
sanitize_label(label),
|
||||
field_str(fields)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn m_heading(text: &str, level: usize) -> String {
|
||||
format!("{}{text}\n", ">".repeat(level))
|
||||
}
|
||||
|
||||
pub fn m_italic(text: &str) -> String {
|
||||
format!("`*{text}`*")
|
||||
}
|
||||
|
||||
pub fn m_divider() -> String {
|
||||
"-\u{2500}\n".to_string()
|
||||
}
|
||||
|
||||
pub fn m_escape(text: &str) -> String {
|
||||
text.replace('`', "\\`")
|
||||
}
|
||||
|
||||
/// `os.path.basename`.
|
||||
pub(crate) fn basename(path: &str) -> &str {
|
||||
path.rsplit('/').next().unwrap_or(path)
|
||||
}
|
||||
|
||||
/// `os.path.splitext(path)[1]`.
|
||||
pub(crate) fn extension(path: &str) -> &str {
|
||||
let name = basename(path);
|
||||
let stem_start = name.len() - name.trim_start_matches('.').len();
|
||||
match name[stem_start..].rfind('.') {
|
||||
Some(i) => &name[stem_start + i..],
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.path.splitext(name)[0]`.
|
||||
pub(crate) fn stem(name: &str) -> &str {
|
||||
let ext = extension(name);
|
||||
&name[..name.len() - ext.len()]
|
||||
}
|
||||
|
||||
/// `RNS.prettyhexrep`.
|
||||
pub(crate) fn prettyhexrep(hash: &[u8]) -> String {
|
||||
format!("<{}>", hex::encode(hash))
|
||||
}
|
||||
|
||||
pub(crate) fn prettysize(size: u64) -> String {
|
||||
rns_tools::format::prettysize(size as f64, "B")
|
||||
}
|
||||
|
||||
/// `time.strftime` with `%Y-%m-%d`, then `%H:%M` and `:%S` as asked.
|
||||
pub(crate) fn local_time(ts: f64, minutes: bool, seconds: bool) -> String {
|
||||
let Some(tm) = crate::platform::localtime(ts.floor() as i64) else {
|
||||
return String::new();
|
||||
};
|
||||
let mut out = format!("{:04}-{:02}-{:02}", tm.year, tm.month, tm.day);
|
||||
if minutes {
|
||||
out.push_str(&format!(" {:02}:{:02}", tm.hour, tm.minute));
|
||||
}
|
||||
if seconds {
|
||||
out.push_str(&format!(":{:02}", tm.second));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn now() -> f64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0.0, |d| d.as_secs_f64())
|
||||
}
|
||||
|
||||
/// `format_relative_time`.
|
||||
pub(crate) fn relative_time(timestamp: i64) -> String {
|
||||
let diff = now() - timestamp as f64;
|
||||
let unit = |n: i64, word: &str| format!("{n} {word}{} ago", if n != 1 { "s" } else { "" });
|
||||
if diff < 60.0 {
|
||||
"just now".to_string()
|
||||
} else if diff < 3600.0 {
|
||||
unit((diff / 60.0) as i64, "minute")
|
||||
} else if diff < 86400.0 {
|
||||
unit((diff / 3600.0) as i64, "hour")
|
||||
} else if diff < 604800.0 {
|
||||
unit((diff / 86400.0) as i64, "day")
|
||||
} else if diff < 2592000.0 {
|
||||
unit((diff / 604800.0) as i64, "week")
|
||||
} else if diff < 31536000.0 {
|
||||
unit((diff / 2592000.0) as i64, "month")
|
||||
} else {
|
||||
unit((diff / 31536000.0) as i64, "year")
|
||||
}
|
||||
}
|
||||
|
||||
/// A release tag or artifact name that names an entry inside its directory.
|
||||
pub(crate) fn plain_name(name: &str) -> bool {
|
||||
!name.is_empty() && name != "." && name != ".." && !name.contains('/') && !name.contains('\0')
|
||||
}
|
||||
|
||||
/// A map field of an unpacked value.
|
||||
pub(crate) fn field<'v>(value: &'v Value, key: &str) -> Option<&'v Value> {
|
||||
match value {
|
||||
Value::Map(entries) => entries
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some(key))
|
||||
.map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn field_str_or(value: &Value, key: &str, default: &str) -> String {
|
||||
match field(value, key) {
|
||||
None => default.to_string(),
|
||||
Some(v) => rns_tools::rsg::pyfmt::py_str(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// A number field as Python holds it; non-numbers are 0.
|
||||
pub(crate) fn field_num(value: &Value, key: &str) -> f64 {
|
||||
match field(value, key) {
|
||||
Some(Value::Integer(i)) => i.as_f64().unwrap_or(0.0),
|
||||
Some(Value::F64(f)) => *f,
|
||||
Some(Value::F32(f)) => f64::from(*f),
|
||||
Some(Value::Boolean(b)) => f64::from(u8::from(*b)),
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::PageOptions;
|
||||
|
||||
#[test]
|
||||
fn page_stamp_keys_follow_upstream() {
|
||||
let options = PageOptions::from_config_text("[pages]\nserve_nomadnet = yes\n").unwrap();
|
||||
assert_eq!((options.stamp_value, options.link_cost), (None, 18.0));
|
||||
let options =
|
||||
PageOptions::from_config_text("[pages]\nstamp_value = 27.5\nlink_cost = 18.7\n")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(options.stamp_value, options.link_cost),
|
||||
(Some(27.5), 4787.0 / 256.0)
|
||||
);
|
||||
assert!(PageOptions::from_config_text("[pages]\nlink_cost = x\n").is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,179 @@
|
||||
//! The Unix calls rngit makes, and what other platforms do in their place.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// `os.access(path, os.X_OK)`. Windows has no execute permission (upstream's
|
||||
/// check passes for any file there and the run then fails), so nothing is
|
||||
/// treated as executable and permission files and templates are read as text.
|
||||
pub(crate) fn executable(path: &Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
nix::unistd::access(path, nix::unistd::AccessFlags::X_OK).is_ok()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = path;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Any execute bit in `meta`'s mode; never on platforms without one.
|
||||
pub(crate) fn mode_executable(meta: &std::fs::Metadata) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode() & 0o111 != 0
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = meta;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.makedirs(path, mode=0o755)`; the mode applies only on Unix, as in Python.
|
||||
pub(crate) fn create_dir_all_755(path: &Path) -> std::io::Result<()> {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::DirBuilderExt;
|
||||
builder.mode(0o755);
|
||||
}
|
||||
builder.create(path)
|
||||
}
|
||||
|
||||
/// Copy the symbolic link `from` as a link at `to`, as `copytree(symlinks=True)`.
|
||||
/// Windows needs the link's kind, which follows what `from` names (a file
|
||||
/// link when it names nothing).
|
||||
pub(crate) fn copy_symlink(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
let target = std::fs::read_link(from)?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(target, to)
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if std::fs::metadata(from).is_ok_and(|m| m.is_dir()) {
|
||||
std::os::windows::fs::symlink_dir(target, to)
|
||||
} else {
|
||||
std::os::windows::fs::symlink_file(target, to)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A finished process's return code as Python reports it: negative for the
|
||||
/// signal that ended it on Unix.
|
||||
pub(crate) fn return_code(status: std::process::ExitStatus) -> i32 {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
status
|
||||
.code()
|
||||
.unwrap_or_else(|| -status.signal().unwrap_or(0))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
status.code().unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Broken-down local time, as `time.localtime`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct LocalTime {
|
||||
pub year: i32,
|
||||
/// 1 to 12.
|
||||
pub month: i32,
|
||||
pub day: i32,
|
||||
pub hour: i32,
|
||||
pub minute: i32,
|
||||
pub second: i32,
|
||||
}
|
||||
|
||||
/// `time.localtime(secs)`; `None` where the C library refuses the time.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn localtime(secs: i64) -> Option<LocalTime> {
|
||||
let time = secs as nix::libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<nix::libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_r is reentrant.
|
||||
if unsafe { nix::libc::localtime_r(&time, tm.as_mut_ptr()) }.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: localtime_r filled `tm` when it returned non-null.
|
||||
let tm = unsafe { tm.assume_init() };
|
||||
Some(LocalTime {
|
||||
year: tm.tm_year + 1900,
|
||||
month: tm.tm_mon + 1,
|
||||
day: tm.tm_mday,
|
||||
hour: tm.tm_hour,
|
||||
minute: tm.tm_min,
|
||||
second: tm.tm_sec,
|
||||
})
|
||||
}
|
||||
|
||||
/// `time.localtime(secs)` through the C runtime's `localtime_s`.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn localtime(secs: i64) -> Option<LocalTime> {
|
||||
let time = secs as libc::time_t;
|
||||
let mut tm = std::mem::MaybeUninit::<libc::tm>::zeroed();
|
||||
// SAFETY: both pointers are valid for the call; localtime_s writes only `tm`.
|
||||
if unsafe { libc::localtime_s(tm.as_mut_ptr(), &time) } != 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: localtime_s filled `tm` when it returned zero.
|
||||
let tm = unsafe { tm.assume_init() };
|
||||
Some(LocalTime {
|
||||
year: tm.tm_year + 1900,
|
||||
month: tm.tm_mon + 1,
|
||||
day: tm.tm_mday,
|
||||
hour: tm.tm_hour,
|
||||
minute: tm.tm_min,
|
||||
second: tm.tm_sec,
|
||||
})
|
||||
}
|
||||
|
||||
/// `time.mktime` of local midnight on `year-month-day`, a day past the month's
|
||||
/// end rolling over as C's `mktime` does.
|
||||
#[cfg(unix)]
|
||||
pub(crate) fn local_midnight(year: i32, month: i32, day: i32) -> i64 {
|
||||
// SAFETY: an all-zero `tm` is a valid value of the C struct.
|
||||
let mut tm: nix::libc::tm = unsafe { std::mem::zeroed() };
|
||||
tm.tm_year = year - 1900;
|
||||
tm.tm_mon = month - 1;
|
||||
tm.tm_mday = day;
|
||||
tm.tm_isdst = -1;
|
||||
// SAFETY: `tm` is initialised; mktime reads and normalises it in place.
|
||||
let secs = unsafe { nix::libc::mktime(&mut tm) };
|
||||
secs as i64
|
||||
}
|
||||
|
||||
/// `time.mktime` of local midnight on `year-month-day`: the Windows C runtime
|
||||
/// offers no `mktime` binding here, so the time is found from `localtime`,
|
||||
/// correcting once for an offset that differs at the result.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn local_midnight(year: i32, month: i32, day: i32) -> i64 {
|
||||
let wall = days_from_civil(i64::from(year), i64::from(month), i64::from(day)) * 86_400;
|
||||
let offset = |secs: i64| {
|
||||
localtime(secs).map_or(0, |t| {
|
||||
days_from_civil(i64::from(t.year), i64::from(t.month), i64::from(t.day)) * 86_400
|
||||
+ i64::from(t.hour) * 3600
|
||||
+ i64::from(t.minute) * 60
|
||||
+ i64::from(t.second)
|
||||
- secs
|
||||
})
|
||||
};
|
||||
let first = wall - offset(wall);
|
||||
wall - offset(first)
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 of a proleptic Gregorian date; linear in `day`.
|
||||
#[cfg(windows)]
|
||||
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
|
||||
let year = if month <= 2 { year - 1 } else { year };
|
||||
let era = year.div_euclid(400);
|
||||
let yoe = year - era * 400;
|
||||
let mp = (month + 9) % 12;
|
||||
let doy = (153 * mp + 2) / 5 + day - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe - 719_468
|
||||
}
|
||||
@@ -0,0 +1,738 @@
|
||||
//! `git-remote-rns`, the git remote helper for `rns://` URLs
|
||||
//! (`RNS/Utilities/rngit/client.py`), without the network part.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{BufRead, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use rmpv::Value;
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_runtime::config::{Config, ConfigError};
|
||||
use rns_tools::rsg::pyfmt::py_fromhex;
|
||||
|
||||
use crate::server::{
|
||||
IDX_REPOSITORY, IDX_RESULT_CODE, PATH_DELETE, PATH_FETCH, PATH_LIST, PATH_PUSH,
|
||||
};
|
||||
|
||||
/// The file written when the config directory has none (`client.py`).
|
||||
pub const DEFAULT_CLIENT_CONFIG: &str = include_str!("client_default_config.txt");
|
||||
|
||||
pub const REF_BATCH_SIZE: usize = 25;
|
||||
pub const PATH_TIMEOUT: f64 = 15.0;
|
||||
/// `send_request`'s default timeout, used for every request (`client.py`).
|
||||
pub const REQUEST_TIMEOUT: f64 = 7200.0;
|
||||
|
||||
const LOG_NONE: i64 = -1;
|
||||
const LOG_EXTREME: i64 = 8;
|
||||
|
||||
/// The parts of an `rns://<destination>/<group>/<repo>` URL (`client.py`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HelperUrl {
|
||||
pub destination: String,
|
||||
pub group: String,
|
||||
pub repo: String,
|
||||
}
|
||||
|
||||
impl HelperUrl {
|
||||
/// The repository path sent on the wire (`client.py`).
|
||||
pub fn repo_path(&self) -> String {
|
||||
format!("{}/{}", self.group, self.repo)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the helper's arguments after the program name: `<remote-name> <url>`.
|
||||
/// The error is the stderr line and the exit code.
|
||||
pub fn parse_args(args: &[String]) -> Result<HelperUrl, (String, i32)> {
|
||||
if args.len() < 2 {
|
||||
return Err(("Usage: git-remote-rns <remote-name> <url>".into(), 1));
|
||||
}
|
||||
let Some(rest) = args[1].strip_prefix("rns://") else {
|
||||
return Err(("Invalid URL scheme. Must be rns://".into(), 1));
|
||||
};
|
||||
let parts: Vec<&str> = rest.splitn(3, '/').collect();
|
||||
if parts.len() < 3 {
|
||||
return Err((
|
||||
"Invalid URL format. Use rns://<hash>/<group>/<repo>".into(),
|
||||
1,
|
||||
));
|
||||
}
|
||||
Ok(HelperUrl {
|
||||
destination: parts[0].to_string(),
|
||||
group: parts[1].to_string(),
|
||||
repo: parts[2].to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The config directory (`client.py`). When `~/.config/rngit/config`
|
||||
/// exists upstream picks `~/.rngit/reticulum`, not `~/.config/rngit`.
|
||||
pub fn resolve_config_dir(configdir: Option<&Path>, home: &Path) -> PathBuf {
|
||||
if let Some(dir) = configdir {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
let user = home.join(".config/rngit");
|
||||
if user.is_dir() && user.join("config").is_file() {
|
||||
home.join(".rngit/reticulum")
|
||||
} else {
|
||||
home.join(".rngit")
|
||||
}
|
||||
}
|
||||
|
||||
/// What `__apply_config` takes from `client_config` (`client.py`).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ClientConfig {
|
||||
pub ref_batch_size: usize,
|
||||
/// `[logging] loglevel`, clamped; `None` when absent.
|
||||
pub loglevel: Option<i64>,
|
||||
/// Alias name to lowercase destination hash hex.
|
||||
pub aliases: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ClientConfigError {
|
||||
/// The file does not parse; upstream logs it and exits 1 before starting Reticulum.
|
||||
Parse(PathBuf, ConfigError),
|
||||
/// A value `as_int` rejects; upstream raises out of `__init__` (exit 1).
|
||||
Value(ConfigError),
|
||||
Io(PathBuf, std::io::Error),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ClientConfigError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Parse(path, _) => {
|
||||
write!(f, "Could not parse the configuration at {}", path.display())
|
||||
}
|
||||
Self::Value(e) => write!(f, "{e}"),
|
||||
Self::Io(path, e) => write!(f, "{}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_hash_hex(value: &str) -> bool {
|
||||
value.chars().count() == 32 && py_fromhex(value).is_ok_and(|h| !h.is_empty())
|
||||
}
|
||||
|
||||
impl ClientConfig {
|
||||
/// Read `<configdir>/client_config`, writing the default first when missing.
|
||||
pub fn load(configdir: &Path) -> Result<Self, ClientConfigError> {
|
||||
let path = configdir.join("client_config");
|
||||
let text = if path.is_file() {
|
||||
std::fs::read_to_string(&path).map_err(|e| ClientConfigError::Io(path.clone(), e))?
|
||||
} else {
|
||||
std::fs::create_dir_all(configdir)
|
||||
.and_then(|()| std::fs::write(&path, DEFAULT_CLIENT_CONFIG))
|
||||
.map_err(|e| ClientConfigError::Io(path.clone(), e))?;
|
||||
DEFAULT_CLIENT_CONFIG.to_string()
|
||||
};
|
||||
let config = Config::parse(&text).map_err(|e| ClientConfigError::Parse(path, e))?;
|
||||
Self::apply(&config).map_err(ClientConfigError::Value)
|
||||
}
|
||||
|
||||
fn apply(config: &Config) -> Result<Self, ConfigError> {
|
||||
let as_int = |section: &str, key: &str| -> Result<Option<i64>, ConfigError> {
|
||||
let Some(s) = config.section(section).filter(|s| s.has(key)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
s.get_int(key)
|
||||
.map(Some)
|
||||
.ok_or_else(|| ConfigError::InvalidValue {
|
||||
section: section.into(),
|
||||
key: key.into(),
|
||||
message: "not an integer".into(),
|
||||
})
|
||||
};
|
||||
let loglevel = as_int("logging", "loglevel")?.map(|l| l.clamp(LOG_NONE, LOG_EXTREME));
|
||||
// Differs from `__apply_config` (`client.py`), whose lower bound of 0 never fetches.
|
||||
let ref_batch_size = as_int("client", "ref_batch_size")?
|
||||
.map_or(REF_BATCH_SIZE, |n| n.clamp(1, 1024) as usize);
|
||||
let mut aliases = BTreeMap::new();
|
||||
if let Some(section) = config.section("aliases") {
|
||||
for alias in section.values.keys() {
|
||||
let Some(value) = section.get(alias).filter(|v| is_hash_hex(v)) else {
|
||||
continue;
|
||||
};
|
||||
let hash = py_fromhex(value).expect("checked above");
|
||||
aliases
|
||||
.entry(alias.clone())
|
||||
.or_insert_with(|| hex::encode(hash));
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
ref_batch_size,
|
||||
loglevel,
|
||||
aliases,
|
||||
})
|
||||
}
|
||||
|
||||
/// `__resolve_destination_alias` (`client.py`): a 32-character hex
|
||||
/// string as given, else a configured alias, else the input unchanged.
|
||||
pub fn resolve_destination(&self, destination: &str) -> String {
|
||||
if is_hash_hex(destination) {
|
||||
return destination.to_string();
|
||||
}
|
||||
self.aliases
|
||||
.get(destination)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| destination.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Load `client_identity`, creating it when missing (`client.py`).
|
||||
/// A new identity that cannot be saved is still used, as upstream does.
|
||||
pub fn load_or_create_identity(path: &Path) -> Option<Identity> {
|
||||
if path.is_file() {
|
||||
return Identity::from_file(path).ok();
|
||||
}
|
||||
let identity = Identity::new();
|
||||
if let Err(e) = identity.to_file(path) {
|
||||
tracing::error!("Error while saving identity to {}: {e}", path.display());
|
||||
}
|
||||
Some(identity)
|
||||
}
|
||||
|
||||
/// A response as `send_request` returns it.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Response {
|
||||
/// Python `bytes`.
|
||||
Bytes(Vec<u8>),
|
||||
/// A file response: the spooled body and its packed-then-decoded metadata.
|
||||
File { path: PathBuf, metadata: Value },
|
||||
/// Any other response value.
|
||||
Other(Value),
|
||||
}
|
||||
|
||||
/// The link side of the helper. `None` is a failed or timed-out request.
|
||||
pub trait Transport {
|
||||
fn request(&mut self, path: &str, data: Value) -> Option<Response>;
|
||||
}
|
||||
|
||||
/// `abort()`: the process prints `git-remote-rns failed: <reason>` and exits
|
||||
/// with `code`. A `code` of 1 with `traceback` set stands for an uncaught
|
||||
/// Python exception, which prints `reason` alone.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Abort {
|
||||
pub reason: String,
|
||||
pub code: i32,
|
||||
pub traceback: bool,
|
||||
}
|
||||
|
||||
impl Abort {
|
||||
pub fn new(reason: impl Into<String>) -> Self {
|
||||
let reason = reason.into();
|
||||
Self {
|
||||
reason: if reason.is_empty() {
|
||||
"Unknown reason".into()
|
||||
} else {
|
||||
reason
|
||||
},
|
||||
code: 255,
|
||||
traceback: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn exception(reason: impl Into<String>) -> Self {
|
||||
Self {
|
||||
reason: reason.into(),
|
||||
code: 1,
|
||||
traceback: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The stderr line.
|
||||
pub fn message(&self) -> String {
|
||||
if self.traceback {
|
||||
self.reason.clone()
|
||||
} else {
|
||||
format!("git-remote-rns failed: {}", self.reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `escape_for_stdout` (`client.py`), per code point.
|
||||
pub fn escape_for_stdout(value: &str) -> String {
|
||||
let mut out = String::from("\"");
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'"' => out.push_str("\\\""),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
c if (c as u32) < 32 || (c as u32) > 126 => {
|
||||
out.push_str(&format!("\\x{:02x}", c as u32));
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
/// Python `str.split(maxsplit=n)` on whitespace.
|
||||
fn split_max(text: &str, n: usize) -> Vec<&str> {
|
||||
let mut parts = Vec::new();
|
||||
let mut rest = text.trim_start();
|
||||
while !rest.is_empty() {
|
||||
if parts.len() == n {
|
||||
parts.push(rest.trim_end());
|
||||
break;
|
||||
}
|
||||
match rest.find(char::is_whitespace) {
|
||||
Some(end) => {
|
||||
parts.push(&rest[..end]);
|
||||
rest = rest[end..].trim_start();
|
||||
}
|
||||
None => {
|
||||
parts.push(rest);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
fn s(v: &str) -> Value {
|
||||
Value::String(v.into())
|
||||
}
|
||||
|
||||
fn map(entries: Vec<(Value, Value)>) -> Value {
|
||||
Value::Map(entries)
|
||||
}
|
||||
|
||||
/// `RNS.prettysize`.
|
||||
fn prettysize(num: f64) -> String {
|
||||
rns_tools::format::prettysize(num, "B")
|
||||
}
|
||||
|
||||
/// Python truthiness of an unpacked value.
|
||||
fn is_falsy(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Nil => true,
|
||||
Value::Boolean(b) => !b,
|
||||
Value::Integer(i) => i.as_i64() == Some(0) || i.as_u64() == Some(0),
|
||||
Value::F32(f) => *f == 0.0,
|
||||
Value::F64(f) => *f == 0.0,
|
||||
Value::String(s) => s.as_bytes().is_empty(),
|
||||
Value::Binary(b) => b.is_empty(),
|
||||
Value::Array(a) => a.is_empty(),
|
||||
Value::Map(m) => m.is_empty(),
|
||||
Value::Ext(..) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `bytes.decode("utf-8", errors="ignore")`.
|
||||
fn decode_ignore(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(bytes).replace('\u{FFFD}', "")
|
||||
}
|
||||
|
||||
/// The helper's state for one run of git's stdin protocol.
|
||||
pub struct RemoteHelper<T: Transport> {
|
||||
pub transport: T,
|
||||
pub repo_path: String,
|
||||
pub ref_batch_size: usize,
|
||||
/// Directory git commands run in; git itself passes `GIT_DIR`.
|
||||
pub git_dir: PathBuf,
|
||||
pub progress_enabled: bool,
|
||||
/// `remote_refs` from the last `list`, in insertion order.
|
||||
remote_refs: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
enum Flow {
|
||||
Continue,
|
||||
BrokenPipe,
|
||||
}
|
||||
|
||||
fn broken(e: &std::io::Error) -> bool {
|
||||
e.kind() == std::io::ErrorKind::BrokenPipe
|
||||
}
|
||||
|
||||
impl<T: Transport> RemoteHelper<T> {
|
||||
pub fn new(transport: T, repo_path: String, ref_batch_size: usize, git_dir: PathBuf) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
repo_path,
|
||||
ref_batch_size,
|
||||
git_dir,
|
||||
progress_enabled: false,
|
||||
remote_refs: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn git(&self, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.args(args).current_dir(&self.git_dir);
|
||||
cmd
|
||||
}
|
||||
|
||||
fn git_ok(&self, args: &[&str]) -> Option<String> {
|
||||
let out = self.git(args).stdin(Stdio::null()).output().ok()?;
|
||||
out.status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
fn send(&mut self, path: &str, data: Value) -> Result<Response, Abort> {
|
||||
self.transport
|
||||
.request(path, data)
|
||||
.ok_or_else(|| Abort::new("Request failed or timed out"))
|
||||
}
|
||||
|
||||
/// The command loop (`client.py`), from `run()` after the link is up.
|
||||
pub fn run(
|
||||
&mut self,
|
||||
stdin: &mut dyn BufRead,
|
||||
stdout: &mut dyn Write,
|
||||
stderr: &mut dyn Write,
|
||||
) -> Result<(), Abort> {
|
||||
self.progress_enabled = false;
|
||||
let mut fetch_queue: Vec<(String, String)> = Vec::new();
|
||||
let mut push_queue: Vec<(String, String)> = Vec::new();
|
||||
let mut raw = Vec::new();
|
||||
loop {
|
||||
raw.clear();
|
||||
match stdin.read_until(b'\n', &mut raw) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(_) => {}
|
||||
}
|
||||
let text = String::from_utf8_lossy(&raw);
|
||||
let line = text.trim();
|
||||
let written = if line == "capabilities" {
|
||||
stdout
|
||||
.write_all(b"list\nfetch\npush\noption\n\n")
|
||||
.and_then(|()| stdout.flush())
|
||||
} else if line == "list" {
|
||||
self.handle_list(stdout, false)?
|
||||
} else if line.starts_with("list ") {
|
||||
self.handle_list(stdout, true)?
|
||||
} else if line.starts_with("option") {
|
||||
let parts = split_max(line, 2);
|
||||
let name = parts.get(1).copied().unwrap_or("");
|
||||
let value = parts.get(2).copied().unwrap_or("");
|
||||
let reply: &[u8] = if name == "progress" {
|
||||
self.progress_enabled =
|
||||
matches!(value.to_lowercase().as_str(), "true" | "1" | "yes");
|
||||
b"ok\n"
|
||||
} else {
|
||||
b"unsupported\n"
|
||||
};
|
||||
stdout.write_all(reply).and_then(|()| stdout.flush())
|
||||
} else if line.starts_with("fetch") {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
if parts.len() < 3 {
|
||||
return Err(Abort::exception("IndexError: list index out of range"));
|
||||
}
|
||||
let entry = (parts[1].to_string(), parts[2].to_string());
|
||||
if !fetch_queue.contains(&entry) {
|
||||
fetch_queue.push(entry);
|
||||
}
|
||||
push_queue.clear();
|
||||
Ok(())
|
||||
} else if line.starts_with("push") {
|
||||
let parts: Vec<&str> = line.split_whitespace().collect();
|
||||
let Some(refspec) = parts.get(1) else {
|
||||
return Err(Abort::exception("IndexError: list index out of range"));
|
||||
};
|
||||
let Some((local, remote)) = refspec.split_once(':') else {
|
||||
return Err(Abort::exception(
|
||||
"ValueError: not enough values to unpack (expected 2, got 1)",
|
||||
));
|
||||
};
|
||||
push_queue.push((local.to_string(), remote.to_string()));
|
||||
fetch_queue.clear();
|
||||
Ok(())
|
||||
} else if line.is_empty() {
|
||||
let fetches = std::mem::take(&mut fetch_queue);
|
||||
let pushes = std::mem::take(&mut push_queue);
|
||||
let flow = match self.process_fetch_queue(fetches, stderr)? {
|
||||
Flow::Continue => self.process_push_queue(pushes, stdout, stderr)?,
|
||||
Flow::BrokenPipe => Flow::BrokenPipe,
|
||||
};
|
||||
match flow {
|
||||
Flow::Continue => stdout.write_all(b"\n").and_then(|()| stdout.flush()),
|
||||
Flow::BrokenPipe => break,
|
||||
}
|
||||
} else {
|
||||
return Err(Abort::new(format!("Unknown Git command: {line}")));
|
||||
};
|
||||
if let Err(e) = written
|
||||
&& broken(&e)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = stdout.flush();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `handle_git_list` (`client.py`).
|
||||
fn handle_list(
|
||||
&mut self,
|
||||
stdout: &mut dyn Write,
|
||||
for_push: bool,
|
||||
) -> Result<std::io::Result<()>, Abort> {
|
||||
let data = map(vec![
|
||||
(Value::from(IDX_REPOSITORY), s(&self.repo_path)),
|
||||
(s("for_push"), Value::Boolean(for_push)),
|
||||
]);
|
||||
let response = match self.send(PATH_LIST, data)? {
|
||||
Response::Bytes(b) if !b.is_empty() => b,
|
||||
_ => return Err(Abort::new("Invalid list response from server")),
|
||||
};
|
||||
let payload = &response[1..];
|
||||
if response[0] != 0 {
|
||||
return Err(Abort::new(format!(
|
||||
"Server refused list: {}",
|
||||
decode_ignore(payload)
|
||||
)));
|
||||
}
|
||||
let text = std::str::from_utf8(payload).map_err(|e| {
|
||||
Abort::exception(format!(
|
||||
"UnicodeDecodeError: 'utf-8' codec can't decode the list response: {e}"
|
||||
))
|
||||
})?;
|
||||
self.remote_refs.clear();
|
||||
for line in text.split('\n') {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some((sha, name)) = line.split_once(' ') {
|
||||
if name == "HEAD" {
|
||||
continue;
|
||||
}
|
||||
match self.remote_refs.iter_mut().find(|(r, _)| r == name) {
|
||||
Some(entry) => entry.1 = sha.to_string(),
|
||||
None => self.remote_refs.push((name.to_string(), sha.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(stdout
|
||||
.write_all(text.as_bytes())
|
||||
.and_then(|()| stdout.write_all(b"\n"))
|
||||
.and_then(|()| stdout.flush()))
|
||||
}
|
||||
|
||||
/// Remote ref SHAs whose objects exist locally (`git cat-file -t`).
|
||||
fn local_remote_shas(&self) -> Vec<String> {
|
||||
self.remote_refs
|
||||
.iter()
|
||||
.filter(|(_, sha)| self.git_ok(&["cat-file", "-t", sha]).is_some())
|
||||
.map(|(_, sha)| sha.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `process_fetch_queue` (`client.py`).
|
||||
fn process_fetch_queue(
|
||||
&mut self,
|
||||
mut queue: Vec<(String, String)>,
|
||||
stderr: &mut dyn Write,
|
||||
) -> Result<Flow, Abort> {
|
||||
if queue.is_empty() {
|
||||
return Ok(Flow::Continue);
|
||||
}
|
||||
let have_shas = self.local_remote_shas();
|
||||
// A batch size of 0, which the config never yields, sends an empty batch each
|
||||
// time and never shrinks the queue; the node answers "No refs specified", which aborts.
|
||||
while !queue.is_empty() {
|
||||
let take = self.ref_batch_size.min(queue.len());
|
||||
let batch: Vec<_> = queue.drain(..take).collect();
|
||||
let mut refs = Vec::new();
|
||||
for (sha, name) in &batch {
|
||||
let mut entry = vec![(s("sha"), s(sha)), (s("ref"), s(name))];
|
||||
if let Some(local) = self.git_ok(&["rev-parse", name])
|
||||
&& &local != sha
|
||||
{
|
||||
entry.push((s("have"), s(&local)));
|
||||
}
|
||||
refs.push(map(entry));
|
||||
}
|
||||
let mut data = vec![
|
||||
(Value::from(IDX_REPOSITORY), s(&self.repo_path)),
|
||||
(s("refs"), Value::Array(refs)),
|
||||
];
|
||||
if !have_shas.is_empty() {
|
||||
data.push((
|
||||
s("have"),
|
||||
Value::Array(have_shas.iter().map(|h| s(h)).collect()),
|
||||
));
|
||||
}
|
||||
match self.send(PATH_FETCH, map(data))? {
|
||||
Response::Bytes(b) if b.is_empty() => {
|
||||
return Err(Abort::new("No data in fetch response for batch"));
|
||||
}
|
||||
Response::Bytes(b) => {
|
||||
if b[0] != 0 {
|
||||
return Err(Abort::new(format!(
|
||||
"Fetch failed for batch: {}",
|
||||
decode_ignore(&b[1..])
|
||||
)));
|
||||
}
|
||||
}
|
||||
Response::Other(v) if is_falsy(&v) => {
|
||||
return Err(Abort::new("No data in fetch response for batch"));
|
||||
}
|
||||
Response::Other(_) => return Err(Abort::new("Invalid fetch response for batch")),
|
||||
Response::File { metadata, .. } if is_falsy(&metadata) => {
|
||||
return Err(Abort::new("Invalid fetch response for batch"));
|
||||
}
|
||||
Response::File { path, metadata } => {
|
||||
self.unbundle(&path, &metadata, stderr)?;
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Flow::Continue)
|
||||
}
|
||||
|
||||
fn unbundle(&self, path: &Path, metadata: &Value, stderr: &mut dyn Write) -> Result<(), Abort> {
|
||||
let status = metadata.as_map().and_then(|m| {
|
||||
m.iter()
|
||||
.find(|(k, _)| k.as_u64() == Some(u64::from(IDX_RESULT_CODE)))
|
||||
.map(|(_, v)| v.clone())
|
||||
});
|
||||
let Some(status) = status else {
|
||||
return Err(Abort::new("No result metadata on bundle response"));
|
||||
};
|
||||
if status.as_u64() != Some(0) {
|
||||
return Err(Abort::new("Unknown remote state for batch ref fetch"));
|
||||
}
|
||||
let bundle = path.to_string_lossy().to_string();
|
||||
if self.progress_enabled {
|
||||
let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
|
||||
let _ = writeln!(
|
||||
stderr,
|
||||
"Transferring: 100% ({}). ",
|
||||
prettysize(size as f64)
|
||||
);
|
||||
let _ = stderr.flush();
|
||||
}
|
||||
let verified = self
|
||||
.git(&["bundle", "verify", "-q", &bundle])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
if !verified.is_ok_and(|s| s.success()) {
|
||||
return Err(Abort::new("Bundle verification failed for batch"));
|
||||
}
|
||||
let mut args = vec!["bundle", "unbundle"];
|
||||
if self.progress_enabled {
|
||||
args.push("--progress");
|
||||
}
|
||||
args.push(&bundle);
|
||||
let unbundled = self
|
||||
.git(&args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(if self.progress_enabled {
|
||||
Stdio::inherit()
|
||||
} else {
|
||||
Stdio::null()
|
||||
})
|
||||
.status();
|
||||
if !unbundled.is_ok_and(|s| s.success()) {
|
||||
return Err(Abort::new(
|
||||
"Bundle unbundle failed for batch: Non-zero return code",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send a push or delete request and turn its reply into the status line's error, if any.
|
||||
fn status_request(&mut self, path: &str, data: Value) -> Result<Option<String>, Abort> {
|
||||
Ok(match self.send(path, data)? {
|
||||
Response::Bytes(b) if !b.is_empty() => (b[0] != 0).then(|| decode_ignore(&b[1..])),
|
||||
_ => Some("No response from server".into()),
|
||||
})
|
||||
}
|
||||
|
||||
/// `process_push_queue` (`client.py`).
|
||||
fn process_push_queue(
|
||||
&mut self,
|
||||
queue: Vec<(String, String)>,
|
||||
stdout: &mut dyn Write,
|
||||
stderr: &mut dyn Write,
|
||||
) -> Result<Flow, Abort> {
|
||||
for (local_ref, remote_ref) in queue {
|
||||
let error = self.push_one(&local_ref, &remote_ref, stderr)?;
|
||||
let line = match error {
|
||||
None => format!("ok {remote_ref}\n"),
|
||||
Some(msg) => format!("error {remote_ref} {}\n", escape_for_stdout(&msg)),
|
||||
};
|
||||
if let Err(e) = stdout
|
||||
.write_all(line.as_bytes())
|
||||
.and_then(|()| stdout.flush())
|
||||
&& broken(&e)
|
||||
{
|
||||
return Ok(Flow::BrokenPipe);
|
||||
}
|
||||
}
|
||||
Ok(Flow::Continue)
|
||||
}
|
||||
|
||||
fn push_one(
|
||||
&mut self,
|
||||
local_ref: &str,
|
||||
remote_ref: &str,
|
||||
stderr: &mut dyn Write,
|
||||
) -> Result<Option<String>, Abort> {
|
||||
let repo = (Value::from(IDX_REPOSITORY), s(&self.repo_path));
|
||||
if local_ref.is_empty() {
|
||||
let data = map(vec![repo, (s("ref"), s(remote_ref))]);
|
||||
return self.status_request(PATH_DELETE, data);
|
||||
}
|
||||
let force = local_ref.starts_with('+');
|
||||
let local_ref = local_ref.strip_prefix('+').unwrap_or(local_ref);
|
||||
let Some(local_sha) = self.git_ok(&["rev-parse", local_ref]) else {
|
||||
return Ok(Some(format!("Could not resolve local ref {local_ref}")));
|
||||
};
|
||||
let tmp = tempfile::tempdir().map_err(|e| {
|
||||
Abort::exception(format!("Could not create a temporary directory: {e}"))
|
||||
})?;
|
||||
let bundle_path = tmp.path().join("push.bundle");
|
||||
let bundle = bundle_path.to_string_lossy().to_string();
|
||||
let excludes: Vec<String> = self
|
||||
.local_remote_shas()
|
||||
.into_iter()
|
||||
.map(|sha| format!("^{sha}"))
|
||||
.collect();
|
||||
let mut args = vec!["bundle", "create", bundle.as_str(), local_ref];
|
||||
args.extend(excludes.iter().map(String::as_str));
|
||||
if self.progress_enabled {
|
||||
args.insert(2, "--progress");
|
||||
}
|
||||
let created = self
|
||||
.git(&args)
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.map_err(|e| Abort::exception(format!("FileNotFoundError: {e}")))?;
|
||||
let data = if created.status.success() {
|
||||
let bundle_data = std::fs::read(&bundle_path)
|
||||
.map_err(|e| Abort::exception(format!("FileNotFoundError: {e}")))?;
|
||||
map(vec![
|
||||
repo,
|
||||
(s("local_ref"), s(local_ref)),
|
||||
(s("remote_ref"), s(remote_ref)),
|
||||
(s("force"), Value::Boolean(force)),
|
||||
(s("bundle"), Value::Binary(bundle_data)),
|
||||
])
|
||||
} else {
|
||||
let err = String::from_utf8_lossy(&created.stderr);
|
||||
if !err.to_lowercase().contains("empty bundle") {
|
||||
if self.progress_enabled && !err.is_empty() {
|
||||
let _ = stderr.write_all(err.as_bytes());
|
||||
}
|
||||
return Ok(Some("Bundle creation failed".into()));
|
||||
}
|
||||
let operation = map(vec![
|
||||
(s("action"), s("update_ref")),
|
||||
(s("ref"), s(remote_ref)),
|
||||
(s("sha"), s(&local_sha)),
|
||||
(s("force"), Value::Boolean(force)),
|
||||
]);
|
||||
map(vec![repo, (s("operations"), Value::Array(vec![operation]))])
|
||||
};
|
||||
self.status_request(PATH_PUSH, data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! The `rngit create` client side (`ReticulumGitClient`, `server.py`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use rns_tools::rsg::pyfmt::py_fromhex;
|
||||
|
||||
/// `__default_rngit_config__` (`client.py`) as ConfigObj writes it.
|
||||
pub const DEFAULT_CLIENT_CONFIG: &str = include_str!("default_client_config.txt");
|
||||
|
||||
const PROTO_SPEC: &str = "rns://";
|
||||
|
||||
/// `ReticulumGitClient.__init__` config directory (`server.py`),
|
||||
/// including upstream's `~/.rngit/reticulum` when `~/.config/rngit/config` exists.
|
||||
pub fn client_config_dir(configdir: Option<&Path>) -> PathBuf {
|
||||
if let Some(dir) = configdir {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
let home = super::config::expand_user("~");
|
||||
if home.join(".config/rngit/config").is_file() {
|
||||
home.join(".rngit/reticulum")
|
||||
} else {
|
||||
home.join(".rngit")
|
||||
}
|
||||
}
|
||||
|
||||
/// The `[logging] loglevel` and `[aliases]` that `__apply_config` reads
|
||||
/// (`server.py`). A missing file is created from the default.
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||
pub struct ClientConfig {
|
||||
pub loglevel: Option<i64>,
|
||||
pub aliases: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl ClientConfig {
|
||||
pub fn load_or_create(configdir: &Path) -> Result<Self, String> {
|
||||
let path = configdir.join("client_config");
|
||||
let text = if path.is_file() {
|
||||
std::fs::read_to_string(&path).map_err(|e| e.to_string())?
|
||||
} else {
|
||||
std::fs::create_dir_all(configdir).map_err(|e| e.to_string())?;
|
||||
std::fs::write(&path, DEFAULT_CLIENT_CONFIG).map_err(|e| e.to_string())?;
|
||||
DEFAULT_CLIENT_CONFIG.to_string()
|
||||
};
|
||||
Self::parse(&text)
|
||||
}
|
||||
|
||||
pub fn parse(text: &str) -> Result<Self, String> {
|
||||
let config = rns_runtime::config::Config::parse(text).map_err(|e| e.to_string())?;
|
||||
let mut out = ClientConfig::default();
|
||||
if let Some(section) = config.section("logging").filter(|s| s.has("loglevel")) {
|
||||
let level = section
|
||||
.get_int("loglevel")
|
||||
.ok_or("invalid literal for int() with base 10")?;
|
||||
out.loglevel = Some(level.clamp(-1, 7));
|
||||
}
|
||||
if let Some(section) = config.section("aliases") {
|
||||
for alias in section.values.keys() {
|
||||
let Some(hexhash) = section.get(alias) else {
|
||||
continue;
|
||||
};
|
||||
let hash = py_fromhex(hexhash).ok().filter(|h| !h.is_empty());
|
||||
if let Some(hash) = hash.filter(|_| hexhash.chars().count() == 32) {
|
||||
out.aliases
|
||||
.entry(alias.clone())
|
||||
.or_insert_with(|| hex::encode(hash));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `__resolve_destination_alias` (`server.py`).
|
||||
fn resolve(&self, alias: &str) -> String {
|
||||
let is_hash = alias.chars().count() == 32 && py_fromhex(alias).is_ok_and(|h| !h.is_empty());
|
||||
if is_hash {
|
||||
alias.to_string()
|
||||
} else {
|
||||
self.aliases
|
||||
.get(alias)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| alias.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn destination(&self, remote: &str) -> Result<(Vec<u8>, Vec<String>), String> {
|
||||
let prefix_ok = remote
|
||||
.get(..PROTO_SPEC.len())
|
||||
.is_some_and(|p| p.eq_ignore_ascii_case(PROTO_SPEC));
|
||||
if !prefix_ok {
|
||||
return Err("Invalid protocol in remote URL".into());
|
||||
}
|
||||
let components: Vec<String> = remote[PROTO_SPEC.len()..]
|
||||
.split('/')
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
let hexhash = self.resolve(&components[0]);
|
||||
Ok((hexhash.into_bytes(), components))
|
||||
}
|
||||
|
||||
fn decode(hexhash: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let hexhash = String::from_utf8_lossy(hexhash);
|
||||
if hexhash.chars().count() != 32 {
|
||||
return Err("Invalid destination hash length".into());
|
||||
}
|
||||
py_fromhex(&hexhash).map_err(|e| format!("Invalid destination hash: {e}"))
|
||||
}
|
||||
|
||||
/// `parse_remote_destination_url` (`server.py`): the abort text on error.
|
||||
pub fn parse_remote_destination_url(&self, remote: &str) -> Result<Vec<u8>, String> {
|
||||
let (hexhash, _) = self.destination(remote)?;
|
||||
Self::decode(&hexhash)
|
||||
}
|
||||
|
||||
/// `parse_remote_group_url` (`server.py`): hash and group.
|
||||
pub fn parse_remote_group_url(&self, remote: &str) -> Result<(Vec<u8>, String), String> {
|
||||
let (hexhash, components) = self.destination(remote)?;
|
||||
if components.len() != 2 {
|
||||
return Err("Invalid number of URL components".into());
|
||||
}
|
||||
let hash = Self::decode(&hexhash)?;
|
||||
Ok((hash, components[1].clone()))
|
||||
}
|
||||
|
||||
/// `parse_remote_url` (`server.py`): hash, group and repository.
|
||||
pub fn parse_remote_url(&self, remote: &str) -> Result<(Vec<u8>, String, String), String> {
|
||||
let (hexhash, components) = self.destination(remote)?;
|
||||
if components.len() != 3 {
|
||||
return Err("Invalid number of URL components".into());
|
||||
}
|
||||
let hash = Self::decode(&hexhash)?;
|
||||
Ok((hash, components[1].clone(), components[2].clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// What `create_repository` prints for a `/git/create` reply
|
||||
/// (`server.py`): `Ok` on success, `Err` for the abort text.
|
||||
pub fn create_outcome(repo_path: &str, response: Option<&[u8]>) -> Result<String, String> {
|
||||
let Some(response) = response.filter(|r| !r.is_empty()) else {
|
||||
return Err("No response from remote".into());
|
||||
};
|
||||
let text = |fallback: &str| {
|
||||
if response.len() > 1 {
|
||||
response[1..]
|
||||
.utf8_chunks()
|
||||
.map(|chunk| chunk.valid())
|
||||
.collect()
|
||||
} else {
|
||||
fallback.to_string()
|
||||
}
|
||||
};
|
||||
match response[0] {
|
||||
super::RES_OK => Ok(format!("Repository {repo_path} created")),
|
||||
super::RES_INVALID_REQ => Err("Remote error: Invalid request".into()),
|
||||
super::RES_NOT_FOUND => Err("Not found".into()),
|
||||
super::RES_DISALLOWED => Err(text("Not allowed")),
|
||||
_ => Err(format!("Remote error: {}", text("Unknown error"))),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Node configuration: `ReticulumGitNode.__init__` and `__apply_config`
|
||||
//! (`server.py`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_runtime::config::{Config, ConfigError, ConfigSection};
|
||||
use rns_tools::rsg::pyfmt::py_fromhex;
|
||||
|
||||
use super::perms::{ALL_TGTS, resolve_identity_alias};
|
||||
use super::py_len;
|
||||
|
||||
/// The file upstream writes when the config directory has none
|
||||
/// (`__default_rngit_config__`, `server.py`), plus the fetch limit keys.
|
||||
pub const DEFAULT_CONFIG: &str = include_str!("default_config.txt");
|
||||
|
||||
pub const DEFAULT_NODE_NAME: &str = "Anonymous Git Node";
|
||||
/// `DEFAULT_LINK_COST` of both rngit destinations (`server.py`, `pages.py`).
|
||||
pub const DEFAULT_LINK_COST: f64 = 18.0;
|
||||
const LOG_NONE: i64 = -1;
|
||||
const LOG_EXTREME: i64 = 8;
|
||||
|
||||
/// Bounds on the `git fetch` of a fork, mirror, or sync, which upstream runs
|
||||
/// unbounded (`_handle_remote_clone`, `__sync_mirror`, `__sync_fork`, `server.py`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct FetchLimits {
|
||||
/// `fetch_time_limit`, minutes in the config file.
|
||||
pub time: Duration,
|
||||
/// `fetch_size_limit`, megabytes in the config file: the bytes a fetch may add on disk.
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
impl Default for FetchLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
time: Duration::from_secs(30 * 60),
|
||||
size: 1024 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `__apply_config` takes from the config file.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct NodeConfig {
|
||||
pub node_name: String,
|
||||
/// Seconds; 0 never announces.
|
||||
pub announce_interval: i64,
|
||||
/// `[rngit] stamp_value`, quantized; applied to the repositories
|
||||
/// destination only when above 0, as upstream tests it for truth.
|
||||
pub stamp_value: Option<f64>,
|
||||
/// `[rngit] link_cost`, quantized: the announced link request cost.
|
||||
pub link_cost: f64,
|
||||
/// Seconds; 0 disables periodic mirror sync.
|
||||
pub mirror_interval: i64,
|
||||
pub record_stats: bool,
|
||||
pub serve_nomadnet: bool,
|
||||
/// `[logging] loglevel` plus verbosity, clamped; `None` when the key is absent.
|
||||
pub loglevel: Option<i64>,
|
||||
/// Alias name to lowercase identity hash hex.
|
||||
pub aliases: BTreeMap<String, String>,
|
||||
pub stats_ignored: Vec<Vec<u8>>,
|
||||
pub stats_push_ignored: Vec<Vec<u8>>,
|
||||
pub blocked_identities: Vec<Vec<u8>>,
|
||||
pub fetch_limits: FetchLimits,
|
||||
/// `[repositories]` group name to the configured path, before `~` expansion.
|
||||
pub repositories: BTreeMap<String, String>,
|
||||
/// `[access]` group name to its permission statements.
|
||||
pub access: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Default for NodeConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
node_name: DEFAULT_NODE_NAME.to_string(),
|
||||
announce_interval: 0,
|
||||
stamp_value: None,
|
||||
link_cost: DEFAULT_LINK_COST,
|
||||
mirror_interval: 24 * 60 * 60,
|
||||
record_stats: false,
|
||||
serve_nomadnet: false,
|
||||
loglevel: None,
|
||||
aliases: BTreeMap::new(),
|
||||
stats_ignored: Vec::new(),
|
||||
stats_push_ignored: Vec::new(),
|
||||
blocked_identities: Vec::new(),
|
||||
fetch_limits: FetchLimits::default(),
|
||||
repositories: BTreeMap::new(),
|
||||
access: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(section: &str, key: &str, message: &str) -> ConfigError {
|
||||
ConfigError::InvalidValue {
|
||||
section: section.to_string(),
|
||||
key: key.to_string(),
|
||||
message: message.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// ConfigObj `as_int`, which raises on a value `int()` rejects.
|
||||
fn as_int(section: &ConfigSection, name: &str, key: &str) -> Result<i64, ConfigError> {
|
||||
section
|
||||
.get_int(key)
|
||||
.ok_or_else(|| invalid(name, key, "not an integer"))
|
||||
}
|
||||
|
||||
/// A fetch limit: there is no unlimited value, so anything below 1 counts as 1.
|
||||
fn as_limit(section: &ConfigSection, name: &str, key: &str) -> Result<u64, ConfigError> {
|
||||
let value = as_int(section, name, key)?;
|
||||
if value < 1 {
|
||||
tracing::warn!("{key} = {value} in configuration file is below 1, using 1");
|
||||
}
|
||||
Ok(value.max(1) as u64)
|
||||
}
|
||||
|
||||
/// `Stamps.quantize_cost(section.as_float(key))`, which raises on a value
|
||||
/// `float()` rejects and on NaN or infinity.
|
||||
pub(crate) fn as_cost(section: &ConfigSection, name: &str, key: &str) -> Result<f64, ConfigError> {
|
||||
let value = section
|
||||
.get_float(key)
|
||||
.ok_or_else(|| invalid(name, key, "not a float"))?;
|
||||
rns_identity::stamps::quantize_cost(value).map_err(|e| invalid(name, key, &e.to_string()))
|
||||
}
|
||||
|
||||
/// ConfigObj `as_bool`, which raises on anything but its boolean words.
|
||||
fn as_bool(section: &ConfigSection, name: &str, key: &str) -> Result<bool, ConfigError> {
|
||||
section
|
||||
.get_bool(key)
|
||||
.ok_or_else(|| invalid(name, key, "not a boolean"))
|
||||
}
|
||||
|
||||
impl NodeConfig {
|
||||
/// Parse config text as `__apply_config` reads it. `verbosity` is the
|
||||
/// `-v` count minus the `-q` count, 0 in service mode.
|
||||
pub fn parse(text: &str, verbosity: i64) -> Result<Self, ConfigError> {
|
||||
let config = Config::parse(text)?;
|
||||
let mut node = NodeConfig::default();
|
||||
|
||||
if let Some(section) = config.section("aliases") {
|
||||
for alias in section.values.keys() {
|
||||
let Some(hexhash) = section.get(alias) else {
|
||||
tracing::warn!(
|
||||
"Invalid identity hash for alias {alias} in configuration file, ignoring"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let hash = py_fromhex(hexhash).ok().filter(|h| !h.is_empty());
|
||||
let Some(hash) = hash.filter(|_| py_len(hexhash) == 32) else {
|
||||
tracing::warn!(
|
||||
"Invalid identity hash for alias {alias} in configuration file, ignoring"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
if ALL_TGTS.contains(&alias.as_str()) {
|
||||
tracing::warn!("Invalid alias {alias} in configuration file, ignoring");
|
||||
continue;
|
||||
}
|
||||
node.aliases
|
||||
.entry(alias.clone())
|
||||
.or_insert_with(|| hex::encode(hash));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(section) = config.section("rngit") {
|
||||
let name = "rngit";
|
||||
if let Some(value) = section.get("node_name") {
|
||||
node.node_name = value.to_string();
|
||||
}
|
||||
if section.has("announce_interval") {
|
||||
node.announce_interval = as_int(section, name, "announce_interval")? * 60;
|
||||
}
|
||||
if section.has("stamp_value") {
|
||||
node.stamp_value = Some(as_cost(section, name, "stamp_value")?);
|
||||
}
|
||||
if section.has("link_cost") {
|
||||
node.link_cost = as_cost(section, name, "link_cost")?;
|
||||
}
|
||||
if section.has("mirror_interval") {
|
||||
node.mirror_interval = (as_int(section, name, "mirror_interval")? * 3600).max(0);
|
||||
}
|
||||
if section.has("record_stats") {
|
||||
node.record_stats = as_bool(section, name, "record_stats")?;
|
||||
}
|
||||
if section.has("fetch_time_limit") {
|
||||
let minutes = as_limit(section, name, "fetch_time_limit")?;
|
||||
node.fetch_limits.time = Duration::from_secs(minutes.saturating_mul(60));
|
||||
}
|
||||
if section.has("fetch_size_limit") {
|
||||
let megabytes = as_limit(section, name, "fetch_size_limit")?;
|
||||
node.fetch_limits.size = megabytes.saturating_mul(1024 * 1024);
|
||||
}
|
||||
for (key, target) in [
|
||||
("stats_ignore_identities", &mut node.stats_ignored),
|
||||
("stats_push_ignore_identities", &mut node.stats_push_ignored),
|
||||
("blocked_identities", &mut node.blocked_identities),
|
||||
] {
|
||||
for entry in section.get_list(key).unwrap_or_default() {
|
||||
let resolved = resolve_identity_alias(&entry, &node.aliases);
|
||||
if py_len(&resolved) != 32 {
|
||||
continue;
|
||||
}
|
||||
match py_fromhex(&resolved) {
|
||||
Ok(hash) if !target.contains(&hash) => target.push(hash),
|
||||
Ok(_) => {}
|
||||
Err(_) => tracing::warn!("Invalid identity hash in {key}: {resolved}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(section) = config.section("logging").filter(|s| s.has("loglevel")) {
|
||||
let level = as_int(section, "logging", "loglevel")? + verbosity;
|
||||
node.loglevel = Some(level.clamp(LOG_NONE, LOG_EXTREME));
|
||||
}
|
||||
|
||||
if let Some(section) = config.section("pages").filter(|s| s.has("serve_nomadnet")) {
|
||||
node.serve_nomadnet = as_bool(section, "pages", "serve_nomadnet")?;
|
||||
}
|
||||
|
||||
if let Some(section) = config.section("repositories") {
|
||||
for key in section.values.keys() {
|
||||
if let Some(path) = section.get(key) {
|
||||
node.repositories.insert(key.clone(), path.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(section) = config.section("access") {
|
||||
for key in section.values.keys() {
|
||||
node.access
|
||||
.insert(key.clone(), section.get_list(key).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(node)
|
||||
}
|
||||
}
|
||||
|
||||
/// The config directory as `ReticulumGitNode.__init__` picks it
|
||||
/// (`server.py`).
|
||||
pub fn resolve_config_dir(configdir: Option<&Path>) -> PathBuf {
|
||||
if let Some(dir) = configdir {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
let etc = Path::new("/etc/rngit");
|
||||
if etc.is_dir() && etc.join("config").is_file() {
|
||||
return etc.to_path_buf();
|
||||
}
|
||||
let home = rns_runtime::platform::home_dir().unwrap_or_default();
|
||||
let user = home.join(".config/rngit");
|
||||
if user.is_dir() && user.join("config").is_file() {
|
||||
return user;
|
||||
}
|
||||
home.join(".rngit")
|
||||
}
|
||||
|
||||
/// The config text, writing [`DEFAULT_CONFIG`] first when the file is
|
||||
/// missing (`__create_default_config`, `server.py`).
|
||||
pub fn read_or_create_config(configdir: &Path) -> std::io::Result<String> {
|
||||
let path = configdir.join("config");
|
||||
if path.is_file() {
|
||||
return std::fs::read_to_string(path);
|
||||
}
|
||||
tracing::info!("Could not load config file, creating default configuration file...");
|
||||
std::fs::create_dir_all(configdir)?;
|
||||
std::fs::write(&path, DEFAULT_CONFIG)?;
|
||||
Ok(DEFAULT_CONFIG.to_string())
|
||||
}
|
||||
|
||||
/// Load `repositories_identity`, creating it when missing.
|
||||
pub fn load_or_create_identity(
|
||||
path: &Path,
|
||||
) -> Result<Identity, rns_identity::identity::IdentityError> {
|
||||
if path.is_file() {
|
||||
return Identity::from_file(path);
|
||||
}
|
||||
let identity = Identity::new();
|
||||
identity.to_file(path)?;
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
/// Python `os.path.expanduser` for `~` and `~/...`, and `~\...` on Windows.
|
||||
pub fn expand_user(path: &str) -> PathBuf {
|
||||
match path.strip_prefix('~') {
|
||||
Some(rest) if rest.is_empty() || rest.starts_with(std::path::is_separator) => {
|
||||
let mut home = rns_runtime::platform::home_dir()
|
||||
.unwrap_or_default()
|
||||
.into_os_string();
|
||||
home.push(rest);
|
||||
PathBuf::from(home)
|
||||
}
|
||||
_ => PathBuf::from(path),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stamp_value_and_link_cost_follow_upstream() {
|
||||
let node = NodeConfig::parse("[rngit]\n", 0).unwrap();
|
||||
assert_eq!((node.stamp_value, node.link_cost), (None, 18.0));
|
||||
let node = NodeConfig::parse("[rngit]\nstamp_value = 27.5\nlink_cost = 18.7\n", 0).unwrap();
|
||||
// quantize_cost: 18.7 is 4787/256.
|
||||
assert_eq!(
|
||||
(node.stamp_value, node.link_cost),
|
||||
(Some(27.5), 4787.0 / 256.0)
|
||||
);
|
||||
let node = NodeConfig::parse("[rngit]\nstamp_value = -3\nlink_cost = 150\n", 0).unwrap();
|
||||
assert_eq!((node.stamp_value, node.link_cost), (Some(0.0), 100.0));
|
||||
for body in ["stamp_value = high", "link_cost = nan", "link_cost = inf"] {
|
||||
assert!(
|
||||
NodeConfig::parse(&format!("[rngit]\n{body}\n"), 0).is_err(),
|
||||
"{body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_config_carries_the_upstream_stamp_lines() {
|
||||
// A Windows checkout embeds the template with CRLF line endings.
|
||||
let config = DEFAULT_CONFIG.replace("\r\n", "\n");
|
||||
for (section, destination) in [("[rngit]", "repository node"), ("[pages]", "page node")] {
|
||||
let start = config.find(section).unwrap();
|
||||
let text = &config[start..];
|
||||
assert!(text.contains(&format!(
|
||||
"# You can configure the required link stamp cost for\n# connecting to the {destination}.\n\n# link_cost = 18.0\n"
|
||||
)));
|
||||
}
|
||||
assert_eq!(config.matches("# stamp_value = 25.0\n").count(), 2);
|
||||
let node = NodeConfig::parse(DEFAULT_CONFIG, 0).unwrap();
|
||||
assert_eq!((node.stamp_value, node.link_cost), (None, 18.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
# This is the default rngit client config file.
|
||||
|
||||
[client]
|
||||
|
||||
# You can control the batch size of ref transfers
|
||||
# using the ref_batch_size directive:
|
||||
|
||||
ref_batch_size = 25
|
||||
|
||||
|
||||
[aliases]
|
||||
|
||||
# You can define aliases for commonly used destination
|
||||
# hashes in this section. Each line must be in the format
|
||||
# aliased_name = DESTINATION_HASH
|
||||
#
|
||||
# These hashes are used for resolving remote destinations.
|
||||
# For rngit node permissions and identity resolution,
|
||||
# aliases must be defined in ~/.rngit/config.
|
||||
|
||||
# my_node = 063d38912bffc850af4a1b8a270a9d85
|
||||
# bobs_node = 714981d03e41deda0e4468cb274414cc
|
||||
|
||||
|
||||
[logging]
|
||||
# Valid log levels are 0 through 7:
|
||||
# 0: Log only critical information
|
||||
# 1: Log errors and lower log levels
|
||||
# 2: Log warnings and lower log levels
|
||||
# 3: Log notices and lower log levels
|
||||
# 4: Log info and lower (this is the default)
|
||||
# 5: Verbose logging
|
||||
# 6: Debug logging
|
||||
# 7: Extreme logging
|
||||
|
||||
loglevel = 4
|
||||
@@ -0,0 +1,193 @@
|
||||
# This is the default rngit config file.
|
||||
# You will need to edit it to specify repository locations and
|
||||
# access permissions.
|
||||
|
||||
[rngit]
|
||||
|
||||
# Automatic announce interval in minutes.
|
||||
# 6 hours by default.
|
||||
|
||||
announce_interval = 360
|
||||
|
||||
# An optional name for this node, included
|
||||
# in announces.
|
||||
|
||||
# node_name = Anonymous Git Node
|
||||
|
||||
# You can configure the required link stamp cost for
|
||||
# connecting to the repository node.
|
||||
|
||||
# link_cost = 18.0
|
||||
|
||||
# The target stamp value for the repositories destination
|
||||
# can also be configured.
|
||||
|
||||
# stamp_value = 25.0
|
||||
|
||||
# You can enable collecting view, fetch and push statistics
|
||||
# which can be displayed on the stats pages of repositories.
|
||||
# Remember to set the "s" (stats) permission appropriately
|
||||
# for statistics to actually be viewable by anyone.
|
||||
|
||||
# record_stats = no
|
||||
# stats_ignore_identities = 9710b86ba12c42d1d8f30f74fe509286
|
||||
# stats_push_ignore_identities = 5bffebe038654304dafcbe12cbcd0412
|
||||
|
||||
# You can block specific identities from any interaction
|
||||
# with this node.
|
||||
|
||||
# blocked_identities = d31aeea49873006f13b3415520666a4e
|
||||
|
||||
# To make it easier to handle scrapers, crawlers, slopware
|
||||
# and other annoyances, you can block unidentified peers by
|
||||
# adding the null_ident hash to to blocked identities.
|
||||
|
||||
# blocked_identities = d7db22f63b453c23bb0688dde565b7c1
|
||||
|
||||
# Longest a fork, mirror, or sync fetch may run, in minutes.
|
||||
|
||||
# fetch_time_limit = 30
|
||||
|
||||
# Most a fork, mirror, or sync fetch may add on disk, in megabytes.
|
||||
|
||||
# fetch_size_limit = 1024
|
||||
|
||||
[repositories]
|
||||
|
||||
# You can define multiple repository groups, each with a path
|
||||
# to the directory containing "repo_name.git" directories.
|
||||
|
||||
internal = /path/to/directory/with/git/repositories
|
||||
public = /another/path/to/directory/with/git/repositories
|
||||
showcase = /another/path/to/directory/with/git/repositories
|
||||
|
||||
# To add a short description to your repositories, you can
|
||||
# either place a "repo_name.description" file in the same
|
||||
# directory as the repository folder, or set it in the bare
|
||||
# repository with `git config repository.description`.
|
||||
|
||||
# If you have mirrored repositories with the "rngit mirror"
|
||||
# command, you can configure the global mirroring interval
|
||||
# in hours.
|
||||
|
||||
# mirror_interval = 24
|
||||
|
||||
|
||||
[aliases]
|
||||
|
||||
# You can define aliases for commonly used identity hashes
|
||||
# in this section. Each line must be in the format
|
||||
# aliased_name = IDENTITY_HASH
|
||||
#
|
||||
# These hashes are used for the permissions system and
|
||||
# identity resolution. For rngit CLI client operations,
|
||||
# aliases must be defined in ~/.rngit/client_config.
|
||||
|
||||
# alice = d09285e660cfe27cee6d9a0beb58b7e0
|
||||
# bob = ffcffb4e255e156e77f79b82c13086a6
|
||||
|
||||
[access]
|
||||
|
||||
# You can apply permissions for all repositories within
|
||||
# different repository collections like this:
|
||||
|
||||
public = r:all, w:9710b86ba12c42d1d8f30f74fe509286
|
||||
internal = rw:9710b86ba12c42d1d8f30f74fe509286
|
||||
|
||||
# By default, all repositories sourced from the con-
|
||||
# figured repository collection paths have no permissions
|
||||
# enabled, and will be neither readable nor writable.
|
||||
#
|
||||
# The following permissions are supported:
|
||||
# r = read (clone, fetch, view)
|
||||
# w = write (push, create and manage work documents)
|
||||
# rw = read/write
|
||||
# c = create (create new repositories in group)
|
||||
# s = stats (view repository statistics)
|
||||
# rel = release (create and manage releases)
|
||||
# i = interact (comment on work documents)
|
||||
# p = propose (propose new work documents)
|
||||
# adm = admin (full administrative access)
|
||||
#
|
||||
# To configure permissions per repository, you must create
|
||||
# an ".allowed" file matching the repository name. If the
|
||||
# repository is in a folder called "my_project.git", create
|
||||
# a "my_project.allowed" file next to it. This file must
|
||||
# contain a permission statement on each line in the form of
|
||||
# "r:IDENTITY_HASH", "w:IDENTITY_HASH" or "r:IDENTITY_HASH".
|
||||
# Instead of IDENTITY_HASH, you can also use "all" or "none".
|
||||
#
|
||||
# You can also make the allow-files executable, and have them
|
||||
# evaluate or source the permissions from somewhere else,
|
||||
# and then output the results to stdout.
|
||||
#
|
||||
# Additionally, you can create a "group.allowed" file in the
|
||||
# root of a repository group directory, which will apply to
|
||||
# all repositories within this group. The same syntax and
|
||||
# functionality applies here.
|
||||
|
||||
|
||||
[pages]
|
||||
# You can run a nomadnet-compatible page node to serve
|
||||
# repository information if required. Access permissions
|
||||
# will follow those configured per group and repository.
|
||||
#
|
||||
# The page server supports automatic markdown to micron
|
||||
# conversion for repository readmes and other files. If
|
||||
# you have the pygments Python module installed, syntax
|
||||
# highlighting will also be automatically applied.
|
||||
#
|
||||
# The page server is highly customizable, and you can
|
||||
# provide custom templates for each page type by placing
|
||||
# a corresponding "template_name.mu" file in the
|
||||
# ~/.rngit/templates directory. The supported template
|
||||
# names are "base", "front", "group", "repo", "tree",
|
||||
# "blob", "commits", "commit", "refs", "stats", "releases",
|
||||
# "release", "work" and "work_doc". You should include a
|
||||
# {PAGE_CONTENT} variable somewhere in your templates,
|
||||
# the rendered page content will be injected into this
|
||||
# variable.
|
||||
|
||||
# serve_nomadnet = no
|
||||
|
||||
# You can configure the required link stamp cost for
|
||||
# connecting to the page node.
|
||||
|
||||
# link_cost = 18.0
|
||||
|
||||
# The target stamp value for the node destination can
|
||||
# also be configured.
|
||||
|
||||
# stamp_value = 25.0
|
||||
|
||||
# It is possible to disable Nerd Font icons and instead
|
||||
# use simpler (but more compatible) unicode icons.
|
||||
|
||||
# unicode_icons = yes
|
||||
|
||||
# You can configure whether the page server should try
|
||||
# to convert media files to WebP on the fly, for serving
|
||||
# to nomadnet clients. Enabled by default, but will
|
||||
# require an available encoding backend installed on
|
||||
# your system. Supported backends utilities are "magick",
|
||||
# "convert", "gm", "ffmpeg" and "avconv". If any one is
|
||||
# installed, rngit will auto-detect and use it, but you
|
||||
# can force a specific backend with the environment
|
||||
# variable RNGIT_MEDIA_BACKEND.
|
||||
|
||||
# media_conversion = yes
|
||||
|
||||
|
||||
[logging]
|
||||
# Valid log levels are 0 through 8:
|
||||
# 0: Log only critical information
|
||||
# 1: Log errors and lower log levels
|
||||
# 2: Log warnings and lower log levels
|
||||
# 3: Log notices and lower log levels
|
||||
# 4: Log info and lower (this is the default)
|
||||
# 5: Verbose logging
|
||||
# 6: Debug logging
|
||||
# 7: Pathing logging
|
||||
# 8: Extreme logging
|
||||
|
||||
loglevel = 4
|
||||
@@ -0,0 +1,860 @@
|
||||
//! `/git/fork`, `/git/mirror`, `/git/sync` and the periodic mirror job
|
||||
//! (`server.py`).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsString;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::{Mutex, RwLock};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
use super::config::FetchLimits;
|
||||
use super::handlers::{
|
||||
REPO_CREATE_PERMS_TEMPLATE, get, identity_text, log_request, status, truthy,
|
||||
};
|
||||
use super::layout::{Repositories, parse_repository_path};
|
||||
use super::perms::Perm;
|
||||
use super::{
|
||||
IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_OK, RES_REMOTE_FAIL,
|
||||
};
|
||||
|
||||
/// `CLONE_PROTOS` (`server.py`).
|
||||
pub const CLONE_PROTOS: [&str; 4] = ["rns", "http", "https", "ssh"];
|
||||
|
||||
/// `sync_check_interval` (`server.py`): seconds between mirror job runs.
|
||||
pub const SYNC_CHECK_INTERVAL: u64 = 15 * 60;
|
||||
|
||||
/// `ls-remote` is the only git call upstream bounds (`server.py`).
|
||||
const LS_REMOTE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Git has no fetch size cap, so the repository is measured as the fetch runs:
|
||||
/// once a second, which bounds the overshoot to a second of transfer for one
|
||||
/// directory walk.
|
||||
const SIZE_SAMPLE_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// What a stopped fetch gets to drop its lock files before it is killed.
|
||||
#[cfg(unix)]
|
||||
const STOP_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Process groups of the fetches in flight.
|
||||
#[cfg(unix)]
|
||||
static FETCHES: Mutex<Vec<nix::libc::pid_t>> = Mutex::new(Vec::new());
|
||||
|
||||
/// What a clone handler makes: a fork or a mirror.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RepoType {
|
||||
Fork,
|
||||
Mirror,
|
||||
}
|
||||
|
||||
impl RepoType {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
RepoType::Fork => "fork",
|
||||
RepoType::Mirror => "mirror",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn git(cwd: Option<&Path>, args: &[&str]) -> std::io::Result<std::process::Output> {
|
||||
let mut cmd = Command::new("git");
|
||||
if let Some(cwd) = cwd {
|
||||
cmd.current_dir(cwd);
|
||||
}
|
||||
cmd.args(args).stdin(Stdio::null()).output()
|
||||
}
|
||||
|
||||
/// `subprocess.run(..., timeout=...)`: the child is killed at the deadline.
|
||||
fn git_with_timeout(
|
||||
args: &[&str],
|
||||
timeout: Duration,
|
||||
) -> std::io::Result<Option<std::process::Output>> {
|
||||
let mut child = Command::new("git")
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
let mut stdout = child.stdout.take().expect("piped");
|
||||
let mut stderr = child.stderr.take().expect("piped");
|
||||
let out = std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = stdout.read_to_end(&mut buf);
|
||||
buf
|
||||
});
|
||||
let err = std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = stderr.read_to_end(&mut buf);
|
||||
buf
|
||||
});
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break Some(status);
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
break None;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
let stdout = out.join().unwrap_or_default();
|
||||
let stderr = err.join().unwrap_or_default();
|
||||
Ok(status.map(|status| std::process::Output {
|
||||
status,
|
||||
stdout,
|
||||
stderr,
|
||||
}))
|
||||
}
|
||||
|
||||
fn lossy(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn signal_group(pgid: nix::libc::pid_t, signal: nix::libc::c_int) {
|
||||
// SAFETY: killpg takes two integers and touches no memory of this process.
|
||||
unsafe { nix::libc::killpg(pgid, signal) };
|
||||
}
|
||||
|
||||
/// Stop the fetches in flight. They run in their own process groups, so a
|
||||
/// terminal interrupt of the node does not reach them. On Windows they share
|
||||
/// the node's console, so its interrupt reaches them directly.
|
||||
pub fn stop_fetches() {
|
||||
#[cfg(unix)]
|
||||
for pgid in FETCHES.lock().unwrap_or_else(|e| e.into_inner()).iter() {
|
||||
signal_group(*pgid, nix::libc::SIGTERM);
|
||||
}
|
||||
}
|
||||
|
||||
/// A fetch's process group, listed in `FETCHES` while it runs.
|
||||
#[cfg(unix)]
|
||||
struct FetchGroup(nix::libc::pid_t);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl FetchGroup {
|
||||
fn new(child: &std::process::Child) -> Self {
|
||||
let pgid = child.id() as nix::libc::pid_t;
|
||||
FETCHES.lock().unwrap_or_else(|e| e.into_inner()).push(pgid);
|
||||
FetchGroup(pgid)
|
||||
}
|
||||
|
||||
/// SIGTERM, so git removes its lock files, then SIGKILL for whatever is left.
|
||||
fn stop(&self, child: &mut std::process::Child) {
|
||||
signal_group(self.0, nix::libc::SIGTERM);
|
||||
let deadline = Instant::now() + STOP_GRACE;
|
||||
while Instant::now() < deadline && !matches!(child.try_wait(), Ok(Some(_))) {
|
||||
std::thread::sleep(POLL_INTERVAL);
|
||||
}
|
||||
signal_group(self.0, nix::libc::SIGKILL);
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for FetchGroup {
|
||||
fn drop(&mut self) {
|
||||
FETCHES
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.retain(|pgid| *pgid != self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Without process groups or signals, a stopped fetch is terminated at once;
|
||||
/// git may leave its lock files behind.
|
||||
#[cfg(not(unix))]
|
||||
struct FetchGroup;
|
||||
|
||||
#[cfg(not(unix))]
|
||||
impl FetchGroup {
|
||||
fn new(_child: &std::process::Child) -> Self {
|
||||
FetchGroup
|
||||
}
|
||||
|
||||
fn stop(&self, child: &mut std::process::Child) {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of the files under `path`; what vanishes during the walk counts as nothing.
|
||||
fn dir_size(path: &Path) -> u64 {
|
||||
let mut total = 0;
|
||||
let mut pending = vec![path.to_path_buf()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
|
||||
match entry.metadata() {
|
||||
Ok(meta) if meta.is_dir() => pending.push(entry.path()),
|
||||
Ok(meta) => total += meta.len(),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn pack_files(repo_path: &Path) -> HashSet<OsString> {
|
||||
std::fs::read_dir(repo_path.join("objects/pack"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|entry| entry.file_name())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Git leaves the pack it was receiving when stopped, and a mirror is retried
|
||||
/// at every sync check, so the packs this fetch left are removed.
|
||||
fn remove_partial_packs(repo_path: &Path, before: &HashSet<OsString>) {
|
||||
for entry in std::fs::read_dir(repo_path.join("objects/pack"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
{
|
||||
let name = entry.file_name();
|
||||
if name.to_string_lossy().starts_with("tmp_") && !before.contains(&name) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a fetch under [`FetchLimits`] ended.
|
||||
enum Fetched {
|
||||
Done,
|
||||
/// Git's stderr.
|
||||
Failed(String),
|
||||
/// The limit it went over, which is already logged.
|
||||
Stopped(String),
|
||||
}
|
||||
|
||||
/// `git fetch <source> +refs/*:refs/*` in `repo_path`, stopped at a time or size limit.
|
||||
/// Differs from `_handle_remote_clone`, `__sync_mirror`, and `__sync_fork`
|
||||
/// (`server.py`), whose fetches have no time or size limit.
|
||||
fn fetch_all(
|
||||
label: &str,
|
||||
repo_path: &Path,
|
||||
source: &str,
|
||||
limits: FetchLimits,
|
||||
) -> std::io::Result<Fetched> {
|
||||
let packs_before = pack_files(repo_path);
|
||||
let size_before = dir_size(repo_path);
|
||||
let grown = || dir_size(repo_path).saturating_sub(size_before);
|
||||
let mut command = Command::new("git");
|
||||
command
|
||||
.args(["fetch", source, "+refs/*:refs/*"])
|
||||
.current_dir(repo_path)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped());
|
||||
// Its own group, so the transport helpers it starts are stopped with it.
|
||||
#[cfg(unix)]
|
||||
std::os::unix::process::CommandExt::process_group(&mut command, 0);
|
||||
let mut child = command.spawn()?;
|
||||
let group = FetchGroup::new(&child);
|
||||
let mut stderr = child.stderr.take().expect("piped");
|
||||
let reader = std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = stderr.read_to_end(&mut buf);
|
||||
buf
|
||||
});
|
||||
let started = Instant::now();
|
||||
let mut sampled = started;
|
||||
let time_limit = || {
|
||||
let minutes = limits.time.as_secs_f64() / 60.0;
|
||||
format!("time limit of {minutes} minutes exceeded")
|
||||
};
|
||||
let size_limit = || {
|
||||
let megabytes = limits.size as f64 / (1024.0 * 1024.0);
|
||||
format!("size limit of {megabytes} megabytes exceeded")
|
||||
};
|
||||
let reason = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) if !status.success() => {
|
||||
return Ok(Fetched::Failed(lossy(&reader.join().unwrap_or_default())));
|
||||
}
|
||||
Ok(Some(_)) if grown() <= limits.size => return Ok(Fetched::Done),
|
||||
// The fetch finished between two samples.
|
||||
Ok(Some(_)) => break size_limit(),
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
group.stop(&mut child);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
let over = if started.elapsed() >= limits.time {
|
||||
Some(time_limit())
|
||||
} else if sampled.elapsed() >= SIZE_SAMPLE_INTERVAL {
|
||||
sampled = Instant::now();
|
||||
(grown() > limits.size).then(size_limit)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(reason) = over {
|
||||
group.stop(&mut child);
|
||||
remove_partial_packs(repo_path, &packs_before);
|
||||
break reason;
|
||||
}
|
||||
std::thread::sleep(POLL_INTERVAL);
|
||||
};
|
||||
tracing::error!("Fetch from {source} for {label} failed: {reason}");
|
||||
Ok(Fetched::Stopped(reason))
|
||||
}
|
||||
|
||||
/// Python `int()` of a stripped string: sign, digits, single underscores between digits.
|
||||
fn py_int(text: &str) -> Option<i64> {
|
||||
let text = text.trim();
|
||||
let (negative, digits) = match text.as_bytes().first()? {
|
||||
b'-' => (true, &text[1..]),
|
||||
b'+' => (false, &text[1..]),
|
||||
_ => (false, text),
|
||||
};
|
||||
if digits.is_empty()
|
||||
|| digits.starts_with('_')
|
||||
|| digits.ends_with('_')
|
||||
|| digits.contains("__")
|
||||
|| !digits.bytes().all(|b| b.is_ascii_digit() || b == b'_')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let value: i64 = digits.replace('_', "").parse().ok()?;
|
||||
Some(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as i64)
|
||||
}
|
||||
|
||||
/// `__mirror_synced` (`server.py`): 0 when unset or unreadable.
|
||||
pub fn mirror_synced(path: &Path) -> i64 {
|
||||
match git(Some(path), &["config", "repository.rngit.upstream.sync"]) {
|
||||
Ok(out) if out.status.success() => py_int(&lossy(&out.stdout)).unwrap_or(0),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// `__set_mirror_synced` (`server.py`).
|
||||
pub fn set_mirror_synced(path: &Path) -> bool {
|
||||
let now = now_secs().to_string();
|
||||
git(
|
||||
Some(path),
|
||||
&["config", "repository.rngit.upstream.sync", &now],
|
||||
)
|
||||
.is_ok_and(|out| out.status.success())
|
||||
}
|
||||
|
||||
/// `__update_head_to_source_default` (`server.py`): point HEAD at
|
||||
/// the source's default branch, else at the first local branch.
|
||||
pub fn update_head_to_source_default(repo_path: &Path, source_url: &str) -> bool {
|
||||
tracing::debug!(
|
||||
"Updating HEAD for {} from {source_url}",
|
||||
repo_path.display()
|
||||
);
|
||||
let mut target: Option<String> = None;
|
||||
match git_with_timeout(
|
||||
&["ls-remote", "--symref", source_url, "HEAD"],
|
||||
LS_REMOTE_TIMEOUT,
|
||||
) {
|
||||
Ok(Some(out)) if out.status.success() => {
|
||||
for line in lossy(&out.stdout).split('\n') {
|
||||
if line.starts_with("ref: refs/heads/") {
|
||||
let parts: Vec<&str> = line.split('\t').collect();
|
||||
if parts.len() >= 2 && parts[1] == "HEAD" {
|
||||
target = Some(parts[0][5..].trim().to_string());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(_)) => {}
|
||||
Ok(None) => tracing::warn!("Timeout querying remote HEAD from {source_url}"),
|
||||
Err(e) => tracing::error!("Could not query remote HEAD from {source_url}: {e}"),
|
||||
}
|
||||
if let Some(branch) = &target {
|
||||
tracing::debug!("Determined target branch as {branch} from {source_url}");
|
||||
let found = git(
|
||||
Some(repo_path),
|
||||
&["show-ref", "--verify", "--quiet", branch],
|
||||
)
|
||||
.is_ok_and(|out| out.status.success());
|
||||
if !found {
|
||||
tracing::warn!("Remote default branch {branch} not found locally, using fallback");
|
||||
target = None;
|
||||
}
|
||||
}
|
||||
let target = match target {
|
||||
Some(target) => target,
|
||||
None => {
|
||||
tracing::warn!(
|
||||
"Could not determine target branch from {source_url}, falling back to first available local branch"
|
||||
);
|
||||
let args = [
|
||||
"for-each-ref",
|
||||
"--format=%(refname:short)",
|
||||
"refs/heads",
|
||||
"--count=1",
|
||||
];
|
||||
match git(Some(repo_path), &args) {
|
||||
Ok(out) if out.status.success() && !lossy(&out.stdout).trim().is_empty() => {
|
||||
format!("refs/heads/{}", lossy(&out.stdout).trim())
|
||||
}
|
||||
Ok(_) => return false,
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Could not determine fallback branch for {}: {e}",
|
||||
repo_path.display()
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
match git(Some(repo_path), &["symbolic-ref", "HEAD", &target]) {
|
||||
Ok(out) if out.status.success() => {
|
||||
tracing::debug!("Updated {} HEAD to {target}", repo_path.display());
|
||||
true
|
||||
}
|
||||
Ok(out) => {
|
||||
tracing::warn!("Failed to update HEAD to {target}: {}", lossy(&out.stderr));
|
||||
false
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Error updating HEAD: {e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `__sync_mirror` / `__sync_fork` (`server.py`): fetch every ref
|
||||
/// from the source; a mirror also follows the source's HEAD.
|
||||
fn sync_upstream(
|
||||
kind: RepoType,
|
||||
label: &str,
|
||||
path: &Path,
|
||||
source: &str,
|
||||
limits: FetchLimits,
|
||||
) -> bool {
|
||||
let what = match kind {
|
||||
RepoType::Mirror => "mirror",
|
||||
RepoType::Fork => "fork",
|
||||
};
|
||||
if source.is_empty() {
|
||||
tracing::error!("Could not determine upstream source for {what} {label}");
|
||||
return false;
|
||||
}
|
||||
match fetch_all(label, path, source, limits) {
|
||||
Ok(Fetched::Done) => {}
|
||||
Ok(Fetched::Failed(stderr)) => {
|
||||
tracing::error!("Failed to sync {what} {label} from {source}: {stderr}");
|
||||
return false;
|
||||
}
|
||||
Ok(Fetched::Stopped(_)) => return false,
|
||||
Err(e) => {
|
||||
tracing::error!("Error syncing {what} {label}: {e}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if kind == RepoType::Mirror {
|
||||
update_head_to_source_default(path, source);
|
||||
}
|
||||
if set_mirror_synced(path) {
|
||||
tracing::info!(
|
||||
"{} {label} synced successfully from {source}",
|
||||
capitalise(what)
|
||||
);
|
||||
} else {
|
||||
tracing::warn!(
|
||||
"{} synced but could not update sync timestamp for {label}",
|
||||
capitalise(what)
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn capitalise(word: &str) -> String {
|
||||
let mut chars = word.chars();
|
||||
chars
|
||||
.next()
|
||||
.map(|c| c.to_uppercase().chain(chars).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `__sync_mirrors` (`server.py`): every mirror whose last sync is
|
||||
/// older than `mirror_interval` seconds. Forks are never synced here. Returns
|
||||
/// at once when a run is already in progress.
|
||||
pub fn sync_mirrors(repos: &RwLock<Repositories>, mirror_interval: i64, sync_lock: &Mutex<()>) {
|
||||
let Ok(_guard) = sync_lock.try_lock() else {
|
||||
return;
|
||||
};
|
||||
let (mirrors, limits): (Vec<(String, PathBuf, String)>, FetchLimits) = {
|
||||
let repos = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let mirrors = repos
|
||||
.groups
|
||||
.values()
|
||||
.flat_map(|g| g.repositories.values())
|
||||
.filter_map(|r| {
|
||||
let source = r.mirror.clone().filter(|s| !s.is_empty())?;
|
||||
Some((format!("{}/{}", r.group, r.name), r.path.clone(), source))
|
||||
})
|
||||
.collect();
|
||||
(mirrors, repos.fetch_limits)
|
||||
};
|
||||
for (label, path, source) in mirrors {
|
||||
if now_secs() > mirror_synced(&path) + mirror_interval {
|
||||
tracing::info!("Syncing mirror {label}");
|
||||
sync_upstream(RepoType::Mirror, &label, &path, &source, limits);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `shutil.move` of a directory: a rename, or a copy and delete across filesystems.
|
||||
fn move_dir(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
match std::fs::rename(from, to) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
|
||||
copy_dir(from, to)?;
|
||||
std::fs::remove_dir_all(from)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
std::fs::create_dir(to)?;
|
||||
std::fs::set_permissions(to, std::fs::metadata(from)?.permissions())?;
|
||||
for entry in std::fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let target = to.join(entry.file_name());
|
||||
let kind = entry.file_type()?;
|
||||
if kind.is_symlink() {
|
||||
crate::platform::copy_symlink(&entry.path(), &target)?;
|
||||
} else if kind.is_dir() {
|
||||
copy_dir(&entry.path(), &target)?;
|
||||
} else {
|
||||
std::fs::copy(entry.path(), &target)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `handle_fork` (`server.py`). `None` sends no response.
|
||||
pub fn handle_fork(
|
||||
repos: &RwLock<Repositories>,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
{
|
||||
let r = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let message = format!("Fork request from remote {}", identity_text(identity));
|
||||
log_request(&r, &message, identity);
|
||||
}
|
||||
handle_remote_clone(repos, identity, data, RepoType::Fork)
|
||||
}
|
||||
|
||||
/// `handle_mirror` (`server.py`). `None` sends no response.
|
||||
pub fn handle_mirror(
|
||||
repos: &RwLock<Repositories>,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
{
|
||||
let r = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let message = format!("Mirror request from remote {}", identity_text(identity));
|
||||
log_request(&r, &message, identity);
|
||||
}
|
||||
handle_remote_clone(repos, identity, data, RepoType::Mirror)
|
||||
}
|
||||
|
||||
/// `_handle_remote_clone` (`server.py`). An identified link and a
|
||||
/// remote identity are the same condition here: both come from LINKIDENTIFY.
|
||||
fn handle_remote_clone(
|
||||
repos: &RwLock<Repositories>,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
repo_type: RepoType,
|
||||
) -> Option<Vec<u8>> {
|
||||
let Some(hash) = identity else {
|
||||
return Some(status(RES_DISALLOWED, "Not identified"));
|
||||
};
|
||||
let Value::Map(map) = data else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
let Some(path_value) = get(map, &Value::from(IDX_REPOSITORY)) else {
|
||||
return Some(status(RES_INVALID_REQ, "No repository specified"));
|
||||
};
|
||||
// Differs from `_handle_remote_clone` (`server.py`), which admits a blocked identity.
|
||||
if repos
|
||||
.read()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.is_blocked(hash)
|
||||
{
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
let source = get(map, &Value::from("source"));
|
||||
if !source.is_some_and(truthy) {
|
||||
return Some(status(RES_INVALID_REQ, "No source specified"));
|
||||
}
|
||||
let Some(source_url) = source.and_then(Value::as_str) else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid source URL"));
|
||||
};
|
||||
let lowered = source_url.to_lowercase();
|
||||
let scheme = lowered.split("://").next().unwrap_or_default();
|
||||
if !CLONE_PROTOS.contains(&scheme) {
|
||||
return Some(status(RES_DISALLOWED, "Prohibited source URL"));
|
||||
}
|
||||
// `str.split` on anything but a string raises before the try: no reply.
|
||||
let path_str = path_value.as_str()?;
|
||||
let Some((group, repo)) =
|
||||
parse_repository_path(path_str).filter(|(g, r)| !g.is_empty() && !r.is_empty())
|
||||
else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
|
||||
let (final_path, limits) = {
|
||||
let r = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let Some(group_path) = r.groups.get(group).map(|g| g.path.clone()) else {
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
};
|
||||
let read = r.resolve_group_permission(hash, group, Perm::Read);
|
||||
let create = r.resolve_group_permission(hash, group, Perm::Create);
|
||||
if !Path::new(&group_path).exists() {
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
if !create {
|
||||
return Some(if read {
|
||||
status(RES_DISALLOWED, "Not allowed")
|
||||
} else {
|
||||
status(RES_NOT_FOUND, "Not found")
|
||||
});
|
||||
}
|
||||
let final_path = Path::new(&group_path).join(repo);
|
||||
if r.repository(group, repo).is_some() || final_path.exists() {
|
||||
return Some(if r.resolve_permission(hash, group, repo, Perm::Read) {
|
||||
status(RES_DISALLOWED, "Repository already exists")
|
||||
} else {
|
||||
status(RES_NOT_FOUND, "Not found")
|
||||
});
|
||||
}
|
||||
(final_path, r.fetch_limits)
|
||||
};
|
||||
|
||||
let reply = clone_into(
|
||||
repos,
|
||||
hash,
|
||||
group,
|
||||
repo,
|
||||
source_url,
|
||||
&final_path,
|
||||
repo_type,
|
||||
limits,
|
||||
);
|
||||
Some(reply.unwrap_or_else(|e| {
|
||||
tracing::error!(
|
||||
"Error while {}ing repository {group}/{repo}: {e}",
|
||||
repo_type.name()
|
||||
);
|
||||
if final_path.exists() {
|
||||
let _ = std::fs::remove_dir_all(&final_path);
|
||||
}
|
||||
status(RES_REMOTE_FAIL, "Remote error")
|
||||
}))
|
||||
}
|
||||
|
||||
/// The `try` body of `_handle_remote_clone` (`server.py`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn clone_into(
|
||||
repos: &RwLock<Repositories>,
|
||||
hash: &[u8; 16],
|
||||
group: &str,
|
||||
repo: &str,
|
||||
source_url: &str,
|
||||
final_path: &Path,
|
||||
repo_type: RepoType,
|
||||
limits: FetchLimits,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let kind = repo_type.name();
|
||||
tracing::debug!(
|
||||
"{}ing {source_url} to {group}/{repo} for {}",
|
||||
capitalise(kind),
|
||||
identity_text(Some(hash))
|
||||
);
|
||||
let tmpdir = tempfile::TempDir::new().map_err(|e| e.to_string())?;
|
||||
tracing::debug!("Created temporary directory {}", tmpdir.path().display());
|
||||
let temp_path = tmpdir.path().join(repo);
|
||||
crate::platform::create_dir_all_755(&temp_path).map_err(|e| e.to_string())?;
|
||||
let run = |args: &[&str]| git(Some(&temp_path), args).map_err(|e| e.to_string());
|
||||
|
||||
let result = run(&["init", "--bare"])?;
|
||||
if !result.status.success() {
|
||||
tracing::error!(
|
||||
"Failed to initialize bare repository at {}: {}",
|
||||
temp_path.display(),
|
||||
lossy(&result.stderr)
|
||||
);
|
||||
return Ok(status(RES_REMOTE_FAIL, "Failed to initialize repository"));
|
||||
}
|
||||
tracing::debug!("Fetching from {source_url}...");
|
||||
let label = format!("{group}/{repo}");
|
||||
match fetch_all(&label, &temp_path, source_url, limits).map_err(|e| e.to_string())? {
|
||||
Fetched::Done => {}
|
||||
Fetched::Failed(stderr) => {
|
||||
tracing::error!("Failed to fetch from {source_url}: {stderr}");
|
||||
return Ok(status(
|
||||
RES_REMOTE_FAIL,
|
||||
&format!("Failed to fetch from source: {stderr}"),
|
||||
));
|
||||
}
|
||||
Fetched::Stopped(reason) => {
|
||||
return Ok(status(
|
||||
RES_REMOTE_FAIL,
|
||||
&format!("Failed to fetch from source: {reason}"),
|
||||
));
|
||||
}
|
||||
}
|
||||
update_head_to_source_default(&temp_path, source_url);
|
||||
|
||||
let result = run(&["config", "repository.rngit.type", kind])?;
|
||||
if !result.status.success() {
|
||||
let stderr = lossy(&result.stderr);
|
||||
tracing::warn!("Failed to set rngit.type config: {stderr}");
|
||||
return Ok(status(
|
||||
RES_REMOTE_FAIL,
|
||||
&format!("Failed to configure repository type: {stderr}"),
|
||||
));
|
||||
}
|
||||
let result = run(&["config", "repository.rngit.upstream.source", source_url])?;
|
||||
if !result.status.success() {
|
||||
let stderr = lossy(&result.stderr);
|
||||
tracing::warn!("Failed to set rngit.upstream.source config: {stderr}");
|
||||
return Ok(status(
|
||||
RES_REMOTE_FAIL,
|
||||
&format!("Failed to configure repository upstream source: {stderr}"),
|
||||
));
|
||||
}
|
||||
if !set_mirror_synced(&temp_path) {
|
||||
// Upstream reports the stderr of the previous (successful) call.
|
||||
let stderr = lossy(&result.stderr);
|
||||
tracing::warn!("Failed to set rngit.upstream.sync config: {stderr}");
|
||||
return Ok(status(
|
||||
RES_REMOTE_FAIL,
|
||||
&format!("Failed to configure repository type: {stderr}"),
|
||||
));
|
||||
}
|
||||
|
||||
let allowed = format!("{}.allowed", final_path.display());
|
||||
let tmp_allowed = format!("{allowed}.tmp");
|
||||
let permissions = REPO_CREATE_PERMS_TEMPLATE.replace("{IDENTITY_HASH}", &hex::encode(hash));
|
||||
if std::fs::write(&tmp_allowed, permissions)
|
||||
.and_then(|()| std::fs::rename(&tmp_allowed, &allowed))
|
||||
.is_err()
|
||||
{
|
||||
tracing::error!("Could not set default repository permissions for {group}/{repo}");
|
||||
return Ok(status(RES_REMOTE_FAIL, "Could not initialize repository"));
|
||||
}
|
||||
|
||||
if move_dir(&temp_path, final_path).is_err() {
|
||||
tracing::warn!("Failed to deploy fetched repository to group directory");
|
||||
return Ok(status(RES_REMOTE_FAIL, "Could not write repository"));
|
||||
}
|
||||
tracing::debug!(
|
||||
"Deployed fetched repository from {} to {}",
|
||||
temp_path.display(),
|
||||
final_path.display()
|
||||
);
|
||||
let loaded = repos
|
||||
.write()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.load_repository(group, final_path);
|
||||
match loaded {
|
||||
Ok(true) => {
|
||||
tracing::debug!("Repository {group}/{repo} {kind}ed successfully from {source_url}");
|
||||
Ok(vec![RES_OK])
|
||||
}
|
||||
Ok(false) => {
|
||||
tracing::error!(
|
||||
"Repository {} created, but runtime loading failed",
|
||||
final_path.display()
|
||||
);
|
||||
if std::fs::remove_dir_all(final_path).is_err() {
|
||||
tracing::error!(
|
||||
"Could not clean up failed repository init at {}",
|
||||
final_path.display()
|
||||
);
|
||||
}
|
||||
Ok(status(RES_REMOTE_FAIL, "Failed to register repository"))
|
||||
}
|
||||
Err(e) => Err(format!("{e:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// `handle_sync` (`server.py`). `None` sends no response.
|
||||
pub fn handle_sync(
|
||||
repos: &RwLock<Repositories>,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
let target = {
|
||||
let r = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let message = format!(
|
||||
"Upstream sync request from remote {}",
|
||||
identity_text(identity)
|
||||
);
|
||||
log_request(&r, &message, identity);
|
||||
let Some(hash) = identity else {
|
||||
return Some(status(RES_DISALLOWED, "Not identified"));
|
||||
};
|
||||
let Value::Map(map) = data else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
let Some(path_value) = get(map, &Value::from(IDX_REPOSITORY)) else {
|
||||
return Some(status(RES_INVALID_REQ, "No repository specified"));
|
||||
};
|
||||
let path = parse_repository_path(path_value.as_str()?);
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let read = path.is_some() && r.resolve_permission(hash, group, repo, Perm::Read);
|
||||
let write = path.is_some() && r.resolve_permission(hash, group, repo, Perm::Write);
|
||||
if !read {
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
if !write {
|
||||
return Some(status(RES_DISALLOWED, "Not allowed"));
|
||||
}
|
||||
let repository = r.repository(group, repo).expect("resolved");
|
||||
let label = format!("{group}/{repo}");
|
||||
let mirror = repository.mirror.clone().filter(|s| !s.is_empty());
|
||||
let fork = repository.fork.clone().filter(|s| !s.is_empty());
|
||||
(label, repository.path.clone(), mirror, fork, r.fetch_limits)
|
||||
};
|
||||
let (label, path, mirror, fork, limits) = target;
|
||||
if let Some(source) = mirror {
|
||||
tracing::info!("Syncing mirror {label}");
|
||||
return Some(
|
||||
if sync_upstream(RepoType::Mirror, &label, &path, &source, limits) {
|
||||
vec![RES_OK]
|
||||
} else {
|
||||
status(RES_REMOTE_FAIL, "Mirror sync failed")
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(source) = fork {
|
||||
tracing::info!("Syncing fork {label} with upstream");
|
||||
return Some(
|
||||
if sync_upstream(RepoType::Fork, &label, &path, &source, limits) {
|
||||
vec![RES_OK]
|
||||
} else {
|
||||
status(RES_REMOTE_FAIL, "Fork sync failed")
|
||||
},
|
||||
);
|
||||
}
|
||||
Some(status(
|
||||
RES_INVALID_REQ,
|
||||
"Repository is neither fork nor mirror",
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,707 @@
|
||||
//! `/git/*` request handlers (`server.py`).
|
||||
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
use super::layout::{Repositories, parse_repository_path};
|
||||
use super::perms::Perm;
|
||||
use super::stats::Stats;
|
||||
use super::{IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_REMOTE_FAIL};
|
||||
|
||||
pub(super) fn status(code: u8, message: &str) -> Vec<u8> {
|
||||
let mut reply = vec![code];
|
||||
reply.extend_from_slice(message.as_bytes());
|
||||
reply
|
||||
}
|
||||
|
||||
/// Python truthiness of an unpacked request value.
|
||||
pub(super) fn truthy(value: &Value) -> bool {
|
||||
match value {
|
||||
Value::Nil => false,
|
||||
Value::Boolean(b) => *b,
|
||||
Value::Integer(i) => i.as_i64() != Some(0) && i.as_u64() != Some(0),
|
||||
Value::F32(f) => *f != 0.0,
|
||||
Value::F64(f) => *f != 0.0,
|
||||
Value::String(s) => !s.as_bytes().is_empty(),
|
||||
Value::Binary(b) => !b.is_empty(),
|
||||
Value::Array(a) => !a.is_empty(),
|
||||
Value::Map(m) => !m.is_empty(),
|
||||
Value::Ext(_, d) => !d.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `data.get(key)` for an integer or string key.
|
||||
pub(super) fn get<'a>(map: &'a [(Value, Value)], key: &Value) -> Option<&'a Value> {
|
||||
map.iter().find(|(k, _)| k == key).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// A request map and its parsed repository path.
|
||||
type Parsed<'a> = (&'a [(Value, Value)], Option<(&'a str, &'a str)>);
|
||||
|
||||
/// Common checks of every handler (`server.py`); `Err` is the reply.
|
||||
/// `Ok(None)` is upstream raising before its try (key 0 not a string), which
|
||||
/// sends no response.
|
||||
fn request_path<'a>(
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &'a Value,
|
||||
) -> Result<Option<Parsed<'a>>, Vec<u8>> {
|
||||
if identity.is_none() {
|
||||
return Err(status(RES_DISALLOWED, "Not identified"));
|
||||
}
|
||||
let Value::Map(map) = data else {
|
||||
return Err(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
let Some(path) = get(map, &Value::from(IDX_REPOSITORY)) else {
|
||||
return Err(status(RES_INVALID_REQ, "No repository specified"));
|
||||
};
|
||||
let Some(path) = path.as_str() else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some((map, parse_repository_path(path))))
|
||||
}
|
||||
|
||||
/// `handle_list` (`server.py`). `None` sends no response.
|
||||
pub fn handle_list(
|
||||
repos: &Repositories,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
let (map, path) = match request_path(identity, data) {
|
||||
Err(reply) => return Some(reply),
|
||||
Ok(None) => return None,
|
||||
Ok(Some(parsed)) => parsed,
|
||||
};
|
||||
let hash = identity.expect("checked");
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let for_push = get(map, &Value::from("for_push")).is_some_and(truthy);
|
||||
let read = path.is_some() && repos.resolve_permission(hash, group, repo, Perm::Read);
|
||||
let write = path.is_some() && repos.resolve_permission(hash, group, repo, Perm::Write);
|
||||
let access = if for_push { write } else { read };
|
||||
if !access {
|
||||
let message = if read { "Not allowed" } else { "Not found" };
|
||||
return Some(status(RES_NOT_FOUND, message));
|
||||
}
|
||||
let repository = repos.repository(group, repo).expect("resolved");
|
||||
let mut head_ref = "master".to_string();
|
||||
let head = std::fs::read(repository.path.join("HEAD")).unwrap_or_default();
|
||||
if let Some(rest) = head.strip_prefix(b"ref: ") {
|
||||
// bytes.strip() then decode("utf-8", errors="ignore")
|
||||
let ws = |b: &u8| b" \t\n\r\x0b\x0c".contains(b);
|
||||
let start = rest.iter().position(|b| !ws(b)).unwrap_or(rest.len());
|
||||
let end = rest.iter().rposition(|b| !ws(b)).map_or(start, |i| i + 1);
|
||||
head_ref = rest[start..end]
|
||||
.utf8_chunks()
|
||||
.map(|chunk| chunk.valid())
|
||||
.collect();
|
||||
}
|
||||
let output = Command::new("git")
|
||||
.args(["for-each-ref", "--format", "%(objectname) %(refname)"])
|
||||
.current_dir(&repository.path)
|
||||
.stdin(Stdio::null())
|
||||
.output();
|
||||
let output = match output {
|
||||
Ok(output) if output.status.success() => output,
|
||||
Ok(output) => {
|
||||
tracing::error!(
|
||||
"Error while listing refs for {group}/{repo}: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Some(status(RES_REMOTE_FAIL, "Could not list refs"));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Error while handling list request for {group}/{repo}: {e}");
|
||||
return Some(status(RES_REMOTE_FAIL, "Remote error"));
|
||||
}
|
||||
};
|
||||
let Ok(stdout) = String::from_utf8(output.stdout) else {
|
||||
return Some(status(RES_REMOTE_FAIL, "Remote error"));
|
||||
};
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut lines = Vec::new();
|
||||
for line in stdout.trim().split('\n') {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some((_, name)) = line.split_once(' ')
|
||||
&& seen.insert(name.to_string())
|
||||
{
|
||||
lines.push(line);
|
||||
}
|
||||
}
|
||||
let text = if lines.is_empty() {
|
||||
format!("@{head_ref} HEAD\n")
|
||||
} else {
|
||||
format!("{}\n@{head_ref} HEAD\n", lines.join("\n"))
|
||||
};
|
||||
let mut reply = vec![super::RES_OK];
|
||||
reply.extend_from_slice(text.as_bytes());
|
||||
Some(reply)
|
||||
}
|
||||
|
||||
/// A handler's answer: status bytes, or a bundle file with its metadata. The
|
||||
/// temporary directory holding the file must outlive the transfer.
|
||||
#[derive(Debug)]
|
||||
pub enum Reply {
|
||||
Bytes(Vec<u8>),
|
||||
File {
|
||||
file: std::fs::File,
|
||||
metadata: Vec<u8>,
|
||||
tmpdir: tempfile::TempDir,
|
||||
},
|
||||
}
|
||||
|
||||
/// Upstream raised inside its `try`, replying "Remote error".
|
||||
struct Raised;
|
||||
|
||||
/// `RNS.prettyhexrep` of the identity, or `None`, as `str(remote_identity)`.
|
||||
pub fn identity_text(identity: Option<&[u8; 16]>) -> String {
|
||||
identity.map_or("None".to_string(), |h| format!("<{}>", hex::encode(h)))
|
||||
}
|
||||
|
||||
/// `log_request` (`server.py`).
|
||||
pub fn log_request(repos: &Repositories, message: &str, identity: Option<&[u8; 16]>) {
|
||||
if identity.is_some_and(|h| repos.is_blocked(h)) {
|
||||
tracing::debug!("Blocked: {message}");
|
||||
} else {
|
||||
tracing::debug!("{message}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run_git(cwd: &std::path::Path, args: &[&str]) -> std::io::Result<std::process::Output> {
|
||||
Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
}
|
||||
|
||||
/// `san_ref` on an unpacked value; anything but a string raises.
|
||||
fn san_ref_value(value: &Value) -> Result<Option<String>, Raised> {
|
||||
let s = value.as_str().ok_or(Raised)?;
|
||||
Ok(crate::util::san_ref(s).map(str::to_string))
|
||||
}
|
||||
|
||||
/// `san_sha` on an unpacked value: `len()` raises for scalars, and
|
||||
/// `bytes.fromhex` rejects (into `None`) anything but a string.
|
||||
fn san_sha_value(value: &Value) -> Result<Option<String>, Raised> {
|
||||
match value {
|
||||
Value::String(s) => Ok(s
|
||||
.as_str()
|
||||
.and_then(crate::util::san_sha)
|
||||
.map(str::to_string)),
|
||||
Value::Binary(_) | Value::Array(_) | Value::Map(_) => Ok(None),
|
||||
_ => Err(Raised),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python iteration over an unpacked value in a `for` loop.
|
||||
fn py_iter(value: &Value) -> Result<Vec<Value>, Raised> {
|
||||
match value {
|
||||
Value::Array(items) => Ok(items.clone()),
|
||||
Value::Map(entries) => Ok(entries.iter().map(|(k, _)| k.clone()).collect()),
|
||||
Value::String(s) => Ok(s
|
||||
.as_str()
|
||||
.ok_or(Raised)?
|
||||
.chars()
|
||||
.map(|c| Value::from(c.to_string()))
|
||||
.collect()),
|
||||
Value::Binary(b) => Ok(b.iter().map(|&x| Value::from(x)).collect()),
|
||||
_ => Err(Raised),
|
||||
}
|
||||
}
|
||||
|
||||
/// Permission and repository lookup shared by fetch, push and delete.
|
||||
/// `Ok(Ok(path))` is the repository directory to work in.
|
||||
fn writable_repository(
|
||||
repos: &Repositories,
|
||||
hash: &[u8; 16],
|
||||
path: Option<(&str, &str)>,
|
||||
write: bool,
|
||||
) -> Result<std::path::PathBuf, Vec<u8>> {
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let read = path.is_some() && repos.resolve_permission(hash, group, repo, Perm::Read);
|
||||
if !write {
|
||||
if !read {
|
||||
return Err(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
} else if !(path.is_some() && repos.resolve_permission(hash, group, repo, Perm::Write)) {
|
||||
return Err(if read {
|
||||
status(RES_DISALLOWED, "Not allowed")
|
||||
} else {
|
||||
status(RES_NOT_FOUND, "Not found")
|
||||
});
|
||||
}
|
||||
Ok(repos
|
||||
.repository(group, repo)
|
||||
.expect("resolved")
|
||||
.path
|
||||
.clone())
|
||||
}
|
||||
|
||||
/// `handle_fetch` (`server.py`). `None` sends no response.
|
||||
pub fn handle_fetch(
|
||||
repos: &std::sync::RwLock<Repositories>,
|
||||
stats: &Stats,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Reply> {
|
||||
let (map, path, repository_path) = {
|
||||
let repos = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
log_request(
|
||||
&repos,
|
||||
&format!("Fetch request from remote {}", identity_text(identity)),
|
||||
identity,
|
||||
);
|
||||
let (map, path) = match request_path(identity, data) {
|
||||
Err(reply) => return Some(Reply::Bytes(reply)),
|
||||
Ok(None) => return None,
|
||||
Ok(Some(parsed)) => parsed,
|
||||
};
|
||||
match writable_repository(&repos, identity.expect("checked"), path, false) {
|
||||
Err(reply) => return Some(Reply::Bytes(reply)),
|
||||
Ok(p) => (map, path, p),
|
||||
}
|
||||
};
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let empty = Value::Array(Vec::new());
|
||||
let refs = get(map, &Value::from("refs")).unwrap_or(&empty);
|
||||
if !truthy(refs) {
|
||||
return Some(Reply::Bytes(status(RES_INVALID_REQ, "No refs specified")));
|
||||
}
|
||||
match fetch_bundle(map, refs, &repository_path, group, repo, stats, identity) {
|
||||
Ok(reply) => Some(reply),
|
||||
Err(Raised) => {
|
||||
tracing::error!("Error while handling fetch request for {group}/{repo}");
|
||||
Some(Reply::Bytes(status(RES_REMOTE_FAIL, "Remote error")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch_bundle(
|
||||
map: &[(Value, Value)],
|
||||
refs: &Value,
|
||||
repository_path: &std::path::Path,
|
||||
group: &str,
|
||||
repo: &str,
|
||||
stats: &Stats,
|
||||
identity: Option<&[u8; 16]>,
|
||||
) -> Result<Reply, Raised> {
|
||||
let Value::Array(refs) = refs else {
|
||||
return Err(Raised);
|
||||
};
|
||||
let mut ref_names = Vec::new();
|
||||
for r in refs {
|
||||
let Value::Map(r) = r else {
|
||||
return Err(Raised);
|
||||
};
|
||||
ref_names.push(get(r, &Value::from("ref")).ok_or(Raised)?.clone());
|
||||
}
|
||||
for name in &ref_names {
|
||||
if san_ref_value(name)?.is_none() {
|
||||
return Ok(Reply::Bytes(status(RES_INVALID_REQ, "Invalid request")));
|
||||
}
|
||||
}
|
||||
let names: Vec<&str> = ref_names.iter().filter_map(Value::as_str).collect();
|
||||
tracing::debug!("Fetching refs {names:?} for {group}/{repo}");
|
||||
let tmpdir = tempfile::TempDir::new().map_err(|_| Raised)?;
|
||||
let bundle_path = tmpdir.path().join("fetch.bundle");
|
||||
let mut execv: Vec<String> = ["bundle", "create", "--no-progress"]
|
||||
.map(String::from)
|
||||
.into();
|
||||
execv.push(bundle_path.to_string_lossy().into_owned());
|
||||
let have_known = |sha: &str| {
|
||||
run_git(repository_path, &["cat-file", "-t", sha]).is_ok_and(|o| o.status.success())
|
||||
};
|
||||
for (r, name) in refs.iter().zip(&names) {
|
||||
let Value::Map(r) = r else { unreachable!() };
|
||||
execv.push(name.to_string());
|
||||
if let Some(have) = get(r, &Value::from("have")).filter(|h| truthy(h)) {
|
||||
let Some(sha) = san_sha_value(have)? else {
|
||||
return Ok(Reply::Bytes(status(RES_INVALID_REQ, "Invalid SHA")));
|
||||
};
|
||||
if have_known(&sha) {
|
||||
execv.push(format!("^{sha}"));
|
||||
} else {
|
||||
tracing::warn!("Client have-sha {sha} not found in repository, skipping");
|
||||
}
|
||||
}
|
||||
}
|
||||
let empty = Value::Array(Vec::new());
|
||||
for sha in py_iter(get(map, &Value::from("have")).unwrap_or(&empty))? {
|
||||
let Some(sha) = san_sha_value(&sha)? else {
|
||||
return Ok(Reply::Bytes(status(RES_INVALID_REQ, "Invalid SHA")));
|
||||
};
|
||||
if have_known(&sha) {
|
||||
execv.push(format!("^{sha}"));
|
||||
} else {
|
||||
tracing::warn!("Client have-sha {sha} not found in repository, skipping");
|
||||
}
|
||||
}
|
||||
let args: Vec<&str> = execv.iter().map(String::as_str).collect();
|
||||
let result = run_git(repository_path, &args).map_err(|_| Raised)?;
|
||||
if !result.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&result.stderr);
|
||||
if stderr.to_lowercase().contains("empty bundle") {
|
||||
tracing::debug!("Empty bundle for {names:?}, all objects already on client");
|
||||
return Ok(Reply::Bytes(vec![super::RES_OK]));
|
||||
}
|
||||
tracing::error!("Error while fetching refs {names:?} for {group}/{repo}: {stderr}");
|
||||
return Ok(Reply::Bytes(status(
|
||||
RES_REMOTE_FAIL,
|
||||
"Could not fetch refs",
|
||||
)));
|
||||
}
|
||||
stats.fetch_succeeded(group, repo, identity);
|
||||
let file = std::fs::File::open(&bundle_path).map_err(|_| Raised)?;
|
||||
// {IDX_RESULT_CODE: RES_OK}
|
||||
let metadata = vec![0x81, super::IDX_RESULT_CODE, super::RES_OK];
|
||||
Ok(Reply::File {
|
||||
file,
|
||||
metadata,
|
||||
tmpdir,
|
||||
})
|
||||
}
|
||||
|
||||
/// `handle_push` (`server.py`). `None` sends no response.
|
||||
pub fn handle_push(
|
||||
repos: &std::sync::RwLock<Repositories>,
|
||||
stats: &Stats,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
let (map, path, repository_path) = {
|
||||
let repos = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
log_request(
|
||||
&repos,
|
||||
&format!("Push request from remote {}", identity_text(identity)),
|
||||
identity,
|
||||
);
|
||||
let (map, path) = match request_path(identity, data) {
|
||||
Err(reply) => return Some(reply),
|
||||
Ok(None) => return None,
|
||||
Ok(Some(parsed)) => parsed,
|
||||
};
|
||||
match writable_repository(&repos, identity.expect("checked"), path, true) {
|
||||
Err(reply) => return Some(reply),
|
||||
Ok(p) => (map, path, p),
|
||||
}
|
||||
};
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let field = |key: &str| get(map, &Value::from(key));
|
||||
let empty = Value::from("");
|
||||
// san_ref runs before the try: a non-string ref raises with no response.
|
||||
let local_ref = san_ref_value(field("local_ref").unwrap_or(&empty)).ok()?;
|
||||
let remote_ref = san_ref_value(field("remote_ref").unwrap_or(&empty)).ok()?;
|
||||
let force = field("force").is_some_and(truthy);
|
||||
let bundle = field("bundle").filter(|b| truthy(b));
|
||||
let operations = field("operations").filter(|o| truthy(o));
|
||||
if let Some(bundle) = bundle {
|
||||
let (Some(local_ref), Some(remote_ref)) = (local_ref, remote_ref) else {
|
||||
return Some(status(RES_INVALID_REQ, "Missing ref specification"));
|
||||
};
|
||||
tracing::debug!("Push {local_ref}:{remote_ref} to {group}/{repo}");
|
||||
return Some(
|
||||
push_bundle(
|
||||
bundle,
|
||||
&local_ref,
|
||||
&remote_ref,
|
||||
force,
|
||||
&repository_path,
|
||||
group,
|
||||
repo,
|
||||
stats,
|
||||
)
|
||||
.unwrap_or_else(|Raised| {
|
||||
tracing::error!("Error while handling push request for {group}/{repo}");
|
||||
status(RES_REMOTE_FAIL, "Remote error")
|
||||
}),
|
||||
);
|
||||
}
|
||||
let Some(operations) = operations else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request data"));
|
||||
};
|
||||
let Value::Array(operations) = operations else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid data for operations"));
|
||||
};
|
||||
Some(
|
||||
push_operations(operations, &repository_path, group, repo, stats).unwrap_or_else(
|
||||
|Raised| {
|
||||
tracing::error!("Error while handling push operations for {group}/{repo}");
|
||||
status(RES_REMOTE_FAIL, "Remote error")
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn push_bundle(
|
||||
bundle: &Value,
|
||||
local_ref: &str,
|
||||
remote_ref: &str,
|
||||
force: bool,
|
||||
repository_path: &std::path::Path,
|
||||
group: &str,
|
||||
repo: &str,
|
||||
stats: &Stats,
|
||||
) -> Result<Vec<u8>, Raised> {
|
||||
let tmpdir = tempfile::TempDir::new().map_err(|_| Raised)?;
|
||||
let bundle_path = tmpdir.path().join("push.bundle");
|
||||
let bytes = match bundle {
|
||||
Value::Binary(b) => b.as_slice(),
|
||||
Value::String(s) => s.as_bytes(),
|
||||
_ => return Err(Raised),
|
||||
};
|
||||
std::fs::write(&bundle_path, bytes).map_err(|_| Raised)?;
|
||||
let bundle_arg = bundle_path.to_string_lossy();
|
||||
let failed = |stderr: &[u8]| {
|
||||
tracing::error!(
|
||||
"Bundle verification failed for push {local_ref}:{remote_ref} to {group}/{repo}: {}",
|
||||
String::from_utf8_lossy(stderr)
|
||||
);
|
||||
status(RES_REMOTE_FAIL, "Could not verify bundle")
|
||||
};
|
||||
let result =
|
||||
run_git(repository_path, &["bundle", "verify", &bundle_arg]).map_err(|_| Raised)?;
|
||||
if !result.status.success() {
|
||||
return Ok(failed(&result.stderr));
|
||||
}
|
||||
let refspec = format!("{local_ref}:{remote_ref}");
|
||||
let mut args = vec!["fetch", &bundle_arg, &refspec];
|
||||
if force {
|
||||
args.push("--force");
|
||||
}
|
||||
let result = run_git(repository_path, &args).map_err(|_| Raised)?;
|
||||
if !result.status.success() {
|
||||
return Ok(failed(&result.stderr));
|
||||
}
|
||||
stats.push_succeeded(group, repo);
|
||||
Ok(vec![super::RES_OK])
|
||||
}
|
||||
|
||||
fn push_operations(
|
||||
operations: &[Value],
|
||||
repository_path: &std::path::Path,
|
||||
group: &str,
|
||||
repo: &str,
|
||||
stats: &Stats,
|
||||
) -> Result<Vec<u8>, Raised> {
|
||||
let empty = Value::from("");
|
||||
for op in operations {
|
||||
let Value::Map(op) = op else {
|
||||
return Err(Raised);
|
||||
};
|
||||
let action = get(op, &Value::from("action")).unwrap_or(&empty);
|
||||
let reference = san_ref_value(get(op, &Value::from("ref")).unwrap_or(&empty))?;
|
||||
let sha = san_sha_value(get(op, &Value::from("sha")).unwrap_or(&empty))?;
|
||||
let op_force = get(op, &Value::from("force")).is_some_and(truthy);
|
||||
if action.as_str() != Some("update_ref") {
|
||||
let action = rns_tools::rsg::pyfmt::py_str(action);
|
||||
return Ok(status(
|
||||
RES_INVALID_REQ,
|
||||
&format!("Unknown operation: {action}"),
|
||||
));
|
||||
}
|
||||
let Some(reference) = reference.filter(|r| r.starts_with("refs/")) else {
|
||||
return Ok(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
let Some(sha) = sha else {
|
||||
return Ok(status(RES_INVALID_REQ, "Invalid SHA"));
|
||||
};
|
||||
let exists = run_git(repository_path, &["cat-file", "-t", &sha]).map_err(|_| Raised)?;
|
||||
if !exists.status.success() {
|
||||
return Ok(status(
|
||||
RES_REMOTE_FAIL,
|
||||
&format!("Object {sha} does not exist in repository"),
|
||||
));
|
||||
}
|
||||
let current = run_git(repository_path, &["rev-parse", &reference]).map_err(|_| Raised)?;
|
||||
if current.status.success() {
|
||||
let existing = String::from_utf8(current.stdout).map_err(|_| Raised)?;
|
||||
if existing.trim() != sha && !op_force {
|
||||
return Ok(status(
|
||||
RES_DISALLOWED,
|
||||
&format!("Ref {reference} already exists at different SHA (force required)"),
|
||||
));
|
||||
}
|
||||
}
|
||||
tracing::debug!("Updating ref {reference} to {sha} in {group}/{repo}");
|
||||
let result =
|
||||
run_git(repository_path, &["update-ref", &reference, &sha]).map_err(|_| Raised)?;
|
||||
if !result.status.success() {
|
||||
tracing::error!(
|
||||
"Error while updating ref {reference} to {sha} for {group}/{repo}: {}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
return Ok(status(RES_REMOTE_FAIL, "Could not update refs"));
|
||||
}
|
||||
}
|
||||
stats.push_succeeded(group, repo);
|
||||
Ok(vec![super::RES_OK])
|
||||
}
|
||||
|
||||
/// `handle_delete` (`server.py`). `None` sends no response.
|
||||
pub fn handle_delete(
|
||||
repos: &std::sync::RwLock<Repositories>,
|
||||
stats: &Stats,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
let (map, path, repository_path) = {
|
||||
let repos = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
log_request(
|
||||
&repos,
|
||||
&format!("Delete request from remote {}", identity_text(identity)),
|
||||
identity,
|
||||
);
|
||||
let (map, path) = match request_path(identity, data) {
|
||||
Err(reply) => return Some(reply),
|
||||
Ok(None) => return None,
|
||||
Ok(Some(parsed)) => parsed,
|
||||
};
|
||||
match writable_repository(&repos, identity.expect("checked"), path, true) {
|
||||
Err(reply) => return Some(reply),
|
||||
Ok(p) => (map, path, p),
|
||||
}
|
||||
};
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let empty = Value::from("");
|
||||
let reference = san_ref_value(get(map, &Value::from("ref")).unwrap_or(&empty)).ok()?;
|
||||
let Some(reference) = reference.filter(|r| r.starts_with("refs/")) else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
tracing::debug!("Deleting ref {reference} in {group}/{repo}");
|
||||
match run_git(&repository_path, &["update-ref", "-d", &reference]) {
|
||||
Ok(result) if result.status.success() => {
|
||||
stats.push_succeeded(group, repo);
|
||||
Some(vec![super::RES_OK])
|
||||
}
|
||||
Ok(result) => {
|
||||
tracing::error!(
|
||||
"Error while deleting ref {reference} for {group}/{repo}: {}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
Some(status(RES_REMOTE_FAIL, "Could not delete ref"))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Error while handling delete request for {group}/{repo}: {e}");
|
||||
Some(status(RES_REMOTE_FAIL, "Remote error"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `REPO_CREATE_PERMS_TEMPLATE` (`server.py`).
|
||||
pub(super) const REPO_CREATE_PERMS_TEMPLATE: &str = "adm:{IDENTITY_HASH}";
|
||||
|
||||
/// `handle_create` (`server.py`). `None` sends no response.
|
||||
pub fn handle_create(
|
||||
repos: &std::sync::RwLock<Repositories>,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
let mut repos = repos.write().unwrap_or_else(|e| e.into_inner());
|
||||
log_request(
|
||||
&repos,
|
||||
&format!("Create request from remote {}", identity_text(identity)),
|
||||
identity,
|
||||
);
|
||||
let (_, path) = match request_path(identity, data) {
|
||||
Err(reply) => return Some(reply),
|
||||
Ok(None) => return None,
|
||||
Ok(Some(parsed)) => parsed,
|
||||
};
|
||||
let hash = identity.expect("checked");
|
||||
// Differs from `handle_create` (`server.py`), which admits a blocked identity.
|
||||
if repos.is_blocked(hash) {
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
let Some((group, repo)) = path.filter(|(g, r)| !g.is_empty() && !r.is_empty()) else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
let Some(group_path) = repos.groups.get(group).map(|g| g.path.clone()) else {
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
};
|
||||
let read = repos.resolve_group_permission(hash, group, Perm::Read);
|
||||
let create = repos.resolve_group_permission(hash, group, Perm::Create);
|
||||
if !std::path::Path::new(&group_path).exists() {
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
if !create {
|
||||
return Some(if read {
|
||||
status(RES_DISALLOWED, "Not allowed")
|
||||
} else {
|
||||
status(RES_NOT_FOUND, "Not found")
|
||||
});
|
||||
}
|
||||
let repository_path = std::path::Path::new(&group_path).join(repo);
|
||||
if repos.repository(group, repo).is_some() || repository_path.exists() {
|
||||
return Some(if repos.resolve_permission(hash, group, repo, Perm::Read) {
|
||||
status(RES_DISALLOWED, "Repository already exists")
|
||||
} else {
|
||||
status(RES_NOT_FOUND, "Not found")
|
||||
});
|
||||
}
|
||||
tracing::debug!(
|
||||
"Creating repository {group}/{repo} for {}",
|
||||
identity_text(identity)
|
||||
);
|
||||
let cleanup = |path: &std::path::Path| {
|
||||
if std::fs::remove_dir_all(path).is_err() {
|
||||
tracing::error!(
|
||||
"Could not clean up failed repository init at {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
};
|
||||
if let Err(e) = crate::platform::create_dir_all_755(&repository_path) {
|
||||
tracing::error!(
|
||||
"Error while creating repository {group}/{repo} for {}: {e}",
|
||||
identity_text(identity)
|
||||
);
|
||||
return Some(status(RES_REMOTE_FAIL, "Remote error"));
|
||||
}
|
||||
match run_git(&repository_path, &["init", "--bare"]) {
|
||||
Ok(result) if result.status.success() => {}
|
||||
result => {
|
||||
if let Ok(result) = result {
|
||||
tracing::error!(
|
||||
"Failed to initialize bare repository at {}: {}",
|
||||
repository_path.display(),
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
}
|
||||
cleanup(&repository_path);
|
||||
return Some(status(RES_REMOTE_FAIL, "Could not initialize repository"));
|
||||
}
|
||||
}
|
||||
let allowed = format!("{}.allowed", repository_path.display());
|
||||
let tmp_allowed = format!("{allowed}.tmp");
|
||||
let permissions = REPO_CREATE_PERMS_TEMPLATE.replace("{IDENTITY_HASH}", &hex::encode(hash));
|
||||
if std::fs::write(&tmp_allowed, permissions)
|
||||
.and_then(|()| std::fs::rename(&tmp_allowed, &allowed))
|
||||
.is_err()
|
||||
{
|
||||
tracing::error!("Could not set default repository permissions for {group}/{repo}");
|
||||
cleanup(&repository_path);
|
||||
return Some(status(RES_REMOTE_FAIL, "Could not initialize repository"));
|
||||
}
|
||||
match repos.load_repository(group, &repository_path) {
|
||||
Ok(true) => {
|
||||
tracing::debug!("Repository {group}/{repo} created and loaded successfully");
|
||||
Some(vec![super::RES_OK])
|
||||
}
|
||||
Ok(false) => {
|
||||
tracing::error!(
|
||||
"Repository {} created, but runtime loading failed",
|
||||
repository_path.display()
|
||||
);
|
||||
cleanup(&repository_path);
|
||||
Some(status(RES_REMOTE_FAIL, "Failed to register repository"))
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Error while creating repository {group}/{repo}: {e:?}");
|
||||
cleanup(&repository_path);
|
||||
Some(status(RES_REMOTE_FAIL, "Remote error"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
//! Repository groups and repositories on disk (`load_repository_group`,
|
||||
//! `update_group_permissions`, `load_repository`, `server.py`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use super::config::{FetchLimits, NodeConfig, expand_user};
|
||||
use super::perms::{AllowedError, Perm, Permissions, load_allowed_permissions};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Repository {
|
||||
/// The directory name, including any `.git` suffix.
|
||||
pub name: String,
|
||||
pub group: String,
|
||||
pub path: PathBuf,
|
||||
/// Upstream source URL of a fork or mirror.
|
||||
pub fork: Option<String>,
|
||||
pub mirror: Option<String>,
|
||||
pub permissions: Permissions,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Group {
|
||||
pub name: String,
|
||||
/// The expanded configured path, kept as written (a trailing `/` stays).
|
||||
pub path: String,
|
||||
pub repositories: BTreeMap<String, Repository>,
|
||||
/// Whether the group's `.allowed` file is executable.
|
||||
pub dynamic_perms: bool,
|
||||
pub permissions: Permissions,
|
||||
}
|
||||
|
||||
/// Groups and their repositories, as the node holds them.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Repositories {
|
||||
pub groups: BTreeMap<String, Group>,
|
||||
pub aliases: BTreeMap<String, String>,
|
||||
pub blocked: Vec<Vec<u8>>,
|
||||
pub fetch_limits: FetchLimits,
|
||||
}
|
||||
|
||||
/// A `git` call in `cwd` with output captured; `None` when it cannot run
|
||||
/// or exits non-zero, as `check=True` raising into a bare `except`.
|
||||
fn git_stdout(cwd: &Path, args: &[&str]) -> Option<String> {
|
||||
let output = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
|
||||
}
|
||||
|
||||
/// `_ensure_git` (`server.py`).
|
||||
pub fn git_available() -> bool {
|
||||
Command::new("git")
|
||||
.arg("--version")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status()
|
||||
.is_ok_and(|s| s.success())
|
||||
}
|
||||
|
||||
/// `__is_fork` / `__is_mirror` (`server.py`).
|
||||
fn upstream_source(path: &Path, kind: &str) -> Option<String> {
|
||||
if git_stdout(path, &["config", "repository.rngit.type"])? != kind {
|
||||
return None;
|
||||
}
|
||||
git_stdout(path, &["config", "repository.rngit.upstream.source"])
|
||||
}
|
||||
|
||||
impl Repositories {
|
||||
/// Load every `[repositories]` group whose path is a directory.
|
||||
pub fn load(config: &NodeConfig) -> Result<Self, AllowedError> {
|
||||
let mut repos = Repositories {
|
||||
groups: BTreeMap::new(),
|
||||
aliases: config.aliases.clone(),
|
||||
blocked: config.blocked_identities.clone(),
|
||||
fetch_limits: config.fetch_limits,
|
||||
};
|
||||
for (name, raw_path) in &config.repositories {
|
||||
let path = expand_user(raw_path);
|
||||
if !path.is_dir() {
|
||||
tracing::warn!(
|
||||
"The path \"{}\" specified for repository group \"{name}\" does not exist, skipping.",
|
||||
path.display()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
repos.load_group(name, &path.to_string_lossy(), config)?;
|
||||
}
|
||||
Ok(repos)
|
||||
}
|
||||
|
||||
/// `load_repository_group` (`server.py`).
|
||||
pub fn load_group(
|
||||
&mut self,
|
||||
name: &str,
|
||||
path: &str,
|
||||
config: &NodeConfig,
|
||||
) -> Result<(), AllowedError> {
|
||||
let group = self
|
||||
.groups
|
||||
.entry(name.to_string())
|
||||
.or_insert_with(|| Group {
|
||||
name: name.to_string(),
|
||||
path: path.to_string(),
|
||||
repositories: BTreeMap::new(),
|
||||
dynamic_perms: false,
|
||||
permissions: Permissions::default(),
|
||||
});
|
||||
if group.path != path {
|
||||
tracing::error!(
|
||||
"Repository group path did not match existing entry while loading {name}, aborting load"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
self.update_group_permissions(name, config);
|
||||
let entries = std::fs::read_dir(path).map_err(AllowedError::Io)?;
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(AllowedError::Io)?;
|
||||
let entry_path = format!("{path}/{}", entry.file_name().to_string_lossy());
|
||||
self.load_repository(name, Path::new(&entry_path))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `update_group_permissions` (`server.py`): the group's
|
||||
/// `.allowed` file first, then its `[access]` statements appended.
|
||||
pub fn update_group_permissions(&mut self, name: &str, config: &NodeConfig) {
|
||||
let aliases = self.aliases.clone();
|
||||
let Some(group) = self.groups.get_mut(name) else {
|
||||
tracing::warn!(
|
||||
"Attempt to set group permissions for non-existing group {name}, aborting"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let mut permissions = Permissions::default();
|
||||
let allowed = PathBuf::from(format!("{}.allowed", group.path));
|
||||
if allowed.is_file() {
|
||||
match load_allowed_permissions(&allowed, &aliases) {
|
||||
Ok((loaded, dynamic)) => {
|
||||
permissions = loaded;
|
||||
group.dynamic_perms = dynamic;
|
||||
}
|
||||
Err(e) => tracing::error!(
|
||||
"Could not load group permissions from {}: {e:?}",
|
||||
allowed.display()
|
||||
),
|
||||
}
|
||||
} else {
|
||||
group.dynamic_perms = false;
|
||||
}
|
||||
for statement in config.access.get(name).into_iter().flatten() {
|
||||
permissions.add_statement(statement, &aliases);
|
||||
}
|
||||
group.permissions = permissions;
|
||||
}
|
||||
|
||||
/// `load_repository` (`server.py`). A repository `.allowed`
|
||||
/// file that cannot be read is an error, as upstream lets it raise.
|
||||
pub fn load_repository(&mut self, group_name: &str, path: &Path) -> Result<bool, AllowedError> {
|
||||
let Some(group) = self.groups.get_mut(group_name) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let path_str = path.to_string_lossy();
|
||||
if !path.is_dir() || path_str.ends_with(".work") || path_str.ends_with(".releases") {
|
||||
return Ok(false);
|
||||
}
|
||||
if git_stdout(path, &["rev-parse", "--git-dir"]).as_deref() != Some(".") {
|
||||
tracing::warn!("The directory \"{path_str}\" is not a git repository, skipping");
|
||||
return Ok(false);
|
||||
}
|
||||
if git_stdout(path, &["config", "--bool", "core.bare"]).as_deref() != Some("true") {
|
||||
tracing::warn!("The directory \"{path_str}\" is not a bare git repository, skipping");
|
||||
tracing::warn!(
|
||||
"You can change it to a bare repository using \"git config --bool core.bare true\"."
|
||||
);
|
||||
return Ok(false);
|
||||
}
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let allowed = PathBuf::from(format!("{path_str}.allowed"));
|
||||
let (permissions, _) = load_allowed_permissions(&allowed, &self.aliases)?;
|
||||
let repository = Repository {
|
||||
name: name.clone(),
|
||||
group: group_name.to_string(),
|
||||
path: path.to_path_buf(),
|
||||
fork: upstream_source(path, "fork"),
|
||||
mirror: upstream_source(path, "mirror"),
|
||||
permissions,
|
||||
};
|
||||
group.repositories.insert(name, repository);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Whether `blocked_identities` names this identity.
|
||||
pub fn is_blocked(&self, hash: &[u8; 16]) -> bool {
|
||||
self.blocked.iter().any(|b| b.as_slice() == hash)
|
||||
}
|
||||
|
||||
/// `resolve_permission` (`server.py`).
|
||||
pub fn resolve_permission(
|
||||
&self,
|
||||
hash: &[u8; 16],
|
||||
group: &str,
|
||||
repository: &str,
|
||||
perm: Perm,
|
||||
) -> bool {
|
||||
if self.is_blocked(hash) {
|
||||
return false;
|
||||
}
|
||||
let Some(g) = self.groups.get(group) else {
|
||||
return false;
|
||||
};
|
||||
let Some(r) = g.repositories.get(repository) else {
|
||||
return false;
|
||||
};
|
||||
super::perms::resolve_repository(&g.permissions, &r.permissions, hash, perm)
|
||||
}
|
||||
|
||||
/// `resolve_group_permission` (`server.py`), which upstream runs without the block list.
|
||||
pub fn resolve_group_permission(&self, hash: &[u8; 16], group: &str, perm: Perm) -> bool {
|
||||
!self.is_blocked(hash)
|
||||
&& self
|
||||
.groups
|
||||
.get(group)
|
||||
.is_some_and(|g| super::perms::resolve_group(&g.permissions, hash, perm))
|
||||
}
|
||||
|
||||
pub fn repository(&self, group: &str, repository: &str) -> Option<&Repository> {
|
||||
self.groups.get(group)?.repositories.get(repository)
|
||||
}
|
||||
}
|
||||
|
||||
/// `parse_request_repository_path` (`server.py`).
|
||||
pub fn parse_repository_path(path: &str) -> Option<(&str, &str)> {
|
||||
let mut parts = path.split('/');
|
||||
let (Some(group), Some(repo), None) = (parts.next(), parts.next(), parts.next()) else {
|
||||
return None;
|
||||
};
|
||||
(super::py_len(group) <= 256 && super::py_len(repo) <= 256).then_some((group, repo))
|
||||
}
|
||||
|
||||
/// `parse_request_group_path` (`server.py`).
|
||||
pub fn parse_group_path(path: &str) -> Option<&str> {
|
||||
(!path.contains('/') && super::py_len(path) <= 256).then_some(path)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! The rngit repository node (`RNS/Utilities/rngit/server.py`).
|
||||
|
||||
pub mod client;
|
||||
pub mod config;
|
||||
pub mod forks;
|
||||
pub mod handlers;
|
||||
pub mod layout;
|
||||
pub mod perms;
|
||||
pub mod perms_mgmt;
|
||||
pub mod releases;
|
||||
pub mod stats;
|
||||
pub mod work;
|
||||
|
||||
/// `APP_NAME` plus the aspect (`__init__.py`, `server.py`).
|
||||
pub const APP_NAME: &str = "git.repositories";
|
||||
|
||||
pub const PATH_LIST: &str = "/git/list";
|
||||
pub const PATH_FETCH: &str = "/git/fetch";
|
||||
pub const PATH_PUSH: &str = "/git/push";
|
||||
pub const PATH_DELETE: &str = "/git/delete";
|
||||
pub const PATH_CREATE: &str = "/git/create";
|
||||
pub const PATH_FORK: &str = "/git/fork";
|
||||
pub const PATH_SYNC: &str = "/git/sync";
|
||||
pub const PATH_MIRROR: &str = "/git/mirror";
|
||||
pub const PATH_RELEASE: &str = "/mgmt/release";
|
||||
pub const PATH_PERMS: &str = "/mgmt/perms";
|
||||
pub const PATH_WORK: &str = "/mgmt/work";
|
||||
|
||||
pub const RES_OK: u8 = 0x00;
|
||||
pub const RES_DISALLOWED: u8 = 0x01;
|
||||
pub const RES_INVALID_REQ: u8 = 0x02;
|
||||
pub const RES_NOT_FOUND: u8 = 0x03;
|
||||
pub const RES_REMOTE_FAIL: u8 = 0xFF;
|
||||
|
||||
pub const IDX_REPOSITORY: u8 = 0x00;
|
||||
pub const IDX_RESULT_CODE: u8 = 0x01;
|
||||
pub const IDX_GROUP: u8 = 0x02;
|
||||
|
||||
/// Python `len(s)`: the number of code points.
|
||||
pub(crate) fn py_len(s: &str) -> usize {
|
||||
s.chars().count()
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! Permission statements, `.allowed` files and the permission decision
|
||||
//! (`server.py`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use super::py_len;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum Perm {
|
||||
Read,
|
||||
Write,
|
||||
ReadWrite,
|
||||
Create,
|
||||
Stats,
|
||||
Release,
|
||||
Interact,
|
||||
Propose,
|
||||
Admin,
|
||||
}
|
||||
|
||||
impl Perm {
|
||||
/// The wire value (`PERM_*`, `server.py`).
|
||||
pub fn code(self) -> u8 {
|
||||
match self {
|
||||
Perm::Read => 0x01,
|
||||
Perm::Write => 0x02,
|
||||
Perm::ReadWrite => 0x03,
|
||||
Perm::Create => 0x04,
|
||||
Perm::Stats => 0x05,
|
||||
Perm::Release => 0x06,
|
||||
Perm::Interact => 0x07,
|
||||
Perm::Propose => 0x08,
|
||||
Perm::Admin => 0xFE,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_word(word: &str) -> Option<Perm> {
|
||||
Some(match word {
|
||||
"r" | "read" => Perm::Read,
|
||||
"w" | "write" => Perm::Write,
|
||||
"rw" | "readwrite" => Perm::ReadWrite,
|
||||
"c" | "create" => Perm::Create,
|
||||
"s" | "stats" => Perm::Stats,
|
||||
"rel" | "release" => Perm::Release,
|
||||
"i" | "interact" => Perm::Interact,
|
||||
"p" | "propose" => Perm::Propose,
|
||||
"adm" | "admin" => Perm::Admin,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The permission list this perm reads; `None` for read-write, which
|
||||
/// the resolvers reject.
|
||||
fn list(self) -> Option<PermList> {
|
||||
Some(match self {
|
||||
Perm::Read => PermList::Read,
|
||||
Perm::Write => PermList::Write,
|
||||
Perm::Create => PermList::Create,
|
||||
Perm::Stats => PermList::Stats,
|
||||
Perm::Release => PermList::Release,
|
||||
Perm::Interact => PermList::Interact,
|
||||
Perm::Propose => PermList::Propose,
|
||||
Perm::Admin => PermList::Admin,
|
||||
Perm::ReadWrite => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One of the eight stored lists (`ALL_PERMS`, `server.py`).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum PermList {
|
||||
Read,
|
||||
Write,
|
||||
Create,
|
||||
Stats,
|
||||
Release,
|
||||
Interact,
|
||||
Propose,
|
||||
Admin,
|
||||
}
|
||||
|
||||
impl PermList {
|
||||
pub const ALL: [PermList; 8] = [
|
||||
PermList::Read,
|
||||
PermList::Write,
|
||||
PermList::Create,
|
||||
PermList::Stats,
|
||||
PermList::Release,
|
||||
PermList::Interact,
|
||||
PermList::Propose,
|
||||
PermList::Admin,
|
||||
];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
PermList::Read => "read",
|
||||
PermList::Write => "write",
|
||||
PermList::Create => "create",
|
||||
PermList::Stats => "stats",
|
||||
PermList::Release => "release",
|
||||
PermList::Interact => "interact",
|
||||
PermList::Propose => "propose",
|
||||
PermList::Admin => "admin",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum Target {
|
||||
None,
|
||||
All,
|
||||
/// Identity hash bytes; `bytes.fromhex` can yield fewer than 16, which
|
||||
/// upstream stores and never matches.
|
||||
Identity(Vec<u8>),
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// The wire value (`TGT_NONE`/`TGT_ALL`, `server.py`).
|
||||
pub fn code(&self) -> Option<u8> {
|
||||
match self {
|
||||
Target::None => Some(0x01),
|
||||
Target::All => Some(0x02),
|
||||
Target::Identity(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const TGT_NONE_SMPHR: [&str; 3] = ["n", "none", "nobody"];
|
||||
pub const TGT_ALL_SMPHR: [&str; 3] = ["a", "all", "everyone"];
|
||||
pub const ALL_TGTS: [&str; 6] = ["n", "none", "nobody", "a", "all", "everyone"];
|
||||
|
||||
/// `__resolve_identity_alias` (`server.py`).
|
||||
pub fn resolve_identity_alias(alias: &str, aliases: &BTreeMap<String, String>) -> String {
|
||||
if ALL_TGTS.contains(&alias.to_lowercase().as_str()) {
|
||||
return alias.to_string();
|
||||
}
|
||||
let is_hash = py_len(alias) == 32
|
||||
&& rns_tools::rsg::pyfmt::py_fromhex(alias).is_ok_and(|h| !h.is_empty());
|
||||
if is_hash {
|
||||
return alias.to_string();
|
||||
}
|
||||
aliases
|
||||
.get(alias)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| alias.to_string())
|
||||
}
|
||||
|
||||
/// `parse_permission` (`server.py`): either half is `None` when
|
||||
/// it does not parse.
|
||||
pub fn parse_permission(
|
||||
statement: &str,
|
||||
aliases: &BTreeMap<String, String>,
|
||||
) -> (Option<Perm>, Option<Target>) {
|
||||
let comps: Vec<&str> = statement.split(':').collect();
|
||||
if comps.len() != 2 {
|
||||
return (None, None);
|
||||
}
|
||||
let perm = Perm::from_word(&comps[0].to_lowercase());
|
||||
let target = resolve_identity_alias(comps[1], aliases);
|
||||
let target = if TGT_NONE_SMPHR.contains(&target.as_str()) {
|
||||
Some(Target::None)
|
||||
} else if TGT_ALL_SMPHR.contains(&target.as_str()) {
|
||||
Some(Target::All)
|
||||
} else if py_len(&target) == 32 {
|
||||
match rns_tools::rsg::pyfmt::py_fromhex(&target) {
|
||||
Ok(hash) => Some(Target::Identity(hash)),
|
||||
Err(e) => {
|
||||
tracing::error!("Invalid identity hash \"{target}\" in access permissions: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(perm, target)
|
||||
}
|
||||
|
||||
/// The eight permission lists of a group or repository.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Permissions {
|
||||
lists: BTreeMap<PermList, Vec<Target>>,
|
||||
}
|
||||
|
||||
impl Permissions {
|
||||
pub fn get(&self, list: PermList) -> &[Target] {
|
||||
self.lists.get(&list).map(Vec::as_slice).unwrap_or(&[])
|
||||
}
|
||||
|
||||
fn add(&mut self, list: PermList, target: &Target) {
|
||||
let entries = self.lists.entry(list).or_default();
|
||||
if !entries.contains(target) {
|
||||
entries.push(target.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Add one parsed statement; `rw` adds to both read and write.
|
||||
pub fn add_statement(&mut self, statement: &str, aliases: &BTreeMap<String, String>) {
|
||||
let (Some(perm), Some(target)) = parse_permission(statement, aliases) else {
|
||||
return;
|
||||
};
|
||||
match perm.list() {
|
||||
Some(list) => self.add(list, &target),
|
||||
None => {
|
||||
self.add(PermList::Read, &target);
|
||||
self.add(PermList::Write, &target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `permissions_from_allowed_input` (`server.py`).
|
||||
pub fn from_allowed_input(input: &str, aliases: &BTreeMap<String, String>) -> Self {
|
||||
let mut perms = Permissions::default();
|
||||
for line in py_splitlines(input) {
|
||||
let statement = line.trim();
|
||||
if !statement.starts_with('#') {
|
||||
perms.add_statement(statement, aliases);
|
||||
}
|
||||
}
|
||||
perms
|
||||
}
|
||||
}
|
||||
|
||||
/// Python `str.splitlines`.
|
||||
pub(crate) fn py_splitlines(text: &str) -> Vec<&str> {
|
||||
let mut lines = Vec::new();
|
||||
let mut start = 0;
|
||||
let mut iter = text.char_indices().peekable();
|
||||
while let Some((i, c)) = iter.next() {
|
||||
let end = match c {
|
||||
'\r' => {
|
||||
if let Some((_, '\n')) = iter.peek() {
|
||||
iter.next();
|
||||
i + 2
|
||||
} else {
|
||||
i + 1
|
||||
}
|
||||
}
|
||||
'\n' | '\x0b' | '\x0c' | '\x1c' | '\x1d' | '\x1e' | '\u{85}' | '\u{2028}'
|
||||
| '\u{2029}' => i + c.len_utf8(),
|
||||
_ => continue,
|
||||
};
|
||||
lines.push(&text[start..i]);
|
||||
start = end;
|
||||
}
|
||||
if start < text.len() {
|
||||
lines.push(&text[start..]);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Error from reading an `.allowed` file; upstream raises here.
|
||||
#[derive(Debug)]
|
||||
pub enum AllowedError {
|
||||
Io(std::io::Error),
|
||||
NotUtf8,
|
||||
}
|
||||
|
||||
/// `load_allowed_permissions` (`server.py`): an executable file is
|
||||
/// run with no arguments and its stdout parsed (the exit status is
|
||||
/// ignored); the flag says whether it was run.
|
||||
pub fn load_allowed_permissions(
|
||||
path: &Path,
|
||||
aliases: &BTreeMap<String, String>,
|
||||
) -> Result<(Permissions, bool), AllowedError> {
|
||||
if !path.is_file() {
|
||||
return Ok((Permissions::default(), false));
|
||||
}
|
||||
let executable = crate::platform::executable(path);
|
||||
let (raw, dynamic) = if executable {
|
||||
let output = std::process::Command::new(path)
|
||||
.stdin(std::process::Stdio::inherit())
|
||||
.stderr(std::process::Stdio::inherit())
|
||||
.output()
|
||||
.map_err(AllowedError::Io)?;
|
||||
(output.stdout, true)
|
||||
} else {
|
||||
(std::fs::read(path).map_err(AllowedError::Io)?, false)
|
||||
};
|
||||
let input = String::from_utf8(raw).map_err(|_| AllowedError::NotUtf8)?;
|
||||
Ok((Permissions::from_allowed_input(&input, aliases), dynamic))
|
||||
}
|
||||
|
||||
fn decide(list: &[Target], admins: &[Target], hash: &[u8; 16]) -> Option<bool> {
|
||||
let me = Target::Identity(hash.to_vec());
|
||||
if list.contains(&Target::None) {
|
||||
Some(false)
|
||||
} else if list.contains(&Target::All) || list.contains(&me) || admins.contains(&me) {
|
||||
Some(true)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// `resolve_permission`'s decision once group and repository are known
|
||||
/// (`server.py`); the blocklist is checked by the caller.
|
||||
pub fn resolve_repository(
|
||||
group: &Permissions,
|
||||
repository: &Permissions,
|
||||
hash: &[u8; 16],
|
||||
perm: Perm,
|
||||
) -> bool {
|
||||
let Some(list) = perm.list() else {
|
||||
return false;
|
||||
};
|
||||
let repo_list = repository.get(list);
|
||||
if let Some(decision) = decide(repo_list, repository.get(PermList::Admin), hash) {
|
||||
return decision;
|
||||
}
|
||||
if !repo_list.is_empty() {
|
||||
return false;
|
||||
}
|
||||
decide(group.get(list), group.get(PermList::Admin), hash).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// `resolve_group_permission`'s decision (`server.py`); upstream
|
||||
/// does not check the blocklist here.
|
||||
pub fn resolve_group(group: &Permissions, hash: &[u8; 16], perm: Perm) -> bool {
|
||||
let Some(list) = perm.list() else {
|
||||
return false;
|
||||
};
|
||||
decide(group.get(list), group.get(PermList::Admin), hash).unwrap_or(false)
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! `/mgmt/perms`: group and repository permission files
|
||||
//! (`handle_perms` and helpers, `server.py`).
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::RwLock;
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
use super::config::NodeConfig;
|
||||
use super::handlers::{get, identity_text, log_request, status, truthy};
|
||||
use super::layout::{Repositories, parse_group_path, parse_repository_path};
|
||||
use super::perms::{Perm, load_allowed_permissions, parse_permission, py_splitlines};
|
||||
use super::{
|
||||
IDX_GROUP, IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_OK,
|
||||
RES_REMOTE_FAIL,
|
||||
};
|
||||
|
||||
/// Upstream raised inside its `try`, replying "Remote error".
|
||||
struct Raised;
|
||||
|
||||
fn py_strip(s: &str) -> &str {
|
||||
s.trim_matches(|c: char| c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c))
|
||||
}
|
||||
|
||||
/// The validation every permission setter runs (`server.py`,
|
||||
/// `4504-4517`): the first statement that does not parse, by 1-based line.
|
||||
pub(crate) fn invalid_line(content: &str, aliases: &BTreeMap<String, String>) -> Option<String> {
|
||||
for (number, line) in py_splitlines(content).into_iter().enumerate() {
|
||||
let stripped = py_strip(line);
|
||||
if stripped.is_empty() || stripped.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if let (None, _) | (_, None) = parse_permission(stripped, aliases) {
|
||||
return Some(format!(
|
||||
"Invalid permission \"{stripped}\" on line {}",
|
||||
number + 1
|
||||
));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn get_str<'a>(data: &'a [(Value, Value)], key: &str) -> Option<&'a Value> {
|
||||
get(data, &Value::from(key))
|
||||
}
|
||||
|
||||
/// `data.get("content", "")`, which must be a `str` for `splitlines`.
|
||||
fn content_of(data: &[(Value, Value)]) -> Result<String, Raised> {
|
||||
match get_str(data, "content") {
|
||||
None => Ok(String::new()),
|
||||
Some(Value::String(s)) => s.as_str().map(str::to_string).ok_or(Raised),
|
||||
Some(_) => Err(Raised),
|
||||
}
|
||||
}
|
||||
|
||||
/// `step == "get"` / `"set"`; `Err` is the reply.
|
||||
fn step(data: &[(Value, Value)]) -> Result<bool, Vec<u8>> {
|
||||
match get_str(data, "step")
|
||||
.filter(|s| truthy(s))
|
||||
.map(Value::as_str)
|
||||
{
|
||||
None => Err(status(RES_INVALID_REQ, "Invalid request")),
|
||||
Some(Some("get")) => Ok(false),
|
||||
Some(Some("set")) => Ok(true),
|
||||
Some(_) => Err(status(RES_INVALID_REQ, "Invalid step")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `get` step: the file's text, or "" when there is none.
|
||||
fn read_allowed(path: &Path, what: &str) -> Vec<u8> {
|
||||
let text = if path.is_file() {
|
||||
match super::work::read_text(path) {
|
||||
Ok(text) => text,
|
||||
Err(e) => {
|
||||
tracing::error!("Error getting {what} permissions: {e}");
|
||||
return status(RES_REMOTE_FAIL, "Error getting permissions");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let mut reply = vec![RES_OK];
|
||||
rmpv::encode::write_value(
|
||||
&mut reply,
|
||||
&Value::Map(vec![(Value::from("content"), Value::from(text))]),
|
||||
)
|
||||
.expect("msgpack write to memory");
|
||||
reply
|
||||
}
|
||||
|
||||
/// The file part of the `set` step: refuse an executable resolver, then
|
||||
/// write through `<path>.tmp` and a rename. `Ok(None)` was written.
|
||||
fn write_allowed(path: &Path, content: &str) -> Option<Vec<u8>> {
|
||||
if crate::platform::executable(path) {
|
||||
return Some(status(
|
||||
RES_DISALLOWED,
|
||||
"Executable permission resolvers can only be modified node-side",
|
||||
));
|
||||
}
|
||||
let mut tmp = path.as_os_str().to_os_string();
|
||||
tmp.push(".tmp");
|
||||
let tmp = PathBuf::from(tmp);
|
||||
let written = std::fs::File::create(&tmp)
|
||||
.and_then(|mut f| f.write_all(content.as_bytes()))
|
||||
.and_then(|_| std::fs::rename(&tmp, path));
|
||||
match written {
|
||||
Ok(()) => None,
|
||||
Err(e) => {
|
||||
tracing::error!("Error setting permissions: {e}");
|
||||
Some(status(RES_REMOTE_FAIL, "Error setting permissions"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_group_permissions` and its steps (`server.py`).
|
||||
fn group_permissions(
|
||||
repos: &RwLock<Repositories>,
|
||||
config: &NodeConfig,
|
||||
hash: &[u8; 16],
|
||||
group: Option<&str>,
|
||||
data: &[(Value, Value)],
|
||||
) -> Result<Vec<u8>, Raised> {
|
||||
let guard = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let resolve = |perm| group.is_some_and(|g| guard.resolve_group_permission(hash, g, perm));
|
||||
if !resolve(Perm::Read) {
|
||||
return Ok(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
if !resolve(Perm::Admin) {
|
||||
return Ok(status(RES_DISALLOWED, "Not allowed"));
|
||||
}
|
||||
let set = match step(data) {
|
||||
Ok(set) => set,
|
||||
Err(reply) => return Ok(reply),
|
||||
};
|
||||
let group = group.expect("resolved");
|
||||
let allowed = PathBuf::from(format!("{}.allowed", guard.groups[group].path));
|
||||
if !set {
|
||||
return Ok(read_allowed(&allowed, "group"));
|
||||
}
|
||||
let content = content_of(data)?;
|
||||
if let Some(message) = invalid_line(&content, &guard.aliases) {
|
||||
return Ok(status(RES_INVALID_REQ, &message));
|
||||
}
|
||||
if let Some(reply) = write_allowed(&allowed, &content) {
|
||||
return Ok(reply);
|
||||
}
|
||||
drop(guard);
|
||||
repos
|
||||
.write()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.update_group_permissions(group, config);
|
||||
tracing::info!(
|
||||
"Permissions for group {group} updated by <{}>",
|
||||
hex::encode(hash)
|
||||
);
|
||||
Ok(vec![RES_OK])
|
||||
}
|
||||
|
||||
/// `update_repository_permissions` (`server.py`): the repository
|
||||
/// file alone replaces the repository's lists.
|
||||
fn update_repository_permissions(repos: &mut Repositories, group: &str, repository: &str) {
|
||||
let aliases = repos.aliases.clone();
|
||||
let Some(repo) = repos
|
||||
.groups
|
||||
.get_mut(group)
|
||||
.and_then(|g| g.repositories.get_mut(repository))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let allowed = PathBuf::from(format!("{}.allowed", repo.path.display()));
|
||||
match load_allowed_permissions(&allowed, &aliases) {
|
||||
Ok((permissions, _)) => repo.permissions = permissions,
|
||||
Err(e) => tracing::error!(
|
||||
"Could not update repository permissions for {group}/{repository} from {}: {e:?}",
|
||||
allowed.display()
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// `_repository_permissions` and its steps (`server.py`). Setting
|
||||
/// takes group READ and ADMIN on top of repository ADMIN.
|
||||
fn repository_permissions(
|
||||
repos: &RwLock<Repositories>,
|
||||
hash: &[u8; 16],
|
||||
group: &str,
|
||||
repository: &str,
|
||||
data: &[(Value, Value)],
|
||||
) -> Result<Vec<u8>, Raised> {
|
||||
let guard = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
if !guard.resolve_permission(hash, group, repository, Perm::Read) {
|
||||
return Ok(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
let set = match step(data) {
|
||||
Ok(set) => set,
|
||||
Err(reply) => return Ok(reply),
|
||||
};
|
||||
let allowed = PathBuf::from(format!(
|
||||
"{}.allowed",
|
||||
guard.groups[group].repositories[repository].path.display()
|
||||
));
|
||||
if !set {
|
||||
return Ok(read_allowed(&allowed, "repository"));
|
||||
}
|
||||
if !guard.resolve_group_permission(hash, group, Perm::Read) {
|
||||
return Ok(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
if !guard.resolve_group_permission(hash, group, Perm::Admin) {
|
||||
return Ok(status(RES_DISALLOWED, "Not allowed"));
|
||||
}
|
||||
let content = content_of(data)?;
|
||||
if let Some(message) = invalid_line(&content, &guard.aliases) {
|
||||
return Ok(status(RES_INVALID_REQ, &message));
|
||||
}
|
||||
if let Some(reply) = write_allowed(&allowed, &content) {
|
||||
return Ok(reply);
|
||||
}
|
||||
drop(guard);
|
||||
update_repository_permissions(
|
||||
&mut repos.write().unwrap_or_else(|e| e.into_inner()),
|
||||
group,
|
||||
repository,
|
||||
);
|
||||
tracing::info!(
|
||||
"Permissions for repository {group}/{repository} updated by <{}>",
|
||||
hex::encode(hash)
|
||||
);
|
||||
Ok(vec![RES_OK])
|
||||
}
|
||||
|
||||
/// `handle_perms` (`server.py`).
|
||||
pub fn handle_perms(
|
||||
repos: &RwLock<Repositories>,
|
||||
config: &NodeConfig,
|
||||
identity: Option<&[u8; 16]>,
|
||||
data: &Value,
|
||||
) -> Vec<u8> {
|
||||
{
|
||||
let guard = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let message = format!(
|
||||
"Permissions request from remote {}",
|
||||
identity_text(identity)
|
||||
);
|
||||
log_request(&guard, &message, identity);
|
||||
}
|
||||
let Some(hash) = identity else {
|
||||
return status(RES_DISALLOWED, "Not identified");
|
||||
};
|
||||
let Value::Map(data) = data else {
|
||||
return status(RES_INVALID_REQ, "Invalid request");
|
||||
};
|
||||
let reply = (|| -> Result<Vec<u8>, Raised> {
|
||||
let Some(operation) = get_str(data, "operation").filter(|o| truthy(o)) else {
|
||||
return Ok(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
match operation.as_str() {
|
||||
Some("gperms") => {
|
||||
let Some(group) = get(data, &Value::from(IDX_GROUP)) else {
|
||||
return Ok(status(RES_INVALID_REQ, "No group specified"));
|
||||
};
|
||||
let group = parse_group_path(group.as_str().ok_or(Raised)?);
|
||||
group_permissions(repos, config, hash, group, data)
|
||||
}
|
||||
Some("rperms") => {
|
||||
let Some(path) = get(data, &Value::from(IDX_REPOSITORY)) else {
|
||||
return Ok(status(RES_INVALID_REQ, "No repository specified"));
|
||||
};
|
||||
let path = parse_repository_path(path.as_str().ok_or(Raised)?);
|
||||
let (group, repository) = path.unwrap_or(("", ""));
|
||||
let (read, admin) = {
|
||||
let guard = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let resolve = |perm| {
|
||||
path.is_some() && guard.resolve_permission(hash, group, repository, perm)
|
||||
};
|
||||
(resolve(Perm::Read), resolve(Perm::Admin))
|
||||
};
|
||||
if !admin {
|
||||
return Ok(if read {
|
||||
status(RES_DISALLOWED, "Not allowed")
|
||||
} else {
|
||||
status(RES_NOT_FOUND, "Not found")
|
||||
});
|
||||
}
|
||||
repository_permissions(repos, hash, group, repository, data)
|
||||
}
|
||||
_ => Ok(status(RES_INVALID_REQ, "Invalid request")),
|
||||
}
|
||||
})();
|
||||
reply.unwrap_or_else(|Raised| {
|
||||
tracing::error!(
|
||||
"Error while handling permissions request from {}",
|
||||
identity_text(identity)
|
||||
);
|
||||
status(RES_REMOTE_FAIL, "Remote error")
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,544 @@
|
||||
//! Node statistics: the stats file, the recording gates and the repository
|
||||
//! summary (`server.py`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rmpv::Value;
|
||||
|
||||
/// `stats_job_interval` (`server.py`), seconds between writes of the file.
|
||||
pub const STATS_JOB_INTERVAL: u64 = 180;
|
||||
|
||||
/// A node of the stats tree; maps refer to children by index.
|
||||
#[derive(Debug, Clone)]
|
||||
enum Node {
|
||||
Map(Vec<(Value, usize)>),
|
||||
Leaf(Value),
|
||||
}
|
||||
|
||||
/// The stats tree in an arena.
|
||||
#[derive(Debug)]
|
||||
struct Tree {
|
||||
nodes: Vec<Node>,
|
||||
root: usize,
|
||||
}
|
||||
|
||||
const REPO_METRICS: [&str; 5] = ["view", "fetch", "push", "download", "release_download"];
|
||||
|
||||
impl Tree {
|
||||
fn new() -> Self {
|
||||
let mut tree = Tree {
|
||||
nodes: Vec::new(),
|
||||
root: 0,
|
||||
};
|
||||
let front = tree.empty_map();
|
||||
let pages = tree.map_of(vec![("front", front)]);
|
||||
let groups = tree.empty_map();
|
||||
tree.root = tree.map_of(vec![("pages", pages), ("groups", groups)]);
|
||||
tree
|
||||
}
|
||||
|
||||
/// A group's own counters. Differs from `STATS_INIT_GROUP` (`server.py`),
|
||||
/// one object that upstream shares between every group it first records.
|
||||
fn new_group(&mut self) -> usize {
|
||||
let view = self.empty_map();
|
||||
let repositories = self.empty_map();
|
||||
self.map_of(vec![("view", view), ("repositories", repositories)])
|
||||
}
|
||||
|
||||
/// A repository's own counters. Differs from `STATS_INIT_REPO` (`server.py`),
|
||||
/// one object that upstream shares between every repository it first records.
|
||||
fn new_repo(&mut self) -> usize {
|
||||
let metrics: Vec<(&str, usize)> = REPO_METRICS
|
||||
.iter()
|
||||
.map(|name| (*name, self.empty_map()))
|
||||
.collect();
|
||||
self.map_of(metrics)
|
||||
}
|
||||
|
||||
fn push(&mut self, node: Node) -> usize {
|
||||
self.nodes.push(node);
|
||||
self.nodes.len() - 1
|
||||
}
|
||||
|
||||
fn empty_map(&mut self) -> usize {
|
||||
self.push(Node::Map(Vec::new()))
|
||||
}
|
||||
|
||||
fn map_of(&mut self, entries: Vec<(&str, usize)>) -> usize {
|
||||
let entries = entries
|
||||
.into_iter()
|
||||
.map(|(k, v)| (Value::from(k), v))
|
||||
.collect();
|
||||
self.push(Node::Map(entries))
|
||||
}
|
||||
|
||||
/// The file's content replaces the root.
|
||||
fn load(&mut self, value: &Value) {
|
||||
self.root = self.insert(value);
|
||||
}
|
||||
|
||||
fn insert(&mut self, value: &Value) -> usize {
|
||||
match value {
|
||||
Value::Map(entries) => {
|
||||
let children = entries
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), self.insert(v)))
|
||||
.collect();
|
||||
self.push(Node::Map(children))
|
||||
}
|
||||
other => self.push(Node::Leaf(other.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_value(&self, id: usize) -> Value {
|
||||
match &self.nodes[id] {
|
||||
Node::Map(entries) => Value::Map(
|
||||
entries
|
||||
.iter()
|
||||
.map(|(k, child)| (k.clone(), self.to_value(*child)))
|
||||
.collect(),
|
||||
),
|
||||
Node::Leaf(value) => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `node[key]`; `None` when the key is missing or `node` is not a map.
|
||||
fn get(&self, id: usize, key: &str) -> Option<usize> {
|
||||
let Node::Map(entries) = &self.nodes[id] else {
|
||||
return None;
|
||||
};
|
||||
entries
|
||||
.iter()
|
||||
.find(|(k, _)| k.as_str() == Some(key))
|
||||
.map(|(_, child)| *child)
|
||||
}
|
||||
|
||||
/// `node[key]`, raising `KeyError` when missing.
|
||||
fn index(&self, id: usize, key: &str) -> Result<usize, String> {
|
||||
self.get(id, key).ok_or_else(|| format!("'{key}'"))
|
||||
}
|
||||
|
||||
/// `if not key in node: node[key] = child()`.
|
||||
fn setdefault(
|
||||
&mut self,
|
||||
id: usize,
|
||||
key: &str,
|
||||
child: impl FnOnce(&mut Self) -> usize,
|
||||
) -> Result<usize, String> {
|
||||
if let Some(existing) = self.get(id, key) {
|
||||
return Ok(existing);
|
||||
}
|
||||
if !matches!(self.nodes[id], Node::Map(_)) {
|
||||
return Err("argument of this type is not iterable".into());
|
||||
}
|
||||
let new = child(self);
|
||||
let Node::Map(entries) = &mut self.nodes[id] else {
|
||||
unreachable!()
|
||||
};
|
||||
entries.push((Value::from(key), new));
|
||||
Ok(new)
|
||||
}
|
||||
|
||||
/// `if not day in stats: stats[day] = 0` then `stats[day] += 1`.
|
||||
fn increment(&mut self, counters: usize, day: &str) -> Result<(), String> {
|
||||
let leaf = self.setdefault(counters, day, |t| t.push(Node::Leaf(Value::from(0))))?;
|
||||
match &mut self.nodes[leaf] {
|
||||
Node::Leaf(Value::Integer(count)) => {
|
||||
let next = count
|
||||
.as_i64()
|
||||
.and_then(|c| c.checked_add(1))
|
||||
.ok_or("integer out of range")?;
|
||||
*count = next.into();
|
||||
Ok(())
|
||||
}
|
||||
Node::Leaf(Value::F64(count)) => {
|
||||
*count += 1.0;
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("unsupported operand type(s) for +=: 'int'".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// A day's count as `stats.get(day, 0)`; non-numbers count as 0 here.
|
||||
fn count(&self, counters: Option<usize>, day: &str) -> i64 {
|
||||
let Some(leaf) = counters.and_then(|c| self.get(c, day)) else {
|
||||
return 0;
|
||||
};
|
||||
match &self.nodes[leaf] {
|
||||
Node::Leaf(Value::Integer(i)) => i.as_i64().unwrap_or_default(),
|
||||
Node::Leaf(Value::Boolean(b)) => i64::from(*b),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The days of a counters map whose count is above 0.
|
||||
fn active_days(&self, counters: Option<usize>) -> Vec<String> {
|
||||
let Some(Node::Map(entries)) = counters.map(|c| &self.nodes[c]) else {
|
||||
return Vec::new();
|
||||
};
|
||||
entries
|
||||
.iter()
|
||||
.filter_map(|(k, _)| {
|
||||
let day = k.as_str()?;
|
||||
(self.count(counters, day) > 0).then(|| day.to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn record(&mut self, gate: Gate, group: &str, repo: &str, day: &str) -> Result<(), String> {
|
||||
let pages = |t: &Self| t.index(t.root, "pages").and_then(|p| t.index(p, "front"));
|
||||
let group_node = |t: &mut Self| {
|
||||
let groups = t.index(t.root, "groups")?;
|
||||
t.setdefault(groups, group, Self::new_group)
|
||||
};
|
||||
let counters = match gate {
|
||||
Gate::PageView => pages(self)?,
|
||||
Gate::GroupView => {
|
||||
let g = group_node(self)?;
|
||||
self.setdefault(g, "view", Self::empty_map)?
|
||||
}
|
||||
Gate::Repo(metric) => {
|
||||
let g = group_node(self)?;
|
||||
let repos = self.index(g, "repositories")?;
|
||||
let r = self.setdefault(repos, repo, Self::new_repo)?;
|
||||
self.setdefault(r, metric, Self::empty_map)?
|
||||
}
|
||||
};
|
||||
self.increment(counters, day)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Gate {
|
||||
PageView,
|
||||
GroupView,
|
||||
Repo(&'static str),
|
||||
}
|
||||
|
||||
impl Gate {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Gate::PageView => "page view",
|
||||
Gate::GroupView => "group view",
|
||||
Gate::Repo("view") => "repository view",
|
||||
Gate::Repo("release_download") => "release download",
|
||||
Gate::Repo(metric) => metric,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The stats file, its ignore lists and the recording gates
|
||||
/// (`server.py`).
|
||||
#[derive(Debug)]
|
||||
pub struct Stats {
|
||||
tree: Mutex<Tree>,
|
||||
path: PathBuf,
|
||||
enabled: bool,
|
||||
ignored: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Stats {
|
||||
/// `__load_stats` (`server.py`). A missing file is written with
|
||||
/// the initial value; a file that cannot be read leaves the initial value.
|
||||
/// `ignored` is `stats_ignore_identities`; upstream parses
|
||||
/// `stats_push_ignore_identities` too but never reads it.
|
||||
pub fn load(path: PathBuf, enabled: bool, ignored: Vec<Vec<u8>>) -> Self {
|
||||
let mut tree = Tree::new();
|
||||
if !path.is_file() {
|
||||
let bytes = encode(&tree.to_value(tree.root));
|
||||
if let Err(e) = std::fs::write(&path, bytes) {
|
||||
tracing::error!("Could not persist stats to {}: {e}", path.display());
|
||||
}
|
||||
} else {
|
||||
let read = std::fs::read(&path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|b| {
|
||||
rmpv::decode::read_value(&mut b.as_slice()).map_err(|e| e.to_string())
|
||||
});
|
||||
match read {
|
||||
Ok(value) => tree.load(&value),
|
||||
Err(e) => tracing::error!("Could not read stats file {}: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
Stats {
|
||||
tree: Mutex::new(tree),
|
||||
path,
|
||||
enabled,
|
||||
ignored,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// `__persist_stats` (`server.py`): `stats.tmp`, renamed over the file.
|
||||
pub fn persist(&self) {
|
||||
let tree = self.tree.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let bytes = encode(&tree.to_value(tree.root));
|
||||
let tmp = PathBuf::from(format!("{}.tmp", self.path.display()));
|
||||
if let Err(e) = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, &self.path))
|
||||
{
|
||||
tracing::error!("Could not write stats file to {}: {e}", self.path.display());
|
||||
}
|
||||
}
|
||||
|
||||
fn ignores(&self, identity: Option<&[u8; 16]>) -> bool {
|
||||
identity.is_some_and(|h| self.ignored.iter().any(|i| i.as_slice() == h))
|
||||
}
|
||||
|
||||
fn record(&self, gate: Gate, group: &str, repo: &str) {
|
||||
let day = local_day(now_secs());
|
||||
let mut tree = self.tree.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Err(e) = tree.record(gate, group, repo, &day) {
|
||||
tracing::error!("Error while recording {} stats: {e}", gate.label());
|
||||
}
|
||||
}
|
||||
|
||||
/// `view_succeeded` (`server.py`): the front page, a group, or a repository.
|
||||
pub fn view_succeeded(
|
||||
&self,
|
||||
group: Option<&str>,
|
||||
repo: Option<&str>,
|
||||
identity: Option<&[u8; 16]>,
|
||||
) {
|
||||
if self.ignores(identity) || !self.enabled {
|
||||
return;
|
||||
}
|
||||
match (group, repo) {
|
||||
(None, None) => self.record(Gate::PageView, "", ""),
|
||||
(Some(g), None) => self.record(Gate::GroupView, g, ""),
|
||||
(g, Some(r)) => self.record(Gate::Repo("view"), g.unwrap_or_default(), r),
|
||||
}
|
||||
}
|
||||
|
||||
/// `fetch_succeeded` (`server.py`).
|
||||
pub fn fetch_succeeded(&self, group: &str, repo: &str, identity: Option<&[u8; 16]>) {
|
||||
self.repo_event(Gate::Repo("fetch"), group, repo, identity, true);
|
||||
}
|
||||
|
||||
/// `push_succeeded` (`server.py`): no ignore list is consulted.
|
||||
pub fn push_succeeded(&self, group: &str, repo: &str) {
|
||||
self.repo_event(Gate::Repo("push"), group, repo, None, false);
|
||||
}
|
||||
|
||||
/// `download_succeeded` (`server.py`).
|
||||
pub fn download_succeeded(&self, group: &str, repo: &str, identity: Option<&[u8; 16]>) {
|
||||
self.repo_event(Gate::Repo("download"), group, repo, identity, true);
|
||||
}
|
||||
|
||||
/// `release_download_succeeded` (`server.py`).
|
||||
pub fn release_download_succeeded(&self, group: &str, repo: &str, identity: Option<&[u8; 16]>) {
|
||||
self.repo_event(Gate::Repo("release_download"), group, repo, identity, true);
|
||||
}
|
||||
|
||||
fn repo_event(
|
||||
&self,
|
||||
gate: Gate,
|
||||
group: &str,
|
||||
repo: &str,
|
||||
identity: Option<&[u8; 16]>,
|
||||
check_ignored: bool,
|
||||
) {
|
||||
if check_ignored && self.ignores(identity) {
|
||||
return;
|
||||
}
|
||||
if self.enabled && !group.is_empty() && !repo.is_empty() {
|
||||
self.record(gate, group, repo);
|
||||
}
|
||||
}
|
||||
|
||||
/// `repository_stats` (`server.py`): `None` without the stats permission.
|
||||
pub fn repository_stats(
|
||||
&self,
|
||||
repos: &super::layout::Repositories,
|
||||
identity: &[u8; 16],
|
||||
group: &str,
|
||||
repo: &str,
|
||||
lookback_days: u32,
|
||||
) -> Option<RepositoryStats> {
|
||||
if !repos.resolve_permission(identity, group, repo, super::perms::Perm::Stats) {
|
||||
return None;
|
||||
}
|
||||
let tree = self.tree.lock().unwrap_or_else(|e| e.into_inner());
|
||||
Some(summarise(&tree, group, repo, lookback_days, now_secs()))
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(value: &Value) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
rmpv::encode::write_value(&mut out, value).expect("writing to a Vec");
|
||||
out
|
||||
}
|
||||
|
||||
/// One metric of the summary.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Series {
|
||||
pub daily: Vec<i64>,
|
||||
pub total: i64,
|
||||
pub peak: i64,
|
||||
pub peak_day: Option<String>,
|
||||
}
|
||||
|
||||
impl Series {
|
||||
fn over(days: &[String], count: impl Fn(&str) -> i64) -> Self {
|
||||
let mut series = Series {
|
||||
daily: Vec::new(),
|
||||
total: 0,
|
||||
peak: 0,
|
||||
peak_day: None,
|
||||
};
|
||||
for day in days {
|
||||
let n = count(day);
|
||||
series.daily.push(n);
|
||||
series.total += n;
|
||||
if n > series.peak {
|
||||
series.peak = n;
|
||||
series.peak_day = Some(day.clone());
|
||||
}
|
||||
}
|
||||
series
|
||||
}
|
||||
}
|
||||
|
||||
/// The dict `repository_stats` returns.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct RepositoryStats {
|
||||
pub group: String,
|
||||
pub repository: String,
|
||||
pub lookback_days: u32,
|
||||
pub date_range: String,
|
||||
pub days: Vec<String>,
|
||||
pub day_labels: Vec<String>,
|
||||
pub timeline_labels: [String; 2],
|
||||
pub views: Series,
|
||||
pub fetches: Series,
|
||||
pub pushes: Series,
|
||||
pub downloads: Series,
|
||||
pub release_downloads: Series,
|
||||
pub downloads_combined: Series,
|
||||
pub activity_score: i64,
|
||||
pub actual_days: i64,
|
||||
pub activity_level: &'static str,
|
||||
}
|
||||
|
||||
fn summarise(tree: &Tree, group: &str, repo: &str, lookback: u32, now: i64) -> RepositoryStats {
|
||||
const DAY: i64 = 86_400;
|
||||
let stamps: Vec<i64> = (0..i64::from(lookback))
|
||||
.rev()
|
||||
.map(|i| now - i * DAY)
|
||||
.collect();
|
||||
let days: Vec<String> = stamps.iter().map(|&t| local_day(t)).collect();
|
||||
let day_labels: Vec<String> = stamps.iter().map(|&t| local_day_label(t)).collect();
|
||||
let repo_node = tree
|
||||
.get(tree.root, "groups")
|
||||
.and_then(|g| tree.get(g, group))
|
||||
.and_then(|g| tree.get(g, "repositories"))
|
||||
.and_then(|r| tree.get(r, repo));
|
||||
let metric = |name: &str| repo_node.and_then(|r| tree.get(r, name));
|
||||
let (view, fetch, push) = (metric("view"), metric("fetch"), metric("push"));
|
||||
let (download, release) = (metric("download"), metric("release_download"));
|
||||
let series = |node| Series::over(&days, |d| tree.count(node, d));
|
||||
let views = series(view);
|
||||
let fetches = series(fetch);
|
||||
let pushes = series(push);
|
||||
let downloads = series(download);
|
||||
let release_downloads = series(release);
|
||||
let downloads_combined =
|
||||
Series::over(&days, |d| tree.count(download, d) + tree.count(release, d));
|
||||
let view_total = views.total + downloads.total + release_downloads.total;
|
||||
let score = view_total as f64 * 0.2 + fetches.total as f64 * 2.0 + (pushes.total * 5) as f64;
|
||||
let mut actual_days = i64::from(lookback);
|
||||
let earliest = [view, fetch, push]
|
||||
.into_iter()
|
||||
.flat_map(|node| tree.active_days(node))
|
||||
.min();
|
||||
if let Some(earliest_ts) = earliest.as_deref().and_then(local_midnight) {
|
||||
actual_days = ((now - earliest_ts).div_euclid(DAY) + 1).max(1);
|
||||
}
|
||||
actual_days = actual_days.min(i64::from(lookback));
|
||||
let daily = if actual_days > 0 {
|
||||
score / actual_days as f64
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let activity_level = if daily == 0.0 {
|
||||
"inactive"
|
||||
} else if daily < 3.0 {
|
||||
"low"
|
||||
} else if daily < 10.0 {
|
||||
"moderate"
|
||||
} else {
|
||||
"high"
|
||||
};
|
||||
RepositoryStats {
|
||||
group: group.to_string(),
|
||||
repository: repo.to_string(),
|
||||
lookback_days: lookback,
|
||||
date_range: format!(
|
||||
"{} - {}",
|
||||
day_labels.first().cloned().unwrap_or_default(),
|
||||
day_labels.last().cloned().unwrap_or_default()
|
||||
),
|
||||
days,
|
||||
day_labels,
|
||||
timeline_labels: [format!("{lookback} days ago"), "Today".to_string()],
|
||||
views,
|
||||
fetches,
|
||||
pushes,
|
||||
downloads,
|
||||
release_downloads,
|
||||
downloads_combined,
|
||||
activity_score: score as i64,
|
||||
actual_days,
|
||||
activity_level,
|
||||
}
|
||||
}
|
||||
|
||||
/// Seconds since the epoch, as `time.time()` truncated.
|
||||
fn now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as i64)
|
||||
}
|
||||
|
||||
/// Local calendar time, as Python's `time.localtime`: year, month, day.
|
||||
fn local_date(secs: i64) -> (i64, i64, i64) {
|
||||
match crate::platform::localtime(secs) {
|
||||
Some(t) => (i64::from(t.year), i64::from(t.month), i64::from(t.day)),
|
||||
None => (1970, 1, 1),
|
||||
}
|
||||
}
|
||||
|
||||
/// `_get_day` (`server.py`): `%Y-%m-%d` in local time.
|
||||
pub fn local_day(secs: i64) -> String {
|
||||
let (year, month, day) = local_date(secs);
|
||||
format!("{year:04}-{month:02}-{day:02}")
|
||||
}
|
||||
|
||||
/// `%b %d` in local time (C locale month names).
|
||||
fn local_day_label(secs: i64) -> String {
|
||||
const MONTHS: [&str; 12] = [
|
||||
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
|
||||
];
|
||||
let (_, month, day) = local_date(secs);
|
||||
format!("{} {day:02}", MONTHS[(month.clamp(1, 12) - 1) as usize])
|
||||
}
|
||||
|
||||
/// `time.mktime(time.strptime(day, "%Y-%m-%d"))`; `None` where strptime raises.
|
||||
fn local_midnight(day: &str) -> Option<i64> {
|
||||
let mut parts = day.split('-');
|
||||
let field = |p: Option<&str>, max: usize| {
|
||||
p.filter(|s| !s.is_empty() && s.len() <= max && s.bytes().all(|b| b.is_ascii_digit()))
|
||||
.and_then(|s| s.parse::<i32>().ok())
|
||||
};
|
||||
let year = field(parts.next(), 4)?;
|
||||
let month = field(parts.next(), 2).filter(|m| (1..=12).contains(m))?;
|
||||
let mday = field(parts.next(), 2).filter(|d| (1..=31).contains(d))?;
|
||||
if parts.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(crate::platform::local_midnight(year, month, mday))
|
||||
}
|
||||
@@ -0,0 +1,987 @@
|
||||
//! `/mgmt/work`: work documents on the server
|
||||
//! (`handle_work` and `resolve_doc_permission`, `server.py`,
|
||||
//! `3789-4441`).
|
||||
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Mutex, RwLock};
|
||||
|
||||
use rmpv::Value;
|
||||
use rns_identity::identity::Identity;
|
||||
|
||||
use super::handlers::{get, identity_text, log_request, status, truthy};
|
||||
use super::layout::{Repositories, parse_repository_path};
|
||||
use super::perms::{Perm, PermList, Permissions, Target, resolve_repository};
|
||||
use super::perms_mgmt::invalid_line;
|
||||
use super::{
|
||||
IDX_REPOSITORY, RES_DISALLOWED, RES_INVALID_REQ, RES_NOT_FOUND, RES_OK, RES_REMOTE_FAIL,
|
||||
};
|
||||
|
||||
/// `WORK_DOC_LIMIT` (`server.py`), counted in code points.
|
||||
pub const WORK_DOC_LIMIT: usize = 256 * 1024;
|
||||
|
||||
/// Upstream raised inside its `try`, replying "Remote error".
|
||||
struct Raised;
|
||||
|
||||
const SCOPES: [&str; 3] = ["active", "completed", "proposed"];
|
||||
|
||||
/// Deferred jobs run in parallel; ids are picked from the directory listing,
|
||||
/// so concurrent creates would otherwise share an id.
|
||||
static WORK_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Python `str.isspace()`.
|
||||
fn py_space(c: char) -> bool {
|
||||
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
|
||||
}
|
||||
|
||||
fn py_strip(s: &str) -> &str {
|
||||
s.trim_matches(py_space)
|
||||
}
|
||||
|
||||
/// A request map, read by string key as upstream's `data.get(...)`.
|
||||
struct Request<'a>(&'a [(Value, Value)]);
|
||||
|
||||
impl Request<'_> {
|
||||
fn get(&self, key: &str) -> Option<&Value> {
|
||||
get(self.0, &Value::from(key))
|
||||
}
|
||||
|
||||
/// `data.get(key, default)` where only a `str` can equal the names it is
|
||||
/// compared with; `None` is a value that matches no name.
|
||||
fn name(&self, key: &str, default: &str) -> Option<String> {
|
||||
match self.get(key) {
|
||||
None => Some(default.to_string()),
|
||||
Some(Value::String(s)) => s.as_str().map(str::to_string),
|
||||
Some(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `data.get(key, "")` followed by a `str` method: anything else raises.
|
||||
fn text(&self, key: &str) -> Result<String, Raised> {
|
||||
match self.get(key) {
|
||||
None => Ok(String::new()),
|
||||
Some(Value::String(s)) => s.as_str().map(str::to_string).ok_or(Raised),
|
||||
Some(_) => Err(Raised),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_scope(scope: &Option<String>) -> bool {
|
||||
scope
|
||||
.as_deref()
|
||||
.is_some_and(|s| SCOPES.contains(&s) || s == "all")
|
||||
}
|
||||
|
||||
/// Python `int()` on an unpacked value; `Err` where it raises.
|
||||
fn py_int(value: &Value) -> Result<i128, Raised> {
|
||||
match value {
|
||||
Value::Integer(i) => i
|
||||
.as_i64()
|
||||
.map(i128::from)
|
||||
.or_else(|| i.as_u64().map(i128::from))
|
||||
.ok_or(Raised),
|
||||
Value::F32(f) if f.is_finite() => Ok(*f as i128),
|
||||
Value::F64(f) if f.is_finite() => Ok(*f as i128),
|
||||
Value::Boolean(b) => Ok(i128::from(*b)),
|
||||
Value::String(s) => s.as_str().ok_or(Raised).and_then(py_int_str),
|
||||
Value::Binary(b) => std::str::from_utf8(b)
|
||||
.map_err(|_| Raised)
|
||||
.and_then(py_int_str),
|
||||
_ => Err(Raised),
|
||||
}
|
||||
}
|
||||
|
||||
fn py_int_str(text: &str) -> Result<i128, Raised> {
|
||||
let trimmed = py_strip(text);
|
||||
let (negative, digits) = match trimmed.strip_prefix(['+', '-']) {
|
||||
Some(rest) => (trimmed.starts_with('-'), rest),
|
||||
None => (false, trimmed),
|
||||
};
|
||||
if digits.is_empty()
|
||||
|| digits.starts_with('_')
|
||||
|| digits.ends_with('_')
|
||||
|| digits.contains("__")
|
||||
{
|
||||
return Err(Raised);
|
||||
}
|
||||
let mut value: i128 = 0;
|
||||
for c in digits.chars().filter(|c| *c != '_') {
|
||||
let digit = i128::from(c.to_digit(10).ok_or(Raised)?);
|
||||
value = value
|
||||
.checked_mul(10)
|
||||
.and_then(|v| v.checked_add(digit))
|
||||
.ok_or(Raised)?;
|
||||
}
|
||||
Ok(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn int_value(n: i128) -> Value {
|
||||
match (i64::try_from(n), u64::try_from(n)) {
|
||||
(Ok(v), _) => Value::from(v),
|
||||
(_, Ok(v)) => Value::from(v),
|
||||
_ => Value::Nil,
|
||||
}
|
||||
}
|
||||
|
||||
/// `doc_id = data.get("doc_id")`, the `is None` check and `int(doc_id)`.
|
||||
fn doc_id(data: &Request) -> Result<i128, Vec<u8>> {
|
||||
match data.get("doc_id") {
|
||||
None | Some(Value::Nil) => Err(status(RES_INVALID_REQ, "No document ID specified")),
|
||||
Some(value) => py_int(value).map_err(|_| status(RES_INVALID_REQ, "Invalid document ID")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first scope holding `<scope>/<id>` as a directory.
|
||||
fn find_doc(
|
||||
work_path: &Path,
|
||||
doc_id: i128,
|
||||
scopes: &[&'static str],
|
||||
) -> Option<(&'static str, PathBuf)> {
|
||||
scopes.iter().find_map(|scope| {
|
||||
let dir = work_path.join(scope).join(doc_id.to_string());
|
||||
dir.is_dir().then_some((*scope, dir))
|
||||
})
|
||||
}
|
||||
|
||||
fn allowed_path(work_path: &Path, doc_id: i128) -> PathBuf {
|
||||
PathBuf::from(format!("{}/{doc_id}.allowed", work_path.display()))
|
||||
}
|
||||
|
||||
/// `resolve_doc_permission` (`server.py`): the document's
|
||||
/// `.allowed` file decides first, then the repository and group as
|
||||
/// `resolve_permission` does. Upstream runs it without the block list.
|
||||
pub fn resolve_doc_permission(
|
||||
repos: &Repositories,
|
||||
hash: &[u8; 16],
|
||||
path: Option<(&str, &str)>,
|
||||
doc_id: i128,
|
||||
perm: Perm,
|
||||
) -> bool {
|
||||
if repos.is_blocked(hash) {
|
||||
return false;
|
||||
}
|
||||
let Some((group_name, repository_name)) = path else {
|
||||
return false;
|
||||
};
|
||||
let Some(group) = repos.groups.get(group_name) else {
|
||||
return false;
|
||||
};
|
||||
let Some(repository) = group.repositories.get(repository_name) else {
|
||||
return false;
|
||||
};
|
||||
let list = match perm {
|
||||
Perm::Read => PermList::Read,
|
||||
Perm::Write => PermList::Write,
|
||||
Perm::Create => PermList::Create,
|
||||
Perm::Interact => PermList::Interact,
|
||||
Perm::Propose => PermList::Propose,
|
||||
Perm::Admin => PermList::Admin,
|
||||
Perm::ReadWrite | Perm::Stats | Perm::Release => return false,
|
||||
};
|
||||
let work_path = PathBuf::from(format!("{}.work", repository.path.display()));
|
||||
let allowed = allowed_path(&work_path, doc_id);
|
||||
let mut input = String::new();
|
||||
if work_path.is_dir() && allowed.is_file() {
|
||||
match std::fs::read_to_string(&allowed) {
|
||||
Ok(text) => input = text,
|
||||
Err(e) => tracing::error!(
|
||||
"Error while resolving document permission for {group_name}/{repository_name}/{doc_id}: {e}"
|
||||
),
|
||||
}
|
||||
}
|
||||
let doc = Permissions::from_allowed_input(&input, &repos.aliases);
|
||||
let me = Target::Identity(hash.to_vec());
|
||||
let doc_list = doc.get(list);
|
||||
if doc_list.contains(&Target::None) {
|
||||
return false;
|
||||
}
|
||||
if doc_list.contains(&Target::All)
|
||||
|| doc_list.contains(&me)
|
||||
|| doc.get(PermList::Admin).contains(&me)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
resolve_repository(&group.permissions, &repository.permissions, hash, perm)
|
||||
}
|
||||
|
||||
/// Python's text-mode read: UTF-8, with `\r\n` and `\r` read as `\n`.
|
||||
pub(crate) fn read_text(path: &Path) -> std::io::Result<String> {
|
||||
let text = std::fs::read_to_string(path)?;
|
||||
Ok(text.replace("\r\n", "\n").replace('\r', "\n"))
|
||||
}
|
||||
|
||||
/// `_work_load_document`: any read or decode failure is None.
|
||||
pub(crate) fn load_document(path: &Path) -> Option<Value> {
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
rmpv::decode::read_value(&mut &bytes[..]).ok()
|
||||
}
|
||||
|
||||
/// `_work_save_document` (`server.py`).
|
||||
fn save_document(path: &Path, document: &Value) -> bool {
|
||||
let saved = (|| -> std::io::Result<()> {
|
||||
let dir = path.parent().unwrap_or(Path::new("."));
|
||||
if !dir.is_dir() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let tmp = append_suffix(path, ".tmp");
|
||||
std::fs::File::create(&tmp)?.write_all(&pack(document))?;
|
||||
std::fs::rename(&tmp, path)
|
||||
})();
|
||||
if let Err(e) = &saved {
|
||||
tracing::error!("Error persisting work document: {e}");
|
||||
}
|
||||
saved.is_ok()
|
||||
}
|
||||
|
||||
/// Write `text` through `<path>.tmp` and a rename, as upstream's permission writers.
|
||||
fn write_replacing(path: &Path, text: &str) -> std::io::Result<()> {
|
||||
let tmp = append_suffix(path, ".tmp");
|
||||
std::fs::File::create(&tmp)?.write_all(text.as_bytes())?;
|
||||
std::fs::rename(&tmp, path)
|
||||
}
|
||||
|
||||
fn append_suffix(path: &Path, suffix: &str) -> PathBuf {
|
||||
let mut name = path.as_os_str().to_os_string();
|
||||
name.push(suffix);
|
||||
PathBuf::from(name)
|
||||
}
|
||||
|
||||
fn pack(value: &Value) -> Vec<u8> {
|
||||
let mut bytes = Vec::new();
|
||||
rmpv::encode::write_value(&mut bytes, value).expect("msgpack write to memory");
|
||||
bytes
|
||||
}
|
||||
|
||||
fn ok_with(value: Value) -> Vec<u8> {
|
||||
let mut reply = vec![RES_OK];
|
||||
reply.extend_from_slice(&pack(&value));
|
||||
reply
|
||||
}
|
||||
|
||||
fn map(entries: Vec<(&str, Value)>) -> Value {
|
||||
Value::Map(
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(k, v)| (Value::from(k), v))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Numeric entry names of a directory, as `[int(d) for d in listdir if d.isdigit()]`.
|
||||
fn numeric_entries(dir: &Path) -> Vec<(i128, PathBuf)> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||
return Vec::new();
|
||||
};
|
||||
entries
|
||||
.filter_map(|e| e.ok())
|
||||
.filter_map(|e| {
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
let numeric = !name.is_empty() && name.bytes().all(|b| b.is_ascii_digit());
|
||||
numeric
|
||||
.then(|| name.parse::<i128>().ok())
|
||||
.flatten()
|
||||
.map(|id| (id, e.path()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `_work_get_next_id` and `_work_get_next_comment_id`: one past the highest
|
||||
/// numeric entry, minimum 1. Entries of any type count.
|
||||
fn next_in(dir: &Path) -> i128 {
|
||||
numeric_entries(dir)
|
||||
.iter()
|
||||
.map(|(id, _)| id + 1)
|
||||
.max()
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
fn next_id(work_path: &Path) -> i128 {
|
||||
SCOPES
|
||||
.iter()
|
||||
.map(|s| next_in(&work_path.join(s)))
|
||||
.max()
|
||||
.unwrap_or(1)
|
||||
}
|
||||
|
||||
fn meta_of(document: &Value) -> &[(Value, Value)] {
|
||||
let meta = match document {
|
||||
Value::Map(entries) => get(entries, &Value::from("meta")),
|
||||
_ => None,
|
||||
};
|
||||
match meta {
|
||||
Some(Value::Map(entries)) => entries,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// `meta.get(key, default)`.
|
||||
fn meta_get(meta: &[(Value, Value)], key: &str, default: Value) -> Value {
|
||||
get(meta, &Value::from(key)).cloned().unwrap_or(default)
|
||||
}
|
||||
|
||||
fn doc_get(document: &Value, key: &str, default: Value) -> Value {
|
||||
match document {
|
||||
Value::Map(entries) => get(entries, &Value::from(key)).cloned().unwrap_or(default),
|
||||
_ => default,
|
||||
}
|
||||
}
|
||||
|
||||
/// `RNS.hexrep(meta.get("author"), delimit=False) if meta.get("author") else ""`.
|
||||
fn author_text(meta: &[(Value, Value)]) -> Value {
|
||||
match get(meta, &Value::from("author")) {
|
||||
Some(Value::Binary(b)) if !b.is_empty() => Value::from(hex::encode(b)),
|
||||
_ => Value::from(""),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_author(document: &Value, hash: &[u8; 16]) -> bool {
|
||||
matches!(get(meta_of(document), &Value::from("author")), Some(Value::Binary(b)) if b.as_slice() == hash)
|
||||
}
|
||||
|
||||
/// The stored format: the value when it is one of the two names, else markdown.
|
||||
fn stored_format(format: Option<&Value>) -> Value {
|
||||
match format.and_then(Value::as_str) {
|
||||
Some(f @ ("markdown" | "micron")) => Value::from(f),
|
||||
_ => Value::from("markdown"),
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> f64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs_f64())
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Python `len()` of an unpacked value; `Err` where it raises.
|
||||
fn py_len_of(value: &Value) -> Result<usize, Raised> {
|
||||
match value {
|
||||
Value::String(s) => s.as_str().map(super::py_len).ok_or(Raised),
|
||||
Value::Binary(b) => Ok(b.len()),
|
||||
Value::Array(a) => Ok(a.len()),
|
||||
Value::Map(m) => Ok(m.len()),
|
||||
_ => Err(Raised),
|
||||
}
|
||||
}
|
||||
|
||||
/// The signature checks shared by create, propose and edit. `Ok(None)` passes.
|
||||
fn check_signature(
|
||||
signature: Option<&Value>,
|
||||
identity: &Identity,
|
||||
signed: &[u8],
|
||||
) -> Result<Option<Vec<u8>>, Raised> {
|
||||
let Some(signature) = signature.filter(|s| truthy(s)) else {
|
||||
return Ok(Some(status(RES_INVALID_REQ, "No signature provided")));
|
||||
};
|
||||
if py_len_of(signature)? != 64 {
|
||||
return Ok(Some(status(RES_INVALID_REQ, "Invalid signature length")));
|
||||
}
|
||||
let valid = match signature {
|
||||
Value::Binary(b) => {
|
||||
<[u8; 64]>::try_from(b.as_slice()).is_ok_and(|sig| identity.verify(signed, &sig))
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
Ok((!valid).then(|| status(RES_INVALID_REQ, "Invalid signature")))
|
||||
}
|
||||
|
||||
/// `_work_list` (`server.py`).
|
||||
fn work_list(
|
||||
work_path: &Path,
|
||||
data: &Request,
|
||||
repos: &Repositories,
|
||||
hash: &[u8; 16],
|
||||
path: Option<(&str, &str)>,
|
||||
) -> Vec<u8> {
|
||||
let scope = data.name("scope", "active");
|
||||
let mut result = Vec::new();
|
||||
for folder in SCOPES {
|
||||
let mut docs: Vec<(f64, Value)> = Vec::new();
|
||||
let folder_path = work_path.join(folder);
|
||||
let listed = scope.as_deref().is_some_and(|s| s == folder || s == "all");
|
||||
let entries = if listed && folder_path.is_dir() {
|
||||
std::fs::read_dir(&folder_path)
|
||||
.map(|e| e.filter_map(|e| e.ok()).collect())
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
for entry in entries {
|
||||
let doc_dir = entry.path();
|
||||
if !doc_dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let Ok(doc_id) = py_int_str(&entry.file_name().to_string_lossy()) else {
|
||||
continue;
|
||||
};
|
||||
if !resolve_doc_permission(repos, hash, path, doc_id, Perm::Read) {
|
||||
continue;
|
||||
}
|
||||
let root = doc_dir.join("root");
|
||||
if !root.is_file() {
|
||||
continue;
|
||||
}
|
||||
let Some(doc) = load_document(&root).filter(truthy) else {
|
||||
continue;
|
||||
};
|
||||
let meta = meta_of(&doc);
|
||||
let comments = numeric_entries(&doc_dir)
|
||||
.iter()
|
||||
.filter(|(_, p)| p.is_file())
|
||||
.count();
|
||||
let created = meta_get(meta, "created", Value::from(0));
|
||||
let sort_key = created
|
||||
.as_f64()
|
||||
.or_else(|| created.as_i64().map(|v| v as f64))
|
||||
.unwrap_or(0.0);
|
||||
docs.push((
|
||||
sort_key,
|
||||
map(vec![
|
||||
("id", int_value(doc_id)),
|
||||
("title", meta_get(meta, "title", Value::from("Untitled"))),
|
||||
("created", created),
|
||||
("edited", meta_get(meta, "edited", Value::from(0))),
|
||||
("author", author_text(meta)),
|
||||
("format", meta_get(meta, "format", Value::from("markdown"))),
|
||||
("comments", Value::from(comments as u64)),
|
||||
]),
|
||||
));
|
||||
}
|
||||
// Newest first; a stable sort keeps the listing order of ties.
|
||||
docs.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
result.push((
|
||||
folder,
|
||||
Value::Array(docs.into_iter().map(|(_, v)| v).collect()),
|
||||
));
|
||||
}
|
||||
ok_with(map(result))
|
||||
}
|
||||
|
||||
/// `_work_view` (`server.py`).
|
||||
fn work_view(work_path: &Path, data: &Request) -> Vec<u8> {
|
||||
if !valid_scope(&data.name("scope", "all")) {
|
||||
return status(RES_INVALID_REQ, "Invalid request");
|
||||
}
|
||||
let doc_id = match doc_id(data) {
|
||||
Ok(id) => id,
|
||||
Err(reply) => return reply,
|
||||
};
|
||||
let Some((scope, doc_dir)) = find_doc(work_path, doc_id, &SCOPES) else {
|
||||
return status(RES_NOT_FOUND, "Not found");
|
||||
};
|
||||
let root = doc_dir.join("root");
|
||||
if !root.is_file() {
|
||||
return status(RES_NOT_FOUND, "Document not found");
|
||||
}
|
||||
let Some(doc) = load_document(&root).filter(truthy) else {
|
||||
return status(RES_REMOTE_FAIL, "Error loading document");
|
||||
};
|
||||
let mut comments: Vec<(i128, Value)> = numeric_entries(&doc_dir)
|
||||
.into_iter()
|
||||
.filter(|(_, p)| p.is_file())
|
||||
.filter_map(|(id, p)| {
|
||||
let comment = load_document(&p).filter(truthy)?;
|
||||
let meta = meta_of(&comment);
|
||||
Some((
|
||||
id,
|
||||
map(vec![
|
||||
("id", int_value(id)),
|
||||
("content", doc_get(&comment, "content", Value::from(""))),
|
||||
("created", meta_get(meta, "created", Value::from(0))),
|
||||
("edited", meta_get(meta, "edited", Value::from(0))),
|
||||
("author", author_text(meta)),
|
||||
("format", meta_get(meta, "format", Value::from("markdown"))),
|
||||
]),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
comments.sort_by_key(|(id, _)| *id);
|
||||
let meta = meta_of(&doc);
|
||||
ok_with(map(vec![
|
||||
("id", int_value(doc_id)),
|
||||
("scope", Value::from(scope)),
|
||||
("content", doc_get(&doc, "content", Value::from(""))),
|
||||
(
|
||||
"comments",
|
||||
Value::Array(comments.into_iter().map(|(_, v)| v).collect()),
|
||||
),
|
||||
(
|
||||
"meta",
|
||||
map(vec![
|
||||
("title", meta_get(meta, "title", Value::from("Untitled"))),
|
||||
("created", meta_get(meta, "created", Value::from(0))),
|
||||
("edited", meta_get(meta, "edited", Value::from(0))),
|
||||
("author", author_text(meta)),
|
||||
("identity", meta_get(meta, "identity", Value::Nil)),
|
||||
("signature", meta_get(meta, "signature", Value::Nil)),
|
||||
("format", meta_get(meta, "format", Value::from("markdown"))),
|
||||
]),
|
||||
),
|
||||
]))
|
||||
}
|
||||
|
||||
/// `_work_create` and `_work_propose` (`server.py`), which differ
|
||||
/// in the scope they store under and the ownership file propose writes.
|
||||
fn work_new(
|
||||
work_path: &Path,
|
||||
data: &Request,
|
||||
identity: &Identity,
|
||||
scope: &str,
|
||||
) -> Result<Vec<u8>, Raised> {
|
||||
let title = py_strip(&data.text("title")?).to_string();
|
||||
let content = py_strip(&data.text("content")?).to_string();
|
||||
let format = data
|
||||
.get("format")
|
||||
.cloned()
|
||||
.unwrap_or(Value::from("markdown"));
|
||||
if let Some(reply) = check_signature(data.get("signature"), identity, content.as_bytes())? {
|
||||
return Ok(reply);
|
||||
}
|
||||
if super::py_len(&title) + super::py_len(&content) + py_len_of(&format)? > WORK_DOC_LIMIT {
|
||||
return Ok(status(RES_INVALID_REQ, "Content limit exceeded"));
|
||||
}
|
||||
if title.is_empty() {
|
||||
return Ok(status(RES_INVALID_REQ, "Title is required"));
|
||||
}
|
||||
if content.is_empty() {
|
||||
return Ok(status(RES_INVALID_REQ, "Content is required"));
|
||||
}
|
||||
let doc_id = next_id(work_path);
|
||||
let doc_dir = work_path.join(scope).join(doc_id.to_string());
|
||||
let now = now();
|
||||
let document = map(vec![
|
||||
("content", Value::from(content.as_str())),
|
||||
(
|
||||
"meta",
|
||||
map(vec![
|
||||
("format", stored_format(Some(&format))),
|
||||
("title", Value::from(title.as_str())),
|
||||
("created", Value::F64(now)),
|
||||
("edited", Value::F64(now)),
|
||||
("author", Value::Binary(identity.hash.to_vec())),
|
||||
(
|
||||
"signature",
|
||||
data.get("signature").cloned().unwrap_or(Value::Nil),
|
||||
),
|
||||
(
|
||||
"identity",
|
||||
Value::Binary(identity.get_public_key().to_vec()),
|
||||
),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
if !save_document(&doc_dir.join("root"), &document) {
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error saving document"));
|
||||
}
|
||||
if scope == "proposed" {
|
||||
let owner = hex::encode(identity.hash);
|
||||
if let Err(e) = write_replacing(
|
||||
&allowed_path(work_path, doc_id),
|
||||
&format!("i:{owner}\nw:{owner}\n"),
|
||||
) {
|
||||
tracing::error!("Error setting permissions: {e}");
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error setting document ownership"));
|
||||
}
|
||||
}
|
||||
Ok(ok_with(map(vec![
|
||||
("id", int_value(doc_id)),
|
||||
("scope", Value::from(scope)),
|
||||
])))
|
||||
}
|
||||
|
||||
/// `_work_edit` (`server.py`).
|
||||
fn work_edit(work_path: &Path, data: &Request, identity: &Identity) -> Result<Vec<u8>, Raised> {
|
||||
let scope = data.name("scope", "active");
|
||||
let content = data.text("content")?;
|
||||
let title = match data.get("title") {
|
||||
None => String::new(),
|
||||
Some(Value::String(s)) => s.as_str().ok_or(Raised)?.to_string(),
|
||||
Some(v) if !truthy(v) => String::new(),
|
||||
Some(_) => return Err(Raised),
|
||||
};
|
||||
let size = super::py_len(&title) + super::py_len(&content);
|
||||
if !valid_scope(&scope) {
|
||||
return Ok(status(RES_INVALID_REQ, "Invalid request"));
|
||||
}
|
||||
if let Some(reply) = check_signature(data.get("signature"), identity, content.as_bytes())? {
|
||||
return Ok(reply);
|
||||
}
|
||||
if size > WORK_DOC_LIMIT {
|
||||
return Ok(status(RES_INVALID_REQ, "Content limit exceeded"));
|
||||
}
|
||||
if content.is_empty() && title.is_empty() {
|
||||
return Ok(status(RES_INVALID_REQ, "No changes specified"));
|
||||
}
|
||||
let Some(raw_id) = data.get("doc_id").filter(|v| truthy(v)) else {
|
||||
return Ok(status(RES_INVALID_REQ, "No document ID specified"));
|
||||
};
|
||||
let Ok(doc_id) = py_int(raw_id) else {
|
||||
return Ok(status(RES_INVALID_REQ, "Invalid document ID"));
|
||||
};
|
||||
let Some((_, doc_dir)) = find_doc(work_path, doc_id, &SCOPES) else {
|
||||
return Ok(status(RES_NOT_FOUND, "Not found"));
|
||||
};
|
||||
let root = doc_dir.join("root");
|
||||
if !root.is_file() {
|
||||
return Ok(status(RES_NOT_FOUND, "Document not found"));
|
||||
}
|
||||
let Some(mut doc) = load_document(&root).filter(truthy) else {
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error loading document"));
|
||||
};
|
||||
if !is_author(&doc, &identity.hash) {
|
||||
return Ok(status(RES_DISALLOWED, "No access, not author"));
|
||||
}
|
||||
let Value::Map(entries) = &mut doc else {
|
||||
return Err(Raised);
|
||||
};
|
||||
fn put(entries: &mut Vec<(Value, Value)>, key: &str, value: Value) {
|
||||
match entries.iter_mut().find(|(k, _)| k.as_str() == Some(key)) {
|
||||
Some((_, slot)) => *slot = value,
|
||||
None => entries.push((Value::from(key), value)),
|
||||
}
|
||||
}
|
||||
let Some(Value::Map(meta)) = entries
|
||||
.iter_mut()
|
||||
.find(|(k, _)| k.as_str() == Some("meta"))
|
||||
.map(|(_, v)| v)
|
||||
else {
|
||||
return Err(Raised);
|
||||
};
|
||||
if !title.is_empty() {
|
||||
put(meta, "title", Value::from(py_strip(&title)));
|
||||
}
|
||||
put(meta, "edited", Value::F64(now()));
|
||||
put(
|
||||
meta,
|
||||
"signature",
|
||||
data.get("signature").cloned().unwrap_or(Value::Nil),
|
||||
);
|
||||
put(
|
||||
meta,
|
||||
"identity",
|
||||
Value::Binary(identity.get_public_key().to_vec()),
|
||||
);
|
||||
if !content.is_empty() {
|
||||
put(entries, "content", Value::from(py_strip(&content)));
|
||||
}
|
||||
if !save_document(&root, &doc) {
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error saving document"));
|
||||
}
|
||||
Ok(vec![RES_OK])
|
||||
}
|
||||
|
||||
/// `_work_delete` (`server.py`).
|
||||
fn work_delete(
|
||||
work_path: &Path,
|
||||
data: &Request,
|
||||
repos: &Repositories,
|
||||
hash: &[u8; 16],
|
||||
path: Option<(&str, &str)>,
|
||||
) -> Result<Vec<u8>, Raised> {
|
||||
if !valid_scope(&data.name("scope", "active")) {
|
||||
return Ok(status(RES_INVALID_REQ, "Invalid request"));
|
||||
}
|
||||
let doc_id = match doc_id(data) {
|
||||
Ok(id) => id,
|
||||
Err(reply) => return Ok(reply),
|
||||
};
|
||||
// Upstream joins `None` into the path when no scope holds the document.
|
||||
let (_, doc_dir) = find_doc(work_path, doc_id, &SCOPES).ok_or(Raised)?;
|
||||
let root = doc_dir.join("root");
|
||||
if !root.is_file() {
|
||||
return Ok(status(RES_NOT_FOUND, "Document not found"));
|
||||
}
|
||||
let Some(doc) = load_document(&root).filter(truthy) else {
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error loading document"));
|
||||
};
|
||||
if !(is_author(&doc, hash) || resolve_doc_permission(repos, hash, path, doc_id, Perm::Admin)) {
|
||||
return Ok(status(RES_DISALLOWED, "No access, not author"));
|
||||
}
|
||||
if let Err(e) = std::fs::remove_file(allowed_path(work_path, doc_id)) {
|
||||
tracing::error!(
|
||||
"Error while deleting permissions file for {}/{doc_id}: {e}",
|
||||
work_path.display()
|
||||
);
|
||||
return Ok(status(RES_REMOTE_FAIL, "Remote error"));
|
||||
}
|
||||
if let Err(e) = std::fs::remove_dir_all(&doc_dir) {
|
||||
tracing::error!("Error deleting work document: {e}");
|
||||
return Ok(status(RES_REMOTE_FAIL, "Remote error"));
|
||||
}
|
||||
Ok(vec![RES_OK])
|
||||
}
|
||||
|
||||
/// `_work_comment` (`server.py`).
|
||||
fn work_comment(work_path: &Path, data: &Request, identity: &Identity) -> Result<Vec<u8>, Raised> {
|
||||
let scope = data.name("scope", "active");
|
||||
let content = py_strip(&data.text("content")?).to_string();
|
||||
if !valid_scope(&scope) {
|
||||
return Ok(status(RES_INVALID_REQ, "Invalid request"));
|
||||
}
|
||||
if super::py_len(&content) > WORK_DOC_LIMIT {
|
||||
return Ok(status(RES_INVALID_REQ, "Content limit exceeded"));
|
||||
}
|
||||
let doc_id = match doc_id(data) {
|
||||
Ok(id) => id,
|
||||
Err(reply) => return Ok(reply),
|
||||
};
|
||||
if content.is_empty() {
|
||||
return Ok(status(RES_INVALID_REQ, "Content is required"));
|
||||
}
|
||||
let (_, doc_dir) = find_doc(work_path, doc_id, &SCOPES).ok_or(Raised)?;
|
||||
if !doc_dir.join("root").is_file() {
|
||||
return Ok(status(RES_NOT_FOUND, "Document not found"));
|
||||
}
|
||||
let comment_id = next_in(&doc_dir);
|
||||
let now = now();
|
||||
let comment = map(vec![
|
||||
("content", Value::from(content.as_str())),
|
||||
(
|
||||
"meta",
|
||||
map(vec![
|
||||
("format", stored_format(data.get("format"))),
|
||||
("title", Value::Nil),
|
||||
("created", Value::F64(now)),
|
||||
("edited", Value::F64(now)),
|
||||
(
|
||||
"signature",
|
||||
data.get("signature").cloned().unwrap_or(Value::Nil),
|
||||
),
|
||||
("author", Value::Binary(identity.hash.to_vec())),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
if !save_document(&doc_dir.join(comment_id.to_string()), &comment) {
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error saving comment"));
|
||||
}
|
||||
Ok(ok_with(map(vec![("id", int_value(comment_id))])))
|
||||
}
|
||||
|
||||
/// `shutil.move(src, dst)` for a directory: into `dst` when it is an existing
|
||||
/// directory, creating missing parents.
|
||||
fn move_dir(src: &Path, dst: &Path) -> std::io::Result<()> {
|
||||
let dst = if dst.is_dir() {
|
||||
dst.join(src.file_name().unwrap_or_default())
|
||||
} else {
|
||||
dst.to_path_buf()
|
||||
};
|
||||
if dst.exists() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::AlreadyExists,
|
||||
"Destination path already exists",
|
||||
));
|
||||
}
|
||||
if let Some(parent) = dst.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::rename(src, &dst)
|
||||
}
|
||||
|
||||
/// `_work_complete` and `_work_activate` (`server.py`).
|
||||
fn work_move(
|
||||
work_path: &Path,
|
||||
data: &Request,
|
||||
repos: &Repositories,
|
||||
hash: &[u8; 16],
|
||||
path: Option<(&str, &str)>,
|
||||
to: &'static str,
|
||||
) -> Vec<u8> {
|
||||
let doc_id = match doc_id(data) {
|
||||
Ok(id) => id,
|
||||
Err(reply) => return reply,
|
||||
};
|
||||
let from: &[&'static str] = if to == "completed" {
|
||||
&["active"]
|
||||
} else {
|
||||
&["completed", "proposed"]
|
||||
};
|
||||
let Some((_, doc_dir)) = find_doc(work_path, doc_id, from) else {
|
||||
return status(RES_NOT_FOUND, "Document not found");
|
||||
};
|
||||
let Some(doc) = load_document(&doc_dir.join("root")).filter(truthy) else {
|
||||
return status(RES_REMOTE_FAIL, "Error loading document");
|
||||
};
|
||||
if !is_author(&doc, hash) && !resolve_doc_permission(repos, hash, path, doc_id, Perm::Admin) {
|
||||
return status(RES_DISALLOWED, "Not allowed");
|
||||
}
|
||||
if let Err(e) = move_dir(&doc_dir, &work_path.join(to).join(doc_id.to_string())) {
|
||||
tracing::error!("Error moving work document: {e}");
|
||||
return status(RES_REMOTE_FAIL, "Remote error");
|
||||
}
|
||||
ok_with(map(vec![
|
||||
("id", int_value(doc_id)),
|
||||
("scope", Value::from(to)),
|
||||
]))
|
||||
}
|
||||
|
||||
/// `_work_perms` and its get/set steps (`server.py`).
|
||||
fn work_perms(
|
||||
work_path: &Path,
|
||||
data: &Request,
|
||||
repos: &Repositories,
|
||||
hash: &[u8; 16],
|
||||
path: Option<(&str, &str)>,
|
||||
) -> Result<Vec<u8>, Raised> {
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let resolve = |perm| path.is_some() && repos.resolve_permission(hash, group, repo, perm);
|
||||
let manage = resolve(Perm::Interact) && resolve(Perm::Write);
|
||||
if !resolve(Perm::Read) {
|
||||
return Ok(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
if !manage {
|
||||
return Ok(status(RES_DISALLOWED, "Not allowed"));
|
||||
}
|
||||
let step = data.get("step").filter(|s| truthy(s));
|
||||
let set = match step.map(Value::as_str) {
|
||||
None => return Ok(status(RES_INVALID_REQ, "Invalid request")),
|
||||
Some(Some("get")) => false,
|
||||
Some(Some("set")) => true,
|
||||
Some(_) => return Ok(status(RES_INVALID_REQ, "Invalid step")),
|
||||
};
|
||||
// `content` is read before the document checks; `splitlines` raises later.
|
||||
let content = data.get("content").cloned();
|
||||
let doc_id = match doc_id(data) {
|
||||
Ok(id) => id,
|
||||
Err(reply) => return Ok(reply),
|
||||
};
|
||||
let Some((_, doc_dir)) = find_doc(work_path, doc_id, &SCOPES) else {
|
||||
return Ok(status(RES_NOT_FOUND, "Document not found"));
|
||||
};
|
||||
let Some(doc) = load_document(&doc_dir.join("root")).filter(truthy) else {
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error loading document"));
|
||||
};
|
||||
let admin = resolve_doc_permission(repos, hash, path, doc_id, Perm::Admin);
|
||||
if !((is_author(&doc, hash) && manage) || admin) {
|
||||
return Ok(status(RES_DISALLOWED, "Not allowed"));
|
||||
}
|
||||
let allowed = allowed_path(work_path, doc_id);
|
||||
if !set {
|
||||
let text = if allowed.is_file() {
|
||||
match read_text(&allowed) {
|
||||
Ok(text) => text,
|
||||
Err(e) => {
|
||||
tracing::error!("Error getting document permissions: {e}");
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error getting permissions"));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
return Ok(ok_with(map(vec![("content", Value::from(text))])));
|
||||
}
|
||||
let content = match content {
|
||||
None => String::new(),
|
||||
Some(Value::String(s)) => s.as_str().ok_or(Raised)?.to_string(),
|
||||
Some(_) => return Err(Raised),
|
||||
};
|
||||
if let Some(message) = invalid_line(&content, &repos.aliases) {
|
||||
return Ok(status(RES_INVALID_REQ, &message));
|
||||
}
|
||||
if let Err(e) = write_replacing(&allowed, &content) {
|
||||
tracing::error!("Error setting permissions: {e}");
|
||||
return Ok(status(RES_REMOTE_FAIL, "Error setting permissions"));
|
||||
}
|
||||
Ok(vec![RES_OK])
|
||||
}
|
||||
|
||||
/// `handle_work` (`server.py`). `None` sends no response.
|
||||
pub fn handle_work(
|
||||
repos: &RwLock<Repositories>,
|
||||
identity: Option<&Identity>,
|
||||
data: &Value,
|
||||
) -> Option<Vec<u8>> {
|
||||
let repos = repos.read().unwrap_or_else(|e| e.into_inner());
|
||||
let hash = identity.map(|i| i.hash);
|
||||
log_request(
|
||||
&repos,
|
||||
&format!("Work request from remote {}", identity_text(hash.as_ref())),
|
||||
hash.as_ref(),
|
||||
);
|
||||
let Some(identity) = identity else {
|
||||
return Some(status(RES_DISALLOWED, "Not identified"));
|
||||
};
|
||||
let hash = identity.hash;
|
||||
let Value::Map(entries) = data else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
let Some(repository) = get(entries, &Value::from(IDX_REPOSITORY)) else {
|
||||
return Some(status(RES_INVALID_REQ, "No repository specified"));
|
||||
};
|
||||
let request = Request(entries);
|
||||
let Some(operation) = request.get("operation").filter(|v| truthy(v)) else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
// `parse_request_repository_path` raises outside any try: no response.
|
||||
let path = parse_repository_path(repository.as_str()?);
|
||||
let operation = operation.as_str().unwrap_or("");
|
||||
let (group, repo) = path.unwrap_or(("", ""));
|
||||
let resolve = |perm| path.is_some() && repos.resolve_permission(&hash, group, repo, perm);
|
||||
let mut read = resolve(Perm::Read);
|
||||
let mut write = resolve(Perm::Write);
|
||||
let mut interact = resolve(Perm::Interact);
|
||||
let propose = resolve(Perm::Propose);
|
||||
let admin = resolve(Perm::Admin);
|
||||
if !read {
|
||||
return Some(status(RES_NOT_FOUND, "Not found"));
|
||||
}
|
||||
if let Some(raw_id) = request.get("doc_id").filter(|v| truthy(v))
|
||||
&& ["read", "view", "comment", "edit", "delete", "perms"].contains(&operation)
|
||||
{
|
||||
let Ok(doc_id) = py_int(raw_id) else {
|
||||
return Some(status(RES_INVALID_REQ, "Invalid request"));
|
||||
};
|
||||
let doc = |perm| resolve_doc_permission(&repos, &hash, path, doc_id, perm);
|
||||
read = doc(Perm::Read) || admin;
|
||||
if !read {
|
||||
return Some(status(RES_NOT_FOUND, "Document not found"));
|
||||
}
|
||||
if operation == "comment" || operation == "edit" {
|
||||
interact |= doc(Perm::Interact);
|
||||
}
|
||||
if operation == "edit" {
|
||||
write |= doc(Perm::Write);
|
||||
}
|
||||
}
|
||||
let comment_access = interact && (read || write);
|
||||
let manage_access = interact && write;
|
||||
let access = match operation {
|
||||
"list" | "view" => read,
|
||||
"comment" => comment_access,
|
||||
"propose" => propose,
|
||||
"create" | "edit" | "delete" | "complete" | "activate" => manage_access,
|
||||
"perms" => admin,
|
||||
_ => false,
|
||||
};
|
||||
if !access {
|
||||
return Some(status(RES_DISALLOWED, "Not allowed"));
|
||||
}
|
||||
let repository = repos.repository(group, repo)?;
|
||||
let _serial = WORK_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let work_path = PathBuf::from(format!("{}.work", repository.path.display()));
|
||||
let reply = match operation {
|
||||
"list" => Ok(work_list(&work_path, &request, &repos, &hash, path)),
|
||||
"view" => Ok(work_view(&work_path, &request)),
|
||||
"comment" => work_comment(&work_path, &request, identity),
|
||||
"create" => work_new(&work_path, &request, identity, "active"),
|
||||
"propose" => work_new(&work_path, &request, identity, "proposed"),
|
||||
"edit" => work_edit(&work_path, &request, identity),
|
||||
"delete" => work_delete(&work_path, &request, &repos, &hash, path),
|
||||
"complete" => Ok(work_move(
|
||||
&work_path,
|
||||
&request,
|
||||
&repos,
|
||||
&hash,
|
||||
path,
|
||||
"completed",
|
||||
)),
|
||||
"activate" => Ok(work_move(
|
||||
&work_path, &request, &repos, &hash, path, "active",
|
||||
)),
|
||||
"perms" => work_perms(&work_path, &request, &repos, &hash, path),
|
||||
_ => Ok(status(RES_INVALID_REQ, "Invalid request")),
|
||||
};
|
||||
Some(reply.unwrap_or_else(|Raised| {
|
||||
tracing::error!("Error while handling work request for {group}/{repo}");
|
||||
status(RES_REMOTE_FAIL, "Remote error")
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Request validators from `RNS/Utilities/rngit/util.py`.
|
||||
|
||||
use rns_tools::rsg::pyfmt::py_fromhex;
|
||||
|
||||
/// Python `san_ref` (`util.py`): the ref when it passes upstream's
|
||||
/// subset of `git check-ref-format`. A ref without `/` (`HEAD`, `main`) and
|
||||
/// any character below `(` are rejected, as upstream does.
|
||||
pub fn san_ref(reference: &str) -> Option<&str> {
|
||||
let r = reference;
|
||||
if r.starts_with('-') || r.starts_with('/') || r.ends_with('/') || r.ends_with('.') {
|
||||
return None;
|
||||
}
|
||||
if [" ", "..", "/.", "//", "\\"].iter().any(|s| r.contains(s)) || !r.contains('/') {
|
||||
return None;
|
||||
}
|
||||
if r.split('/').any(|component| component.ends_with(".lock")) {
|
||||
return None;
|
||||
}
|
||||
if r.chars().any(|c| (c as u32) < 40) {
|
||||
return None;
|
||||
}
|
||||
if ["\x7f", "~", "^", ":", "?", "*", "[", "@{"]
|
||||
.iter()
|
||||
.any(|s| r.contains(s))
|
||||
|| r == "@"
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(reference)
|
||||
}
|
||||
|
||||
/// Python `san_refs` (`util.py`) for a list: the list when every ref
|
||||
/// passes [`san_ref`]. Upstream returns an empty list unchanged, which its
|
||||
/// callers then treat as a failure because it is falsy.
|
||||
pub fn san_refs<S: AsRef<str>>(refs: &[S]) -> Option<&[S]> {
|
||||
refs.iter()
|
||||
.all(|r| san_ref(r.as_ref()).is_some())
|
||||
.then_some(refs)
|
||||
}
|
||||
|
||||
/// Python `san_sha` (`util.py`): at least 40 characters that
|
||||
/// `bytes.fromhex` accepts. There is no upper bound, and `fromhex` skips
|
||||
/// whitespace between byte pairs.
|
||||
pub fn san_sha(sha: &str) -> Option<&str> {
|
||||
if sha.chars().count() < 40 {
|
||||
return None;
|
||||
}
|
||||
py_fromhex(sha).ok().map(|_| sha)
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
[package]
|
||||
name = "rns-identity"
|
||||
description = "Identity, Destination, and Announce system for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[dependencies]
|
||||
rns-crypto = { workspace = true, features = ["std"] }
|
||||
@@ -13,9 +15,17 @@ thiserror = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
rmpv = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_bytes = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Storage_FileSystem"] }
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
@@ -12,6 +12,9 @@ const RANDOM_HASH_SIZE: usize = 10;
|
||||
const SIGNATURE_SIZE: usize = 64;
|
||||
const RATCHET_SIZE: usize = 32;
|
||||
|
||||
/// Maximum value carried in the low five bytes of an announce random hash.
|
||||
pub const ANNOUNCE_TIME_MAX: u64 = (1u64 << 40) - 1;
|
||||
|
||||
const MIN_ANNOUNCE_SIZE: usize = PUBKEY_SIZE + NAME_HASH_SIZE + RANDOM_HASH_SIZE + SIGNATURE_SIZE;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -28,9 +31,13 @@ pub enum AnnounceError {
|
||||
InvalidPublicKey,
|
||||
#[error("hash collision detected for destination")]
|
||||
HashCollision,
|
||||
#[error("announce wire time exceeds 40-bit field: {0}")]
|
||||
InvalidWireTime(u64),
|
||||
}
|
||||
|
||||
/// Parsed announce data.
|
||||
/// Parsed announce fields; parsing alone does not authenticate them.
|
||||
/// Call [`Self::validate`] or [`Self::validate_with_known_key`] before learning
|
||||
/// a destination. Replay, age and ingress policy belong to the caller.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AnnounceData {
|
||||
pub public_key: [u8; 64],
|
||||
@@ -44,26 +51,43 @@ pub struct AnnounceData {
|
||||
impl AnnounceData {
|
||||
/// Create and sign an announce for a destination.
|
||||
///
|
||||
/// The `random_hash` is `random(5) || timestamp_be(5)` so receivers can
|
||||
/// detect replays without a shared clock.
|
||||
/// The `random_hash` is `random(5) || timestamp_be(5)`, using current Unix
|
||||
/// seconds. This supplies randomness and ordering information; replay
|
||||
/// rejection requires receiver state and is not performed by this type.
|
||||
pub fn create(
|
||||
identity: &Identity,
|
||||
app_name: &str,
|
||||
app_data: Option<&[u8]>,
|
||||
ratchet_pub: Option<&[u8; 32]>,
|
||||
) -> Result<Self, AnnounceError> {
|
||||
let public_key = identity.get_public_key();
|
||||
let nh = name_hash(app_name);
|
||||
|
||||
let random_bytes = rns_crypto::random::random_bytes(5);
|
||||
let ts = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
let ts_bytes = ts.to_be_bytes();
|
||||
Self::create_at(identity, app_name, app_data, ratchet_pub, ts)
|
||||
}
|
||||
|
||||
/// Create and sign an announce with an explicit 40-bit ordering value.
|
||||
/// The caller manages persistence before transmission, and manages rotation
|
||||
/// and expiry clocks separately. No state is persisted by this method.
|
||||
pub fn create_at(
|
||||
identity: &Identity,
|
||||
app_name: &str,
|
||||
app_data: Option<&[u8]>,
|
||||
ratchet_pub: Option<&[u8; 32]>,
|
||||
wire_time: u64,
|
||||
) -> Result<Self, AnnounceError> {
|
||||
if wire_time > ANNOUNCE_TIME_MAX {
|
||||
return Err(AnnounceError::InvalidWireTime(wire_time));
|
||||
}
|
||||
|
||||
let public_key = identity.get_public_key();
|
||||
let nh = name_hash(app_name);
|
||||
let random_bytes = rns_crypto::random::random_bytes(5);
|
||||
let ts_bytes = wire_time.to_be_bytes();
|
||||
let mut random_hash = [0u8; 10];
|
||||
random_hash[..5].copy_from_slice(&random_bytes);
|
||||
// Low 5 bytes of the u64 timestamp; wraps ~every 34 000 years.
|
||||
// The value was range checked, so these are the complete 40 bits.
|
||||
random_hash[5..].copy_from_slice(&ts_bytes[3..8]);
|
||||
|
||||
let dest_hash = crate::destination::Destination::hash_from_name_and_identity(
|
||||
@@ -129,7 +153,8 @@ impl AnnounceData {
|
||||
/// Parse an announce from packet payload bytes.
|
||||
///
|
||||
/// `has_ratchet` must match the packet header's context flag; the ratchet
|
||||
/// field is not self-delimiting.
|
||||
/// field is not self-delimiting. This checks minimum length only; use the
|
||||
/// validation methods before trusting a parsed announce.
|
||||
pub fn unpack(data: &[u8], has_ratchet: bool) -> Result<Self, AnnounceError> {
|
||||
let min_size = if has_ratchet {
|
||||
MIN_ANNOUNCE_SIZE + RATCHET_SIZE
|
||||
@@ -241,7 +266,8 @@ impl AnnounceData {
|
||||
}
|
||||
|
||||
/// Validate destination-hash binding and first-seen public-key continuity
|
||||
/// after [`verify_signature`] has succeeded.
|
||||
/// after [`Self::verify_signature`] has succeeded. Pass the identity
|
||||
/// returned by that call; this method does not repeat signature validation.
|
||||
pub fn validate_destination_binding(
|
||||
&self,
|
||||
packet_dest_hash: &[u8; 16],
|
||||
@@ -269,21 +295,195 @@ impl AnnounceData {
|
||||
|
||||
// First-seen key binding: a valid signature on a different public key
|
||||
// for an already-known destination hash implies a collision attack.
|
||||
if let Some(known_key) = known_public_key {
|
||||
if known_key != &self.public_key {
|
||||
tracing::error!(
|
||||
dest = hex::encode(packet_dest_hash),
|
||||
"announce has valid signature and destination hash, but public key \
|
||||
if let Some(known_key) = known_public_key
|
||||
&& known_key != &self.public_key
|
||||
{
|
||||
tracing::error!(
|
||||
dest = hex::encode(packet_dest_hash),
|
||||
"announce has valid signature and destination hash, but public key \
|
||||
differs from already known key — possible hash collision attack, rejecting"
|
||||
);
|
||||
return Err(AnnounceError::HashCollision);
|
||||
}
|
||||
);
|
||||
return Err(AnnounceError::HashCollision);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Trailing announce stamp extension: marker, flags, stamp, lr_cost (Identity.py).
|
||||
pub const ANNOUNCE_EXT_LENGTH: usize = 18;
|
||||
pub const ANNOUNCE_EXT_HEADER_LENGTH: usize = 2;
|
||||
pub const ANNOUNCE_EXT_MARKER: u8 = 0xC1;
|
||||
|
||||
/// `Destination.get_ext_flags()` at 1.6.0.
|
||||
pub const ANNOUNCE_EXT_FLAGS: u8 = 0x00;
|
||||
/// Length of the destination stamp material: hash, public key, name hash.
|
||||
pub const DESTINATION_STAMP_MATERIAL_LENGTH: usize = 16 + PUBKEY_SIZE + NAME_HASH_SIZE;
|
||||
|
||||
/// The stamp extension a destination appends to its announce app_data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AnnounceStampExt {
|
||||
pub stamp: [u8; crate::stamps::NETWORK_STAMP_SIZE],
|
||||
/// The link-request cost to announce, already clamped by the destination.
|
||||
pub lr_cost: f64,
|
||||
}
|
||||
|
||||
impl AnnounceStampExt {
|
||||
/// `0xC1 | flags | stamp | cost_bytes[1] | cost_bytes[0]` (Destination.py).
|
||||
pub fn encode(&self) -> Result<[u8; ANNOUNCE_EXT_LENGTH], crate::stamps::StampError> {
|
||||
let cost = crate::stamps::cost_to_bytes(self.lr_cost)?;
|
||||
let mut ext = [0u8; ANNOUNCE_EXT_LENGTH];
|
||||
ext[0] = ANNOUNCE_EXT_MARKER;
|
||||
ext[1] = ANNOUNCE_EXT_FLAGS;
|
||||
ext[ANNOUNCE_EXT_HEADER_LENGTH
|
||||
..ANNOUNCE_EXT_HEADER_LENGTH + crate::stamps::NETWORK_STAMP_SIZE]
|
||||
.copy_from_slice(&self.stamp);
|
||||
ext[ANNOUNCE_EXT_LENGTH - 2] = cost[1];
|
||||
ext[ANNOUNCE_EXT_LENGTH - 1] = cost[0];
|
||||
Ok(ext)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Destination.stamp_material()`: public values only, so a host can stamp for a device.
|
||||
pub fn destination_stamp_material(
|
||||
destination_hash: &[u8; 16],
|
||||
public_key: &[u8; 64],
|
||||
name_hash: &[u8; 10],
|
||||
) -> [u8; DESTINATION_STAMP_MATERIAL_LENGTH] {
|
||||
let mut material = [0u8; DESTINATION_STAMP_MATERIAL_LENGTH];
|
||||
material[..16].copy_from_slice(destination_hash);
|
||||
material[16..16 + PUBKEY_SIZE].copy_from_slice(public_key);
|
||||
material[16 + PUBKEY_SIZE..].copy_from_slice(name_hash);
|
||||
material
|
||||
}
|
||||
|
||||
/// Generate a destination stamp from public material alone, as
|
||||
/// `Destination._await_stamp` does (unexpanded workblock, 14-byte stamp).
|
||||
/// Returns the stamp and its value, or `None` when stopped by `ctl`.
|
||||
pub fn generate_destination_stamp(
|
||||
destination_hash: &[u8; 16],
|
||||
public_key: &[u8; 64],
|
||||
name_hash: &[u8; 10],
|
||||
target_value: f64,
|
||||
ctl: &crate::stamps::StampControl,
|
||||
) -> Result<Option<([u8; crate::stamps::NETWORK_STAMP_SIZE], f64)>, crate::stamps::StampError> {
|
||||
let material = destination_stamp_material(destination_hash, public_key, name_hash);
|
||||
let generated = crate::stamps::generate_stamp(
|
||||
&material,
|
||||
target_value,
|
||||
0,
|
||||
crate::stamps::NETWORK_STAMP_SIZE,
|
||||
ctl,
|
||||
)?;
|
||||
Ok(generated.map(|(stamp, value)| {
|
||||
let stamp = stamp
|
||||
.try_into()
|
||||
.expect("generated with the network stamp size");
|
||||
(stamp, value)
|
||||
}))
|
||||
}
|
||||
|
||||
/// A known-format stamp extension, borrowed from the announce app_data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AnnounceExt<'a> {
|
||||
pub flags: u8,
|
||||
pub stamp: &'a [u8; crate::stamps::NETWORK_STAMP_SIZE],
|
||||
pub lr_cost: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum AnnounceExtParse<'a> {
|
||||
/// Fewer than 18 bytes of app_data.
|
||||
Absent,
|
||||
/// Wrong marker, reserved anchor bit set, or lr_cost above the cap.
|
||||
Unknown,
|
||||
Present(AnnounceExt<'a>),
|
||||
}
|
||||
|
||||
/// Parse the last 18 bytes of app_data as a stamp extension (Identity.py).
|
||||
pub fn parse_announce_ext(app_data: Option<&[u8]>) -> AnnounceExtParse<'_> {
|
||||
let Some(app_data) = app_data else {
|
||||
return AnnounceExtParse::Absent;
|
||||
};
|
||||
if app_data.len() < ANNOUNCE_EXT_LENGTH {
|
||||
return AnnounceExtParse::Absent;
|
||||
}
|
||||
let ext = &app_data[app_data.len() - ANNOUNCE_EXT_LENGTH..];
|
||||
let anchor = ext[ANNOUNCE_EXT_LENGTH - 1];
|
||||
let extended = anchor & 0x80 != 0;
|
||||
let lr_cost = crate::stamps::cost_from_bytes([anchor & 0x7F, ext[ANNOUNCE_EXT_LENGTH - 2]]);
|
||||
if ext[0] != ANNOUNCE_EXT_MARKER || extended || lr_cost > crate::stamps::STAMP_COST_CAP {
|
||||
return AnnounceExtParse::Unknown;
|
||||
}
|
||||
let stamp = ext[ANNOUNCE_EXT_HEADER_LENGTH
|
||||
..ANNOUNCE_EXT_HEADER_LENGTH + crate::stamps::NETWORK_STAMP_SIZE]
|
||||
.try_into()
|
||||
.expect("slice is exactly the stamp length");
|
||||
AnnounceExtParse::Present(AnnounceExt {
|
||||
flags: ext[1],
|
||||
stamp,
|
||||
lr_cost,
|
||||
})
|
||||
}
|
||||
|
||||
/// Outcome of the announce stamp check, as upstream records it.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct AnnounceStampCheck {
|
||||
/// A known-format extension was present.
|
||||
pub stamped: bool,
|
||||
/// The stamp met the required value; the extension is stripped.
|
||||
pub validated: bool,
|
||||
/// Recorded for any known-format extension, valid or not.
|
||||
pub stamp: Option<[u8; crate::stamps::NETWORK_STAMP_SIZE]>,
|
||||
pub value: Option<f64>,
|
||||
/// Recorded only when the stamp is valid.
|
||||
pub lr_cost: Option<f64>,
|
||||
}
|
||||
|
||||
impl AnnounceStampCheck {
|
||||
/// The app_data upstream remembers and hands to handlers: the extension is
|
||||
/// removed only when the stamp validated, and empty app_data becomes `None`.
|
||||
pub fn app_data<'a>(&self, raw_app_data: Option<&'a [u8]>) -> Option<&'a [u8]> {
|
||||
let data = raw_app_data?;
|
||||
let data = if self.validated {
|
||||
&data[..data.len() - ANNOUNCE_EXT_LENGTH]
|
||||
} else {
|
||||
data
|
||||
};
|
||||
(!data.is_empty()).then_some(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl AnnounceData {
|
||||
/// Check the stamp extension against `required_value` (Identity.py).
|
||||
/// The workblock is `destination_hash || public_key || name_hash`, unexpanded.
|
||||
pub fn check_stamp(
|
||||
&self,
|
||||
destination_hash: &[u8; 16],
|
||||
required_value: f64,
|
||||
) -> AnnounceStampCheck {
|
||||
let mut check = AnnounceStampCheck::default();
|
||||
let AnnounceExtParse::Present(ext) = parse_announce_ext(self.app_data.as_deref()) else {
|
||||
return check;
|
||||
};
|
||||
check.stamped = true;
|
||||
check.stamp = Some(*ext.stamp);
|
||||
let material =
|
||||
destination_stamp_material(destination_hash, &self.public_key, &self.name_hash);
|
||||
match crate::stamps::stamp_valid(ext.stamp, required_value, &material) {
|
||||
Ok(valid) => {
|
||||
check.value = Some(crate::stamps::stamp_value(&material, ext.stamp));
|
||||
if valid {
|
||||
check.validated = true;
|
||||
check.lr_cost = Some(ext.lr_cost);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!(error = %e, "announce stamp parsing failed"),
|
||||
}
|
||||
check
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -302,6 +502,21 @@ mod tests {
|
||||
assert_eq!(validated_id.hash, id.hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_wire_time_uses_exact_40_bit_value() {
|
||||
let id = Identity::new();
|
||||
let wire_time = 0x12_3456_789Au64;
|
||||
let announce = AnnounceData::create_at(&id, "test.time", None, None, wire_time).unwrap();
|
||||
assert_eq!(&announce.random_hash[5..], &wire_time.to_be_bytes()[3..]);
|
||||
|
||||
let maximum = AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX);
|
||||
assert!(maximum.is_ok());
|
||||
assert!(matches!(
|
||||
AnnounceData::create_at(&id, "test.time", None, None, ANNOUNCE_TIME_MAX + 1,),
|
||||
Err(AnnounceError::InvalidWireTime(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_and_validate_with_ratchet() {
|
||||
let id = Identity::new();
|
||||
@@ -408,6 +623,91 @@ mod tests {
|
||||
assert!(announce.validate_with_known_key(&dest_hash, None).is_ok());
|
||||
}
|
||||
|
||||
fn ext(marker: u8, anchor: u8, frac: u8) -> Vec<u8> {
|
||||
let mut data = b"app".to_vec();
|
||||
data.extend_from_slice(&[marker, 0x00]);
|
||||
data.extend_from_slice(&[0x5A; 14]);
|
||||
data.extend_from_slice(&[frac, anchor]);
|
||||
data
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_needs_eighteen_trailing_bytes() {
|
||||
assert_eq!(parse_announce_ext(None), AnnounceExtParse::Absent);
|
||||
let data = ext(ANNOUNCE_EXT_MARKER, 12, 0x80);
|
||||
assert_eq!(
|
||||
parse_announce_ext(Some(&data[4..])),
|
||||
AnnounceExtParse::Absent
|
||||
);
|
||||
assert!(matches!(
|
||||
parse_announce_ext(Some(&data[3..])),
|
||||
AnnounceExtParse::Present(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
parse_announce_ext(Some(&data)),
|
||||
AnnounceExtParse::Present(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_fields_are_read_from_the_tail() {
|
||||
let data = ext(ANNOUNCE_EXT_MARKER, 12, 0x80);
|
||||
let AnnounceExtParse::Present(parsed) = parse_announce_ext(Some(&data)) else {
|
||||
panic!("extension not parsed");
|
||||
};
|
||||
assert_eq!(parsed.stamp, &[0x5A; 14]);
|
||||
assert_eq!(parsed.lr_cost, 12.5);
|
||||
assert_eq!(parsed.flags, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_marker_reserved_bit_and_excess_cost_are_unknown_format() {
|
||||
for data in [
|
||||
ext(0xC0, 12, 0),
|
||||
ext(ANNOUNCE_EXT_MARKER, 0x80 | 12, 0),
|
||||
ext(ANNOUNCE_EXT_MARKER, 100, 1),
|
||||
] {
|
||||
assert_eq!(parse_announce_ext(Some(&data)), AnnounceExtParse::Unknown);
|
||||
}
|
||||
assert!(matches!(
|
||||
parse_announce_ext(Some(&ext(ANNOUNCE_EXT_MARKER, 100, 0))),
|
||||
AnnounceExtParse::Present(p) if p.lr_cost == 100.0
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_stamp_is_recorded_but_app_data_is_kept() {
|
||||
let id = Identity::new();
|
||||
let data = ext(ANNOUNCE_EXT_MARKER, 12, 0x80);
|
||||
let announce = AnnounceData::create(&id, "test.stamp", Some(&data), None).unwrap();
|
||||
let dest = crate::destination::Destination::hash_from_name_and_identity(
|
||||
"test.stamp",
|
||||
Some(&id.hash),
|
||||
);
|
||||
let check = announce.check_stamp(&dest, 100.0);
|
||||
assert!(check.stamped && !check.validated);
|
||||
assert_eq!(check.stamp, Some([0x5A; 14]));
|
||||
assert!(check.value.is_some());
|
||||
assert_eq!(check.lr_cost, None);
|
||||
assert_eq!(check.app_data(Some(&data)), Some(&data[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_stamp_strips_extension_and_records_link_cost() {
|
||||
let id = Identity::new();
|
||||
let data = ext(ANNOUNCE_EXT_MARKER, 12, 0x80);
|
||||
let announce = AnnounceData::create(&id, "test.stamp", Some(&data), None).unwrap();
|
||||
let dest = crate::destination::Destination::hash_from_name_and_identity(
|
||||
"test.stamp",
|
||||
Some(&id.hash),
|
||||
);
|
||||
let check = announce.check_stamp(&dest, 0.0);
|
||||
assert!(check.stamped && check.validated);
|
||||
assert_eq!(check.lr_cost, Some(12.5));
|
||||
assert_eq!(check.app_data(Some(&data)), Some(&b"app"[..]));
|
||||
assert_eq!(check.app_data(Some(&data[3..])), None);
|
||||
}
|
||||
|
||||
use proptest::prelude::*;
|
||||
|
||||
type AnnounceBytes = (
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
//! Durable control-plane state for ratcheted announces.
|
||||
//!
|
||||
//! The signed Python-compatible ratchet ring contains only private keys. This
|
||||
//! sidecar deliberately keeps local policy metadata separate: the last wall
|
||||
//! time used for rotation and the last 40-bit value emitted on the wire.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::announce::ANNOUNCE_TIME_MAX;
|
||||
use crate::identity::Identity;
|
||||
use crate::persistence;
|
||||
|
||||
const CONTROL_STATE_VERSION: u8 = 1;
|
||||
const CONTROL_STATE_MAX_BYTES: usize = 4096;
|
||||
|
||||
fn invalid_data(message: impl Into<String>) -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, message.into())
|
||||
}
|
||||
|
||||
/// Signed, identity- and destination-bound state used to plan a ratcheted
|
||||
/// announce without mutating live state before persistence succeeds.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RatchetControlState {
|
||||
identity_hash: [u8; 16],
|
||||
destination_hash: [u8; 16],
|
||||
last_rotation_wall: Option<u64>,
|
||||
last_announce_wire: Option<u64>,
|
||||
}
|
||||
|
||||
impl RatchetControlState {
|
||||
pub fn new(identity_hash: [u8; 16], destination_hash: [u8; 16]) -> Self {
|
||||
Self {
|
||||
identity_hash,
|
||||
destination_hash,
|
||||
last_rotation_wall: None,
|
||||
last_announce_wire: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn identity_hash(&self) -> [u8; 16] {
|
||||
self.identity_hash
|
||||
}
|
||||
|
||||
pub fn destination_hash(&self) -> [u8; 16] {
|
||||
self.destination_hash
|
||||
}
|
||||
|
||||
pub fn last_rotation_wall(&self) -> Option<u64> {
|
||||
self.last_rotation_wall
|
||||
}
|
||||
|
||||
pub fn last_announce_wire(&self) -> Option<u64> {
|
||||
self.last_announce_wire
|
||||
}
|
||||
|
||||
/// Anchor unknown rotation age at the current wall time. Existing age is
|
||||
/// never overwritten by this operation.
|
||||
pub fn anchor_rotation_if_unknown(&mut self, wall_now: u64) {
|
||||
if self.last_rotation_wall.is_none() {
|
||||
self.last_rotation_wall = Some(wall_now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rotation is due only when an age anchor exists and the wall clock has
|
||||
/// advanced by the full interval. Clock rollback never looks elapsed.
|
||||
pub fn rotation_due(&self, wall_now: u64, interval_secs: u64) -> bool {
|
||||
self.last_rotation_wall
|
||||
.is_some_and(|last| wall_now >= last && wall_now.saturating_sub(last) >= interval_secs)
|
||||
}
|
||||
|
||||
/// Return a cloned candidate recording the supplied rotation time.
|
||||
/// The caller performs the rotation and persists the candidate.
|
||||
pub fn with_rotation_at(&self, wall_now: u64) -> Self {
|
||||
let mut candidate = self.clone();
|
||||
candidate.last_rotation_wall = Some(wall_now);
|
||||
candidate
|
||||
}
|
||||
|
||||
/// Prepare the next wire-ordering value without mutating this live state.
|
||||
///
|
||||
/// `None` means wall time has not advanced beyond the last durable value;
|
||||
/// callers must coalesce/defer instead of inventing `last + 1`, which could
|
||||
/// make an announce appear to come from the future.
|
||||
pub fn prepare_announce(&self, wall_now: u64) -> std::io::Result<Option<Self>> {
|
||||
if wall_now > ANNOUNCE_TIME_MAX {
|
||||
return Err(invalid_data(format!(
|
||||
"wall time {wall_now} exceeds 40-bit announce field"
|
||||
)));
|
||||
}
|
||||
if self.last_announce_wire.is_some_and(|last| wall_now <= last) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut candidate = self.clone();
|
||||
candidate.last_announce_wire = Some(wall_now);
|
||||
Ok(Some(candidate))
|
||||
}
|
||||
|
||||
/// Persist this state as a signed, bounded MessagePack envelope.
|
||||
pub fn save_verified(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
|
||||
self.save_verified_impl(path, identity, false)
|
||||
}
|
||||
|
||||
/// Persist announce ordering through [`persistence::durable_write`].
|
||||
/// The caller must wait for success before releasing the corresponding
|
||||
/// wire bytes and must handle the storage limits documented by that helper.
|
||||
pub fn save_verified_durable(&self, path: &Path, identity: &Identity) -> std::io::Result<()> {
|
||||
self.save_verified_impl(path, identity, true)
|
||||
}
|
||||
|
||||
fn save_verified_impl(
|
||||
&self,
|
||||
path: &Path,
|
||||
identity: &Identity,
|
||||
durable: bool,
|
||||
) -> std::io::Result<()> {
|
||||
if identity.hash != self.identity_hash {
|
||||
return Err(invalid_data("control state identity binding mismatch"));
|
||||
}
|
||||
self.validate()?;
|
||||
|
||||
let body = ControlStateBody {
|
||||
version: CONTROL_STATE_VERSION,
|
||||
identity_hash: self.identity_hash.to_vec(),
|
||||
destination_hash: self.destination_hash.to_vec(),
|
||||
last_rotation_wall: self.last_rotation_wall,
|
||||
last_announce_wire: self.last_announce_wire,
|
||||
};
|
||||
let packed = Zeroizing::new(
|
||||
rmp_serde::to_vec_named(&body).map_err(|e| std::io::Error::other(e.to_string()))?,
|
||||
);
|
||||
let signature = identity.sign(&packed).ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"identity cannot sign ratchet control state",
|
||||
)
|
||||
})?;
|
||||
let envelope = ControlStateEnvelope {
|
||||
signature: signature.to_vec(),
|
||||
state: packed.to_vec(),
|
||||
};
|
||||
let encoded = Zeroizing::new(
|
||||
rmp_serde::to_vec_named(&envelope).map_err(|e| std::io::Error::other(e.to_string()))?,
|
||||
);
|
||||
if encoded.len() > CONTROL_STATE_MAX_BYTES {
|
||||
return Err(invalid_data("ratchet control state exceeds size limit"));
|
||||
}
|
||||
if durable {
|
||||
persistence::durable_write(path, &encoded)
|
||||
.map(|_| ())
|
||||
.map_err(std::io::Error::other)
|
||||
} else {
|
||||
persistence::atomic_write(path, &encoded)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load and verify state for exactly `identity` and `destination_hash`.
|
||||
pub fn load_verified(
|
||||
path: &Path,
|
||||
identity: &Identity,
|
||||
destination_hash: [u8; 16],
|
||||
) -> std::io::Result<Self> {
|
||||
let encoded = Zeroizing::new(
|
||||
persistence::read_file_bounded(path, CONTROL_STATE_MAX_BYTES)?
|
||||
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?,
|
||||
);
|
||||
let envelope: ControlStateEnvelope =
|
||||
rmp_serde::from_slice(&encoded).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
if envelope.signature.len() != 64 {
|
||||
return Err(invalid_data("invalid control-state signature length"));
|
||||
}
|
||||
let signature: [u8; 64] = envelope
|
||||
.signature
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| invalid_data("invalid control-state signature length"))?;
|
||||
let packed = Zeroizing::new(envelope.state);
|
||||
if !identity.verify(&packed, &signature) {
|
||||
return Err(invalid_data("invalid ratchet control-state signature"));
|
||||
}
|
||||
|
||||
let body: ControlStateBody =
|
||||
rmp_serde::from_slice(&packed).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
if body.version != CONTROL_STATE_VERSION {
|
||||
return Err(invalid_data(format!(
|
||||
"unsupported ratchet control-state version {}",
|
||||
body.version
|
||||
)));
|
||||
}
|
||||
let identity_hash: [u8; 16] = body
|
||||
.identity_hash
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| invalid_data("invalid control-state identity hash"))?;
|
||||
let stored_destination: [u8; 16] = body
|
||||
.destination_hash
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| invalid_data("invalid control-state destination hash"))?;
|
||||
if identity_hash != identity.hash {
|
||||
return Err(invalid_data("control state belongs to another identity"));
|
||||
}
|
||||
if stored_destination != destination_hash {
|
||||
return Err(invalid_data("control state belongs to another destination"));
|
||||
}
|
||||
|
||||
let state = Self {
|
||||
identity_hash,
|
||||
destination_hash: stored_destination,
|
||||
last_rotation_wall: body.last_rotation_wall,
|
||||
last_announce_wire: body.last_announce_wire,
|
||||
};
|
||||
state.validate()?;
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn validate(&self) -> std::io::Result<()> {
|
||||
if self
|
||||
.last_announce_wire
|
||||
.is_some_and(|value| value > ANNOUNCE_TIME_MAX)
|
||||
{
|
||||
return Err(invalid_data("stored announce time exceeds 40-bit field"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ControlStateBody {
|
||||
version: u8,
|
||||
#[serde(with = "serde_bytes")]
|
||||
identity_hash: Vec<u8>,
|
||||
#[serde(with = "serde_bytes")]
|
||||
destination_hash: Vec<u8>,
|
||||
last_rotation_wall: Option<u64>,
|
||||
last_announce_wire: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ControlStateEnvelope {
|
||||
#[serde(with = "serde_bytes")]
|
||||
signature: Vec<u8>,
|
||||
#[serde(with = "serde_bytes")]
|
||||
state: Vec<u8>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn announce_time_never_moves_into_the_future() {
|
||||
let identity = Identity::new();
|
||||
let destination = [0x22; 16];
|
||||
let state = RatchetControlState::new(identity.hash, destination);
|
||||
let state = state.prepare_announce(100).unwrap().unwrap();
|
||||
assert_eq!(state.last_announce_wire(), Some(100));
|
||||
assert!(state.prepare_announce(100).unwrap().is_none());
|
||||
assert!(state.prepare_announce(99).unwrap().is_none());
|
||||
let next = state.prepare_announce(101).unwrap().unwrap();
|
||||
assert_eq!(next.last_announce_wire(), Some(101));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_rotation_age_is_anchored_without_immediate_rotation() {
|
||||
let identity = Identity::new();
|
||||
let mut state = RatchetControlState::new(identity.hash, [0x33; 16]);
|
||||
assert!(!state.rotation_due(100, 30));
|
||||
state.anchor_rotation_if_unknown(100);
|
||||
assert!(!state.rotation_due(100, 30));
|
||||
assert!(!state.rotation_due(99, 30));
|
||||
assert!(!state.rotation_due(129, 30));
|
||||
assert!(state.rotation_due(130, 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_state_roundtrip_enforces_identity_and_destination_binding() {
|
||||
let dir = std::env::temp_dir().join("reticulum_ratchet_control_state");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("control");
|
||||
let identity = Identity::new();
|
||||
let wrong_identity = Identity::new();
|
||||
let destination = [0x44; 16];
|
||||
let mut state = RatchetControlState::new(identity.hash, destination);
|
||||
state.anchor_rotation_if_unknown(100);
|
||||
let state = state.prepare_announce(101).unwrap().unwrap();
|
||||
state.save_verified(&path, &identity).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
RatchetControlState::load_verified(&path, &identity, destination).unwrap(),
|
||||
state
|
||||
);
|
||||
assert!(RatchetControlState::load_verified(&path, &wrong_identity, destination).is_err());
|
||||
assert!(RatchetControlState::load_verified(&path, &identity, [0x55; 16]).is_err());
|
||||
assert!(
|
||||
path.exists(),
|
||||
"rejected state remains available for recovery"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_candidate_persistence_cannot_mutate_live_state() {
|
||||
let identity = Identity::new();
|
||||
let destination = [0x66; 16];
|
||||
let live = RatchetControlState::new(identity.hash, destination);
|
||||
let candidate = live.prepare_announce(100).unwrap().unwrap();
|
||||
let missing_parent = std::env::temp_dir()
|
||||
.join("reticulum_missing_control_parent")
|
||||
.join("nested")
|
||||
.join("state");
|
||||
let _ = std::fs::remove_dir_all(
|
||||
missing_parent
|
||||
.parent()
|
||||
.and_then(Path::parent)
|
||||
.unwrap_or_else(|| Path::new("/tmp")),
|
||||
);
|
||||
|
||||
assert!(candidate.save_verified(&missing_parent, &identity).is_err());
|
||||
assert_eq!(live.last_announce_wire(), None);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,15 +3,29 @@ use rns_crypto::hkdf::derive_key_64;
|
||||
use rns_crypto::sha::truncated_hash;
|
||||
use rns_crypto::token;
|
||||
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::Deserialize;
|
||||
use thiserror::Error;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
use crate::persistence;
|
||||
use crate::persistence::{self, SecretBytes};
|
||||
use crate::stamps::{self, StampControl, StampError};
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// HKDF-derived key length: 32 bytes AES key || 32 bytes HMAC key.
|
||||
/// Elliptic curve used for identity encryption and ratchets.
|
||||
pub const CURVE: &str = "Curve25519";
|
||||
/// Combined X25519 and Ed25519 public/private key size, in bits.
|
||||
pub const KEY_SIZE_BITS: usize = 512;
|
||||
/// X25519 ratchet key size, in bits.
|
||||
pub const RATCHET_SIZE_BITS: usize = 256;
|
||||
/// X25519 ratchet key size, in bytes (Python `Identity.RATCHETSIZE`).
|
||||
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
|
||||
/// Addressable identity hash size, in bits.
|
||||
pub const HASH_LENGTH_BITS: usize = 128;
|
||||
/// Ratchet identifier size, in bytes.
|
||||
pub const RATCHET_ID_LENGTH: usize = 10;
|
||||
/// HKDF-derived token key length: 32-byte HMAC key || 32-byte AES key.
|
||||
pub const DERIVED_KEY_LENGTH: usize = 64;
|
||||
|
||||
/// Per-message overhead of `Identity::encrypt` before PKCS7 padding:
|
||||
@@ -28,6 +42,8 @@ pub enum IdentityError {
|
||||
VerificationFailed,
|
||||
#[error("decryption failed")]
|
||||
DecryptionFailed,
|
||||
#[error("encryption failed")]
|
||||
EncryptionFailed,
|
||||
#[error("ed25519 error: {0}")]
|
||||
Ed25519(#[from] Ed25519Error),
|
||||
#[error("io error: {0}")]
|
||||
@@ -44,7 +60,8 @@ pub trait LocalKeyBackend: Send + Sync {
|
||||
/// X25519 ECDH shared secret with `peer_pub`, or `None` if unavailable.
|
||||
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]>;
|
||||
/// Drop any cached authentication so the next operation must re-authenticate
|
||||
/// (e.g. a hardware token re-locks its PIN). No-op for software backends.
|
||||
/// (e.g. a hardware token re-locks its PIN). The default is a no-op;
|
||||
/// backends with cached authentication must implement their own reset.
|
||||
fn lock(&self) {}
|
||||
}
|
||||
|
||||
@@ -54,6 +71,10 @@ pub trait LocalKeyBackend: Send + Sync {
|
||||
/// - Private (64 B): `X25519_prv(32) || Ed25519_seed(32)`
|
||||
/// - Public (64 B): `X25519_pub(32) || Ed25519_pub(32)`
|
||||
/// - Hash (16 B): `SHA-256(public_64)[:16]`
|
||||
///
|
||||
/// Public-only identities can verify and encrypt. Hardware-backed identities
|
||||
/// delegate private operations without exposing a software private key. Keep
|
||||
/// the public `hash` unchanged: encryption derivation uses it as the HKDF salt.
|
||||
pub struct Identity {
|
||||
prv: Option<X25519PrivateKey>,
|
||||
sig_prv: Option<Ed25519PrivateKey>,
|
||||
@@ -64,6 +85,15 @@ pub struct Identity {
|
||||
backend: Option<Arc<dyn LocalKeyBackend>>,
|
||||
}
|
||||
|
||||
/// Successful identity decryption plus the ratchet that authenticated it.
|
||||
///
|
||||
/// `ratchet_id` is absent when the identity's base key performed decryption.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DecryptionResult {
|
||||
pub plaintext: Vec<u8>,
|
||||
pub ratchet_id: Option<[u8; RATCHET_ID_LENGTH]>,
|
||||
}
|
||||
|
||||
impl Clone for Identity {
|
||||
/// Software identities clone their key material; hardware-backed identities
|
||||
/// share the same `LocalKeyBackend` (Arc) — there is no extractable key to copy.
|
||||
@@ -92,6 +122,13 @@ impl Default for Identity {
|
||||
}
|
||||
|
||||
impl Identity {
|
||||
pub const CURVE: &'static str = CURVE;
|
||||
pub const KEY_SIZE_BITS: usize = KEY_SIZE_BITS;
|
||||
pub const RATCHET_SIZE_BITS: usize = RATCHET_SIZE_BITS;
|
||||
pub const RATCHETSIZE: usize = RATCHET_SIZE_BITS / 8;
|
||||
pub const HASH_LENGTH_BITS: usize = HASH_LENGTH_BITS;
|
||||
|
||||
/// Generate a software identity with fresh X25519 and Ed25519 keys.
|
||||
pub fn new() -> Self {
|
||||
let prv = X25519PrivateKey::generate();
|
||||
let sig_prv = Ed25519PrivateKey::generate();
|
||||
@@ -109,6 +146,35 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a software identity whose X25519 key stamps its Ed25519
|
||||
/// public key with at least `value` (Python `Identity(value=...)`).
|
||||
/// Returns `None` when the search is cancelled or passes its deadline.
|
||||
pub fn new_with_value(value: f64, ctl: &StampControl) -> Result<Option<Self>, StampError> {
|
||||
let sig_prv = Ed25519PrivateKey::generate();
|
||||
let sig_pub = sig_prv.public_key();
|
||||
let Some(key) = stamps::generate_stamped_key(&sig_pub.to_bytes(), value, ctl)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let pub_key = key.private.public_key();
|
||||
let hash = Self::compute_hash(&pub_key, &sig_pub);
|
||||
Ok(Some(Self {
|
||||
prv: Some(key.private),
|
||||
sig_prv: Some(sig_prv),
|
||||
pub_key,
|
||||
sig_pub,
|
||||
hash,
|
||||
backend: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Stamp value of the X25519 public key over the Ed25519 public key
|
||||
/// (Python `Identity.get_value`).
|
||||
pub fn get_value(&self) -> f64 {
|
||||
stamps::stamp_value(&self.sig_pub.to_bytes(), &self.pub_key.to_bytes())
|
||||
}
|
||||
|
||||
/// Load exactly 64 bytes: an X25519 private key followed by an Ed25519 seed.
|
||||
/// The caller remains responsible for protecting and wiping its input.
|
||||
pub fn from_private_key(key: &[u8]) -> Result<Self, IdentityError> {
|
||||
if key.len() != 64 {
|
||||
return Err(IdentityError::InvalidPrivateKeyLength(key.len()));
|
||||
@@ -135,6 +201,8 @@ impl Identity {
|
||||
}
|
||||
|
||||
/// Construct a verify/encrypt-only identity from its 64-byte public key.
|
||||
/// Checks the length and Ed25519 key encoding; it does not establish who
|
||||
/// owns the key or reject low-order X25519 input.
|
||||
pub fn from_public_key(key: &[u8]) -> Result<Self, IdentityError> {
|
||||
if key.len() != 64 {
|
||||
return Err(IdentityError::InvalidPublicKeyLength(key.len()));
|
||||
@@ -160,7 +228,9 @@ impl Identity {
|
||||
|
||||
/// Construct an identity whose private operations are served by `backend`
|
||||
/// (e.g. a hardware token). Public-key-only in memory; `sign` and `decrypt`
|
||||
/// delegate to the backend. Wire-identical to a software identity.
|
||||
/// delegate to the backend for base-key operations. The caller must ensure
|
||||
/// the backend owns the matching private keys and implements the trait
|
||||
/// contract; construction does not perform a signing or ECDH challenge.
|
||||
pub fn from_backend(
|
||||
public_key: &[u8],
|
||||
backend: Arc<dyn LocalKeyBackend>,
|
||||
@@ -170,12 +240,16 @@ impl Identity {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Load an identity from file, accepting either the current msgpack envelope
|
||||
/// or a legacy raw 64-byte private key.
|
||||
/// Load an identity from file, accepting either the raw 64-byte private key
|
||||
/// that Python and [`Self::to_file`] write, or the older msgpack envelope.
|
||||
/// A file larger than 1 KiB is refused once 1025 bytes have been read.
|
||||
pub fn from_file(path: &Path) -> Result<Self, IdentityError> {
|
||||
let data = std::fs::read(path)?;
|
||||
let data = persistence::read_secret_file(path, IDENTITY_FILE_MAX_BYTES)?;
|
||||
|
||||
if let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data) {
|
||||
// An envelope never fits in 64 bytes, so a raw key is never parsed as one.
|
||||
if data.len() != 64
|
||||
&& let Ok(persisted) = rmp_serde::from_slice::<IdentityPersisted>(&data)
|
||||
{
|
||||
return Self::from_private_key(&persisted.private_key);
|
||||
}
|
||||
|
||||
@@ -183,7 +257,9 @@ impl Identity {
|
||||
}
|
||||
|
||||
/// Persist the identity as the raw 64-byte private key used by the Python
|
||||
/// reference implementation, so identity files are interchangeable.
|
||||
/// reference implementation. This is an unencrypted secret-key file.
|
||||
/// Fails for public-only and hardware-backed identities because their
|
||||
/// private key is not extractable here. Uses [`persistence::atomic_write`].
|
||||
pub fn to_file(&self, path: &Path) -> Result<(), IdentityError> {
|
||||
let key = self
|
||||
.get_private_key()
|
||||
@@ -198,7 +274,8 @@ impl Identity {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the 64-byte private key (`X25519_prv || Ed25519_seed`), zeroised on drop.
|
||||
/// Return a copy of the software private key (`X25519_prv || Ed25519_seed`),
|
||||
/// zeroised on drop. Returns `None` for public-only or backend identities.
|
||||
pub fn get_private_key(&self) -> Option<Zeroizing<[u8; 64]>> {
|
||||
let prv = self.prv.as_ref()?;
|
||||
let sig_prv = self.sig_prv.as_ref()?;
|
||||
@@ -216,6 +293,13 @@ impl Identity {
|
||||
key
|
||||
}
|
||||
|
||||
/// Lowercase, delimiter-free hexadecimal identity hash.
|
||||
pub fn hexhash(&self) -> String {
|
||||
hex::encode(self.hash)
|
||||
}
|
||||
|
||||
/// Whether both software private keys are present. A hardware-backed
|
||||
/// identity returns false even when its backend can sign or decrypt.
|
||||
pub fn has_private_key(&self) -> bool {
|
||||
self.prv.is_some() && self.sig_prv.is_some()
|
||||
}
|
||||
@@ -225,14 +309,16 @@ impl Identity {
|
||||
self.backend.is_some()
|
||||
}
|
||||
|
||||
/// Re-lock the hardware backend (drop its cached authentication). No-op for
|
||||
/// software identities. The next private operation will fail until re-auth.
|
||||
/// Ask the backend to clear cached authentication; a no-op without a backend.
|
||||
/// Subsequent authentication behavior is defined by [`LocalKeyBackend::lock`].
|
||||
pub fn lock(&self) {
|
||||
if let Some(b) = self.backend.as_ref() {
|
||||
b.lock();
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy the software signing key; returns `None` for public-only and
|
||||
/// backend identities. Use [`Self::sign`] to support either private backend.
|
||||
pub fn get_signing_key(&self) -> Option<Ed25519PrivateKey> {
|
||||
self.sig_prv
|
||||
.as_ref()
|
||||
@@ -248,6 +334,7 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify an Ed25519 signature with this identity's public signing key.
|
||||
pub fn verify(&self, message: &[u8], signature: &[u8; 64]) -> bool {
|
||||
self.sig_pub.verify(message, signature).is_ok()
|
||||
}
|
||||
@@ -257,8 +344,10 @@ impl Identity {
|
||||
/// Output layout: `ephemeral_X25519_pub(32) || IV(16) || AES-256-CBC(PKCS7(pt)) || HMAC(32)`.
|
||||
///
|
||||
/// Passing a `ratchet` public key substitutes it for the identity's X25519
|
||||
/// public key in the ECDH, giving forward secrecy against later key
|
||||
/// compromise.
|
||||
/// public key in ECDH. Later compromise of the base identity key alone
|
||||
/// does not reveal that ciphertext; compromise of a retained ratchet
|
||||
/// private key still does. The caller must authenticate the target key.
|
||||
/// Encryption does not sign the plaintext or identify its sender.
|
||||
pub fn encrypt(
|
||||
&self,
|
||||
plaintext: &[u8],
|
||||
@@ -272,13 +361,15 @@ impl Identity {
|
||||
None => self.pub_key.clone(),
|
||||
};
|
||||
|
||||
let mut shared = ephemeral.exchange(&target);
|
||||
let mut shared = ephemeral
|
||||
.exchange(&target)
|
||||
.map_err(|_| IdentityError::EncryptionFailed)?;
|
||||
let derived =
|
||||
derive_key_64(&shared, &self.hash).map_err(|_| IdentityError::DecryptionFailed);
|
||||
shared.zeroize();
|
||||
let derived = derived?;
|
||||
let ciphertext =
|
||||
token::encrypt(plaintext, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
|
||||
token::encrypt(plaintext, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
|
||||
|
||||
let mut result = Vec::with_capacity(32 + ciphertext.len());
|
||||
result.extend_from_slice(&ephemeral_pub.to_bytes());
|
||||
@@ -294,6 +385,21 @@ impl Identity {
|
||||
ratchets: Option<&[&[u8; 32]]>,
|
||||
enforce_ratchets: bool,
|
||||
) -> Result<Vec<u8>, IdentityError> {
|
||||
self.decrypt_with_ratchet_id(ciphertext, ratchets, enforce_ratchets)
|
||||
.map(|result| result.plaintext)
|
||||
}
|
||||
|
||||
/// Decrypt ciphertext and report the ratchet key that authenticated it.
|
||||
///
|
||||
/// The identifier is `SHA-256(ratchet_public_key)[:10]`, matching the
|
||||
/// reference implementation. Base-identity decryption returns no ratchet
|
||||
/// identifier.
|
||||
pub fn decrypt_with_ratchet_id(
|
||||
&self,
|
||||
ciphertext: &[u8],
|
||||
ratchets: Option<&[&[u8; 32]]>,
|
||||
enforce_ratchets: bool,
|
||||
) -> Result<DecryptionResult, IdentityError> {
|
||||
if ciphertext.len() < 32 {
|
||||
return Err(IdentityError::DecryptionFailed);
|
||||
}
|
||||
@@ -306,13 +412,18 @@ impl Identity {
|
||||
if let Some(ratchets) = ratchets {
|
||||
for ratchet in ratchets {
|
||||
let ratchet_prv = X25519PrivateKey::from_bytes(ratchet);
|
||||
let mut shared = ratchet_prv.exchange(&peer_pub);
|
||||
let Ok(mut shared) = ratchet_prv.exchange(&peer_pub) else {
|
||||
continue;
|
||||
};
|
||||
let derived_result = derive_key_64(&shared, &self.hash);
|
||||
shared.zeroize();
|
||||
if let Ok(derived) = derived_result {
|
||||
if let Ok(plaintext) = token::decrypt(ct, &derived) {
|
||||
return Ok(plaintext);
|
||||
}
|
||||
if let Ok(derived) = derived_result
|
||||
&& let Ok(plaintext) = token::decrypt(ct, &derived[..])
|
||||
{
|
||||
return Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: Some(Self::ratchet_id(&ratchet_prv.public_key().to_bytes())),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -324,9 +435,11 @@ impl Identity {
|
||||
// Identity-key ECDH: in-memory key if present, else the hardware backend.
|
||||
let mut shared: [u8; 32] = if let Some(prv) = self.prv.as_ref() {
|
||||
prv.exchange(&peer_pub)
|
||||
.map_err(|_| IdentityError::DecryptionFailed)?
|
||||
} else if let Some(backend) = self.backend.as_ref() {
|
||||
backend
|
||||
.ecdh(&peer_pub_bytes)
|
||||
.filter(|shared| shared.iter().any(|byte| *byte != 0))
|
||||
.ok_or(IdentityError::DecryptionFailed)?
|
||||
} else {
|
||||
return Err(IdentityError::DecryptionFailed);
|
||||
@@ -336,14 +449,26 @@ impl Identity {
|
||||
shared.zeroize();
|
||||
let derived = derived_result?;
|
||||
let plaintext =
|
||||
token::decrypt(ct, &derived).map_err(|_| IdentityError::DecryptionFailed)?;
|
||||
Ok(plaintext)
|
||||
token::decrypt(ct, &derived[..]).map_err(|_| IdentityError::DecryptionFailed)?;
|
||||
Ok(DecryptionResult {
|
||||
plaintext,
|
||||
ratchet_id: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Derive the stable 80-bit identifier for a ratchet public key.
|
||||
pub fn ratchet_id(ratchet_public_key: &[u8; 32]) -> [u8; RATCHET_ID_LENGTH] {
|
||||
let full = rns_crypto::sha::sha256(ratchet_public_key);
|
||||
let mut id = [0u8; RATCHET_ID_LENGTH];
|
||||
id.copy_from_slice(&full[..RATCHET_ID_LENGTH]);
|
||||
id
|
||||
}
|
||||
|
||||
/// Sign `packet_hash` and return proof bytes.
|
||||
///
|
||||
/// `implicit_proof = true` returns the 64-byte signature alone; `false`
|
||||
/// returns `packet_hash(32) || signature(64)` (96 bytes).
|
||||
/// returns `packet_hash || signature`. Pass a 32-byte packet hash for the
|
||||
/// 96-byte wire form; this method accepts other input lengths without validation.
|
||||
pub fn prove(
|
||||
&self,
|
||||
packet_hash: &[u8],
|
||||
@@ -371,10 +496,21 @@ impl Identity {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Identity {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(formatter, "<{}>", self.hexhash())
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity files are a raw key or a small envelope; reading stops one byte
|
||||
/// past this limit and refuses the file.
|
||||
const IDENTITY_FILE_MAX_BYTES: usize = 1024;
|
||||
|
||||
// Msgpack envelope wrapping the raw 64-byte private key on disk.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct IdentityPersisted {
|
||||
private_key: Vec<u8>,
|
||||
#[derive(Deserialize)]
|
||||
struct IdentityPersisted<'a> {
|
||||
#[serde(borrow)]
|
||||
private_key: SecretBytes<'a, IDENTITY_FILE_MAX_BYTES>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -384,6 +520,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_generate_identity() {
|
||||
let id = Identity::new();
|
||||
assert_eq!(Identity::CURVE, "Curve25519");
|
||||
assert_eq!(Identity::RATCHETSIZE, 32);
|
||||
assert!(id.has_private_key());
|
||||
assert_ne!(id.hash, [0u8; 16]);
|
||||
}
|
||||
@@ -443,8 +581,38 @@ mod tests {
|
||||
assert!(id.decrypt(&ct, None, false).is_err());
|
||||
|
||||
let ratchets: Vec<&[u8; 32]> = vec![&ratchet_prv_bytes];
|
||||
let pt = id.decrypt(&ct, Some(&ratchets), false).unwrap();
|
||||
assert_eq!(&pt, plaintext);
|
||||
let decrypted = id
|
||||
.decrypt_with_ratchet_id(&ct, Some(&ratchets), false)
|
||||
.unwrap();
|
||||
assert_eq!(&decrypted.plaintext, plaintext);
|
||||
assert_eq!(
|
||||
decrypted.ratchet_id,
|
||||
Some(Identity::ratchet_id(&ratchet_pub))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_identity_decryption_reports_no_ratchet() {
|
||||
let id = Identity::new();
|
||||
let ciphertext = id.encrypt(b"base identity", None).unwrap();
|
||||
let decrypted = id
|
||||
.decrypt_with_ratchet_id(&ciphertext, None, false)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(decrypted.plaintext, b"base identity");
|
||||
assert_eq!(decrypted.ratchet_id, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_metadata_and_display_match_wire_identity() {
|
||||
let id = Identity::new();
|
||||
|
||||
assert_eq!(CURVE, "Curve25519");
|
||||
assert_eq!(KEY_SIZE_BITS, id.get_public_key().len() * 8);
|
||||
assert_eq!(RATCHET_SIZE_BITS, 32 * 8);
|
||||
assert_eq!(HASH_LENGTH_BITS, id.hash.len() * 8);
|
||||
assert_eq!(id.hexhash(), hex::encode(id.hash));
|
||||
assert_eq!(id.to_string(), format!("<{}>", hex::encode(id.hash)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -492,6 +660,39 @@ mod tests {
|
||||
let _ = std::fs::remove_dir(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_keys_that_begin_like_an_envelope_load_as_raw_keys() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"reticulum_identity_test_envelope_prefix_{}",
|
||||
std::process::id()
|
||||
));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
// One-field msgpack arrays holding an empty array, 61 bytes of binary
|
||||
// that end exactly at byte 64, and three integers.
|
||||
let prefixes: [&[u8]; 3] = [&[0x91, 0x90], &[0x91, 0xc4, 0x3d], &[0x91, 0x93, 1, 2, 3]];
|
||||
let mut failures = Vec::new();
|
||||
for (index, prefix) in prefixes.into_iter().enumerate() {
|
||||
let mut key = [0u8; 64];
|
||||
for (offset, byte) in key.iter_mut().enumerate() {
|
||||
*byte = (offset as u8).wrapping_mul(37).wrapping_add(index as u8);
|
||||
}
|
||||
key[..prefix.len()].copy_from_slice(prefix);
|
||||
let expected = Identity::from_private_key(&key).unwrap();
|
||||
let path = dir.join(format!("identity-{index}"));
|
||||
std::fs::write(&path, key).unwrap();
|
||||
|
||||
match Identity::from_file(&path) {
|
||||
Ok(loaded) => {
|
||||
assert_eq!(loaded.hash, expected.hash, "prefix {prefix:02x?}");
|
||||
assert_eq!(*loaded.get_private_key().unwrap(), key);
|
||||
}
|
||||
Err(e) => failures.push(format!("prefix {prefix:02x?}: {e}")),
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
assert!(failures.is_empty(), "{failures:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_file_backward_compat_raw() {
|
||||
let dir = std::env::temp_dir().join("reticulum_identity_test_compat");
|
||||
@@ -573,7 +774,7 @@ mod tests {
|
||||
}
|
||||
fn ecdh(&self, peer_pub: &[u8; 32]) -> Option<[u8; 32]> {
|
||||
let peer = rns_crypto::x25519::X25519PublicKey::from_bytes(peer_pub);
|
||||
Some(self.x.exchange(&peer))
|
||||
self.x.exchange(&peer).ok()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+113
-10
@@ -1,9 +1,16 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use rns_crypto::hkdf::hkdf_sha256;
|
||||
use rns_crypto::sha::sha256;
|
||||
use thiserror::Error;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
// Fixed IFAC HKDF salt. Shared with the Python reference; changing it breaks interop.
|
||||
const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
|
||||
/// Fixed IFAC HKDF salt shared with the Python reference.
|
||||
///
|
||||
/// This is public for applications that need to derive or inspect
|
||||
/// Python-compatible IFAC material outside the runtime helper. Changing it
|
||||
/// would break interoperability.
|
||||
pub const IFAC_SALT: &str = "adf54d882c9a9b80771eb4995d702d4a3e733391b2a0f53f416d9f907e55cff8";
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum IfacError {
|
||||
@@ -17,13 +24,24 @@ pub enum IfacError {
|
||||
///
|
||||
/// `ifac_origin` concatenates `SHA-256(network_name)` and `SHA-256(passphrase)`
|
||||
/// for whichever fields are `Some(_)` (a `None` field is omitted, so `None`
|
||||
/// and `Some("")` differ), then HKDF-SHA256 expands it under the fixed salt.
|
||||
/// and `Some("")` differ). HKDF-SHA256 expands `SHA-256(ifac_origin)` under
|
||||
/// the fixed salt.
|
||||
/// First 32 bytes → X25519 private; second 32 → Ed25519 seed.
|
||||
pub fn derive_ifac_key(
|
||||
network_name: Option<&str>,
|
||||
passphrase: Option<&str>,
|
||||
) -> Result<[u8; 64], IfacError> {
|
||||
let mut ifac_origin = Vec::new();
|
||||
let mut key = [0u8; 64];
|
||||
derive_into(network_name, passphrase, &mut key)?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
fn derive_into(
|
||||
network_name: Option<&str>,
|
||||
passphrase: Option<&str>,
|
||||
key: &mut [u8; 64],
|
||||
) -> Result<(), IfacError> {
|
||||
let mut ifac_origin = Zeroizing::new(Vec::with_capacity(64));
|
||||
|
||||
if let Some(name) = network_name {
|
||||
ifac_origin.extend_from_slice(&sha256(name.as_bytes()));
|
||||
@@ -32,14 +50,60 @@ pub fn derive_ifac_key(
|
||||
ifac_origin.extend_from_slice(&sha256(key.as_bytes()));
|
||||
}
|
||||
|
||||
let ifac_origin_hash = sha256(&ifac_origin);
|
||||
let ifac_origin_hash = Zeroizing::new(sha256(&ifac_origin));
|
||||
|
||||
let salt = hex_decode(IFAC_SALT).ok_or(IfacError::InvalidSalt)?;
|
||||
|
||||
let derived = hkdf_sha256(64, &ifac_origin_hash, Some(&salt), None)?;
|
||||
let mut key = [0u8; 64];
|
||||
let derived = hkdf_sha256(64, &*ifac_origin_hash, Some(&salt), None)?;
|
||||
key.copy_from_slice(&derived);
|
||||
Ok(key)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A derived IFAC key in one heap allocation, wiped when its last clone
|
||||
/// drops. Clones share the allocation, so tables and queues that move or copy
|
||||
/// an interface's settings never copy the key.
|
||||
#[derive(Clone)]
|
||||
pub struct IfacKey(Arc<Zeroizing<[u8; 64]>>);
|
||||
|
||||
impl IfacKey {
|
||||
/// [`derive_ifac_key`], written straight into the shared allocation.
|
||||
pub fn derive(network_name: Option<&str>, passphrase: Option<&str>) -> Result<Self, IfacError> {
|
||||
let mut key = Arc::new(Zeroizing::new([0u8; 64]));
|
||||
derive_into(
|
||||
network_name,
|
||||
passphrase,
|
||||
Arc::get_mut(&mut key).expect("a new Arc is unique"),
|
||||
)?;
|
||||
Ok(Self(key))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<[u8; 64]> for IfacKey {
|
||||
fn from(key: [u8; 64]) -> Self {
|
||||
Self(Arc::new(Zeroizing::new(key)))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for IfacKey {
|
||||
type Target = [u8; 64];
|
||||
|
||||
fn deref(&self) -> &[u8; 64] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for IfacKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0[..] == other.0[..]
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for IfacKey {}
|
||||
|
||||
impl std::fmt::Debug for IfacKey {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("IfacKey(<redacted>)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the IFAC identity plus a self-signature over `SHA-256(ifac_key)`.
|
||||
@@ -60,13 +124,24 @@ pub fn derive_ifac_identity(
|
||||
Ok((identity, ifac_key, signature))
|
||||
}
|
||||
|
||||
/// Split IFAC key into `(signing_key, masking_key)`, each 32 bytes.
|
||||
/// The IFAC identity's signature over `SHA-256(ifac_key)`, which Python
|
||||
/// publishes as an interface's `ifac_signature`.
|
||||
pub fn ifac_signature(ifac_key: &[u8; 64]) -> Option<[u8; 64]> {
|
||||
crate::identity::Identity::from_private_key(ifac_key)
|
||||
.ok()?
|
||||
.sign(&sha256(ifac_key))
|
||||
}
|
||||
|
||||
/// Split the derived identity material into its first and second 32-byte halves.
|
||||
/// They are the X25519 private bytes and Ed25519 seed, respectively.
|
||||
/// IFAC packet masking uses the full 64-byte key as its HKDF salt; the first
|
||||
/// half is not a separate packet-signing key.
|
||||
pub fn split_ifac_key(key: &[u8; 64]) -> (&[u8], &[u8]) {
|
||||
(&key[..32], &key[32..])
|
||||
}
|
||||
|
||||
fn hex_decode(s: &str) -> Option<Vec<u8>> {
|
||||
if s.len() % 2 != 0 {
|
||||
if !s.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
(0..s.len())
|
||||
@@ -79,6 +154,17 @@ fn hex_decode(s: &str) -> Option<Vec<u8>> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_key_matches_the_derived_bytes() {
|
||||
let key = IfacKey::derive(Some("testnet"), Some("password")).unwrap();
|
||||
assert_eq!(
|
||||
*key,
|
||||
derive_ifac_key(Some("testnet"), Some("password")).unwrap()
|
||||
);
|
||||
assert_eq!(key, IfacKey::from(*key));
|
||||
assert_eq!(format!("{key:?}"), "IfacKey(<redacted>)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ifac_derivation_deterministic() {
|
||||
let key1 = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
|
||||
@@ -135,5 +221,22 @@ mod tests {
|
||||
|
||||
let key_hash = sha256(&ifac_key);
|
||||
assert!(identity.verify(&key_hash, &signature));
|
||||
assert_eq!(ifac_signature(&ifac_key), Some(signature));
|
||||
}
|
||||
|
||||
/// Upstream `Identity.from_bytes(key).sign(Identity.full_hash(key))` for
|
||||
/// the `ifac_testnet_password` vector key.
|
||||
#[test]
|
||||
fn ifac_signature_matches_upstream() {
|
||||
let key = derive_ifac_key(Some("testnet"), Some("password")).unwrap();
|
||||
let expected = hex_decode(
|
||||
"ce6b8bc4028852077243868e4b5f7faadb715c7a2fb75d1a211d30035f65b0c1\
|
||||
fc4271ef61e91599e7bcc42723afe97503e3c432b01264185233274e3603e708",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ifac_signature(&key).unwrap().as_slice(),
|
||||
expected.as_slice()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,8 @@ use std::path::Path;
|
||||
use crate::persistence;
|
||||
use rmpv::Value;
|
||||
|
||||
/// Record of a destination learnt from a validated announce.
|
||||
/// Record intended for a destination learned from a validated announce.
|
||||
/// Construction and file loading do not perform announce authentication.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct KnownDestination {
|
||||
/// Learn time as a Unix timestamp (seconds).
|
||||
@@ -33,6 +34,8 @@ impl KnownDestinations {
|
||||
|
||||
/// Insert or refresh the entry for `dest_hash`. The `retained` flag is
|
||||
/// preserved on update so a fresh announce never un-pins an entry.
|
||||
/// The caller validates the announce, destination binding and key continuity;
|
||||
/// this method can replace an existing key without checking them.
|
||||
pub fn remember(
|
||||
&mut self,
|
||||
dest_hash: [u8; 16],
|
||||
@@ -147,7 +150,8 @@ impl KnownDestinations {
|
||||
|
||||
/// Drop stale entries past `destination_timeout_secs`. `has_path` is a
|
||||
/// caller-supplied path-table lookup (this crate doesn't depend on
|
||||
/// rns-transport). Returns the hashes that were dropped.
|
||||
/// rns-transport). Pinned entries and entries with a current path are retained.
|
||||
/// Returns the hashes that were dropped.
|
||||
pub fn cleanup(
|
||||
&mut self,
|
||||
now: f64,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Python reference: `RNS/Identity.py`, `RNS/Destination.py`.
|
||||
|
||||
pub mod announce;
|
||||
pub mod announce_state;
|
||||
pub mod destination;
|
||||
pub mod identity;
|
||||
pub mod ifac;
|
||||
@@ -10,3 +11,4 @@ pub mod known_destinations;
|
||||
pub mod name_hash;
|
||||
pub mod persistence;
|
||||
pub mod ratchet;
|
||||
pub mod stamps;
|
||||
@@ -1,43 +1,261 @@
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// Write `data` to `path` via `<path>.tmp` + `rename`, fsyncing first.
|
||||
mod file_lock;
|
||||
mod strict;
|
||||
pub use file_lock::try_lock_exclusive;
|
||||
pub use strict::{
|
||||
DurableCleanupOutcome, DurableCommitPhase, DurableDirectoryReceipt, DurableErrorKind,
|
||||
DurableFileReceipt, DurableWriteError, StorageRisk, durable_create_dir_all, durable_reconcile,
|
||||
durable_reconcile_directory, durable_reconcile_hash, durable_remove, durable_rename_directory,
|
||||
durable_write, storage_risk, validate_durable_storage_directory,
|
||||
};
|
||||
|
||||
static TEMP_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
static ATOMIC_WRITE_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn invalid_data(message: &'static str) -> std::io::Error {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
|
||||
fn unique_temp_path(path: &Path) -> std::io::Result<PathBuf> {
|
||||
let parent = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
let file_name = path.file_name().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"atomic-write target has no file name",
|
||||
)
|
||||
})?;
|
||||
let sequence = TEMP_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let mut temp_name = file_name.to_os_string();
|
||||
temp_name.push(format!(".tmp-{}-{sequence}", std::process::id()));
|
||||
Ok(parent.join(temp_name))
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
|
||||
fs::rename(source, destination)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn atomic_replace(source: &Path, destination: &Path) -> std::io::Result<()> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::Storage::FileSystem::{
|
||||
MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW,
|
||||
};
|
||||
|
||||
let source: Vec<u16> = source.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let destination: Vec<u16> = destination
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(Some(0))
|
||||
.collect();
|
||||
// Same-directory temporary files keep this on one volume. MoveFileExW is
|
||||
// the Windows replacement primitive; std::fs::rename rejects an existing
|
||||
// destination on Windows instead of replacing it.
|
||||
let replaced = unsafe {
|
||||
MoveFileExW(
|
||||
source.as_ptr(),
|
||||
destination.as_ptr(),
|
||||
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
|
||||
)
|
||||
};
|
||||
if replaced == 0 {
|
||||
Err(std::io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `Read::read`, retried when a signal interrupts it.
|
||||
fn read_retrying(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
loop {
|
||||
match reader.read(buf) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compare the file at `path` with `data`. The file is read through a stack
|
||||
/// buffer that is wiped afterwards, so reading back a secret leaves no copy.
|
||||
fn verify_bytes(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
let mut file = fs::File::open(path)?;
|
||||
let mut offset: usize = 0;
|
||||
let mut chunk = Zeroizing::new([0u8; 8192]);
|
||||
loop {
|
||||
let count = read_retrying(&mut file, &mut chunk[..])?;
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
let end = offset
|
||||
.checked_add(count)
|
||||
.filter(|end| data.get(offset..*end) == Some(&chunk[..count]))
|
||||
.ok_or_else(|| invalid_data("file readback mismatch"))?;
|
||||
offset = end;
|
||||
}
|
||||
if offset != data.len() {
|
||||
return Err(invalid_data("file readback length mismatch"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a secret file of at most `max_len` bytes into one buffer that is
|
||||
/// allocated up front and wiped on drop, so neither growth nor a failed read
|
||||
/// leaves a copy behind. A longer file is refused with `InvalidData` once
|
||||
/// `max_len + 1` bytes have been read.
|
||||
pub fn read_secret_file(path: &Path, max_len: usize) -> std::io::Result<Zeroizing<Vec<u8>>> {
|
||||
let mut file = fs::File::open(path)?;
|
||||
let mut data = Zeroizing::new(vec![0u8; max_len.saturating_add(1)]);
|
||||
let mut filled = 0;
|
||||
while filled < data.len() {
|
||||
match read_retrying(&mut file, &mut data[filled..])? {
|
||||
0 => break,
|
||||
count => filled += count,
|
||||
}
|
||||
}
|
||||
if filled > max_len {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("file exceeds {max_len}-byte limit"),
|
||||
));
|
||||
}
|
||||
data.truncate(filled);
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// A msgpack byte field read from a secret file. Binary and string values
|
||||
/// borrow from a slice input; integer arrays fill a buffer reserved once (at
|
||||
/// most `MAX` bytes) and wiped on drop, so neither growth nor a failed decode
|
||||
/// leaves a copy behind.
|
||||
pub(crate) enum SecretBytes<'a, const MAX: usize> {
|
||||
Borrowed(&'a [u8]),
|
||||
Owned(Zeroizing<Vec<u8>>),
|
||||
}
|
||||
|
||||
impl<const MAX: usize> std::ops::Deref for SecretBytes<'_, MAX> {
|
||||
type Target = [u8];
|
||||
|
||||
fn deref(&self) -> &[u8] {
|
||||
match self {
|
||||
Self::Borrowed(bytes) => bytes,
|
||||
Self::Owned(bytes) => bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de: 'a, 'a, const MAX: usize> serde::Deserialize<'de> for SecretBytes<'a, MAX> {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
deserializer.deserialize_bytes(SecretBytesVisitor::<MAX>)
|
||||
}
|
||||
}
|
||||
|
||||
struct SecretBytesVisitor<const MAX: usize>;
|
||||
|
||||
impl<'de, const MAX: usize> serde::de::Visitor<'de> for SecretBytesVisitor<MAX> {
|
||||
type Value = SecretBytes<'de, MAX>;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str("a byte array")
|
||||
}
|
||||
|
||||
fn visit_borrowed_bytes<E: serde::de::Error>(self, bytes: &'de [u8]) -> Result<Self::Value, E> {
|
||||
Ok(SecretBytes::Borrowed(bytes))
|
||||
}
|
||||
|
||||
fn visit_borrowed_str<E: serde::de::Error>(self, text: &'de str) -> Result<Self::Value, E> {
|
||||
Ok(SecretBytes::Borrowed(text.as_bytes()))
|
||||
}
|
||||
|
||||
fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
|
||||
Ok(SecretBytes::Owned(Zeroizing::new(bytes.to_vec())))
|
||||
}
|
||||
|
||||
fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Self::Value, E> {
|
||||
self.visit_bytes(text.as_bytes())
|
||||
}
|
||||
|
||||
fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Self::Value, E> {
|
||||
Ok(SecretBytes::Owned(Zeroizing::new(bytes)))
|
||||
}
|
||||
|
||||
fn visit_string<E: serde::de::Error>(self, text: String) -> Result<Self::Value, E> {
|
||||
self.visit_byte_buf(text.into_bytes())
|
||||
}
|
||||
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||
let capacity = seq.size_hint().unwrap_or(0).min(MAX);
|
||||
let mut bytes = Zeroizing::new(Vec::with_capacity(capacity));
|
||||
while let Some(byte) = seq.next_element::<u8>()? {
|
||||
if bytes.len() == capacity {
|
||||
return Err(serde::de::Error::invalid_length(capacity + 1, &self));
|
||||
}
|
||||
bytes.push(byte);
|
||||
}
|
||||
Ok(SecretBytes::Owned(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `data` to `path` via a unique same-directory temporary file and
|
||||
/// atomic rename.
|
||||
///
|
||||
/// On Unix the temp file is created with mode `0600` so that key material is
|
||||
/// not world-readable even during the write. After the rename the parent
|
||||
/// directory is fsynced best-effort so the rename itself survives power loss.
|
||||
/// not world-readable even during the write. The bytes are flushed, fsynced,
|
||||
/// and verified before the rename, then verified again at the final path. After
|
||||
/// the rename, parent-directory fsync is best-effort on Unix; its failure does
|
||||
/// not fail this operation. This is not a guarantee of survival after power
|
||||
/// loss. Use [`durable_write`] when the caller needs its stricter receipt and
|
||||
/// recovery-path handling, subject to that helper's filesystem limits.
|
||||
pub fn atomic_write(path: &Path, data: &[u8]) -> std::io::Result<()> {
|
||||
let tmp_path = path.with_extension("tmp");
|
||||
let _write_guard = ATOMIC_WRITE_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let tmp_path = unique_temp_path(path)?;
|
||||
|
||||
{
|
||||
let result = (|| {
|
||||
#[cfg(unix)]
|
||||
let mut f = {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&tmp_path)?
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let mut f = fs::File::create(&tmp_path)?;
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&tmp_path)?;
|
||||
|
||||
f.write_all(data)?;
|
||||
f.flush()?;
|
||||
f.sync_all()?;
|
||||
}
|
||||
drop(f);
|
||||
|
||||
fs::rename(&tmp_path, path)?;
|
||||
verify_bytes(&tmp_path, data)?;
|
||||
atomic_replace(&tmp_path, path)?;
|
||||
verify_bytes(path, data)?;
|
||||
|
||||
#[cfg(unix)]
|
||||
if let Some(dir) = path.parent() {
|
||||
if let Ok(d) = fs::File::open(dir) {
|
||||
#[cfg(unix)]
|
||||
if let Some(dir) = path.parent()
|
||||
&& let Ok(d) = fs::File::open(dir)
|
||||
{
|
||||
let _ = d.sync_all();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp_path);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
result
|
||||
}
|
||||
|
||||
/// Read `path` in full, returning `None` if the file does not exist.
|
||||
@@ -49,29 +267,336 @@ pub fn read_file(path: &Path) -> std::io::Result<Option<Vec<u8>>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read at most `max_len` bytes from `path`.
|
||||
///
|
||||
/// A file larger than the supplied bound is rejected before it can be handed
|
||||
/// to a deserializer. `None` means the path did not exist.
|
||||
pub fn read_file_bounded(path: &Path, max_len: usize) -> std::io::Result<Option<Vec<u8>>> {
|
||||
let file = match fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
|
||||
let mut data = Vec::with_capacity(max_len.min(4096));
|
||||
file.take(max_len.saturating_add(1) as u64)
|
||||
.read_to_end(&mut data)?;
|
||||
if data.len() > max_len {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("file exceeds {max_len}-byte limit"),
|
||||
));
|
||||
}
|
||||
Ok(Some(data))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) fn unique_test_dir(label: &str) -> PathBuf {
|
||||
static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!(
|
||||
"reticulum-{label}-{}-{}-{id}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos()
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_atomic_write_and_read() {
|
||||
let dir = std::env::temp_dir().join("reticulum_test_persistence");
|
||||
let _ = fs::create_dir_all(&dir);
|
||||
let dir = unique_test_dir("persistence");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("test_atomic");
|
||||
|
||||
atomic_write(&path, b"hello world").unwrap();
|
||||
let data = read_file(&path).unwrap().unwrap();
|
||||
assert_eq!(data, b"hello world");
|
||||
|
||||
let _ = fs::remove_file(&path);
|
||||
let _ = fs::remove_dir(&dir);
|
||||
atomic_write(&path, b"replacement").unwrap();
|
||||
let data = read_file(&path).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
data, b"replacement",
|
||||
"Windows must replace an existing state file instead of failing after the first write"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_read_nonexistent() {
|
||||
let path = PathBuf::from("/tmp/reticulum_nonexistent_file_xyz");
|
||||
let path = unique_test_dir("nonexistent").join("missing");
|
||||
let result = read_file(&path).unwrap();
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bounded_read_rejects_oversize_file() {
|
||||
let dir = unique_test_dir("bounded-read");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("bounded");
|
||||
fs::write(&path, [0xA5; 17]).unwrap();
|
||||
|
||||
let err = read_file_bounded(&path, 16).unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
|
||||
assert_eq!(read_file_bounded(&path, 17).unwrap().unwrap().len(), 17);
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Root ignores directory permissions.
|
||||
#[cfg(unix)]
|
||||
pub(super) fn is_root() -> bool {
|
||||
unsafe { libc::geteuid() == 0 }
|
||||
}
|
||||
|
||||
/// Holds the macOS user immutable flag (`chflags uchg`) on a file.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(super) struct Immutable(PathBuf);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Immutable {
|
||||
pub(super) fn new(path: &Path) -> Self {
|
||||
Self::set(path, libc::UF_IMMUTABLE);
|
||||
Self(path.to_path_buf())
|
||||
}
|
||||
|
||||
fn set(path: &Path, flags: libc::c_uint) {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
|
||||
assert_eq!(unsafe { libc::chflags(path.as_ptr(), flags) }, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Drop for Immutable {
|
||||
fn drop(&mut self) {
|
||||
Self::set(&self.0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_write_into_a_missing_directory_fails_without_creating_it() {
|
||||
let dir = unique_test_dir("atomic-missing-parent");
|
||||
let err = atomic_write(&dir.join("state"), b"candidate").unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
|
||||
assert!(!dir.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn atomic_write_in_a_read_only_directory_keeps_the_previous_file() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if is_root() {
|
||||
return;
|
||||
}
|
||||
let dir = unique_test_dir("atomic-read-only");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
fs::write(&path, b"previous").unwrap();
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o500)).unwrap();
|
||||
|
||||
let result = atomic_write(&path, b"candidate");
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result.unwrap_err().kind(),
|
||||
std::io::ErrorKind::PermissionDenied
|
||||
);
|
||||
assert_eq!(fs::read(&path).unwrap(), b"previous");
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_write_onto_a_directory_leaves_it_and_no_temporary_file() {
|
||||
let dir = unique_test_dir("atomic-directory-target");
|
||||
let target = dir.join("state");
|
||||
fs::create_dir_all(&target).unwrap();
|
||||
fs::write(target.join("kept"), b"kept").unwrap();
|
||||
|
||||
assert!(atomic_write(&target, b"candidate").is_err());
|
||||
|
||||
assert_eq!(fs::read(target.join("kept")).unwrap(), b"kept");
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn atomic_write_onto_an_immutable_file_keeps_it() {
|
||||
let dir = unique_test_dir("atomic-immutable");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
fs::write(&path, b"previous").unwrap();
|
||||
let immutable = Immutable::new(&path);
|
||||
|
||||
let result = atomic_write(&path, b"candidate");
|
||||
drop(immutable);
|
||||
|
||||
assert!(result.is_err());
|
||||
assert_eq!(fs::read(&path).unwrap(), b"previous");
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn readback_verification_rejects_changed_short_and_long_files() {
|
||||
let dir = unique_test_dir("readback");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
let data: Vec<u8> = (0..20_000u32).map(|i| (i % 251) as u8).collect();
|
||||
|
||||
fs::write(&path, &data).unwrap();
|
||||
verify_bytes(&path, &data).unwrap();
|
||||
let mut changed = data.clone();
|
||||
changed[12_345] ^= 1;
|
||||
for (name, contents) in [
|
||||
("changed", changed),
|
||||
("short", data[..data.len() - 1].to_vec()),
|
||||
("long", [&data[..], b"!"].concat()),
|
||||
("empty", Vec::new()),
|
||||
] {
|
||||
fs::write(&path, contents).unwrap();
|
||||
let err = verify_bytes(&path, &data).unwrap_err();
|
||||
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData, "{name}");
|
||||
}
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secret_reads_are_bounded() {
|
||||
let dir = unique_test_dir("secret-read");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("secret");
|
||||
|
||||
fs::write(&path, [0xA5; 64]).unwrap();
|
||||
assert_eq!(&read_secret_file(&path, 64).unwrap()[..], &[0xA5; 64]);
|
||||
assert_eq!(
|
||||
read_secret_file(&path, 63).unwrap_err().kind(),
|
||||
std::io::ErrorKind::InvalidData
|
||||
);
|
||||
fs::write(&path, b"").unwrap();
|
||||
assert!(read_secret_file(&path, 64).unwrap().is_empty());
|
||||
assert_eq!(
|
||||
read_secret_file(&dir.join("missing"), 64)
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
std::io::ErrorKind::NotFound
|
||||
);
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_atomic_writers_do_not_share_temp_paths() {
|
||||
let dir = unique_test_dir("atomic-concurrent");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("state");
|
||||
|
||||
let mut writers = Vec::new();
|
||||
for byte in 0u8..16 {
|
||||
let path = path.clone();
|
||||
writers.push(std::thread::spawn(move || atomic_write(&path, &[byte; 64])));
|
||||
}
|
||||
for writer in writers {
|
||||
writer.join().unwrap().unwrap();
|
||||
}
|
||||
|
||||
let final_data = fs::read(&path).unwrap();
|
||||
assert_eq!(final_data.len(), 64);
|
||||
assert!(final_data.iter().all(|byte| *byte == final_data[0]));
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Feed `data` to `read` through a FIFO in two halves, signalling the
|
||||
/// reading thread while it waits for the second. The handler is installed
|
||||
/// without `SA_RESTART`, so that wait fails with EINTR.
|
||||
#[cfg(unix)]
|
||||
pub(super) fn read_through_a_signal<T: Send + 'static>(
|
||||
label: &str,
|
||||
data: &[u8],
|
||||
read: impl FnOnce(&Path) -> std::io::Result<T> + Send + 'static,
|
||||
) -> std::io::Result<T> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
extern "C" fn ignore(_: libc::c_int) {}
|
||||
|
||||
let dir = unique_test_dir(label);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("fifo");
|
||||
let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap();
|
||||
unsafe {
|
||||
assert_eq!(libc::mkfifo(c_path.as_ptr(), 0o600), 0);
|
||||
let mut action: libc::sigaction = std::mem::zeroed();
|
||||
action.sa_sigaction = ignore as extern "C" fn(libc::c_int) as libc::sighandler_t;
|
||||
libc::sigemptyset(&mut action.sa_mask);
|
||||
assert_eq!(
|
||||
libc::sigaction(libc::SIGUSR1, &action, std::ptr::null_mut()),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
let (thread_tx, thread_rx) = std::sync::mpsc::channel();
|
||||
let reader_path = path.clone();
|
||||
let reader = std::thread::spawn(move || {
|
||||
thread_tx
|
||||
.send(unsafe { libc::pthread_self() } as usize)
|
||||
.unwrap();
|
||||
read(&reader_path)
|
||||
});
|
||||
let thread = thread_rx.recv().unwrap() as libc::pthread_t;
|
||||
let mut fifo = fs::OpenOptions::new().write(true).open(&path).unwrap();
|
||||
let (first, second) = data.split_at(data.len() / 2);
|
||||
fifo.write_all(first).unwrap();
|
||||
for _ in 0..5 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
unsafe { libc::pthread_kill(thread, libc::SIGUSR1) };
|
||||
}
|
||||
// A reader that gave up has closed its end.
|
||||
let _ = fifo.write_all(second);
|
||||
drop(fifo);
|
||||
// Fail instead of hanging if another descriptor still holds the writer.
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
while !reader.is_finished() {
|
||||
assert!(
|
||||
std::time::Instant::now() < deadline,
|
||||
"reader of {} saw no EOF 30 s after the writer closed",
|
||||
path.display()
|
||||
);
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
let result = reader.join().unwrap();
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn readback_verification_retries_an_interrupted_read() {
|
||||
let data = vec![0x5a; 64];
|
||||
let expected = data.clone();
|
||||
let result = read_through_a_signal("verify-interrupted", &data, move |path| {
|
||||
verify_bytes(path, &expected)
|
||||
});
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn secret_file_read_retries_an_interrupted_read() {
|
||||
let data = vec![0xa5; 64];
|
||||
let read = read_through_a_signal("secret-read-interrupted", &data, |path| {
|
||||
read_secret_file(path, 1024)
|
||||
});
|
||||
assert_eq!(read.unwrap()[..], data[..]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Nonblocking OS file-lock portability. Android's standard-library File lock
|
||||
//! implementation is unsupported on some supported toolchains; bionic flock
|
||||
//! provides the same retained-open-file-description ownership on that target.
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
|
||||
/// Take an exclusive advisory lock without waiting. Retain the original file
|
||||
/// for the complete protected operation; do not clone/close handles to transfer
|
||||
/// ownership since duplication semantics differ by platform. Closing the owning
|
||||
/// handles (including on process exit) releases the lock. Contention is
|
||||
/// `WouldBlock`, and unsupported or failed backends are errors, never success.
|
||||
/// Do not delete/recreate the lock file while an owner may still hold it.
|
||||
pub fn try_lock_exclusive(file: &File) -> io::Result<()> {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
use std::os::fd::AsRawFd;
|
||||
// SAFETY: the borrowed File keeps its descriptor alive for this call;
|
||||
// flock neither takes ownership nor writes through any Rust pointer.
|
||||
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::last_os_error())
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "android"))]
|
||||
file.try_lock().map_err(|error| match error {
|
||||
std::fs::TryLockError::WouldBlock => {
|
||||
io::Error::new(io::ErrorKind::WouldBlock, "file is locked by another owner")
|
||||
}
|
||||
std::fs::TryLockError::Error(error) => error,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn lock_files() -> (std::path::PathBuf, File, File) {
|
||||
let path = super::super::tests::unique_test_dir("native-lock");
|
||||
let first = File::create_new(&path).unwrap();
|
||||
let second = File::options().read(true).write(true).open(&path).unwrap();
|
||||
(path, first, second)
|
||||
}
|
||||
#[test]
|
||||
fn native_file_lock_contends_and_releases_on_drop() {
|
||||
let (path, first, second) = lock_files();
|
||||
try_lock_exclusive(&first).unwrap();
|
||||
assert_eq!(
|
||||
try_lock_exclusive(&second).unwrap_err().kind(),
|
||||
io::ErrorKind::WouldBlock
|
||||
);
|
||||
drop(first);
|
||||
try_lock_exclusive(&second).unwrap();
|
||||
drop(second);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn native_file_lock_duplicate_keeps_exclusion_until_last_close() {
|
||||
let (path, first, second) = lock_files();
|
||||
try_lock_exclusive(&first).unwrap();
|
||||
let retained = first.try_clone().unwrap();
|
||||
drop(first);
|
||||
assert_eq!(
|
||||
try_lock_exclusive(&second).unwrap_err().kind(),
|
||||
io::ErrorKind::WouldBlock
|
||||
);
|
||||
drop(retained);
|
||||
try_lock_exclusive(&second).unwrap();
|
||||
drop(second);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+804
-227
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,934 @@
|
||||
//! Proof-of-work stamps: fixed-point costs, values, validation and generation.
|
||||
//!
|
||||
//! Python reference: `RNS/Stamps.py` (1.6.0). Costs and values are fixed point
|
||||
//! with 8 fractional bits; a cost of 1.0 is 256.
|
||||
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use rand::RngCore;
|
||||
use rns_crypto::hkdf::hkdf_sha256;
|
||||
use rns_crypto::sha::full_hash;
|
||||
use rns_crypto::x25519::X25519PrivateKey;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub const WORKBLOCK_EXPAND_CHUNK: usize = 256;
|
||||
pub const WORKBLOCK_EXPAND_ROUNDS: usize = 3000;
|
||||
pub const STAMP_SIZE: usize = 32;
|
||||
/// Size of detached destination and path-request stamps (`Identity.STAMPLENGTH`).
|
||||
pub const NETWORK_STAMP_SIZE: usize = 14;
|
||||
pub const STOP_CHECK_INTERVAL: u32 = 64;
|
||||
pub const MANTISSA_BITS: u32 = 33;
|
||||
pub const COST_FP_BITS: u32 = 8;
|
||||
pub const COST_FP: u32 = 1 << COST_FP_BITS;
|
||||
pub const STAMP_COST_CAP: f64 = 100.0;
|
||||
pub const STAMP_COST_CAP_FP: u16 = 100 * 256;
|
||||
pub const LINK_COST_CAP: f64 = 40.0;
|
||||
/// Fixed-point value of a stamp whose hash is zero.
|
||||
pub const MAX_VALUE_FP: u32 = 256 * COST_FP;
|
||||
|
||||
pub const TAB_DIGEST: &str = "55ba3ce1df224895b0dfdc102eb4359fc2f5a7efefee68df0cc90c8a8ac24f48";
|
||||
pub const PRM_DIGEST: &str = "21436fc98e76a12cad7c52ebeb6ab76c2ae93b4cd768949df7fdd4e2f98c378d";
|
||||
|
||||
/// `floor(2^33 * 2^(f/256))` for `f` in `0..256`, copied verbatim from
|
||||
/// upstream. Never compute these: the table is the wire contract.
|
||||
pub const TAB: [u64; 256] = [
|
||||
0x200000000,
|
||||
0x201635f4b,
|
||||
0x202c7b53f,
|
||||
0x2042d0287,
|
||||
0x2059347ce,
|
||||
0x206fa85c2,
|
||||
0x20862bd0d,
|
||||
0x209cbee5e,
|
||||
0x20b361a62,
|
||||
0x20ca141c7,
|
||||
0x20e0d653b,
|
||||
0x20f7a856e,
|
||||
0x210e8a30e,
|
||||
0x21257becc,
|
||||
0x213c7d958,
|
||||
0x21538f363,
|
||||
0x216ab0d9f,
|
||||
0x2181e28bc,
|
||||
0x21992456e,
|
||||
0x21b076467,
|
||||
0x21c7d865a,
|
||||
0x21df4abfb,
|
||||
0x21f6cd5ff,
|
||||
0x220e6051a,
|
||||
0x222603a02,
|
||||
0x223db756b,
|
||||
0x22557b80d,
|
||||
0x226d5029e,
|
||||
0x2285355d5,
|
||||
0x229d2b269,
|
||||
0x22b531914,
|
||||
0x22cd48a8e,
|
||||
0x22e57078f,
|
||||
0x22fda90d2,
|
||||
0x2315f2711,
|
||||
0x232e4cb06,
|
||||
0x2346b7d6d,
|
||||
0x235f33f02,
|
||||
0x2377c1080,
|
||||
0x23905f2a5,
|
||||
0x23a90e62d,
|
||||
0x23c1cebd6,
|
||||
0x23daa045f,
|
||||
0x23f383087,
|
||||
0x240c7710c,
|
||||
0x24257c6af,
|
||||
0x243e9322f,
|
||||
0x2457bb44f,
|
||||
0x2470f4dce,
|
||||
0x248a3ff70,
|
||||
0x24a39c9f6,
|
||||
0x24bd0ae23,
|
||||
0x24d68acbc,
|
||||
0x24f01c683,
|
||||
0x2509bfc3e,
|
||||
0x252374eb2,
|
||||
0x253d3bea3,
|
||||
0x255714cda,
|
||||
0x2570ffa1b,
|
||||
0x258afc72e,
|
||||
0x25a50b4dc,
|
||||
0x25bf2c3ec,
|
||||
0x25d95f527,
|
||||
0x25f3a4957,
|
||||
0x260dfc146,
|
||||
0x262865dbd,
|
||||
0x2642e1f89,
|
||||
0x265d70775,
|
||||
0x26781164c,
|
||||
0x2692c4cdc,
|
||||
0x26ad8abf2,
|
||||
0x26c86345b,
|
||||
0x26e34e6e7,
|
||||
0x26fe4c463,
|
||||
0x27195cda0,
|
||||
0x27348036e,
|
||||
0x274fb669c,
|
||||
0x276aff7fd,
|
||||
0x27865b862,
|
||||
0x27a1ca89d,
|
||||
0x27bd4c982,
|
||||
0x27d8e1be3,
|
||||
0x27f48a095,
|
||||
0x28104586c,
|
||||
0x282c1443e,
|
||||
0x2847f64e1,
|
||||
0x2863ebb2a,
|
||||
0x287ff47f0,
|
||||
0x289c10c0c,
|
||||
0x28b840854,
|
||||
0x28d483da3,
|
||||
0x28f0dacd1,
|
||||
0x290d456b8,
|
||||
0x2929c3c32,
|
||||
0x294655e1a,
|
||||
0x2962fbd4d,
|
||||
0x297fb5aa6,
|
||||
0x299c83702,
|
||||
0x29b96533f,
|
||||
0x29d65b03b,
|
||||
0x29f364ed3,
|
||||
0x2a1082fe8,
|
||||
0x2a2db5459,
|
||||
0x2a4afbd07,
|
||||
0x2a6856ad3,
|
||||
0x2a85c5e9e,
|
||||
0x2aa34994b,
|
||||
0x2ac0e1bbd,
|
||||
0x2ade8e6d6,
|
||||
0x2afc4fb7c,
|
||||
0x2b1a25a92,
|
||||
0x2b38104ff,
|
||||
0x2b560fba9,
|
||||
0x2b7423f75,
|
||||
0x2b924d14b,
|
||||
0x2bb08b213,
|
||||
0x2bcede2b5,
|
||||
0x2bed4641b,
|
||||
0x2c0bc372e,
|
||||
0x2c2a55cd9,
|
||||
0x2c48fd607,
|
||||
0x2c67ba3a3,
|
||||
0x2c868c699,
|
||||
0x2ca573fd7,
|
||||
0x2cc47104a,
|
||||
0x2ce3838e1,
|
||||
0x2d02aba89,
|
||||
0x2d21e9633,
|
||||
0x2d413cccf,
|
||||
0x2d60a5f4e,
|
||||
0x2d8024ea1,
|
||||
0x2d9fb9bba,
|
||||
0x2dbf6478c,
|
||||
0x2ddf2530b,
|
||||
0x2dfefbf2a,
|
||||
0x2e1ee8cde,
|
||||
0x2e3eebd1d,
|
||||
0x2e5f050dd,
|
||||
0x2e7f34914,
|
||||
0x2e9f7a6ba,
|
||||
0x2ebfd6ac8,
|
||||
0x2ee049635,
|
||||
0x2f00d29fb,
|
||||
0x2f2172715,
|
||||
0x2f4228e7d,
|
||||
0x2f62f612e,
|
||||
0x2f83da026,
|
||||
0x2fa4d4c5f,
|
||||
0x2fc5e66d9,
|
||||
0x2fe70f092,
|
||||
0x30084ea87,
|
||||
0x3029a55ba,
|
||||
0x304b13329,
|
||||
0x306c983d7,
|
||||
0x308e348c4,
|
||||
0x30afe82f3,
|
||||
0x30d1b3368,
|
||||
0x30f395b26,
|
||||
0x31158fb31,
|
||||
0x3137a148f,
|
||||
0x3159ca845,
|
||||
0x317c0b75a,
|
||||
0x319e642d6,
|
||||
0x31c0d4bc1,
|
||||
0x31e35d322,
|
||||
0x3205fda05,
|
||||
0x3228b6172,
|
||||
0x324b86a75,
|
||||
0x326e6f619,
|
||||
0x32917056b,
|
||||
0x32b489979,
|
||||
0x32d7bb34e,
|
||||
0x32fb053fb,
|
||||
0x331e67c8f,
|
||||
0x3341e2e19,
|
||||
0x3365769aa,
|
||||
0x338923054,
|
||||
0x33ace8329,
|
||||
0x33d0c633c,
|
||||
0x33f4bd1a0,
|
||||
0x3418ccf6b,
|
||||
0x343cf5db1,
|
||||
0x346137d89,
|
||||
0x348593008,
|
||||
0x34aa07647,
|
||||
0x34ce9515e,
|
||||
0x34f33c266,
|
||||
0x3517fca78,
|
||||
0x353cd6aaf,
|
||||
0x3561ca426,
|
||||
0x3586d77fa,
|
||||
0x35abfe747,
|
||||
0x35d13f32b,
|
||||
0x35f699cc4,
|
||||
0x361c0e531,
|
||||
0x36419cd93,
|
||||
0x366745709,
|
||||
0x368d082b6,
|
||||
0x36b2e51bc,
|
||||
0x36d8dc53e,
|
||||
0x36feede5f,
|
||||
0x372519e44,
|
||||
0x374b60614,
|
||||
0x3771c16f3,
|
||||
0x37983d209,
|
||||
0x37bed387e,
|
||||
0x37e584b7a,
|
||||
0x380c50c28,
|
||||
0x383337bb0,
|
||||
0x385a39b3f,
|
||||
0x388156bff,
|
||||
0x38a88ef1f,
|
||||
0x38cfe25ca,
|
||||
0x38f751131,
|
||||
0x391edb280,
|
||||
0x394680aea,
|
||||
0x396e41b9d,
|
||||
0x39961e5cd,
|
||||
0x39be16aab,
|
||||
0x39e62ab6b,
|
||||
0x3a0e5a940,
|
||||
0x3a36a6561,
|
||||
0x3a5f0e101,
|
||||
0x3a8791d59,
|
||||
0x3ab031b9f,
|
||||
0x3ad8edd0c,
|
||||
0x3b01c62d9,
|
||||
0x3b2abae3f,
|
||||
0x3b53cc07b,
|
||||
0x3b7cf9ac7,
|
||||
0x3ba643e60,
|
||||
0x3bcfaac83,
|
||||
0x3bf92e66f,
|
||||
0x3c22ced63,
|
||||
0x3c4c8c29e,
|
||||
0x3c7666762,
|
||||
0x3ca05dcf1,
|
||||
0x3cca7248c,
|
||||
0x3cf4a3f78,
|
||||
0x3d1ef2ef9,
|
||||
0x3d495f454,
|
||||
0x3d73e90cf,
|
||||
0x3d9e905b1,
|
||||
0x3dc955443,
|
||||
0x3df437dcc,
|
||||
0x3e1f38396,
|
||||
0x3e4a566ed,
|
||||
0x3e759291b,
|
||||
0x3ea0ecb6d,
|
||||
0x3ecc64f31,
|
||||
0x3ef7fb5b3,
|
||||
0x3f23b0044,
|
||||
0x3f4f83033,
|
||||
0x3f7b746d2,
|
||||
0x3fa784571,
|
||||
0x3fd3b2d65,
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, thiserror::Error)]
|
||||
pub enum StampError {
|
||||
#[error("stamp cost is not a finite number")]
|
||||
NonFiniteCost,
|
||||
#[error("stamp cost {0} is outside 0..=100")]
|
||||
InvalidCost(f64),
|
||||
#[error("fixed-point stamp cost {0} is outside 0..=25600")]
|
||||
FpOutOfRange(u16),
|
||||
}
|
||||
|
||||
/// Round a cost to fixed point, clamped to `0..=100`.
|
||||
pub fn cost_to_fp(cost: f64) -> Result<u16, StampError> {
|
||||
let scaled = (cost * f64::from(COST_FP) + 0.5).floor();
|
||||
if !scaled.is_finite() {
|
||||
return Err(StampError::NonFiniteCost);
|
||||
}
|
||||
Ok(scaled.clamp(0.0, f64::from(STAMP_COST_CAP_FP)) as u16)
|
||||
}
|
||||
|
||||
/// Wire encoding: integer byte first.
|
||||
pub fn fp_to_bytes(fp: u16) -> [u8; 2] {
|
||||
fp.to_be_bytes()
|
||||
}
|
||||
|
||||
pub fn cost_to_bytes(cost: f64) -> Result<[u8; 2], StampError> {
|
||||
cost_to_fp(cost).map(fp_to_bytes)
|
||||
}
|
||||
|
||||
/// Not clamped: wire bytes can carry up to 65535.
|
||||
pub fn fp_from_bytes(bytes: [u8; 2]) -> u16 {
|
||||
u16::from_be_bytes(bytes)
|
||||
}
|
||||
|
||||
pub fn cost_from_fp(fp: u32) -> f64 {
|
||||
f64::from(fp) / f64::from(COST_FP)
|
||||
}
|
||||
|
||||
pub fn cost_from_bytes(bytes: [u8; 2]) -> f64 {
|
||||
cost_from_fp(u32::from(fp_from_bytes(bytes)))
|
||||
}
|
||||
|
||||
pub fn quantize_cost(cost: f64) -> Result<f64, StampError> {
|
||||
cost_to_fp(cost).map(|fp| cost_from_fp(u32::from(fp)))
|
||||
}
|
||||
|
||||
/// Largest stamp hash that meets a cost, as a 264-bit big-endian integer.
|
||||
/// Cost 0 gives `2^256`, which is why 32 bytes are not enough.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StampTarget([u8; 33]);
|
||||
|
||||
impl StampTarget {
|
||||
/// A stamp meets the cost when its hash is at most the target.
|
||||
pub fn accepts(&self, hash: &[u8; 32]) -> bool {
|
||||
self.0[0] != 0 || hash[..] <= self.0[1..]
|
||||
}
|
||||
|
||||
pub fn to_be_bytes(&self) -> [u8; 33] {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn target_from_fp(fp: u16) -> Result<StampTarget, StampError> {
|
||||
if fp > STAMP_COST_CAP_FP {
|
||||
return Err(StampError::FpOutOfRange(fp));
|
||||
}
|
||||
let exponent = 256 * COST_FP - u32::from(fp);
|
||||
let (whole, fraction) = (exponent / COST_FP, exponent % COST_FP);
|
||||
// `(TAB[f] << i) >> 33`; `i` is at least 156, so no bits are lost.
|
||||
let shift = whole - MANTISSA_BITS;
|
||||
let mantissa = TAB[fraction as usize];
|
||||
let mut target = [0u8; 33];
|
||||
for bit in 0..=MANTISSA_BITS {
|
||||
if (mantissa >> bit) & 1 == 1 {
|
||||
let position = (shift + bit) as usize;
|
||||
target[32 - position / 8] |= 1 << (position % 8);
|
||||
}
|
||||
}
|
||||
Ok(StampTarget(target))
|
||||
}
|
||||
|
||||
pub fn target_from_cost(cost: f64) -> Result<StampTarget, StampError> {
|
||||
target_from_fp(cost_to_fp(cost)?)
|
||||
}
|
||||
|
||||
/// Expand `material` into a workblock. Zero rounds return the material
|
||||
/// itself, which is how the detached network stamps are hashed.
|
||||
pub fn stamp_workblock(material: &[u8], expand_rounds: usize) -> Vec<u8> {
|
||||
if expand_rounds == 0 {
|
||||
return material.to_vec();
|
||||
}
|
||||
let mut workblock = Vec::with_capacity(expand_rounds * WORKBLOCK_EXPAND_CHUNK);
|
||||
let mut salt_input = Vec::with_capacity(material.len() + 9);
|
||||
for round in 0..expand_rounds {
|
||||
salt_input.clear();
|
||||
salt_input.extend_from_slice(material);
|
||||
push_msgpack_uint(&mut salt_input, round as u64);
|
||||
let salt = full_hash(&salt_input);
|
||||
let chunk = hkdf_sha256(WORKBLOCK_EXPAND_CHUNK, material, Some(&salt), None)
|
||||
.expect("256 bytes is within the HKDF output limit");
|
||||
workblock.extend_from_slice(&chunk);
|
||||
}
|
||||
workblock
|
||||
}
|
||||
|
||||
fn push_msgpack_uint(out: &mut Vec<u8>, value: u64) {
|
||||
match value {
|
||||
0..=0x7f => out.push(value as u8),
|
||||
0x80..=0xff => out.extend_from_slice(&[0xcc, value as u8]),
|
||||
0x100..=0xffff => {
|
||||
out.push(0xcd);
|
||||
out.extend_from_slice(&(value as u16).to_be_bytes());
|
||||
}
|
||||
0x1_0000..=0xffff_ffff => {
|
||||
out.push(0xce);
|
||||
out.extend_from_slice(&(value as u32).to_be_bytes());
|
||||
}
|
||||
_ => {
|
||||
out.push(0xcf);
|
||||
out.extend_from_slice(&value.to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_with(workblock: &[u8], stamp: &[u8]) -> [u8; 32] {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(workblock);
|
||||
hasher.update(stamp);
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
/// Fixed-point value of a stamp hash, `0..=65536`.
|
||||
pub fn stamp_value_fp_from_hash(hash: &[u8; 32]) -> u32 {
|
||||
let mut leading_zeros = 0usize;
|
||||
for byte in hash {
|
||||
if *byte == 0 {
|
||||
leading_zeros += 8;
|
||||
} else {
|
||||
leading_zeros += byte.leading_zeros() as usize;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if leading_zeros == 256 {
|
||||
return MAX_VALUE_FP;
|
||||
}
|
||||
// The 34 bits from the leading one, zero-padded past the end of the hash.
|
||||
let mut mantissa = 0u64;
|
||||
for offset in 0..=MANTISSA_BITS as usize {
|
||||
let position = leading_zeros + offset;
|
||||
let bit = if position < 256 {
|
||||
(hash[position / 8] >> (7 - position % 8)) & 1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
mantissa = (mantissa << 1) | u64::from(bit);
|
||||
}
|
||||
let not_above = TAB.partition_point(|entry| *entry <= mantissa) as u32;
|
||||
((leading_zeros as u32 + 1) << COST_FP_BITS) - not_above
|
||||
}
|
||||
|
||||
pub fn stamp_value_fp(workblock: &[u8], stamp: &[u8]) -> u32 {
|
||||
stamp_value_fp_from_hash(&hash_with(workblock, stamp))
|
||||
}
|
||||
|
||||
/// Fractional stamp value, `0.0..=256.0`. Not clamped to the cost cap.
|
||||
pub fn stamp_value(workblock: &[u8], stamp: &[u8]) -> f64 {
|
||||
cost_from_fp(stamp_value_fp(workblock, stamp))
|
||||
}
|
||||
|
||||
/// Costs above 100 are checked as 100; a cost of 0 always passes.
|
||||
pub fn stamp_valid(stamp: &[u8], target_cost: f64, workblock: &[u8]) -> Result<bool, StampError> {
|
||||
Ok(target_from_cost(target_cost)?.accepts(&hash_with(workblock, stamp)))
|
||||
}
|
||||
|
||||
pub fn stamp_valid_fp(stamp: &[u8], target_fp: u16, workblock: &[u8]) -> Result<bool, StampError> {
|
||||
Ok(target_from_fp(target_fp)?.accepts(&hash_with(workblock, stamp)))
|
||||
}
|
||||
|
||||
/// Python `Stamps.NICENESS`.
|
||||
pub const DEFAULT_WORKER_NICENESS: u8 = 16;
|
||||
/// Upper clamp of `[stamps] worker_niceness`.
|
||||
pub const MAX_WORKER_NICENESS: u8 = 20;
|
||||
|
||||
static MAX_WORKERS: AtomicUsize = AtomicUsize::new(0);
|
||||
static WORKER_NICENESS: AtomicU8 = AtomicU8::new(DEFAULT_WORKER_NICENESS);
|
||||
|
||||
/// Process-wide limits on stamp search threads: Python `Stamps.MAX_WORKERS`
|
||||
/// and `Stamps.NICENESS`, set from `[stamps] max_workers` and `worker_niceness`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct StampWorkers {
|
||||
/// Cap on the threads of one search; `None` keeps the caller's count.
|
||||
pub max_workers: Option<NonZeroUsize>,
|
||||
/// Nice increment each thread of a multi-threaded search applies to
|
||||
/// itself, `0..=20`. Linux only, where nice values are per thread; a no-op
|
||||
/// elsewhere.
|
||||
pub niceness: u8,
|
||||
}
|
||||
|
||||
impl Default for StampWorkers {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_workers: None,
|
||||
niceness: DEFAULT_WORKER_NICENESS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StampWorkers {
|
||||
/// Python `max(1, v)`.
|
||||
pub fn clamp_max_workers(value: i64) -> NonZeroUsize {
|
||||
usize::try_from(value)
|
||||
.ok()
|
||||
.and_then(NonZeroUsize::new)
|
||||
.unwrap_or(NonZeroUsize::MIN)
|
||||
}
|
||||
|
||||
/// Python `min(20, max(0, v))`.
|
||||
pub fn clamp_niceness(value: i64) -> u8 {
|
||||
value.clamp(0, i64::from(MAX_WORKER_NICENESS)) as u8
|
||||
}
|
||||
|
||||
/// The installed process settings.
|
||||
pub fn current() -> Self {
|
||||
Self {
|
||||
max_workers: NonZeroUsize::new(MAX_WORKERS.load(Ordering::Relaxed)),
|
||||
niceness: WORKER_NICENESS.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
/// Install for every later search in this process.
|
||||
pub fn install(self) {
|
||||
MAX_WORKERS.store(
|
||||
self.max_workers.map_or(0, NonZeroUsize::get),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
WORKER_NICENESS.store(self.niceness.min(MAX_WORKER_NICENESS), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// `threads` capped at `max_workers`.
|
||||
pub fn cap(&self, threads: NonZeroUsize) -> NonZeroUsize {
|
||||
self.max_workers.map_or(threads, |max| threads.min(max))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn renice_search_thread(increment: u8) {
|
||||
if increment > 0 {
|
||||
// SAFETY: nice(2) only adjusts the calling thread; errors are ignored, as upstream ignores them.
|
||||
unsafe {
|
||||
libc::nice(libc::c_int::from(increment));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn renice_search_thread(_increment: u8) {}
|
||||
|
||||
/// Stop conditions and parallelism for a stamp search.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StampControl {
|
||||
pub cancel: Arc<AtomicBool>,
|
||||
pub deadline: Option<Instant>,
|
||||
pub threads: NonZeroUsize,
|
||||
}
|
||||
|
||||
impl Default for StampControl {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
cancel: Arc::new(AtomicBool::new(false)),
|
||||
deadline: None,
|
||||
threads: NonZeroUsize::MIN,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StampControl {
|
||||
fn stopped(&self) -> bool {
|
||||
self.cancel.load(Ordering::Relaxed)
|
||||
|| self
|
||||
.deadline
|
||||
.is_some_and(|deadline| Instant::now() >= deadline)
|
||||
}
|
||||
}
|
||||
|
||||
fn generation_target(cost: f64) -> Result<StampTarget, StampError> {
|
||||
if cost.is_nan() {
|
||||
return Err(StampError::NonFiniteCost);
|
||||
}
|
||||
if !(0.0..=STAMP_COST_CAP).contains(&cost) {
|
||||
return Err(StampError::InvalidCost(cost));
|
||||
}
|
||||
target_from_cost(cost)
|
||||
}
|
||||
|
||||
/// Run `worker` on `ctl.threads` threads, capped by the installed
|
||||
/// [`StampWorkers`], until one returns a result or all stop.
|
||||
fn search<T: Send>(
|
||||
ctl: &StampControl,
|
||||
worker: impl Fn(&AtomicBool) -> Option<T> + Sync,
|
||||
) -> Option<T> {
|
||||
search_with(ctl, StampWorkers::current(), worker)
|
||||
}
|
||||
|
||||
fn search_with<T: Send>(
|
||||
ctl: &StampControl,
|
||||
workers: StampWorkers,
|
||||
worker: impl Fn(&AtomicBool) -> Option<T> + Sync,
|
||||
) -> Option<T> {
|
||||
let found = AtomicBool::new(false);
|
||||
let threads = workers.cap(ctl.threads).get();
|
||||
if threads == 1 {
|
||||
return worker(&found);
|
||||
}
|
||||
let result = Mutex::new(None);
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..threads {
|
||||
scope.spawn(|| {
|
||||
renice_search_thread(workers.niceness);
|
||||
if let Some(hit) = worker(&found) {
|
||||
found.store(true, Ordering::Relaxed);
|
||||
result
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.get_or_insert(hit);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
result.into_inner().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// Search for a detached stamp of `size` random bytes over `material`.
|
||||
/// Returns the stamp and its real value, or `None` when cancelled or past
|
||||
/// the deadline. A cost of 0 still returns a random stamp.
|
||||
pub fn generate_stamp(
|
||||
material: &[u8],
|
||||
cost: f64,
|
||||
expand_rounds: usize,
|
||||
size: usize,
|
||||
ctl: &StampControl,
|
||||
) -> Result<Option<(Vec<u8>, f64)>, StampError> {
|
||||
let target = generation_target(cost)?;
|
||||
let workblock = stamp_workblock(material, expand_rounds);
|
||||
let mut base = Sha256::new();
|
||||
base.update(&workblock);
|
||||
|
||||
let stamp = search(ctl, |found| {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut candidate = vec![0u8; size];
|
||||
let mut since_check = 0u32;
|
||||
loop {
|
||||
since_check += 1;
|
||||
if since_check >= STOP_CHECK_INTERVAL {
|
||||
since_check = 0;
|
||||
if ctl.stopped() || found.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
rng.fill_bytes(&mut candidate);
|
||||
let mut hasher = base.clone();
|
||||
hasher.update(&candidate);
|
||||
if target.accepts(&hasher.finalize().into()) {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(stamp.map(|stamp| {
|
||||
let value = stamp_value(&workblock, &stamp);
|
||||
(stamp, value)
|
||||
}))
|
||||
}
|
||||
|
||||
/// An X25519 key whose public half is a stamp over some material.
|
||||
pub struct StampedKey {
|
||||
pub private: X25519PrivateKey,
|
||||
pub public: [u8; 32],
|
||||
pub value: f64,
|
||||
}
|
||||
|
||||
/// Search for an X25519 key whose public key stamps `material`. Only ever
|
||||
/// use the result as an X25519 key.
|
||||
pub fn generate_stamped_key(
|
||||
material: &[u8],
|
||||
cost: f64,
|
||||
ctl: &StampControl,
|
||||
) -> Result<Option<StampedKey>, StampError> {
|
||||
let target = generation_target(cost)?;
|
||||
let mut base = Sha256::new();
|
||||
base.update(material);
|
||||
|
||||
let key = search(ctl, |found| {
|
||||
loop {
|
||||
if ctl.stopped() || found.load(Ordering::Relaxed) {
|
||||
return None;
|
||||
}
|
||||
let private = X25519PrivateKey::generate();
|
||||
let public = private.public_key().to_bytes();
|
||||
let mut hasher = base.clone();
|
||||
hasher.update(public);
|
||||
if target.accepts(&hasher.finalize().into()) {
|
||||
return Some((private, public));
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(key.map(|(private, public)| StampedKey {
|
||||
value: stamp_value(material, &public),
|
||||
private,
|
||||
public,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rns_crypto::sha::sha256;
|
||||
|
||||
fn sample_hash(index: u32) -> [u8; 32] {
|
||||
sha256(format!("stamp-sample-{index}").as_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_matches_upstream_digests() {
|
||||
assert_eq!(TAB.len() as u32, COST_FP);
|
||||
assert_eq!(TAB[0], 1 << MANTISSA_BITS);
|
||||
assert!(TAB.windows(2).all(|pair| pair[1] > pair[0]));
|
||||
let joined = TAB.iter().map(u64::to_string).collect::<Vec<_>>().join(",");
|
||||
assert_eq!(hex::encode(sha256(joined.as_bytes())), TAB_DIGEST);
|
||||
let parameters = format!(
|
||||
"master|{TAB_DIGEST}|{MANTISSA_BITS}|{}|{COST_FP_BITS}|{COST_FP}|",
|
||||
TAB.len()
|
||||
);
|
||||
assert_eq!(hex::encode(sha256(parameters.as_bytes())), PRM_DIGEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_cost_target_is_a_power_of_two() {
|
||||
for cost in 0..=100u16 {
|
||||
let target = target_from_fp(cost * 256).unwrap().to_be_bytes();
|
||||
let position = 256 - cost as usize;
|
||||
let mut expected = [0u8; 33];
|
||||
expected[32 - position / 8] = 1 << (position % 8);
|
||||
assert_eq!(target, expected, "cost {cost}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_rounding_and_clamping() {
|
||||
assert_eq!(cost_to_fp(0.0), Ok(0));
|
||||
assert_eq!(cost_to_fp(0.5 / 256.0), Ok(1));
|
||||
assert_eq!(cost_to_fp(1.5 / 256.0), Ok(2));
|
||||
assert_eq!(cost_to_fp(12.5), Ok(3200));
|
||||
assert_eq!(cost_to_fp(150.0), Ok(STAMP_COST_CAP_FP));
|
||||
assert_eq!(cost_to_fp(-5.0), Ok(0));
|
||||
assert_eq!(cost_to_fp(f64::NAN), Err(StampError::NonFiniteCost));
|
||||
assert_eq!(cost_to_fp(f64::INFINITY), Err(StampError::NonFiniteCost));
|
||||
assert_eq!(fp_to_bytes(3200), [12, 128]);
|
||||
assert_eq!(fp_from_bytes([0xff, 0xff]), 65535);
|
||||
assert_eq!(target_from_fp(25601), Err(StampError::FpOutOfRange(25601)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_is_the_highest_cost_a_hash_meets() {
|
||||
for index in 0..2000 {
|
||||
let mut hash = sample_hash(index);
|
||||
// Spread the samples over a range of leading-zero counts.
|
||||
let zero_bits = (index % 40) as usize;
|
||||
for bit in 0..zero_bits {
|
||||
hash[bit / 8] &= !(0x80 >> (bit % 8));
|
||||
}
|
||||
let value = stamp_value_fp_from_hash(&hash);
|
||||
let capped = value.min(u32::from(STAMP_COST_CAP_FP)) as u16;
|
||||
assert!(target_from_fp(capped).unwrap().accepts(&hash), "{index}");
|
||||
if capped < STAMP_COST_CAP_FP {
|
||||
assert!(
|
||||
!target_from_fp(capped + 1).unwrap().accepts(&hash),
|
||||
"{index}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_edges() {
|
||||
assert_eq!(stamp_value_fp_from_hash(&[0u8; 32]), 65536);
|
||||
let mut one = [0u8; 32];
|
||||
one[31] = 1;
|
||||
assert_eq!(stamp_value_fp_from_hash(&one), 65535);
|
||||
assert_eq!(stamp_value_fp_from_hash(&[0xff; 32]), 0);
|
||||
let mut top = [0u8; 32];
|
||||
top[0] = 0x80;
|
||||
assert_eq!(stamp_value_fp_from_hash(&top), 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workblock_without_rounds_is_the_material() {
|
||||
assert_eq!(stamp_workblock(b"material", 0), b"material");
|
||||
assert_eq!(stamp_workblock(b"material", 2).len(), 512);
|
||||
assert_eq!(stamp_workblock(b"", 1).len(), 256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_stamp_meets_its_cost() {
|
||||
let ctl = StampControl::default();
|
||||
for (cost, size) in [(0.0, 14), (6.5, 14), (8.25, 32)] {
|
||||
let (stamp, value) = generate_stamp(b"material", cost, 0, size, &ctl)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(stamp.len(), size);
|
||||
assert!(value >= quantize_cost(cost).unwrap());
|
||||
assert_eq!(stamp_valid(&stamp, cost, b"material"), Ok(true));
|
||||
assert_eq!(value, stamp_value(b"material", &stamp));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_runs_on_several_threads() {
|
||||
let ctl = StampControl {
|
||||
threads: NonZeroUsize::new(4).unwrap(),
|
||||
..StampControl::default()
|
||||
};
|
||||
let (stamp, _) = generate_stamp(b"material", 10.0, 2, 32, &ctl)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let workblock = stamp_workblock(b"material", 2);
|
||||
assert_eq!(stamp_valid(&stamp, 10.0, &workblock), Ok(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_settings_clamp_as_python() {
|
||||
assert_eq!(StampWorkers::default().max_workers, None);
|
||||
assert_eq!(StampWorkers::default().niceness, 16);
|
||||
assert_eq!(StampWorkers::clamp_max_workers(0).get(), 1);
|
||||
assert_eq!(StampWorkers::clamp_max_workers(-3).get(), 1);
|
||||
assert_eq!(StampWorkers::clamp_max_workers(6).get(), 6);
|
||||
assert_eq!(StampWorkers::clamp_niceness(-3), 0);
|
||||
assert_eq!(StampWorkers::clamp_niceness(25), 20);
|
||||
assert_eq!(StampWorkers::clamp_niceness(7), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_workers_caps_search_threads() {
|
||||
let ctl = StampControl {
|
||||
threads: NonZeroUsize::new(4).unwrap(),
|
||||
..StampControl::default()
|
||||
};
|
||||
let count = |workers: StampWorkers| {
|
||||
let started = AtomicUsize::new(0);
|
||||
search_with(&ctl, workers, |_| {
|
||||
started.fetch_add(1, Ordering::Relaxed);
|
||||
None::<()>
|
||||
});
|
||||
started.into_inner()
|
||||
};
|
||||
let capped = StampWorkers {
|
||||
max_workers: NonZeroUsize::new(2),
|
||||
niceness: 0,
|
||||
};
|
||||
assert_eq!(count(capped), 2);
|
||||
assert_eq!(
|
||||
count(StampWorkers {
|
||||
niceness: 0,
|
||||
..StampWorkers::default()
|
||||
}),
|
||||
4
|
||||
);
|
||||
let above = StampWorkers {
|
||||
max_workers: NonZeroUsize::new(9),
|
||||
niceness: 0,
|
||||
};
|
||||
assert_eq!(count(above), 4);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn pooled_search_threads_are_niced() {
|
||||
// SAFETY: getpriority(2) reads the calling thread's nice value.
|
||||
let nice = || unsafe { libc::getpriority(libc::PRIO_PROCESS, 0) };
|
||||
let base = nice();
|
||||
let ctl = StampControl {
|
||||
threads: NonZeroUsize::new(2).unwrap(),
|
||||
..StampControl::default()
|
||||
};
|
||||
let workers = StampWorkers {
|
||||
max_workers: None,
|
||||
niceness: 16,
|
||||
};
|
||||
assert_eq!(
|
||||
search_with(&ctl, workers, |_| Some(nice())),
|
||||
Some((base + 16).min(19))
|
||||
);
|
||||
let single = StampControl::default();
|
||||
assert_eq!(search_with(&single, workers, |_| Some(nice())), Some(base));
|
||||
assert_eq!(nice(), base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_rejects_costs_python_rejects() {
|
||||
let ctl = StampControl::default();
|
||||
assert_eq!(
|
||||
generate_stamp(b"m", 100.5, 0, 14, &ctl).unwrap_err(),
|
||||
StampError::InvalidCost(100.5)
|
||||
);
|
||||
assert_eq!(
|
||||
generate_stamp(b"m", -0.5, 0, 14, &ctl).unwrap_err(),
|
||||
StampError::InvalidCost(-0.5)
|
||||
);
|
||||
assert_eq!(
|
||||
generate_stamp(b"m", f64::NAN, 0, 14, &ctl).unwrap_err(),
|
||||
StampError::NonFiniteCost
|
||||
);
|
||||
assert!(matches!(
|
||||
generate_stamped_key(b"m", 101.0, &ctl),
|
||||
Err(StampError::InvalidCost(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_generation_returns_none() {
|
||||
let ctl = StampControl::default();
|
||||
ctl.cancel.store(true, Ordering::Relaxed);
|
||||
assert_eq!(generate_stamp(b"m", 60.0, 0, 14, &ctl), Ok(None));
|
||||
assert!(generate_stamped_key(b"m", 60.0, &ctl).unwrap().is_none());
|
||||
let expired = StampControl {
|
||||
deadline: Some(Instant::now()),
|
||||
..StampControl::default()
|
||||
};
|
||||
assert_eq!(generate_stamp(b"m", 60.0, 0, 14, &expired), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamped_key_public_half_is_the_stamp() {
|
||||
let key = generate_stamped_key(b"material", 5.5, &StampControl::default())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(key.private.public_key().to_bytes(), key.public);
|
||||
assert_eq!(stamp_valid(&key.public, 5.5, b"material"), Ok(true));
|
||||
assert_eq!(key.value, stamp_value(b"material", &key.public));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Writes beyond the process file-size limit fail with EFBIG and keep the
|
||||
//! previous file. Each test re-runs itself in a child with a lowered limit.
|
||||
//! Spawning stays out of the unit-test binary: until a child execs it holds
|
||||
//! copies of all its parent's descriptors, close-on-exec ones included, so a
|
||||
//! sibling test's lock or FIFO end would outlive that test's close.
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use rns_identity::persistence::{DurableCommitPhase, atomic_write, durable_write};
|
||||
|
||||
fn unique_test_dir(label: &str) -> PathBuf {
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"reticulum-{label}-{}-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_nanos(),
|
||||
NEXT_ID.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Re-run `test` in a child process whose files are limited to `limit`
|
||||
/// bytes, with SIGXFSZ ignored so a longer write fails with EFBIG. Returns
|
||||
/// true in the child, which then runs the test body.
|
||||
fn in_file_size_limited_child(test: &str, limit: u64) -> bool {
|
||||
const CHILD: &str = "RNS_FILE_SIZE_LIMITED_CHILD";
|
||||
if std::env::var_os(CHILD).is_some() {
|
||||
unsafe {
|
||||
libc::signal(libc::SIGXFSZ, libc::SIG_IGN);
|
||||
let mut current = std::mem::zeroed::<libc::rlimit>();
|
||||
assert_eq!(libc::getrlimit(libc::RLIMIT_FSIZE, &mut current), 0);
|
||||
current.rlim_cur = limit as libc::rlim_t;
|
||||
assert_eq!(libc::setrlimit(libc::RLIMIT_FSIZE, ¤t), 0);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([test, "--exact", "--nocapture", "--test-threads=1"])
|
||||
.env(CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("1 passed"),
|
||||
"file-size-limited child failed:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_write_beyond_the_file_size_limit_keeps_the_previous_file() {
|
||||
if !in_file_size_limited_child(
|
||||
"atomic_write_beyond_the_file_size_limit_keeps_the_previous_file",
|
||||
4096,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let dir = unique_test_dir("atomic-file-size");
|
||||
let path = dir.join("state");
|
||||
fs::write(&path, b"previous").unwrap();
|
||||
|
||||
let err = atomic_write(&path, &[0x5a; 16384]).unwrap_err();
|
||||
|
||||
assert_eq!(err.raw_os_error(), Some(libc::EFBIG));
|
||||
assert_eq!(fs::read(&path).unwrap(), b"previous");
|
||||
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_write_beyond_the_file_size_limit_keeps_the_previous_file() {
|
||||
if !in_file_size_limited_child(
|
||||
"strict_write_beyond_the_file_size_limit_keeps_the_previous_file",
|
||||
4096,
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let root = unique_test_dir("durable-file-size");
|
||||
let target = root.join("state");
|
||||
durable_write(&target, b"old").unwrap();
|
||||
|
||||
let failure = durable_write(&target, &[0x5a; 16384]).unwrap_err();
|
||||
|
||||
assert_eq!(failure.phase, DurableCommitPhase::NotCommitted);
|
||||
let source = std::error::Error::source(&failure)
|
||||
.and_then(|source| source.downcast_ref::<std::io::Error>())
|
||||
.unwrap();
|
||||
assert_eq!(source.raw_os_error(), Some(libc::EFBIG));
|
||||
assert_eq!(fs::read(&target).unwrap(), b"old");
|
||||
assert_eq!(failure.recovery_paths.len(), 2);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
//! Private keys, derived keys and plaintext must not survive in freed heap
|
||||
//! memory when identities are stored, loaded and used.
|
||||
|
||||
#[path = "../../rns-crypto/tests/residue/mod.rs"]
|
||||
mod residue;
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use residue::{assert_no_residue, freed_by, pseudo_random, serial};
|
||||
use rns_crypto::hkdf::hkdf_sha256;
|
||||
use rns_crypto::sha::sha256;
|
||||
use rns_crypto::x25519::{X25519PrivateKey, X25519PublicKey};
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_identity::ifac::derive_ifac_key;
|
||||
use rns_identity::ratchet::{RatchetRing, RatchetRingFormat};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
static NEXT: AtomicUsize = AtomicUsize::new(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"rns-residue-{label}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn derived_key(private: &[u8; 32], ephemeral_public: &[u8], salt: &[u8]) -> Zeroizing<Vec<u8>> {
|
||||
let private = X25519PrivateKey::from_bytes(private);
|
||||
let public = X25519PublicKey::from_bytes(ephemeral_public.try_into().unwrap());
|
||||
let shared = Zeroizing::new(private.exchange(&public).unwrap());
|
||||
hkdf_sha256(64, &*shared, Some(salt), None).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_to_file_frees_no_key() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("to-file");
|
||||
let key: [u8; 64] = pseudo_random(11);
|
||||
let identity = Identity::from_private_key(&key).unwrap();
|
||||
let path = dir.0.join("identity");
|
||||
|
||||
let ((), freed) = freed_by(|| identity.to_file(&path).unwrap());
|
||||
|
||||
assert_no_residue(&freed, &[("private key", &key)]);
|
||||
assert_eq!(std::fs::read(&path).unwrap(), key);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_from_file_frees_no_key() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("from-file");
|
||||
let key: [u8; 64] = pseudo_random(12);
|
||||
let expected = Identity::from_private_key(&key).unwrap().hash;
|
||||
let path = dir.0.join("identity");
|
||||
std::fs::write(&path, key).unwrap();
|
||||
|
||||
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
|
||||
|
||||
assert_no_residue(&freed, &[("private key", &key)]);
|
||||
assert_eq!(hash, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_from_file_with_a_msgpack_looking_key_frees_no_key() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("from-file-msgpack-prefix");
|
||||
// A one-field array holding a long integer array: a parse of this key as
|
||||
// an envelope runs out of input partway through.
|
||||
let mut key = [0u8; 64];
|
||||
key[..4].copy_from_slice(&[0x91, 0xdc, 0xff, 0xff]);
|
||||
let tail: [u8; 60] = pseudo_random(13);
|
||||
for (out, byte) in key[4..].iter_mut().zip(tail) {
|
||||
*out = byte & 0x7f;
|
||||
}
|
||||
let expected = Identity::from_private_key(&key).unwrap().hash;
|
||||
let path = dir.0.join("identity");
|
||||
std::fs::write(&path, key).unwrap();
|
||||
|
||||
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
|
||||
|
||||
assert_no_residue(&freed, &[("private key", &key[4..])]);
|
||||
assert_eq!(hash, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_from_envelope_file_frees_no_key() {
|
||||
#[derive(serde::Serialize)]
|
||||
struct Envelope {
|
||||
private_key: Vec<u8>,
|
||||
}
|
||||
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("from-envelope");
|
||||
let key: [u8; 64] = pseudo_random(14);
|
||||
let expected = Identity::from_private_key(&key).unwrap().hash;
|
||||
let envelope = Envelope {
|
||||
private_key: key.to_vec(),
|
||||
};
|
||||
for (name, bytes) in [
|
||||
("named", rmp_serde::to_vec_named(&envelope).unwrap()),
|
||||
("compact", rmp_serde::to_vec(&envelope).unwrap()),
|
||||
] {
|
||||
let path = dir.0.join(name);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
|
||||
let (hash, freed) = freed_by(|| Identity::from_file(&path).unwrap().hash);
|
||||
|
||||
assert_no_residue(
|
||||
&freed,
|
||||
&[
|
||||
("private key", &key),
|
||||
("msgpack integers private key", &msgpack_integers(&key)),
|
||||
],
|
||||
);
|
||||
assert_eq!(hash, expected, "{name} envelope");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_from_file_refuses_an_oversize_file_without_reading_it_whole() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("from-file-oversize");
|
||||
let path = dir.0.join("identity");
|
||||
std::fs::write(&path, vec![0xc1; 1 << 20]).unwrap();
|
||||
|
||||
let (result, freed) = freed_by(|| Identity::from_file(&path));
|
||||
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
freed.peak_allocation < 64 * 1024,
|
||||
"loading allocated {} bytes",
|
||||
freed.peak_allocation
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_encrypt_frees_no_plaintext_or_key() {
|
||||
let _serial = serial();
|
||||
let key: [u8; 64] = pseudo_random(15);
|
||||
let identity = Identity::from_private_key(&key).unwrap();
|
||||
let plaintext: [u8; 100] = pseudo_random(16);
|
||||
|
||||
let (ciphertext, freed) = freed_by(|| identity.encrypt(&plaintext, None).unwrap());
|
||||
|
||||
let derived = derived_key(
|
||||
key[..32].try_into().unwrap(),
|
||||
&ciphertext[..32],
|
||||
&identity.hash,
|
||||
);
|
||||
assert_no_residue(
|
||||
&freed,
|
||||
&[("plaintext", &plaintext), ("derived key", &derived)],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_decrypt_frees_no_plaintext_or_key() {
|
||||
let _serial = serial();
|
||||
let key: [u8; 64] = pseudo_random(17);
|
||||
let identity = Identity::from_private_key(&key).unwrap();
|
||||
let plaintext: [u8; 100] = pseudo_random(18);
|
||||
let ciphertext = identity.encrypt(&plaintext, None).unwrap();
|
||||
let derived = derived_key(
|
||||
key[..32].try_into().unwrap(),
|
||||
&ciphertext[..32],
|
||||
&identity.hash,
|
||||
);
|
||||
|
||||
let ((), freed) = freed_by(|| {
|
||||
let decrypted = Zeroizing::new(identity.decrypt(&ciphertext, None, false).unwrap());
|
||||
assert_eq!(&decrypted[..], &plaintext[..]);
|
||||
});
|
||||
|
||||
assert_no_residue(
|
||||
&freed,
|
||||
&[("plaintext", &plaintext), ("derived key", &derived)],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_ratchet_decrypt_frees_no_plaintext_or_key() {
|
||||
let _serial = serial();
|
||||
let key: [u8; 64] = pseudo_random(19);
|
||||
let identity = Identity::from_private_key(&key).unwrap();
|
||||
let ratchet: [u8; 32] = pseudo_random(20);
|
||||
let ratchet_public = X25519PrivateKey::from_bytes(&ratchet)
|
||||
.public_key()
|
||||
.to_bytes();
|
||||
let plaintext: [u8; 100] = pseudo_random(21);
|
||||
let ciphertext = identity.encrypt(&plaintext, Some(&ratchet_public)).unwrap();
|
||||
let derived = derived_key(&ratchet, &ciphertext[..32], &identity.hash);
|
||||
|
||||
let ((), freed) = freed_by(|| {
|
||||
let ratchets = [&ratchet];
|
||||
let decrypted = identity
|
||||
.decrypt_with_ratchet_id(&ciphertext, Some(&ratchets), true)
|
||||
.unwrap();
|
||||
let plaintext_copy = Zeroizing::new(decrypted.plaintext);
|
||||
assert_eq!(&plaintext_copy[..], &plaintext[..]);
|
||||
});
|
||||
|
||||
assert_no_residue(
|
||||
&freed,
|
||||
&[
|
||||
("plaintext", &plaintext),
|
||||
("derived key", &derived),
|
||||
("ratchet key", &ratchet),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ratchet_ring_save_and_load_free_no_ratchet_keys() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("ratchets");
|
||||
let identity = Identity::from_private_key(&pseudo_random::<64>(22)).unwrap();
|
||||
let mut ring = RatchetRing::new();
|
||||
for _ in 0..200 {
|
||||
ring.rotate();
|
||||
}
|
||||
let keys = Zeroizing::new(ring.private_keys().to_vec());
|
||||
let path = dir.0.join("ratchets");
|
||||
|
||||
let ((), saved) = freed_by(|| ring.save_verified(&path, &identity).unwrap());
|
||||
let ((), read) = freed_by(|| {
|
||||
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
|
||||
assert_eq!(loaded.ring().private_keys(), &keys[..]);
|
||||
});
|
||||
|
||||
let mut found = Vec::new();
|
||||
for (stage, freed) in [("save", &saved), ("load", &read)] {
|
||||
for residue in ratchet_key_residue(freed, &keys) {
|
||||
found.push(format!("{stage}: {residue}"));
|
||||
}
|
||||
}
|
||||
assert!(found.is_empty(), "secret residue: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ifac_key_derivation_frees_no_key() {
|
||||
let _serial = serial();
|
||||
let passphrase = "correct horse battery staple";
|
||||
|
||||
let key = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
|
||||
|
||||
let ((), freed) = freed_by(|| {
|
||||
let derived = derive_ifac_key(Some("residue"), Some(passphrase)).unwrap();
|
||||
assert_eq!(derived, key);
|
||||
});
|
||||
|
||||
assert_no_residue(
|
||||
&freed,
|
||||
&[
|
||||
("IFAC key", &key),
|
||||
("passphrase hash", &sha256(passphrase.as_bytes())),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// A key as msgpack writes it in an integer array: bytes above 0x7f carry a
|
||||
/// 0xcc prefix.
|
||||
fn msgpack_integers(key: &[u8]) -> Vec<u8> {
|
||||
key.iter()
|
||||
.flat_map(|&byte| {
|
||||
if byte < 0x80 {
|
||||
vec![byte]
|
||||
} else {
|
||||
vec![0xcc, byte]
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ratchet keys found in freed blocks: raw, as packed in an integer array, and
|
||||
/// as that packing appears again inside the file's integer array.
|
||||
fn ratchet_key_residue(freed: &residue::Freed, keys: &[[u8; 32]]) -> Vec<String> {
|
||||
type Encode = fn(&[u8]) -> Vec<u8>;
|
||||
let forms: [(&str, Encode); 3] = [
|
||||
("raw", |key| key.to_vec()),
|
||||
("msgpack integers", msgpack_integers),
|
||||
("nested msgpack integers", |key| {
|
||||
msgpack_integers(&msgpack_integers(key))
|
||||
}),
|
||||
];
|
||||
let mut found = Vec::new();
|
||||
for (form, encode) in forms {
|
||||
let encoded: Vec<Vec<u8>> = keys.iter().map(|key| encode(key)).collect();
|
||||
let secrets: Vec<&[u8]> = encoded.iter().map(Vec::as_slice).collect();
|
||||
let sizes: Vec<usize> = residue::find(&freed.blocks, &secrets)
|
||||
.into_iter()
|
||||
.map(|(len, _)| len)
|
||||
.collect();
|
||||
if !sizes.is_empty() {
|
||||
found.push(format!(
|
||||
"{form} ratchet keys in freed blocks of {sizes:?} bytes"
|
||||
));
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Releases before the canonical envelope wrote the packed ring and its keys
|
||||
/// as msgpack integer arrays.
|
||||
#[derive(serde::Serialize)]
|
||||
struct LegacyRatchets<T> {
|
||||
signature: Vec<u8>,
|
||||
ratchets: Vec<u8>,
|
||||
last_rotation: T,
|
||||
}
|
||||
|
||||
fn legacy_keys(count: u64, seed: u64) -> Vec<[u8; 32]> {
|
||||
(0..count).map(|i| pseudo_random(seed + i)).collect()
|
||||
}
|
||||
|
||||
fn legacy_signature(identity: &Identity, keys: &[[u8; 32]]) -> Vec<u8> {
|
||||
let current_public = X25519PrivateKey::from_bytes(&keys[0])
|
||||
.public_key()
|
||||
.to_bytes();
|
||||
identity.sign(¤t_public).unwrap().to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_ratchet_ring_load_frees_no_ratchet_keys() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("legacy-ratchets");
|
||||
let identity = Identity::from_private_key(&pseudo_random::<64>(23)).unwrap();
|
||||
let keys = legacy_keys(120, 1000);
|
||||
let legacy = LegacyRatchets {
|
||||
signature: legacy_signature(&identity, &keys),
|
||||
ratchets: rmp_serde::to_vec(&keys).unwrap(),
|
||||
last_rotation: 0.0,
|
||||
};
|
||||
let path = dir.0.join("ratchets");
|
||||
std::fs::write(&path, rmp_serde::to_vec(&legacy).unwrap()).unwrap();
|
||||
|
||||
let ((), freed) = freed_by(|| {
|
||||
let loaded = RatchetRing::load_verified(&path, &identity).unwrap();
|
||||
assert_eq!(loaded.format(), RatchetRingFormat::LegacyRust);
|
||||
assert_eq!(loaded.ring().private_keys(), &keys[..]);
|
||||
});
|
||||
|
||||
let found = ratchet_key_residue(&freed, &keys);
|
||||
assert!(found.is_empty(), "secret residue: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_legacy_ratchet_ring_loads_free_no_ratchet_keys() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("legacy-ratchets-failed");
|
||||
let identity = Identity::from_private_key(&pseudo_random::<64>(25)).unwrap();
|
||||
// Few enough keys that the packed ring is decoded without regrowing.
|
||||
let keys = legacy_keys(40, 2000);
|
||||
let signature = legacy_signature(&identity, &keys);
|
||||
let packed = rmp_serde::to_vec(&keys).unwrap();
|
||||
assert_eq!(packed[..3], [0xdc, 0x00, 40]);
|
||||
let mut short_packed = packed.clone();
|
||||
short_packed[2] += 1;
|
||||
let file = |signature: &[u8], ratchets: &[u8]| {
|
||||
rmp_serde::to_vec(&LegacyRatchets {
|
||||
signature: signature.to_vec(),
|
||||
ratchets: ratchets.to_vec(),
|
||||
last_rotation: 0.0,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let cases = [
|
||||
("short signature", file(&signature[..63], &packed)),
|
||||
(
|
||||
"malformed rotation",
|
||||
rmp_serde::to_vec(&LegacyRatchets {
|
||||
signature: signature.clone(),
|
||||
ratchets: packed.clone(),
|
||||
last_rotation: "never",
|
||||
})
|
||||
.unwrap(),
|
||||
),
|
||||
("missing key", file(&signature, &short_packed)),
|
||||
];
|
||||
|
||||
let mut found = Vec::new();
|
||||
for (case, bytes) in cases {
|
||||
let path = dir.0.join(case.replace(' ', "-"));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
|
||||
let (result, freed) = freed_by(|| RatchetRing::load_verified(&path, &identity).map(drop));
|
||||
|
||||
assert!(result.is_err(), "{case}");
|
||||
for residue in ratchet_key_residue(&freed, &keys) {
|
||||
found.push(format!("{case}: {residue}"));
|
||||
}
|
||||
}
|
||||
assert!(found.is_empty(), "secret residue: {found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_from_a_truncated_envelope_frees_no_key() {
|
||||
let _serial = serial();
|
||||
let dir = TempDir::new("truncated-envelope");
|
||||
let mut key: [u8; 64] = pseudo_random(24);
|
||||
for byte in &mut key {
|
||||
*byte &= 0x7f;
|
||||
}
|
||||
// A one-field envelope declaring 65 key bytes and ending after 64.
|
||||
let path = dir.0.join("identity");
|
||||
std::fs::write(&path, [&[0x91, 0xdc, 0x00, 0x41][..], &key].concat()).unwrap();
|
||||
|
||||
let (result, freed) = freed_by(|| Identity::from_file(&path));
|
||||
|
||||
assert!(result.is_err());
|
||||
assert_no_residue(&freed, &[("private key", &key)]);
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
[package]
|
||||
name = "rns-interface"
|
||||
description = "Network interface trait and implementations for Reticulum"
|
||||
publish = false
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
license-file.workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
serial = ["dep:serialport"]
|
||||
rnode-tcp = []
|
||||
ble = ["dep:btleplug", "dep:futures", "dep:uuid", "dep:bluer"]
|
||||
ble_peer = ["ble"]
|
||||
# See rns-transport's mobile-throttle. When enabled, auto-interface beacons
|
||||
# and reverse-peering probes slow down in the background; BLE peer scan
|
||||
# cadence adjusts to `is_foreground`. Disabled on desktop builds.
|
||||
@@ -19,6 +20,7 @@ mobile-throttle = ["rns-transport/mobile-throttle"]
|
||||
[dependencies]
|
||||
rns-crypto = { workspace = true, features = ["std"] }
|
||||
rns-wire = { workspace = true, features = ["std"] }
|
||||
rns-identity = { workspace = true }
|
||||
rns-transport = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
@@ -27,28 +29,32 @@ tracing = { workspace = true }
|
||||
socket2 = { workspace = true }
|
||||
if-addrs = { workspace = true }
|
||||
serialport = { workspace = true, optional = true }
|
||||
btleplug = { version = "0.11", optional = true }
|
||||
btleplug = { version = "=0.13.4", optional = true }
|
||||
futures = { version = "0.3", optional = true }
|
||||
uuid = { version = "1", optional = true }
|
||||
rand = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
hex = { workspace = true }
|
||||
md-5 = { workspace = true }
|
||||
|
||||
# Apple BLE Peripheral (CoreBluetooth GATT server, iOS + macOS).
|
||||
# Version pinned to match btleplug's internal objc2 version so the shared
|
||||
# runtime types stay binary-compatible. objc2-core-bluetooth gives us
|
||||
# These native owners do not exchange Objective-C types with btleplug. Keep
|
||||
# their binding generation and required features explicit. objc2-core-bluetooth gives us
|
||||
# linked-symbol access to NSString constants (CBCentralManagerScanOption*,
|
||||
# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal
|
||||
# values, which Apple is free to change.
|
||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||
objc2 = "0.5"
|
||||
objc2-foundation = "0.2"
|
||||
objc2-core-bluetooth = "0.2"
|
||||
objc2 = "0.6"
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.3", default-features = false, features = ["std", "CBAdvertisementData", "CBCentralManagerConstants", "CBPeripheralManagerConstants"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
# Keepalive-tuning tests read socket options back via getsockopt.
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = "0.2"
|
||||
@@ -71,6 +77,11 @@ bluer = { version = "0.17", features = ["bluetoothd"], optional = true }
|
||||
# unavailable event so embedding UIs can direct users to an MSIX build for
|
||||
# discoverability.
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
# Resolution floor for Tokio's socket backend: older Mio lets child processes
|
||||
# inherit sockets and keep shared/network listeners alive after shutdown.
|
||||
# 1.2.3 includes the no-inheritance fix and its Wine compatibility follow-up.
|
||||
# https://github.com/tokio-rs/mio/pull/1946
|
||||
mio = { version = "1.2.3", default-features = false }
|
||||
windows = { version = "0.58", features = [
|
||||
"Devices_Bluetooth",
|
||||
"Devices_Bluetooth_Advertisement",
|
||||
|
||||
+2187
-359
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,999 @@
|
||||
//! Production descriptor selection and serial control requests for Android USB.
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct UsbEndpointDescriptor {
|
||||
pub direction: i32,
|
||||
pub transfer_type: i32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct UsbInterfaceDescriptor {
|
||||
pub number: u16,
|
||||
pub alternate_setting: i32,
|
||||
pub class: i32,
|
||||
pub subclass: i32,
|
||||
pub endpoints: Vec<UsbEndpointDescriptor>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum UsbSerialKind {
|
||||
Cp210x,
|
||||
CdcAcm,
|
||||
Ftdi,
|
||||
Ch34x,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[cfg_attr(not(feature = "serial"), allow(dead_code))]
|
||||
pub(crate) enum UsbParity {
|
||||
None,
|
||||
Even,
|
||||
Odd,
|
||||
}
|
||||
|
||||
/// Serial line settings the Android Serial and KISS interfaces pass to
|
||||
/// usbserial4a: speed, data bits, parity `N`/`E`/`O` and stop bits.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct UsbSerialLine {
|
||||
pub baud_rate: u32,
|
||||
pub data_bits: u8,
|
||||
pub parity: UsbParity,
|
||||
pub stop_bits: u8,
|
||||
}
|
||||
|
||||
impl UsbSerialLine {
|
||||
pub(crate) const fn eight_n_one(baud_rate: u32) -> Self {
|
||||
Self {
|
||||
baud_rate,
|
||||
data_bits: 8,
|
||||
parity: UsbParity::None,
|
||||
stop_bits: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// usbserial4a 0.4.0 `vidpid4a.FTDI_VID_PID_GROUP`: FTDI chips under other vendors.
|
||||
const FTDI_VID_PID_GROUP: &[(i32, i32)] = &[
|
||||
(0x03eb, 0x2109),
|
||||
(0x0456, 0xf000),
|
||||
(0x0456, 0xf001),
|
||||
(0x04d8, 0x000a),
|
||||
(0x0584, 0xb020),
|
||||
(0x0647, 0x0100),
|
||||
(0x06ce, 0x8311),
|
||||
(0x06d3, 0x0284),
|
||||
(0x0856, 0xac01),
|
||||
(0x0856, 0xac02),
|
||||
(0x0856, 0xac03),
|
||||
(0x0856, 0xac11),
|
||||
(0x0856, 0xac12),
|
||||
(0x0856, 0xac16),
|
||||
(0x0856, 0xac17),
|
||||
(0x0856, 0xac18),
|
||||
(0x0856, 0xac19),
|
||||
(0x0856, 0xac25),
|
||||
(0x0856, 0xac26),
|
||||
(0x0856, 0xac27),
|
||||
(0x0856, 0xac33),
|
||||
(0x0856, 0xac34),
|
||||
(0x0856, 0xac49),
|
||||
(0x0856, 0xac50),
|
||||
(0x0856, 0xba02),
|
||||
(0x093c, 0x0601),
|
||||
(0x093c, 0x0701),
|
||||
(0x0acd, 0x0300),
|
||||
(0x0b39, 0x0103),
|
||||
(0x0b39, 0x0421),
|
||||
(0x0c26, 0x0004),
|
||||
(0x0c26, 0x0018),
|
||||
(0x0c26, 0x0009),
|
||||
(0x0c26, 0x000a),
|
||||
(0x0c26, 0x000b),
|
||||
(0x0c26, 0x000c),
|
||||
(0x0c26, 0x000d),
|
||||
(0x0c26, 0x0010),
|
||||
(0x0c26, 0x0011),
|
||||
(0x0c26, 0x0012),
|
||||
(0x0c26, 0x0013),
|
||||
(0x0c33, 0x0010),
|
||||
(0x0c52, 0x2101),
|
||||
(0x0c52, 0x2102),
|
||||
(0x0c52, 0x2103),
|
||||
(0x0c52, 0x2104),
|
||||
(0x0c52, 0x9020),
|
||||
(0x0c52, 0x2211),
|
||||
(0x0c52, 0x2221),
|
||||
(0x0c52, 0x2212),
|
||||
(0x0c52, 0x2222),
|
||||
(0x0c52, 0x2213),
|
||||
(0x0c52, 0x2223),
|
||||
(0x0c52, 0x2411),
|
||||
(0x0c52, 0x2421),
|
||||
(0x0c52, 0x2431),
|
||||
(0x0c52, 0x2441),
|
||||
(0x0c52, 0x2412),
|
||||
(0x0c52, 0x2422),
|
||||
(0x0c52, 0x2432),
|
||||
(0x0c52, 0x2442),
|
||||
(0x0c52, 0x2413),
|
||||
(0x0c52, 0x2423),
|
||||
(0x0c52, 0x2433),
|
||||
(0x0c52, 0x2443),
|
||||
(0x0c52, 0x2811),
|
||||
(0x0c52, 0x2821),
|
||||
(0x0c52, 0x2831),
|
||||
(0x0c52, 0x2841),
|
||||
(0x0c52, 0x2851),
|
||||
(0x0c52, 0x2861),
|
||||
(0x0c52, 0x2871),
|
||||
(0x0c52, 0x2881),
|
||||
(0x0c52, 0x2812),
|
||||
(0x0c52, 0x2822),
|
||||
(0x0c52, 0x2832),
|
||||
(0x0c52, 0x2842),
|
||||
(0x0c52, 0x2852),
|
||||
(0x0c52, 0x2862),
|
||||
(0x0c52, 0x2872),
|
||||
(0x0c52, 0x2882),
|
||||
(0x0c52, 0x2813),
|
||||
(0x0c52, 0x2823),
|
||||
(0x0c52, 0x2833),
|
||||
(0x0c52, 0x2843),
|
||||
(0x0c52, 0x2853),
|
||||
(0x0c52, 0x2863),
|
||||
(0x0c52, 0x2873),
|
||||
(0x0c52, 0x2883),
|
||||
(0x0c52, 0xa02a),
|
||||
(0x0c52, 0xa02b),
|
||||
(0x0c52, 0xa02c),
|
||||
(0x0c52, 0xa02d),
|
||||
(0x0c6c, 0x04b2),
|
||||
(0x0c7d, 0x0005),
|
||||
(0x0d3a, 0x0300),
|
||||
(0x0d46, 0x2020),
|
||||
(0x0d46, 0x2021),
|
||||
(0x0dcd, 0x0001),
|
||||
(0x0f94, 0x0001),
|
||||
(0x0f94, 0x0005),
|
||||
(0x0fd8, 0x0001),
|
||||
(0x103e, 0x03e8),
|
||||
(0x104d, 0x3000),
|
||||
(0x104d, 0x3002),
|
||||
(0x104d, 0x3006),
|
||||
(0x1209, 0x1002),
|
||||
(0x1209, 0x1006),
|
||||
(0x128d, 0x0001),
|
||||
(0x1342, 0x0202),
|
||||
(0x1457, 0x5118),
|
||||
(0x15ba, 0x0003),
|
||||
(0x15ba, 0x002b),
|
||||
(0x1781, 0x0c30),
|
||||
(0x2100, 0x9001),
|
||||
(0x2100, 0x9e50),
|
||||
(0x2100, 0x9e51),
|
||||
(0x2100, 0x9e52),
|
||||
(0x2100, 0x9e53),
|
||||
(0x2100, 0x9e54),
|
||||
(0x2100, 0x9e55),
|
||||
(0x2100, 0x9e56),
|
||||
(0x2100, 0x9e57),
|
||||
(0x2100, 0x9e58),
|
||||
(0x2100, 0x9e59),
|
||||
(0x2100, 0x9e5a),
|
||||
(0x2100, 0x9e5b),
|
||||
(0x2100, 0x9e5c),
|
||||
(0x2100, 0x9e5d),
|
||||
(0x2100, 0x9e5e),
|
||||
(0x2100, 0x9e5f),
|
||||
(0x2100, 0x9e60),
|
||||
(0x2100, 0x9e61),
|
||||
(0x2100, 0x9e62),
|
||||
(0x2100, 0x9e63),
|
||||
(0x2100, 0x9e64),
|
||||
(0x2100, 0x9e65),
|
||||
(0x2100, 0x9e66),
|
||||
(0x2100, 0x9e67),
|
||||
(0x2100, 0x9e68),
|
||||
(0x2100, 0x9e69),
|
||||
(0x2100, 0x9e6a),
|
||||
(0x1a72, 0x1000),
|
||||
(0x1a72, 0x1001),
|
||||
(0x1a72, 0x1002),
|
||||
(0x1a72, 0x1005),
|
||||
(0x1a72, 0x1007),
|
||||
(0x1a72, 0x1008),
|
||||
(0x1a72, 0x1009),
|
||||
(0x1a72, 0x100d),
|
||||
(0x1a72, 0x100e),
|
||||
(0x1a72, 0x100f),
|
||||
(0x1a72, 0x1011),
|
||||
(0x1a72, 0x1012),
|
||||
(0x1a72, 0x1013),
|
||||
(0x1a72, 0x1014),
|
||||
(0x1a72, 0x1015),
|
||||
(0x1a72, 0x1016),
|
||||
(0x165c, 0x0002),
|
||||
(0x1a79, 0x6001),
|
||||
(0x1b3d, 0x0100),
|
||||
(0x1b3d, 0x0101),
|
||||
(0x1b3d, 0x0102),
|
||||
(0x1b3d, 0x0103),
|
||||
(0x1b3d, 0x0104),
|
||||
(0x1b3d, 0x0105),
|
||||
(0x1b3d, 0x0106),
|
||||
(0x1b3d, 0x0107),
|
||||
(0x1b3d, 0x0108),
|
||||
(0x1b3d, 0x0109),
|
||||
(0x1b3d, 0x010a),
|
||||
(0x1b3d, 0x010b),
|
||||
(0x1b3d, 0x010c),
|
||||
(0x1b3d, 0x010d),
|
||||
(0x1b3d, 0x010e),
|
||||
(0x1b3d, 0x010f),
|
||||
(0x1b3d, 0x0110),
|
||||
(0x1b3d, 0x0111),
|
||||
(0x1b3d, 0x0112),
|
||||
(0x1b3d, 0x0113),
|
||||
(0x1b3d, 0x0114),
|
||||
(0x1b3d, 0x0115),
|
||||
(0x1b3d, 0x0116),
|
||||
(0x1b3d, 0x0117),
|
||||
(0x1b3d, 0x0118),
|
||||
(0x1b3d, 0x0119),
|
||||
(0x1b3d, 0x011a),
|
||||
(0x1b3d, 0x011b),
|
||||
(0x1b3d, 0x011c),
|
||||
(0x1b3d, 0x011d),
|
||||
(0x1b3d, 0x011e),
|
||||
(0x1b3d, 0x011f),
|
||||
(0x1b3d, 0x0120),
|
||||
(0x1b3d, 0x0121),
|
||||
(0x1b3d, 0x0122),
|
||||
(0x1b3d, 0x0123),
|
||||
(0x1b3d, 0x0124),
|
||||
(0x1b3d, 0x0125),
|
||||
(0x1b3d, 0x0126),
|
||||
(0x1b3d, 0x0127),
|
||||
(0x1b3d, 0x0128),
|
||||
(0x1b3d, 0x0129),
|
||||
(0x1b3d, 0x012a),
|
||||
(0x1b3d, 0x012b),
|
||||
(0x1b3d, 0x012c),
|
||||
(0x1b3d, 0x012e),
|
||||
(0x1b3d, 0x012f),
|
||||
(0x1b3d, 0x0130),
|
||||
(0x1b91, 0x0064),
|
||||
(0x1bc9, 0x6001),
|
||||
(0x1c0c, 0x0102),
|
||||
(0x1cf1, 0x0001),
|
||||
(0x1cf1, 0x0041),
|
||||
(0x0483, 0x3746),
|
||||
(0x0483, 0x3747),
|
||||
(0x5050, 0x0100),
|
||||
(0x5050, 0x0101),
|
||||
(0x5050, 0x0102),
|
||||
(0x5050, 0x0103),
|
||||
(0x5050, 0x0104),
|
||||
(0x5050, 0x0105),
|
||||
(0x5050, 0x0106),
|
||||
(0x5050, 0x0107),
|
||||
(0x5050, 0x0300),
|
||||
(0x5050, 0x0301),
|
||||
(0x5050, 0x0400),
|
||||
(0x5050, 0x0500),
|
||||
(0x5050, 0x0700),
|
||||
(0x5050, 0x0800),
|
||||
(0x5050, 0x0900),
|
||||
(0x5050, 0x0a00),
|
||||
(0x5050, 0x0b00),
|
||||
(0x5050, 0x0c00),
|
||||
(0x5050, 0x0d00),
|
||||
(0x5050, 0x0e00),
|
||||
(0x5050, 0x0f00),
|
||||
(0x5050, 0x1000),
|
||||
(0x5050, 0x8000),
|
||||
(0x5050, 0x8001),
|
||||
(0x5050, 0x8002),
|
||||
(0x5050, 0x8003),
|
||||
(0x5050, 0x8004),
|
||||
(0x5050, 0x8005),
|
||||
(0x9e88, 0x9e8f),
|
||||
(0xdeee, 0x0300),
|
||||
(0xdeee, 0x02ff),
|
||||
(0xdeee, 0x0302),
|
||||
(0xdeee, 0x0303),
|
||||
(0x05d1, 0x1001),
|
||||
(0x05d1, 0x1002),
|
||||
(0x05d1, 0x1003),
|
||||
(0x05d1, 0x1004),
|
||||
(0x05d1, 0x1011),
|
||||
(0x05d1, 0x1013),
|
||||
(0x05d1, 0x2001),
|
||||
(0x05d1, 0x2002),
|
||||
(0x05d1, 0x2003),
|
||||
(0x05d1, 0x2011),
|
||||
(0x05d1, 0x2012),
|
||||
(0x05d1, 0x2021),
|
||||
(0x05d1, 0x2022),
|
||||
(0x05d1, 0x2023),
|
||||
(0x05d1, 0x2024),
|
||||
(0x05d1, 0x3011),
|
||||
(0x05d1, 0x3012),
|
||||
(0x05d1, 0x5001),
|
||||
(0x05d1, 0x6001),
|
||||
(0x05d1, 0x7001),
|
||||
(0x05d1, 0x8001),
|
||||
(0x05d1, 0x8002),
|
||||
(0x05d1, 0x8003),
|
||||
(0x05d1, 0x8004),
|
||||
(0x05d1, 0x9001),
|
||||
(0x05d1, 0x9002),
|
||||
(0x05d1, 0x9003),
|
||||
(0x05d1, 0x9004),
|
||||
(0x05d1, 0x9005),
|
||||
(0x05d1, 0x9006),
|
||||
(0x05d1, 0x9007),
|
||||
(0x05d1, 0x9008),
|
||||
];
|
||||
|
||||
/// usbserial4a `serial4a.get_serial_port` driver choice, with RNS's override
|
||||
/// of the Qinheng `1a86:55d4` (CH9102) to the CDC driver
|
||||
/// (`RNS/Interfaces/Android/KISSInterface.py` `open_port`).
|
||||
fn usbserial4a_kind(vendor_id: i32, product_id: i32) -> Option<UsbSerialKind> {
|
||||
if vendor_id == 0x1a86 && product_id == 0x55d4 {
|
||||
None
|
||||
} else if vendor_id == 0x0403 || FTDI_VID_PID_GROUP.contains(&(vendor_id, product_id)) {
|
||||
Some(UsbSerialKind::Ftdi)
|
||||
} else if vendor_id == 0x1a86 || (vendor_id, product_id) == (0x4348, 0x5523) {
|
||||
Some(UsbSerialKind::Ch34x)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Python Android `open_port` per-chip `USB_READ_TIMEOUT_MILLIS`.
|
||||
pub(crate) const fn usb_read_timeout_ms(vendor_id: i32, product_id: i32) -> i32 {
|
||||
if vendor_id == 0x10c4 || (vendor_id == 0x1a86 && product_id == 0x55d4) {
|
||||
12
|
||||
} else {
|
||||
100
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct UsbSerialPort {
|
||||
pub kind: UsbSerialKind,
|
||||
/// Positions in UsbDevice's interface array, not bInterfaceNumber.
|
||||
pub data_interface: usize,
|
||||
pub control_interface: usize,
|
||||
/// bInterfaceNumber used as wIndex in control transfers.
|
||||
pub control_number: u16,
|
||||
/// Positions in the data interface's endpoint array.
|
||||
pub input_endpoint: usize,
|
||||
pub output_endpoint: usize,
|
||||
}
|
||||
|
||||
fn bulk_pair(interface: &UsbInterfaceDescriptor) -> Option<(usize, usize)> {
|
||||
let mut input = None;
|
||||
let mut output = None;
|
||||
for (index, endpoint) in interface.endpoints.iter().enumerate() {
|
||||
if endpoint.transfer_type != 2 {
|
||||
continue;
|
||||
}
|
||||
match endpoint.direction {
|
||||
0x80 if input.is_none() => input = Some(index),
|
||||
0x00 if output.is_none() => output = Some(index),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
Some((input?, output?))
|
||||
}
|
||||
|
||||
pub(crate) fn select_serial_port(
|
||||
vendor_id: i32,
|
||||
product_id: i32,
|
||||
interfaces: &[UsbInterfaceDescriptor],
|
||||
) -> Result<UsbSerialPort, String> {
|
||||
if let Some(kind) = usbserial4a_kind(vendor_id, product_id) {
|
||||
// usbserial4a uses interface 0 for FTDI and the last interface for
|
||||
// CH34x, with its bulk IN and OUT endpoints.
|
||||
let data_interface = match kind {
|
||||
UsbSerialKind::Ftdi => 0,
|
||||
_ => interfaces
|
||||
.len()
|
||||
.checked_sub(1)
|
||||
.ok_or("USB device has no interfaces")?,
|
||||
};
|
||||
let interface = &interfaces[data_interface];
|
||||
let (input_endpoint, output_endpoint) = bulk_pair(interface)
|
||||
.ok_or_else(|| "No USB serial interface with bulk IN and OUT endpoints".to_string())?;
|
||||
return Ok(UsbSerialPort {
|
||||
kind,
|
||||
data_interface,
|
||||
control_interface: data_interface,
|
||||
control_number: interface.number,
|
||||
input_endpoint,
|
||||
output_endpoint,
|
||||
});
|
||||
}
|
||||
// Heltec V3 uses the standard CP2102/CP2102N VID/PID. Do not apply
|
||||
// Silicon Labs requests to every vendor-specific interface or VID.
|
||||
let cp210x = vendor_id == 0x10c4 && product_id == 0xea60;
|
||||
let mut candidates = interfaces
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, interface)| {
|
||||
if interface.alternate_setting != 0
|
||||
|| interface.class != if cp210x { 0xff } else { 0x0a }
|
||||
{
|
||||
return None;
|
||||
}
|
||||
bulk_pair(interface).map(|pair| (index, pair))
|
||||
});
|
||||
let (data_interface, (input_endpoint, output_endpoint)) =
|
||||
candidates.next().ok_or_else(|| {
|
||||
"No supported USB serial interface with bulk IN and OUT endpoints".to_string()
|
||||
})?;
|
||||
if candidates.next().is_some() {
|
||||
return Err("Multiple USB serial data interfaces are unsupported".into());
|
||||
}
|
||||
let control_interface = if cp210x {
|
||||
data_interface
|
||||
} else {
|
||||
// A single CDC-ACM function is unambiguous even when unrelated JTAG
|
||||
// or other interfaces precede it. Multi-port CDC needs a union/IAD
|
||||
// association parser; never guess a control interface for it.
|
||||
let mut controls = interfaces.iter().enumerate().filter(|(_, interface)| {
|
||||
interface.alternate_setting == 0
|
||||
&& interface.class == 0x02
|
||||
&& interface.subclass == 0x02
|
||||
});
|
||||
let (index, _) = controls
|
||||
.next()
|
||||
.ok_or_else(|| "No CDC-ACM control interface found".to_string())?;
|
||||
if controls.next().is_some() {
|
||||
return Err("Multiple CDC-ACM control interfaces are unsupported".into());
|
||||
}
|
||||
index
|
||||
};
|
||||
Ok(UsbSerialPort {
|
||||
kind: if cp210x {
|
||||
UsbSerialKind::Cp210x
|
||||
} else {
|
||||
UsbSerialKind::CdcAcm
|
||||
},
|
||||
data_interface,
|
||||
control_interface,
|
||||
control_number: interfaces[control_interface].number,
|
||||
input_endpoint,
|
||||
output_endpoint,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) struct UsbControlRequest<'a> {
|
||||
pub request_type: u8,
|
||||
pub request: u8,
|
||||
pub value: u16,
|
||||
pub index: u16,
|
||||
pub payload: &'a [u8],
|
||||
}
|
||||
|
||||
/// Configure the UART. Device-to-host requests (request type bit 7) carry a
|
||||
/// zeroed payload of the expected length; every request must transfer exactly
|
||||
/// its payload length.
|
||||
pub(crate) fn configure_serial_port(
|
||||
port: &UsbSerialPort,
|
||||
line: &UsbSerialLine,
|
||||
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
|
||||
) -> Result<(), String> {
|
||||
let baud_rate = line.baud_rate;
|
||||
if baud_rate == 0 {
|
||||
return Err("USB serial baud rate must be nonzero".into());
|
||||
}
|
||||
match port.kind {
|
||||
UsbSerialKind::Ftdi => return configure_ftdi(port, line, transfer),
|
||||
UsbSerialKind::Ch34x => return configure_ch34x(line, transfer),
|
||||
_ => {}
|
||||
}
|
||||
let request_type = match port.kind {
|
||||
UsbSerialKind::Cp210x => 0x41,
|
||||
_ => 0x21,
|
||||
};
|
||||
let mut send = |request, value, payload: &[u8]| {
|
||||
let setup = UsbControlRequest {
|
||||
request_type,
|
||||
request,
|
||||
value,
|
||||
index: port.control_number,
|
||||
payload,
|
||||
};
|
||||
let transferred = transfer(&setup)
|
||||
.map_err(|error| format!("USB serial setup request 0x{request:02x}: {error}"))?;
|
||||
if transferred != payload.len() as i32 {
|
||||
return Err(format!(
|
||||
"USB serial setup request 0x{request:02x} transferred {transferred} bytes; expected {}",
|
||||
payload.len()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
match port.kind {
|
||||
UsbSerialKind::Cp210x => {
|
||||
// Silicon Labs AN571 sections 5.1, 5.5, 5.7, 5.9, 5.11 and
|
||||
// tables 9-11: https://www.silabs.com/documents/public/application-notes/AN571.pdf
|
||||
send(0x00, 0x0001, &[])?; // IFC_ENABLE must precede other requests.
|
||||
send(0x1e, 0, &baud_rate.to_le_bytes())?;
|
||||
send(0x03, 0x0800, &[])?; // 8 data bits, no parity, 1 stop bit.
|
||||
// Static DTR/RTS active, no CTS/DSR/DCD or XON/XOFF handshake,
|
||||
// no NULL stripping or inserted characters. Thresholds unused.
|
||||
let mut flow = [0u8; 16];
|
||||
flow[0..4].copy_from_slice(&1u32.to_le_bytes());
|
||||
flow[4..8].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
send(0x13, 0, &flow)?;
|
||||
// Set both lines together, with both write masks. No reset pulse
|
||||
// or one-line transition to ESP download mode is requested.
|
||||
// https://docs.espressif.com/projects/esptool/en/latest/esp32s3/advanced-topics/boot-mode-selection.html
|
||||
send(0x07, 0x0303, &[])?;
|
||||
}
|
||||
UsbSerialKind::CdcAcm => {
|
||||
// SET_LINE_CODING: rate, stop-bit code, parity code, data bits.
|
||||
let mut line_coding = [0u8; 7];
|
||||
line_coding[..4].copy_from_slice(&baud_rate.to_le_bytes());
|
||||
line_coding[4] = if line.stop_bits == 2 { 2 } else { 0 };
|
||||
line_coding[5] = match line.parity {
|
||||
UsbParity::None => 0,
|
||||
UsbParity::Odd => 1,
|
||||
UsbParity::Even => 2,
|
||||
};
|
||||
line_coding[6] = line.data_bits;
|
||||
// usbserial4a `CdcAcmSerial.open`: DTR and RTS, then the coding.
|
||||
send(0x22, 3, &[])?; // SET_CONTROL_LINE_STATE
|
||||
send(0x20, 0, &line_coding)?;
|
||||
}
|
||||
UsbSerialKind::Ftdi | UsbSerialKind::Ch34x => unreachable!("handled above"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn control(
|
||||
transfer: &mut impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
|
||||
request_type: u8,
|
||||
request: u8,
|
||||
value: u16,
|
||||
index: u16,
|
||||
payload: &[u8],
|
||||
) -> Result<(), String> {
|
||||
let setup = UsbControlRequest {
|
||||
request_type,
|
||||
request,
|
||||
value,
|
||||
index,
|
||||
payload,
|
||||
};
|
||||
let transferred = transfer(&setup)
|
||||
.map_err(|error| format!("USB serial setup request 0x{request:02x}: {error}"))?;
|
||||
if transferred != payload.len() as i32 {
|
||||
return Err(format!(
|
||||
"USB serial setup request 0x{request:02x} transferred {transferred} bytes; expected {}",
|
||||
payload.len()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// usbserial4a `FtdiSerial._reconfigure_port`: SET_BAUDRATE, SET_DATA, then
|
||||
/// flow control off. wIndex carries the port (`interface id + 1`).
|
||||
fn configure_ftdi(
|
||||
port: &UsbSerialPort,
|
||||
line: &UsbSerialLine,
|
||||
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
|
||||
) -> Result<(), String> {
|
||||
const OUT: u8 = 0x40;
|
||||
let port_index = port.control_number + 1;
|
||||
let (value, index) = ftdi_baud_divisor(line.baud_rate, port_index)?;
|
||||
control(&mut transfer, OUT, 0x03, value, index, &[])?;
|
||||
let parity: u16 = match line.parity {
|
||||
UsbParity::None => 0,
|
||||
UsbParity::Odd => 1,
|
||||
UsbParity::Even => 2,
|
||||
};
|
||||
let stop: u16 = if line.stop_bits == 2 { 2 } else { 0 };
|
||||
let data = u16::from(line.data_bits & 0x0f) | (parity << 8) | (stop << 11);
|
||||
control(&mut transfer, OUT, 0x04, data, port_index, &[])?;
|
||||
control(&mut transfer, OUT, 0x02, 0, port_index, &[])
|
||||
}
|
||||
|
||||
/// usbserial4a `FtdiSerial._convert_baudrate` (3 % tolerance in
|
||||
/// `_set_baudrate`). usbserial4a tests `_is_legacy`, `_has_mpsse` and
|
||||
/// `_is_H_series` without calling them, so all three are always true; the
|
||||
/// wire values follow that.
|
||||
fn ftdi_baud_divisor(baud_rate: u32, port_index: u16) -> Result<(u16, u16), String> {
|
||||
const REF_BASE: u64 = 3_000_000;
|
||||
const REF_HIGH: u64 = 12_000_000;
|
||||
let baud = u64::from(baud_rate);
|
||||
if baud < (2 * REF_BASE) / (2 * 16_384 + 1) {
|
||||
return Err(format!("Invalid FTDI baud rate {baud_rate} (too low)"));
|
||||
}
|
||||
let (refclock, hispeed) = if baud > REF_BASE {
|
||||
if baud > REF_HIGH {
|
||||
return Err(format!("Invalid FTDI baud rate {baud_rate} (too high)"));
|
||||
}
|
||||
(REF_HIGH, true)
|
||||
} else {
|
||||
(REF_BASE, false)
|
||||
};
|
||||
const AM_ADJUST_UP: [u64; 8] = [0, 0, 0, 1, 0, 3, 2, 1];
|
||||
const AM_ADJUST_DN: [u64; 8] = [0, 0, 0, 1, 0, 1, 2, 3];
|
||||
const FRAC_CODE: [u64; 8] = [0, 3, 2, 4, 1, 5, 6, 7];
|
||||
let mut divisor = (refclock * 8) / baud;
|
||||
divisor -= AM_ADJUST_DN[(divisor & 7) as usize];
|
||||
let (mut best_divisor, mut best_baud, mut best_diff) = (0, 0, 0);
|
||||
for i in 0..2 {
|
||||
let mut try_divisor = divisor + i;
|
||||
if !hispeed {
|
||||
if try_divisor <= 8 {
|
||||
try_divisor = 8;
|
||||
} else if try_divisor < 12 {
|
||||
try_divisor = 12;
|
||||
} else if divisor < 16 {
|
||||
try_divisor = 16;
|
||||
} else {
|
||||
try_divisor += AM_ADJUST_UP[(try_divisor & 7) as usize];
|
||||
try_divisor = try_divisor.min(0x1fff8);
|
||||
}
|
||||
}
|
||||
let estimate = (refclock * 8 + try_divisor / 2) / try_divisor;
|
||||
let diff = estimate.abs_diff(baud);
|
||||
if i == 0 || diff < best_diff {
|
||||
(best_divisor, best_baud, best_diff) = (try_divisor, estimate, diff);
|
||||
if diff == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let delta = 100.0 * best_baud.abs_diff(baud) as f64 / baud as f64;
|
||||
if delta > 3.0 {
|
||||
return Err(format!(
|
||||
"FTDI baud rate tolerance exceeded: {delta:.2}% (wanted {baud_rate}, achievable {best_baud})"
|
||||
));
|
||||
}
|
||||
let mut encoded = (best_divisor >> 3) | (FRAC_CODE[(best_divisor & 7) as usize] << 14);
|
||||
if encoded == 1 {
|
||||
encoded = 0;
|
||||
} else if encoded == 0x4001 {
|
||||
encoded = 1;
|
||||
}
|
||||
let value = (encoded & 0xffff) as u16;
|
||||
let mut index = (((encoded >> 8) & 0xff00) as u16) | port_index;
|
||||
if hispeed {
|
||||
index |= 1 << 9;
|
||||
}
|
||||
Ok((value, index))
|
||||
}
|
||||
|
||||
/// usbserial4a `Ch34xSerial._init_device` and `_reconfigure_port`.
|
||||
fn configure_ch34x(
|
||||
line: &UsbSerialLine,
|
||||
mut transfer: impl FnMut(&UsbControlRequest<'_>) -> Result<i32, String>,
|
||||
) -> Result<(), String> {
|
||||
const OUT: u8 = 0x40;
|
||||
const IN: u8 = 0xc0;
|
||||
let write = |transfer: &mut _, value, index| control(transfer, OUT, 0x9a, value, index, &[]);
|
||||
let check = |transfer: &mut _| control(transfer, IN, 0x95, 0x0706, 0, &[0, 0]);
|
||||
control(&mut transfer, OUT, 0xa1, 0xc29c, 0xb2b9, &[])?;
|
||||
control(&mut transfer, OUT, 0xa4, 0xdf, 0, &[])?;
|
||||
control(&mut transfer, OUT, 0xa4, 0x9f, 0, &[])?;
|
||||
check(&mut transfer)?;
|
||||
write(&mut transfer, 0x2727, 0)?;
|
||||
write(&mut transfer, 0x1312, 0xb282)?;
|
||||
write(&mut transfer, 0x0f2c, 0x0008)?;
|
||||
write(&mut transfer, 0x2518, 0x00c3)?;
|
||||
check(&mut transfer)?;
|
||||
write(&mut transfer, 0x2727, 0)?;
|
||||
|
||||
let (index1312, index0f2c) = match line.baud_rate {
|
||||
0..=300 => (0xd980, 0xeb),
|
||||
301..=600 => (0x6481, 0x76),
|
||||
601..=1_200 => (0xb281, 0x3b),
|
||||
1_201..=2_400 => (0xd981, 0x1e),
|
||||
2_401..=4_800 => (0x6482, 0x0f),
|
||||
4_801..=9_600 => (0xb282, 0x08),
|
||||
9_601..=19_200 => (0xd982, 0x07),
|
||||
19_201..=38_400 => (0x6483, 0x07),
|
||||
38_401..=57_600 => (0x9883, 0x07),
|
||||
57_601..=115_200 => (0xcc83, 0x07),
|
||||
115_201..=230_400 => (0xe683, 0x07),
|
||||
230_401..=460_800 => (0xf383, 0x07),
|
||||
460_801..=921_600 => (0xf387, 0x07),
|
||||
_ => return Err(format!("CH34x baud rate {} out of range", line.baud_rate)),
|
||||
};
|
||||
write(&mut transfer, 0x1312, index1312)?;
|
||||
write(&mut transfer, 0x0f2c, index0f2c)?;
|
||||
check(&mut transfer)?;
|
||||
write(&mut transfer, 0x2727, 0)?;
|
||||
|
||||
let mut lcr: u16 = 0x80 | 0x40;
|
||||
lcr |= match line.data_bits {
|
||||
5 => 0x00,
|
||||
6 => 0x01,
|
||||
7 => 0x02,
|
||||
8 => 0x03,
|
||||
bits => return Err(format!("CH34x cannot use {bits} data bits")),
|
||||
};
|
||||
lcr |= match line.parity {
|
||||
UsbParity::None => 0,
|
||||
UsbParity::Odd => 0x08,
|
||||
UsbParity::Even => 0x18,
|
||||
};
|
||||
if line.stop_bits == 2 {
|
||||
lcr |= 0x04;
|
||||
}
|
||||
write(&mut transfer, 0x2518, lcr)?;
|
||||
check(&mut transfer)?;
|
||||
write(&mut transfer, 0x2727, 0)?;
|
||||
|
||||
check(&mut transfer)?;
|
||||
write(&mut transfer, 0x2727, 0)
|
||||
}
|
||||
|
||||
/// usbserial4a `FtdiSerial._filterStatusBytes`: every bulk IN packet starts
|
||||
/// with two modem-status bytes.
|
||||
pub(crate) fn strip_ftdi_status(raw: &[u8], max_packet_size: usize) -> Vec<u8> {
|
||||
let mut payload = Vec::with_capacity(raw.len());
|
||||
for packet in raw.chunks(max_packet_size.max(3)) {
|
||||
if packet.len() > 2 {
|
||||
payload.extend_from_slice(&packet[2..]);
|
||||
}
|
||||
}
|
||||
payload
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every control request usbserial4a 0.4.0 issues when upstream's Android
|
||||
/// interfaces open an FTDI, CH34x or force-CDC CH9102 adapter.
|
||||
#[test]
|
||||
fn usb_serial_setup_matches_usbserial4a() {
|
||||
let golden: serde_json::Value = serde_json::from_str(include_str!(
|
||||
"../tests/fixtures/android_usb_serial/cases.json"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(golden["usbserial4a_version"], "0.4.0");
|
||||
for case in golden["cases"].as_array().unwrap() {
|
||||
let vid = case["vid"].as_i64().unwrap() as i32;
|
||||
let pid = case["pid"].as_i64().unwrap() as i32;
|
||||
let descriptors: Vec<_> = match case["device"].as_str().unwrap() {
|
||||
"ch340" => vec![interface(0, 0xff, 0, &[(0x80, 3), (0x80, 2), (0, 2)])],
|
||||
"ch9102_forced_cdc" => vec![
|
||||
interface(0, 2, 2, &[(0x80, 3)]),
|
||||
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]),
|
||||
],
|
||||
_ => vec![interface(0, 0xff, 0, &[(0x80, 2), (0, 2)])],
|
||||
};
|
||||
let port = select_serial_port(vid, pid, &descriptors).expect("selectable");
|
||||
let line = UsbSerialLine {
|
||||
baud_rate: case["baud"].as_u64().unwrap() as u32,
|
||||
data_bits: case["databits"].as_u64().unwrap() as u8,
|
||||
parity: match case["parity"].as_str().unwrap() {
|
||||
"E" => UsbParity::Even,
|
||||
"O" => UsbParity::Odd,
|
||||
_ => UsbParity::None,
|
||||
},
|
||||
stop_bits: case["stopbits"].as_u64().unwrap() as u8,
|
||||
};
|
||||
let mut requests = Vec::new();
|
||||
configure_serial_port(&port, &line, |request| {
|
||||
let input = request.request_type & 0x80 != 0;
|
||||
requests.push(serde_json::json!([
|
||||
request.request_type,
|
||||
request.request,
|
||||
request.value,
|
||||
request.index,
|
||||
if input {
|
||||
String::new()
|
||||
} else {
|
||||
hex::encode(request.payload)
|
||||
},
|
||||
request.payload.len(),
|
||||
]));
|
||||
Ok(request.payload.len() as i32)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(&requests, case["requests"].as_array().unwrap(), "{case}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ftdi_status_bytes_are_stripped_per_packet() {
|
||||
let raw: Vec<u8> = [vec![0x01, 0x60], vec![7; 62], vec![0x01, 0x60], vec![9, 9]].concat();
|
||||
assert_eq!(
|
||||
strip_ftdi_status(&raw, 64),
|
||||
[vec![7; 62], vec![9, 9]].concat()
|
||||
);
|
||||
assert!(strip_ftdi_status(&[0x01, 0x60], 64).is_empty());
|
||||
assert_eq!(usb_read_timeout_ms(0x10c4, 0xea60), 12);
|
||||
assert_eq!(usb_read_timeout_ms(0x1a86, 0x55d4), 12);
|
||||
assert_eq!(usb_read_timeout_ms(0x0403, 0x6001), 100);
|
||||
}
|
||||
|
||||
fn interface(
|
||||
number: u16,
|
||||
class: i32,
|
||||
subclass: i32,
|
||||
endpoints: &[(i32, i32)],
|
||||
) -> UsbInterfaceDescriptor {
|
||||
UsbInterfaceDescriptor {
|
||||
number,
|
||||
alternate_setting: 0,
|
||||
class,
|
||||
subclass,
|
||||
endpoints: endpoints
|
||||
.iter()
|
||||
.map(|&(direction, transfer_type)| UsbEndpointDescriptor {
|
||||
direction,
|
||||
transfer_type,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cp210x() -> UsbSerialPort {
|
||||
select_serial_port(
|
||||
0x10c4,
|
||||
0xea60,
|
||||
&[interface(4, 0xff, 0, &[(0x80, 2), (0, 2)])],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cp210x_setup_is_scoped_and_uses_vendor_requests_without_reset() {
|
||||
let descriptors = [interface(4, 0xff, 0, &[(0x80, 2), (0, 2)])];
|
||||
for (vid, pid) in [(0x10c4, 0xea61), (0x303a, 0x1001)] {
|
||||
assert!(select_serial_port(vid, pid, &descriptors).is_err());
|
||||
}
|
||||
let mut requests = Vec::new();
|
||||
configure_serial_port(&cp210x(), &UsbSerialLine::eight_n_one(115_200), |request| {
|
||||
requests.push((
|
||||
request.request_type,
|
||||
request.request,
|
||||
request.value,
|
||||
request.index,
|
||||
request.payload.to_vec(),
|
||||
));
|
||||
Ok(request.payload.len() as i32)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
requests,
|
||||
vec![
|
||||
(0x41, 0x00, 1, 4, vec![]),
|
||||
(0x41, 0x1e, 0, 4, vec![0x00, 0xc2, 0x01, 0x00]),
|
||||
(0x41, 0x03, 0x0800, 4, vec![]),
|
||||
(
|
||||
0x41,
|
||||
0x13,
|
||||
0,
|
||||
4,
|
||||
vec![1, 0, 0, 0, 0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
),
|
||||
(0x41, 0x07, 0x0303, 4, vec![]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cdc_uses_actual_control_number_and_only_bulk_endpoints() {
|
||||
let port = select_serial_port(
|
||||
0x303a,
|
||||
0x1001,
|
||||
&[
|
||||
interface(0, 0xff, 0, &[(0x80, 2), (0, 2)]), // JTAG, not CDC.
|
||||
interface(6, 0x02, 0x02, &[(0x80, 3)]),
|
||||
interface(7, 0x0a, 0, &[(0x80, 3), (0x80, 2), (0, 2), (0, 3)]),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(port.data_interface, 2);
|
||||
assert_eq!(port.control_interface, 1);
|
||||
assert_eq!((port.input_endpoint, port.output_endpoint), (1, 2));
|
||||
let mut requests = Vec::new();
|
||||
configure_serial_port(&port, &UsbSerialLine::eight_n_one(9_600), |request| {
|
||||
requests.push((
|
||||
request.request_type,
|
||||
request.request,
|
||||
request.value,
|
||||
request.index,
|
||||
request.payload.to_vec(),
|
||||
));
|
||||
Ok(request.payload.len() as i32)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
requests,
|
||||
vec![
|
||||
(0x21, 0x22, 3, 6, vec![]),
|
||||
(0x21, 0x20, 0, 6, vec![0x80, 0x25, 0, 0, 0, 0, 8]),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selection_rejects_incomplete_ambiguous_and_nonbulk_interfaces() {
|
||||
let control = interface(0, 2, 2, &[(0x80, 3)]);
|
||||
let data = interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]);
|
||||
for descriptors in [
|
||||
vec![data.clone()],
|
||||
vec![control.clone(), interface(1, 0x0a, 0, &[(0x80, 3), (0, 3)])],
|
||||
vec![
|
||||
control.clone(),
|
||||
interface(1, 0x0a, 0, &[(0x80, 2)]),
|
||||
interface(2, 0x0a, 0, &[(0, 2)]),
|
||||
],
|
||||
vec![control.clone(), data.clone(), interface(2, 2, 2, &[])],
|
||||
vec![
|
||||
control.clone(),
|
||||
data.clone(),
|
||||
interface(2, 0x0a, 0, &[(0x80, 2), (0, 2)]),
|
||||
],
|
||||
vec![
|
||||
control.clone(),
|
||||
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2), (0, 2)]),
|
||||
],
|
||||
] {
|
||||
assert!(select_serial_port(0x303a, 0x1001, &descriptors).is_err());
|
||||
}
|
||||
let mut alternate = data.clone();
|
||||
alternate.alternate_setting = 1;
|
||||
assert!(select_serial_port(0x303a, 0x1001, &[control, alternate]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_stops_on_every_failed_short_or_impossible_control_completion() {
|
||||
let cdc = select_serial_port(
|
||||
0x303a,
|
||||
0x1001,
|
||||
&[
|
||||
interface(0, 2, 2, &[]),
|
||||
interface(1, 0x0a, 0, &[(0x80, 2), (0, 2)]),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
for (port, count) in [(cp210x(), 5), (cdc, 2)] {
|
||||
for fail_at in 0..count {
|
||||
for failure in 0..4 {
|
||||
let mut called = 0;
|
||||
let result = configure_serial_port(
|
||||
&port,
|
||||
&UsbSerialLine::eight_n_one(115_200),
|
||||
|request| {
|
||||
let index = called;
|
||||
called += 1;
|
||||
let length = request.payload.len() as i32;
|
||||
if index != fail_at {
|
||||
return Ok(length);
|
||||
}
|
||||
match failure {
|
||||
0 => Err("JNI exception".into()),
|
||||
1 => Ok(-1),
|
||||
2 => Ok(length - 1),
|
||||
_ => Ok(length + 1),
|
||||
}
|
||||
},
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(called, fail_at + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
configure_serial_port(&cp210x(), &UsbSerialLine::eight_n_one(0), |_| panic!(
|
||||
"invalid baud must not touch USB"
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Owned Objective-C values for the Apple BLE modules. Their calls run on Tokio
|
||||
//! workers and other threads with no autorelease pool, where an autoreleased
|
||||
//! object lives until the thread exits.
|
||||
|
||||
use objc2::msg_send;
|
||||
use objc2::rc::{Allocated, Retained};
|
||||
use objc2::runtime::{AnyClass, AnyObject};
|
||||
use objc2_foundation::NSString;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// `UUIDWithString:` autoreleases, so call this inside `autoreleasepool`.
|
||||
pub(crate) fn cbuuid(uuid: &Uuid) -> Retained<AnyObject> {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
let cls = AnyClass::get(c"CBUUID").expect("CBUUID must exist at runtime");
|
||||
unsafe { msg_send![cls, UUIDWithString: &*s] }
|
||||
}
|
||||
|
||||
/// A copy of `bytes`, never autoreleased.
|
||||
pub(crate) fn nsdata(bytes: &[u8]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSData").expect("NSData must exist at runtime");
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj,
|
||||
initWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Never autoreleased; the array retains each element.
|
||||
pub(crate) fn nsarray(objects: &[&AnyObject]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSArray").expect("NSArray must exist at runtime");
|
||||
let ptrs: Vec<*const AnyObject> = objects.iter().map(|o| *o as *const AnyObject).collect();
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj, initWithObjects: ptrs.as_ptr(), count: ptrs.len()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use objc2::rc::{Weak, autoreleasepool};
|
||||
|
||||
/// Runs `make` on a thread with no autorelease pool, drops what it returns,
|
||||
/// and reports whether every returned object was freed. A stray retain or
|
||||
/// an autorelease outside `make`'s own pool keeps the object alive.
|
||||
pub(crate) fn freed_on_drop<F>(make: F) -> bool
|
||||
where
|
||||
F: FnOnce() -> Vec<Retained<AnyObject>> + Send + 'static,
|
||||
{
|
||||
std::thread::spawn(move || {
|
||||
let weak: Vec<Weak<AnyObject>> = {
|
||||
let objs = make();
|
||||
let weak: Vec<_> = objs.iter().map(Weak::from_retained).collect();
|
||||
// A class without weak-reference support would pass vacuously.
|
||||
assert!(weak.iter().all(|w| w.load().is_some()));
|
||||
weak
|
||||
};
|
||||
weak.iter().all(|w| w.load().is_none())
|
||||
})
|
||||
.join()
|
||||
.expect("probe thread")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_sees_an_autoreleased_object() {
|
||||
assert!(!freed_on_drop(|| {
|
||||
let cls = AnyClass::get(c"NSData").unwrap();
|
||||
let bytes = [0xCDu8; 300];
|
||||
unsafe {
|
||||
let raw: *mut AnyObject = msg_send![cls,
|
||||
dataWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()];
|
||||
vec![Retained::retain(raw).unwrap()]
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsdata_and_nsarray_are_never_autoreleased() {
|
||||
assert!(freed_on_drop(|| {
|
||||
let data = nsdata(&[0xAB; 300]);
|
||||
let arr = nsarray(&[&data]);
|
||||
vec![data, arr]
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cbuuid_holds_no_extra_retain() {
|
||||
assert!(freed_on_drop(|| {
|
||||
autoreleasepool(|_| vec![cbuuid(&crate::ble_peer::RATSPEAK_SERVICE_UUID)])
|
||||
}));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,537 @@
|
||||
//! Host NIC enumeration for AutoInterface.
|
||||
|
||||
use std::net::Ipv6Addr;
|
||||
|
||||
use super::{AutoPlatform, interface_selectable};
|
||||
|
||||
/// One enumerated host NIC, returned by [`list_network_interfaces`].
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct NetworkInterfaceInfo {
|
||||
pub name: String,
|
||||
pub addr_v4: Option<String>,
|
||||
pub addr_v6_link_local: Option<String>,
|
||||
pub is_up: bool,
|
||||
pub is_loopback: bool,
|
||||
}
|
||||
|
||||
/// Enumerate addresses reported by the host and group them by NIC name,
|
||||
/// including loopback and normally ignored names. Callers apply filters.
|
||||
/// `is_up` means an address was found; it is not a carrier or reachability test.
|
||||
pub fn list_network_interfaces() -> Result<Vec<NetworkInterfaceInfo>, String> {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
let mut by_name: BTreeMap<String, NetworkInterfaceInfo> = BTreeMap::new();
|
||||
let ifaces =
|
||||
if_addrs::get_if_addrs().map_err(|e| format!("if_addrs::get_if_addrs() failed: {e}"))?;
|
||||
for iface in ifaces {
|
||||
let entry = by_name
|
||||
.entry(iface.name.clone())
|
||||
.or_insert_with(|| NetworkInterfaceInfo {
|
||||
name: iface.name.clone(),
|
||||
addr_v4: None,
|
||||
addr_v6_link_local: None,
|
||||
is_up: false,
|
||||
is_loopback: iface.is_loopback(),
|
||||
});
|
||||
entry.is_loopback = entry.is_loopback || iface.is_loopback();
|
||||
match iface.addr.ip() {
|
||||
std::net::IpAddr::V4(v4) => {
|
||||
if entry.addr_v4.is_none() {
|
||||
entry.addr_v4 = Some(v4.to_string());
|
||||
}
|
||||
entry.is_up = true;
|
||||
}
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
// fe80::/10 — link-local prefix used by AutoInterface discovery.
|
||||
if (v6.segments()[0] & 0xffc0) == 0xfe80 && entry.addr_v6_link_local.is_none() {
|
||||
entry.addr_v6_link_local = Some(v6.to_string());
|
||||
}
|
||||
entry.is_up = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
match darwin_link_local_addrs(None, &[], false) {
|
||||
Ok(addrs) => {
|
||||
for (name, addr, _) in addrs {
|
||||
let entry =
|
||||
by_name
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| NetworkInterfaceInfo {
|
||||
name,
|
||||
addr_v4: None,
|
||||
addr_v6_link_local: None,
|
||||
is_up: true,
|
||||
is_loopback: false,
|
||||
});
|
||||
entry.addr_v6_link_local = Some(addr.to_string());
|
||||
entry.is_up = true;
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::debug!(error = %e, "Darwin getifaddrs link-local list failed"),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(by_name.into_values().collect())
|
||||
}
|
||||
|
||||
/// Clear the scope that BSD kernels embed in the second segment of a
|
||||
/// link-local address (`descope_linklocal`, AutoInterface.py).
|
||||
#[cfg(any(target_os = "macos", test))]
|
||||
fn normalize_link_local_addr(addr: Ipv6Addr) -> Ipv6Addr {
|
||||
if (addr.segments()[0] & 0xffc0) != 0xfe80 {
|
||||
return addr;
|
||||
}
|
||||
let mut segments = addr.segments();
|
||||
segments[1] = 0;
|
||||
Ipv6Addr::from(segments)
|
||||
}
|
||||
|
||||
fn passes_filters(
|
||||
iface_name: &str,
|
||||
devices: Option<&[String]>,
|
||||
ignored_devices: &[String],
|
||||
) -> bool {
|
||||
interface_selectable(AutoPlatform::CURRENT, iface_name, devices, ignored_devices)
|
||||
}
|
||||
|
||||
/// Enumerate link-local IPv6 addresses, applying device/ignore filters.
|
||||
/// Drops addresses with unresolvable scope id — `scope_id = 0` silently
|
||||
/// routes via the default NIC, which is wrong on multi-homed hosts.
|
||||
pub(super) fn get_link_local_addrs(
|
||||
devices: Option<&[String]>,
|
||||
ignored_devices: &[String],
|
||||
) -> Vec<(String, Ipv6Addr, u32)> {
|
||||
// Android's libc getifaddrs() hides IPv6 link-local from app context;
|
||||
// must use Java NetworkInterface.getNetworkInterfaces() via JNI.
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
match get_link_local_addrs_android(devices, ignored_devices) {
|
||||
Ok(v) if !v.is_empty() => {
|
||||
tracing::info!(count = v.len(), "Android JNI link-local enumerate");
|
||||
return v;
|
||||
}
|
||||
Ok(_) => {
|
||||
tracing::warn!(
|
||||
"Android JNI link-local enumerate returned 0 — falling back to if_addrs"
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "Android JNI link-local enumerate failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut result = Vec::new();
|
||||
match if_addrs::get_if_addrs() {
|
||||
Ok(ifaces) => {
|
||||
tracing::debug!(count = ifaces.len(), "if_addrs enumerated interfaces");
|
||||
for iface in ifaces {
|
||||
tracing::debug!(name = %iface.name, addr = ?iface.addr.ip(), "if_addrs entry");
|
||||
if !passes_filters(&iface.name, devices, ignored_devices) {
|
||||
continue;
|
||||
}
|
||||
if let std::net::IpAddr::V6(addr) = iface.addr.ip()
|
||||
&& (addr.segments()[0] & 0xffc0) == 0xfe80
|
||||
{
|
||||
let scope_id = iface_scope_id(&iface);
|
||||
if scope_id == 0 {
|
||||
tracing::warn!(
|
||||
iface = %iface.name,
|
||||
addr = %addr,
|
||||
"skipping link-local: could not resolve scope id (would send on wrong NIC)"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
result.push((iface.name.clone(), addr, scope_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "if_addrs::get_if_addrs() failed");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
if result.is_empty() {
|
||||
match darwin_link_local_addrs(devices, ignored_devices, true) {
|
||||
Ok(addrs) if !addrs.is_empty() => {
|
||||
tracing::debug!(
|
||||
count = addrs.len(),
|
||||
"Darwin getifaddrs link-local enumerate"
|
||||
);
|
||||
return addrs;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => tracing::warn!(error = %e, "Darwin getifaddrs link-local enumerate failed"),
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn darwin_link_local_addrs(
|
||||
devices: Option<&[String]>,
|
||||
ignored_devices: &[String],
|
||||
apply_filters: bool,
|
||||
) -> Result<Vec<(String, Ipv6Addr, u32)>, String> {
|
||||
use std::ffi::CStr;
|
||||
use std::ptr;
|
||||
|
||||
let mut ifap: *mut libc::ifaddrs = ptr::null_mut();
|
||||
// SAFETY: getifaddrs initialises `ifap` on success; the linked list is
|
||||
// released with freeifaddrs before return.
|
||||
if unsafe { libc::getifaddrs(&mut ifap) } != 0 {
|
||||
return Err(std::io::Error::last_os_error().to_string());
|
||||
}
|
||||
|
||||
struct IfAddrsGuard(*mut libc::ifaddrs);
|
||||
impl Drop for IfAddrsGuard {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: pointer came from successful getifaddrs and is released once.
|
||||
unsafe { libc::freeifaddrs(self.0) };
|
||||
}
|
||||
}
|
||||
let _guard = IfAddrsGuard(ifap);
|
||||
|
||||
let mut result = Vec::new();
|
||||
let mut cursor = ifap;
|
||||
while !cursor.is_null() {
|
||||
// SAFETY: cursor walks the null-terminated getifaddrs list.
|
||||
let ifa = unsafe { &*cursor };
|
||||
cursor = ifa.ifa_next;
|
||||
|
||||
if ifa.ifa_addr.is_null() || ifa.ifa_name.is_null() {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: getifaddrs provides a nul-terminated interface name.
|
||||
let name = unsafe { CStr::from_ptr(ifa.ifa_name) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
if apply_filters && !passes_filters(&name, devices, ignored_devices) {
|
||||
continue;
|
||||
}
|
||||
if ifa.ifa_flags & libc::IFF_UP as u32 == 0 {
|
||||
continue;
|
||||
}
|
||||
// SAFETY: ifa_addr is non-null and points to a sockaddr for this entry.
|
||||
let family = unsafe { (*ifa.ifa_addr).sa_family as i32 };
|
||||
if family != libc::AF_INET6 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// SAFETY: family is AF_INET6, so sockaddr_in6 layout is valid.
|
||||
let sin6 = unsafe { &*(ifa.ifa_addr as *const libc::sockaddr_in6) };
|
||||
let addr = normalize_link_local_addr(Ipv6Addr::from(sin6.sin6_addr.s6_addr));
|
||||
if (addr.segments()[0] & 0xffc0) != 0xfe80 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let scope_id = if sin6.sin6_scope_id != 0 {
|
||||
sin6.sin6_scope_id
|
||||
} else {
|
||||
iface_name_to_scope_id(&name)
|
||||
};
|
||||
if scope_id == 0 {
|
||||
tracing::warn!(
|
||||
iface = %name,
|
||||
addr = %addr,
|
||||
"skipping Darwin link-local: could not resolve scope id"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if result.iter().any(|(existing, _, _)| existing == &name) {
|
||||
continue;
|
||||
}
|
||||
tracing::debug!(iface = %name, addr = %addr, scope_id, "Darwin link-local found");
|
||||
result.push((name, addr, scope_id));
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
fn get_link_local_addrs_android(
|
||||
devices: Option<&[String]>,
|
||||
ignored_devices: &[String],
|
||||
) -> Result<Vec<(String, Ipv6Addr, u32)>, String> {
|
||||
use jni::objects::JObject;
|
||||
|
||||
let vm = crate::android_usb::java_vm().ok_or("JavaVM not initialized")?;
|
||||
let env = vm
|
||||
.attach_current_thread()
|
||||
.map_err(|e| format!("attach_current_thread: {e}"))?;
|
||||
|
||||
let ni_class = env
|
||||
.find_class("java/net/NetworkInterface")
|
||||
.map_err(|e| format!("NetworkInterface class: {e}"))?;
|
||||
let inet6_class = env
|
||||
.find_class("java/net/Inet6Address")
|
||||
.map_err(|e| format!("Inet6Address class: {e}"))?;
|
||||
|
||||
let ifaces_enum = env
|
||||
.call_static_method(
|
||||
ni_class,
|
||||
"getNetworkInterfaces",
|
||||
"()Ljava/util/Enumeration;",
|
||||
&[],
|
||||
)
|
||||
.map_err(|e| format!("getNetworkInterfaces: {e}"))?
|
||||
.l()
|
||||
.map_err(|e| format!("getNetworkInterfaces obj: {e}"))?;
|
||||
if ifaces_enum.is_null() {
|
||||
return Err("getNetworkInterfaces returned null".into());
|
||||
}
|
||||
|
||||
let mut result: Vec<(String, Ipv6Addr, u32)> = Vec::new();
|
||||
|
||||
while env
|
||||
.call_method(ifaces_enum, "hasMoreElements", "()Z", &[])
|
||||
.map_err(|e| format!("hasMoreElements: {e}"))?
|
||||
.z()
|
||||
.map_err(|e| format!("hasMoreElements bool: {e}"))?
|
||||
{
|
||||
let iface_obj: JObject = env
|
||||
.call_method(ifaces_enum, "nextElement", "()Ljava/lang/Object;", &[])
|
||||
.map_err(|e| format!("nextElement (iface): {e}"))?
|
||||
.l()
|
||||
.map_err(|e| format!("nextElement iface obj: {e}"))?;
|
||||
if iface_obj.is_null() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_up = env
|
||||
.call_method(iface_obj, "isUp", "()Z", &[])
|
||||
.map_err(|e| format!("isUp: {e}"))?
|
||||
.z()
|
||||
.map_err(|e| format!("isUp bool: {e}"))?;
|
||||
if !is_up {
|
||||
continue;
|
||||
}
|
||||
|
||||
let name_obj: JObject = env
|
||||
.call_method(iface_obj, "getName", "()Ljava/lang/String;", &[])
|
||||
.map_err(|e| format!("getName: {e}"))?
|
||||
.l()
|
||||
.map_err(|e| format!("getName obj: {e}"))?;
|
||||
let name: String = if name_obj.is_null() {
|
||||
String::new()
|
||||
} else {
|
||||
env.get_string(name_obj.into())
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
if !passes_filters(&name, devices, ignored_devices) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let scope_id = env
|
||||
.call_method(iface_obj, "getIndex", "()I", &[])
|
||||
.map_err(|e| format!("getIndex: {e}"))?
|
||||
.i()
|
||||
.map_err(|e| format!("getIndex int: {e}"))? as u32;
|
||||
if scope_id == 0 {
|
||||
tracing::warn!(
|
||||
iface = %name,
|
||||
"skipping JNI link-local: getIndex returned 0 (interface may have just gone down)"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let addrs_enum: JObject = env
|
||||
.call_method(
|
||||
iface_obj,
|
||||
"getInetAddresses",
|
||||
"()Ljava/util/Enumeration;",
|
||||
&[],
|
||||
)
|
||||
.map_err(|e| format!("getInetAddresses: {e}"))?
|
||||
.l()
|
||||
.map_err(|e| format!("getInetAddresses obj: {e}"))?;
|
||||
if addrs_enum.is_null() {
|
||||
continue;
|
||||
}
|
||||
|
||||
while env
|
||||
.call_method(addrs_enum, "hasMoreElements", "()Z", &[])
|
||||
.map_err(|e| format!("addr hasMoreElements: {e}"))?
|
||||
.z()
|
||||
.map_err(|e| format!("addr hasMoreElements bool: {e}"))?
|
||||
{
|
||||
let addr_obj: JObject = env
|
||||
.call_method(addrs_enum, "nextElement", "()Ljava/lang/Object;", &[])
|
||||
.map_err(|e| format!("nextElement (addr): {e}"))?
|
||||
.l()
|
||||
.map_err(|e| format!("nextElement addr obj: {e}"))?;
|
||||
if addr_obj.is_null() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_v6 = env
|
||||
.is_instance_of(addr_obj, inet6_class)
|
||||
.map_err(|e| format!("is_instance_of Inet6Address: {e}"))?;
|
||||
if !is_v6 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_ll = env
|
||||
.call_method(addr_obj, "isLinkLocalAddress", "()Z", &[])
|
||||
.map_err(|e| format!("isLinkLocalAddress: {e}"))?
|
||||
.z()
|
||||
.map_err(|e| format!("isLinkLocalAddress bool: {e}"))?;
|
||||
if !is_ll {
|
||||
continue;
|
||||
}
|
||||
|
||||
let raw_obj: JObject = env
|
||||
.call_method(addr_obj, "getAddress", "()[B", &[])
|
||||
.map_err(|e| format!("getAddress: {e}"))?
|
||||
.l()
|
||||
.map_err(|e| format!("getAddress obj: {e}"))?;
|
||||
if raw_obj.is_null() {
|
||||
continue;
|
||||
}
|
||||
let raw: Vec<u8> = env
|
||||
.convert_byte_array(raw_obj.into_inner())
|
||||
.unwrap_or_default();
|
||||
if raw.len() != 16 {
|
||||
continue;
|
||||
}
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes.copy_from_slice(&raw);
|
||||
let v6 = Ipv6Addr::from(bytes);
|
||||
tracing::info!(iface = %name, addr = %v6, scope_id, "JNI link-local found");
|
||||
result.push((name.clone(), v6, scope_id));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn scope_id_of(name: &str) -> u32 {
|
||||
iface_name_to_scope_id(name)
|
||||
}
|
||||
|
||||
fn iface_scope_id(iface: &if_addrs::Interface) -> u32 {
|
||||
if let Some(index) = iface.index {
|
||||
return index;
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let adapter_index = iface_name_to_scope_id(&iface.adapter_name);
|
||||
if adapter_index != 0 {
|
||||
return adapter_index;
|
||||
}
|
||||
}
|
||||
|
||||
iface_name_to_scope_id(&iface.name)
|
||||
}
|
||||
|
||||
/// Convert interface name to scope ID via POSIX/Windows `if_nametoindex`.
|
||||
/// Returns 0 if the lookup fails; callers must skip the address.
|
||||
#[cfg(any(unix, windows))]
|
||||
fn iface_name_to_scope_id(name: &str) -> u32 {
|
||||
use std::ffi::CString;
|
||||
if let Ok(cname) = CString::new(name) {
|
||||
// SAFETY: if_nametoindex takes a NUL-terminated C string and returns
|
||||
// an index or 0 on error, with no ownership implications.
|
||||
unsafe { libc_if_nametoindex(cname.as_ptr()) }
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
unsafe extern "C" {
|
||||
#[link_name = "if_nametoindex"]
|
||||
fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32;
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[link(name = "iphlpapi")]
|
||||
unsafe extern "C" {
|
||||
#[link_name = "if_nametoindex"]
|
||||
fn libc_if_nametoindex(ifname: *const std::ffi::c_char) -> u32;
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn iface_name_to_scope_id(_name: &str) -> u32 {
|
||||
0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_interface(name: &str, ip: Ipv6Addr, index: Option<u32>) -> if_addrs::Interface {
|
||||
let addr = if_addrs::IfAddr::V6(if_addrs::Ifv6Addr {
|
||||
ip,
|
||||
netmask: Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0, 0, 0, 0),
|
||||
prefixlen: 64,
|
||||
broadcast: None,
|
||||
});
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if_addrs::Interface {
|
||||
name: name.to_string(),
|
||||
addr,
|
||||
index,
|
||||
adapter_name: name.to_string(),
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
if_addrs::Interface {
|
||||
name: name.to_string(),
|
||||
addr,
|
||||
index,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scope_id_prefers_enumerated_interface_index() {
|
||||
let addr = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
|
||||
let iface = test_interface("__ratspeak_missing_iface__", addr, Some(1234));
|
||||
assert_eq!(iface_scope_id(&iface), 1234);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_link_local_addr_clears_embedded_scope_segment() {
|
||||
let addr = Ipv6Addr::new(0xfe80, 0x18, 0, 0, 0, 0, 0, 1);
|
||||
assert_eq!(
|
||||
normalize_link_local_addr(addr),
|
||||
Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1)
|
||||
);
|
||||
let global = Ipv6Addr::new(0xfddd, 0xebe4, 0, 0, 0, 0, 0, 1);
|
||||
assert_eq!(normalize_link_local_addr(global), global);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn if_addrs_link_local_feature_is_enabled() {
|
||||
let proc_addrs = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default();
|
||||
let host_has_link_local = proc_addrs.lines().any(|line| {
|
||||
line.split_whitespace()
|
||||
.nth(3)
|
||||
.is_some_and(|scope| scope.eq_ignore_ascii_case("20"))
|
||||
});
|
||||
if !host_has_link_local {
|
||||
return;
|
||||
}
|
||||
let addrs = if_addrs::get_if_addrs().expect("list network interfaces");
|
||||
assert!(
|
||||
addrs.iter().any(|iface| {
|
||||
matches!(&iface.addr, if_addrs::IfAddr::V6(addr) if addr.is_link_local())
|
||||
}),
|
||||
"Linux has link-local IPv6 addresses in /proc/net/if_inet6, but if-addrs returned none; \
|
||||
keep the workspace if-addrs dependency feature `link-local` enabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 406 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user