mirror of
https://github.com/MetaCubeX/mihomo.git
synced 2026-02-27 17:27:09 +00:00
Compare commits
2509 Commits
Prerelease
...
Prerelease
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3035ae89e3 | ||
|
|
c251e411e5 | ||
|
|
f6722ab79b | ||
|
|
4ca515896b | ||
|
|
836c972c54 | ||
|
|
43509da1a9 | ||
|
|
3752cb044f | ||
|
|
30391b40c4 | ||
|
|
05fbf552ec | ||
|
|
e4143cf1ad | ||
|
|
5eaf5d16ce | ||
|
|
9dee264f13 | ||
|
|
50480406cf | ||
|
|
6eb27ac3dc | ||
|
|
a949ad883c | ||
|
|
20bf57c117 | ||
|
|
60a9312057 | ||
|
|
9fda032a28 | ||
|
|
c3399fd346 | ||
|
|
445083b624 | ||
|
|
97f25250a6 | ||
|
|
8b0bcb6740 | ||
|
|
022f677385 | ||
|
|
32799662ad | ||
|
|
86257fc83c | ||
|
|
f2222b5e02 | ||
|
|
3ac62152cb | ||
|
|
5516ca18fd | ||
|
|
3bca69c745 | ||
|
|
558b3840ea | ||
|
|
f94da9f2b3 | ||
|
|
2cfc4ba044 | ||
|
|
034f1d1e9b | ||
|
|
dede56fe4b | ||
|
|
5fda87d50e | ||
|
|
5e1b133e4e | ||
|
|
27a3ca6afc | ||
|
|
7573affdd4 | ||
|
|
17fbaf9100 | ||
|
|
710772f993 | ||
|
|
d36b024b10 | ||
|
|
f52c9356c2 | ||
|
|
e45c896185 | ||
|
|
d18a14afeb | ||
|
|
6aaabc97ca | ||
|
|
85c024a4a6 | ||
|
|
c33c90d7af | ||
|
|
65c3d3e4e2 | ||
|
|
98b3060558 | ||
|
|
b90100645e | ||
|
|
46ee1649c0 | ||
|
|
e3b8fc2b77 | ||
|
|
707fe8b207 | ||
|
|
1e1434d1de | ||
|
|
26052ba5e5 | ||
|
|
75a0cd5aff | ||
|
|
e03ba23f65 | ||
|
|
0c995a2479 | ||
|
|
3c526ae06e | ||
|
|
0b009b514c | ||
|
|
18d139a15d | ||
|
|
5f250413fe | ||
|
|
993595df73 | ||
|
|
828fd30dc3 | ||
|
|
11000dccd7 | ||
|
|
0818aa54aa | ||
|
|
edbfebeacd | ||
|
|
06f5fbac06 | ||
|
|
f38fc2020f | ||
|
|
97bce45eba | ||
|
|
bc28cd486a | ||
|
|
cdabd1e8b1 | ||
|
|
c5b0f00bb2 | ||
|
|
c128d23dec | ||
|
|
ee37a353d0 | ||
|
|
0cf37de1a8 | ||
|
|
ae6069c178 | ||
|
|
c8e33a4347 | ||
|
|
19a6b5d6f7 | ||
|
|
efb800866e | ||
|
|
94c8d60f72 | ||
|
|
0f2baca2de | ||
|
|
b18a33552c | ||
|
|
487de9b548 | ||
|
|
1a6230ec03 | ||
|
|
e6bf56b9af | ||
|
|
0ad9ac325a | ||
|
|
d6b1263236 | ||
|
|
4d7670339b | ||
|
|
0cffc8d76d | ||
|
|
1f8bee9710 | ||
|
|
eb30d3f331 | ||
|
|
10f4bebdfa | ||
|
|
06387d5045 | ||
|
|
c393e917eb | ||
|
|
4f0a6fa117 | ||
|
|
4f9bfd216f | ||
|
|
498f81aad3 | ||
|
|
9168bee6b7 | ||
|
|
e6c0e3b19c | ||
|
|
287f9e5185 | ||
|
|
c456370f4f | ||
|
|
10ef29f5cd | ||
|
|
85ba7f6a0a | ||
|
|
7daf37bc15 | ||
|
|
64015b7634 | ||
|
|
5585304d68 | ||
|
|
911211578c | ||
|
|
abb55199f2 | ||
|
|
87c3f700e5 | ||
|
|
4a723e8d3f | ||
|
|
93cf46e430 | ||
|
|
35a1130c92 | ||
|
|
1ebcb25e4a | ||
|
|
cbcacdbb8c | ||
|
|
17966b5418 | ||
|
|
bc8f0dcf77 | ||
|
|
827cd616e8 | ||
|
|
e1384e86ab | ||
|
|
b92b38701c | ||
|
|
1cab34d257 | ||
|
|
a06097c2c4 | ||
|
|
bc9db11cb4 | ||
|
|
69e301820c | ||
|
|
e7a04e0762 | ||
|
|
7e8c2876fb | ||
|
|
936ebc7718 | ||
|
|
b753a57e6a | ||
|
|
dd99bfc892 | ||
|
|
2a1b3b2aed | ||
|
|
2211789a7c | ||
|
|
e652e277a7 | ||
|
|
40863d248d | ||
|
|
17b8eb8772 | ||
|
|
6b40072bc5 | ||
|
|
f44aa22d50 | ||
|
|
c33d9ad857 | ||
|
|
25041b599e | ||
|
|
6539b509cb | ||
|
|
d2007fdc22 | ||
|
|
b5fa3ee99a | ||
|
|
91f5593f4e | ||
|
|
90470ac304 | ||
|
|
b509affe5b | ||
|
|
32ce513977 | ||
|
|
30891f8781 | ||
|
|
e4cdb9b600 | ||
|
|
d33dbbe2f9 | ||
|
|
d8dcaa7500 | ||
|
|
9df8392c65 | ||
|
|
fdb7cb1f58 | ||
|
|
7cd58fbdf6 | ||
|
|
bc719eb96d | ||
|
|
ac90543548 | ||
|
|
9a5e506f66 | ||
|
|
a001b1b110 | ||
|
|
d1f89fa05e | ||
|
|
e2796e2d5c | ||
|
|
93de49d20c | ||
|
|
4d3167ff2f | ||
|
|
5998956a72 | ||
|
|
6cf1743961 | ||
|
|
8b6ba22b90 | ||
|
|
7571c87afb | ||
|
|
d4d2c062a3 | ||
|
|
438d4138d6 | ||
|
|
140d892ccf | ||
|
|
5aa140c493 | ||
|
|
c107c6a824 | ||
|
|
f6e494e73f | ||
|
|
0b3159bf9b | ||
|
|
45fd628788 | ||
|
|
2f545ef634 | ||
|
|
054e63cb3f | ||
|
|
d48bcf1e1e | ||
|
|
0df2f79ece | ||
|
|
644c04fdc9 | ||
|
|
926aaec717 | ||
|
|
a4b76809ac | ||
|
|
ff76576cbe | ||
|
|
1d5890abc1 | ||
|
|
a3c023ae3e | ||
|
|
8b32c4371e | ||
|
|
5a285acd32 | ||
|
|
c2209d68f7 | ||
|
|
fd39c2a7fc | ||
|
|
421dc79aea | ||
|
|
27b47f976c | ||
|
|
c25a38898f | ||
|
|
f3edbc2b45 | ||
|
|
6fb1f796a5 | ||
|
|
99e68e9983 | ||
|
|
6bffbdd9d3 | ||
|
|
cfdaebe952 | ||
|
|
c8af92a01f | ||
|
|
ff62386f6b | ||
|
|
85c56e7446 | ||
|
|
9ed9c3d1c3 | ||
|
|
dcfe664a7d | ||
|
|
fb1ae21fb7 | ||
|
|
90f47a6d0c | ||
|
|
f2bf4a077e | ||
|
|
8701639347 | ||
|
|
5bc0ac7281 | ||
|
|
c5fe3670ef | ||
|
|
de2ff37f4f | ||
|
|
da69b192f2 | ||
|
|
c13549f564 | ||
|
|
ce168c0e67 | ||
|
|
d225625378 | ||
|
|
40e0813869 | ||
|
|
94b591ed44 | ||
|
|
f7bd8b83e5 | ||
|
|
f45c6f5e91 | ||
|
|
3b15cbd9eb | ||
|
|
6f4da5f1fb | ||
|
|
fdc46f0471 | ||
|
|
57b527d54a | ||
|
|
29eaa4d699 | ||
|
|
92ecdfcc00 | ||
|
|
0992ee8adf | ||
|
|
0c25831726 | ||
|
|
9cc208bd47 | ||
|
|
b57f3052a8 | ||
|
|
3a1caf1316 | ||
|
|
1b1f95aa9c | ||
|
|
8a9300d44e | ||
|
|
abe6c3bb35 | ||
|
|
e28c8e6a51 | ||
|
|
74a86f147b | ||
|
|
7917f24f42 | ||
|
|
0dc5e3051d | ||
|
|
40b2cde2b2 | ||
|
|
6786705212 | ||
|
|
00638f30a7 | ||
|
|
2222d0e3fa | ||
|
|
f3ebd5c489 | ||
|
|
74e64d31e3 | ||
|
|
0c556bcaf3 | ||
|
|
7e71d21ab4 | ||
|
|
30bead4e2e | ||
|
|
16836ea465 | ||
|
|
d6f1af5372 | ||
|
|
26335f8ecc | ||
|
|
c4449a9f62 | ||
|
|
5e17d6fe01 | ||
|
|
8cdfd87d1e | ||
|
|
f02766a765 | ||
|
|
cea29e2615 | ||
|
|
a0f1ac4ef5 | ||
|
|
57e14e5b62 | ||
|
|
08fc100c85 | ||
|
|
571be856ea | ||
|
|
ad69ee84a9 | ||
|
|
dd7b3c28ad | ||
|
|
1b99759eaf | ||
|
|
a8f7e25851 | ||
|
|
909729ca8f | ||
|
|
6c527f8d20 | ||
|
|
7061c5a8ea | ||
|
|
23448ec119 | ||
|
|
318b3524c3 | ||
|
|
1d09ed82f1 | ||
|
|
b27325eed0 | ||
|
|
0d3d31dc5f | ||
|
|
108bf645fa | ||
|
|
50e1afd963 | ||
|
|
0336d64e52 | ||
|
|
02d954bfa8 | ||
|
|
9a124a390f | ||
|
|
fed4b369a3 | ||
|
|
f8ee5c1e15 | ||
|
|
8eba1c8afd | ||
|
|
65d3920f02 | ||
|
|
7e9e12cc4c | ||
|
|
80a90f05f3 | ||
|
|
3b63fef2eb | ||
|
|
29872007b3 | ||
|
|
33cde6592e | ||
|
|
c98f5f44b7 | ||
|
|
d094075c88 | ||
|
|
4188277b61 | ||
|
|
545d9b844d | ||
|
|
472cefb6d7 | ||
|
|
ccff0035cb | ||
|
|
455f2136f1 | ||
|
|
63781b3a6a | ||
|
|
c6e596f33f | ||
|
|
45cb45accb | ||
|
|
5c73025b53 | ||
|
|
cdd02a90c3 | ||
|
|
0ced98da4d | ||
|
|
84086a6e6c | ||
|
|
443200a51e | ||
|
|
aca0d97beb | ||
|
|
2605bf78f9 | ||
|
|
d2395fb43a | ||
|
|
e3d9a8e2fd | ||
|
|
1ae050ca3b | ||
|
|
7f38763e22 | ||
|
|
2a8831b0d0 | ||
|
|
cdf5e0c73e | ||
|
|
48f3ea8bc9 | ||
|
|
375e160368 | ||
|
|
b31664beeb | ||
|
|
7960bcae15 | ||
|
|
664ddb8d55 | ||
|
|
e4dfe09744 | ||
|
|
b56068ee1c | ||
|
|
99e888c829 | ||
|
|
873d0deeaa | ||
|
|
7e0a77c99c | ||
|
|
5f09db2655 | ||
|
|
10174d281c | ||
|
|
12c30acdda | ||
|
|
2790481709 | ||
|
|
182f60d424 | ||
|
|
930c70f065 | ||
|
|
fc61715e4e | ||
|
|
438be2d379 | ||
|
|
4e20ed65f2 | ||
|
|
ce760fcf19 | ||
|
|
0f76fdf4c5 | ||
|
|
03f4513f61 | ||
|
|
26f603057f | ||
|
|
b481eca4a4 | ||
|
|
eb028b65fc | ||
|
|
48c1b1cdb2 | ||
|
|
76e40baebc | ||
|
|
946b4025df | ||
|
|
089766b285 | ||
|
|
b643388539 | ||
|
|
0836ec6ee3 | ||
|
|
eeb2ad8dae | ||
|
|
71290b057f | ||
|
|
41b321dfe1 | ||
|
|
a18e99f966 | ||
|
|
f90d0b954c | ||
|
|
0408da2aee | ||
|
|
335d54e488 | ||
|
|
d11f9c895c | ||
|
|
e54ca7ceca | ||
|
|
ce82d49c25 | ||
|
|
8e6be1992b | ||
|
|
0e9102daae | ||
|
|
46dccf26d1 | ||
|
|
854c6a13c3 | ||
|
|
b4c3bbf660 | ||
|
|
6c726d6436 | ||
|
|
a0bdb861a9 | ||
|
|
eca5a27774 | ||
|
|
16d95df100 | ||
|
|
9b90719ddd | ||
|
|
7392529677 | ||
|
|
dc52c38179 | ||
|
|
d7999a32d3 | ||
|
|
b41ea05481 | ||
|
|
e6fe895190 | ||
|
|
adf553a958 | ||
|
|
2a915a5c94 | ||
|
|
1b0c72bfab | ||
|
|
e89af723cd | ||
|
|
e8fddd85af | ||
|
|
f04af734e3 | ||
|
|
00035302a1 | ||
|
|
578e659bb9 | ||
|
|
0f1baeb935 | ||
|
|
16ff9e815b | ||
|
|
5f1f296213 | ||
|
|
66fd5c9f0c | ||
|
|
c3a3009a8c | ||
|
|
01cd7e2c0e | ||
|
|
deec7aafe5 | ||
|
|
a9b7e705f0 | ||
|
|
fb043df1b6 | ||
|
|
748b5df902 | ||
|
|
8cbae59d55 | ||
|
|
a37440c81b | ||
|
|
dbb002a5ba | ||
|
|
1a84153213 | ||
|
|
dfe6e0509b | ||
|
|
b6dde7ded7 | ||
|
|
9f1da11792 | ||
|
|
63ad95e10f | ||
|
|
b06ec5bef8 | ||
|
|
d4fbffd8e8 | ||
|
|
305020175d | ||
|
|
79decdc253 | ||
|
|
407c13b8a4 | ||
|
|
d84b182be3 | ||
|
|
8f18d3f6db | ||
|
|
b9260e06b8 | ||
|
|
6337151207 | ||
|
|
aa555ced5f | ||
|
|
349b773b40 | ||
|
|
300eb8b12a | ||
|
|
2b84dd3618 | ||
|
|
6a620ba287 | ||
|
|
56c3462b76 | ||
|
|
6f4fe71e41 | ||
|
|
ba3e7187a6 | ||
|
|
0d92b6724b | ||
|
|
241ae92bce | ||
|
|
91985c1ef8 | ||
|
|
6a9d428991 | ||
|
|
765cbbcc01 | ||
|
|
5b975275f5 | ||
|
|
166392fe17 | ||
|
|
5c6aa433ca | ||
|
|
2c55dc2557 | ||
|
|
56c0b088e8 | ||
|
|
5344e869a8 | ||
|
|
6cfaf15cbf | ||
|
|
31f0060b30 | ||
|
|
c60750d549 | ||
|
|
ebf5918e94 | ||
|
|
93ca18517c | ||
|
|
32d447ce99 | ||
|
|
617fef84ae | ||
|
|
d19199322d | ||
|
|
87795e3a07 | ||
|
|
85bb40aaf8 | ||
|
|
082bcec281 | ||
|
|
9283cb0f5f | ||
|
|
ae7967f662 | ||
|
|
01f8f2db2f | ||
|
|
255ff5e977 | ||
|
|
939e4109d7 | ||
|
|
40587b62b8 | ||
|
|
85e6d25de5 | ||
|
|
29a37f4f4b | ||
|
|
2f9a3b3469 | ||
|
|
40ea0ba098 | ||
|
|
8d7f947a80 | ||
|
|
71a8705636 | ||
|
|
c0f452b540 | ||
|
|
6c9abe16cc | ||
|
|
213d80c1e2 | ||
|
|
1db89da122 | ||
|
|
689c58f661 | ||
|
|
33590c4066 | ||
|
|
60ae9dce56 | ||
|
|
4741ac6702 | ||
|
|
ef3d7e4dd7 | ||
|
|
a1c7881229 | ||
|
|
12e3952b74 | ||
|
|
88419cbd12 | ||
|
|
4ed830330e | ||
|
|
3ed6ff9402 | ||
|
|
34de62d21d | ||
|
|
d2e255f257 | ||
|
|
a0c46bb4b7 | ||
|
|
9e3bf14b1a | ||
|
|
28c387a9b6 | ||
|
|
15eda703b4 | ||
|
|
b1d12a15db | ||
|
|
5a21bf3642 | ||
|
|
199fb8fd5d | ||
|
|
fd959feff2 | ||
|
|
d5a03901d2 | ||
|
|
257fead538 | ||
|
|
c489c5260b | ||
|
|
8f92b1de13 | ||
|
|
9f7a2a36c1 | ||
|
|
a93479124c | ||
|
|
ed42c4feb8 | ||
|
|
608ddb1b44 | ||
|
|
d036d98128 | ||
|
|
d900c71214 | ||
|
|
1672750c47 | ||
|
|
41b57afb3f | ||
|
|
188372cb04 | ||
|
|
a1350d4985 | ||
|
|
dc958e6a39 | ||
|
|
8a5f3b8909 | ||
|
|
c6d7ef8cb8 | ||
|
|
bb8c47d83d | ||
|
|
5cf0f18c29 | ||
|
|
83213d493e | ||
|
|
90ed01ed53 | ||
|
|
f91a586da8 | ||
|
|
266fb03838 | ||
|
|
76e9607fd7 | ||
|
|
23e2d3a132 | ||
|
|
6e35cf9399 | ||
|
|
2116640886 | ||
|
|
a4fcd3af07 | ||
|
|
d22a893060 | ||
|
|
00cceba890 | ||
|
|
2b4726b9ad | ||
|
|
26e6d83f8b | ||
|
|
50d7834e09 | ||
|
|
86c127db8b | ||
|
|
febb6021aa | ||
|
|
9e57b298bf | ||
|
|
791ea5e568 | ||
|
|
7e7016b567 | ||
|
|
b4fe669848 | ||
|
|
cad26ac6a8 | ||
|
|
f328203bc1 | ||
|
|
5c40a6340c | ||
|
|
61d6a9abd6 | ||
|
|
a013ac32a3 | ||
|
|
ee5d77cfd1 | ||
|
|
936df90ace | ||
|
|
f774276896 | ||
|
|
aa51b9faba | ||
|
|
d55b047125 | ||
|
|
efc7abc6e0 | ||
|
|
c2301f66a4 | ||
|
|
468cfc3cc4 | ||
|
|
5dce957755 | ||
|
|
4ecb49b3b9 | ||
|
|
7de4af28d2 | ||
|
|
48d8efb3e9 | ||
|
|
e6e7aa5ae2 | ||
|
|
99aa1b0de1 | ||
|
|
52ad793d11 | ||
|
|
2fb9331211 | ||
|
|
793ce45db0 | ||
|
|
39d6a0d7ba | ||
|
|
d5243adf89 | ||
|
|
6236cb1cf0 | ||
|
|
619c9dc0c6 | ||
|
|
9c5067e519 | ||
|
|
feee9b320c | ||
|
|
63e66f49ca | ||
|
|
bad61f918f | ||
|
|
69ce4d0f8c | ||
|
|
b59f11f7ac | ||
|
|
30d90d49f0 | ||
|
|
76052b5b26 | ||
|
|
7d7f5c8980 | ||
|
|
e79465d306 | ||
|
|
345d3d7052 | ||
|
|
3d806b5e4c | ||
|
|
b5fcd1d1d1 | ||
|
|
b21b8ee046 | ||
|
|
d0d0c392d7 | ||
|
|
a75e570cca | ||
|
|
9e0889c02c | ||
|
|
55cbbf7f41 | ||
|
|
664b134015 | ||
|
|
ba3c44a169 | ||
|
|
dcb20e2824 | ||
|
|
3d2cb992fa | ||
|
|
984535f006 | ||
|
|
8fa4e8122c | ||
|
|
7551c8a545 | ||
|
|
237e2edea4 | ||
|
|
fe01033efe | ||
|
|
84cd0ef688 | ||
|
|
cedb36df5f | ||
|
|
7a260f7bcf | ||
|
|
8085c68b6d | ||
|
|
dbb5b7db1c | ||
|
|
bfd06ebad0 | ||
|
|
e8af058694 | ||
|
|
487d7fa81f | ||
|
|
4b15568a29 | ||
|
|
cac2bf72e1 | ||
|
|
b2d2890866 | ||
|
|
8752f80595 | ||
|
|
a6c0c02e0d | ||
|
|
2acb0b71ee | ||
|
|
2a40eba0ca | ||
|
|
a22efd5c91 | ||
|
|
9e8f4ada47 | ||
|
|
09c7ee0d12 | ||
|
|
2a08c44f51 | ||
|
|
190047c8c0 | ||
|
|
24a9ff6d03 | ||
|
|
efa224373f | ||
|
|
b0bd4f4caf | ||
|
|
eaaccffcef | ||
|
|
e81f3a97af | ||
|
|
323973f22f | ||
|
|
ed7533ca1a | ||
|
|
7de24e26b4 | ||
|
|
622d99d000 | ||
|
|
7f1225b0c4 | ||
|
|
23ffe451f4 | ||
|
|
7b37fcfc8d | ||
|
|
daa592c7f3 | ||
|
|
577f64a601 | ||
|
|
025ff19fab | ||
|
|
f61534602b | ||
|
|
7b382611bb | ||
|
|
0f32c054f4 | ||
|
|
4f8b70c8c6 | ||
|
|
dcef78782b | ||
|
|
7c444a91d3 | ||
|
|
e3d4ec2476 | ||
|
|
14217e7847 | ||
|
|
68abb1348a | ||
|
|
dee5898e36 | ||
|
|
1e22f4daa9 | ||
|
|
a7a796bb30 | ||
|
|
ff89bf0ea0 | ||
|
|
801f3c35ce | ||
|
|
7ff046a455 | ||
|
|
0ed159e41d | ||
|
|
070eb3142b | ||
|
|
f318b80557 | ||
|
|
c0de3c0e42 | ||
|
|
4bd3ae52bd | ||
|
|
00e6466153 | ||
|
|
c94b4421e5 | ||
|
|
8bc6f77e36 | ||
|
|
a7e56f1c43 | ||
|
|
05e8f13a8d | ||
|
|
136d114196 | ||
|
|
938ab7f44d | ||
|
|
a00f4f1108 | ||
|
|
1213023f11 | ||
|
|
3b40bf76b7 | ||
|
|
1dc4155195 | ||
|
|
d81c19a7c8 | ||
|
|
e2140e62ca | ||
|
|
8d783c65c1 | ||
|
|
91324b76d2 | ||
|
|
e23f40a56b | ||
|
|
5830afcbde | ||
|
|
e2b75b35bb | ||
|
|
06b9e6c367 | ||
|
|
dc1145a484 | ||
|
|
b151e7d69c | ||
|
|
808fdcf624 | ||
|
|
9962a0d091 | ||
|
|
ef29e4501e | ||
|
|
d1d846f1ab | ||
|
|
eaaccbc6dd | ||
|
|
447c416391 | ||
|
|
6d24ca9ae6 | ||
|
|
b52b7537fc | ||
|
|
3cc67fd759 | ||
|
|
9074b78e36 | ||
|
|
ccc3f84da2 | ||
|
|
9bfb10d7ae | ||
|
|
0a5ea37c07 | ||
|
|
a440f64080 | ||
|
|
0ac6c3b185 | ||
|
|
b69e52d4d7 | ||
|
|
9c73b5b750 | ||
|
|
fc233184fd | ||
|
|
192d769f75 | ||
|
|
c99c71a969 | ||
|
|
c7661d7765 | ||
|
|
56c128880c | ||
|
|
f4806b49b4 | ||
|
|
49d54cc293 | ||
|
|
1c5f4a3ab1 | ||
|
|
368b1e1296 | ||
|
|
a9ce5da09d | ||
|
|
301c78ff9a | ||
|
|
72a126e580 | ||
|
|
20739f5db7 | ||
|
|
89dfabe9b3 | ||
|
|
5a9ad0ed3c | ||
|
|
bb803249fa | ||
|
|
3f6823ba49 | ||
|
|
c786b72030 | ||
|
|
269c52575c | ||
|
|
c7fc93df37 | ||
|
|
5d9d8f4d3b | ||
|
|
f3a43fe3a6 | ||
|
|
9a959202ed | ||
|
|
cd23112dc5 | ||
|
|
613becd8ea | ||
|
|
d6b496d3c0 | ||
|
|
5a24efdabf | ||
|
|
9de9f1ef51 | ||
|
|
fbead56ec9 | ||
|
|
1fff34d30e | ||
|
|
a35f712478 | ||
|
|
f805a9f4c6 | ||
|
|
eb985b002e | ||
|
|
462343531e | ||
|
|
671d901ee2 | ||
|
|
80e4eaad14 | ||
|
|
25b3c86d31 | ||
|
|
de19f927e8 | ||
|
|
792f16265e | ||
|
|
215bf0995f | ||
|
|
91d54bdac1 | ||
|
|
ce52c3438b | ||
|
|
d4478dbfa2 | ||
|
|
69454b030e | ||
|
|
e6d1c8cedf | ||
|
|
fabd216c34 | ||
|
|
a86c562852 | ||
|
|
3e966e82c7 | ||
|
|
b9171ade7f | ||
|
|
95af5f7325 | ||
|
|
ca3f1ebae6 | ||
|
|
4437c8861c | ||
|
|
57725078e0 | ||
|
|
08dcef80bf | ||
|
|
9fd63fe938 | ||
|
|
8e6eb70e71 | ||
|
|
9937ae1002 | ||
|
|
8f5a86410c | ||
|
|
9286e21026 | ||
|
|
c63a851bba | ||
|
|
4a16d22398 | ||
|
|
990de84391 | ||
|
|
ecd8facd81 | ||
|
|
a330fa1506 | ||
|
|
fc9d5cfee9 | ||
|
|
264713571d | ||
|
|
a67c379884 | ||
|
|
af5ad3254b | ||
|
|
acfc9f8baa | ||
|
|
1633885794 | ||
|
|
2afa2798b1 | ||
|
|
cd2d1c6bb0 | ||
|
|
88bfe7cffe | ||
|
|
43cb48231a | ||
|
|
4fa15c6334 | ||
|
|
5812a7bdeb | ||
|
|
3922b17067 | ||
|
|
a4e84f0479 | ||
|
|
6c0383026e | ||
|
|
59a2b24593 | ||
|
|
966eeae41b | ||
|
|
150c6ccd25 | ||
|
|
33823f1728 | ||
|
|
781b783346 | ||
|
|
ddfa9e8671 | ||
|
|
b7cb6774bf | ||
|
|
5d242510c8 | ||
|
|
223eae0e06 | ||
|
|
7dafe7889e | ||
|
|
d80e8bb0c2 | ||
|
|
f52fe6aa74 | ||
|
|
a08aa10630 | ||
|
|
794645b7f8 | ||
|
|
f020b20ab9 | ||
|
|
3676d1b79f | ||
|
|
58c973ee2b | ||
|
|
fb4d3c41c8 | ||
|
|
e33d4a4769 | ||
|
|
4c3fe98ebd | ||
|
|
0a2f606e1b | ||
|
|
8230bc8e7d | ||
|
|
ecbbf9d220 | ||
|
|
f305e440ef | ||
|
|
910f236696 | ||
|
|
417d709d60 | ||
|
|
f8557f5fd8 | ||
|
|
89b9438fc0 | ||
|
|
7c8f451892 | ||
|
|
ef244b896a | ||
|
|
595a575cde | ||
|
|
b1301b1b41 | ||
|
|
dc29514fb6 | ||
|
|
8940bdd56f | ||
|
|
ade4234615 | ||
|
|
faaa90f8a6 | ||
|
|
43f21c0b41 | ||
|
|
56fe7d5304 | ||
|
|
802267fb5b | ||
|
|
6306c6b580 | ||
|
|
f6164ac195 | ||
|
|
08ac9a3fae | ||
|
|
38fd37108b | ||
|
|
763a127287 | ||
|
|
a96f72ade4 | ||
|
|
4fecf68b8b | ||
|
|
8483178524 | ||
|
|
3e2c9ce821 | ||
|
|
6e04e1e9dc | ||
|
|
d79423a4fa | ||
|
|
9cf3eb39f5 | ||
|
|
81756fc927 | ||
|
|
518e9bdb0b | ||
|
|
27bcb26ecd | ||
|
|
53425bb9f2 | ||
|
|
f5834dd5e2 | ||
|
|
16c95fca87 | ||
|
|
41efc5e5ab | ||
|
|
c4660e1aad | ||
|
|
512d188384 | ||
|
|
ba605b693b | ||
|
|
c8380335cb | ||
|
|
82984891e4 | ||
|
|
0793998de8 | ||
|
|
6bf419c5fe | ||
|
|
4fedfc47b0 | ||
|
|
92ec5f2236 | ||
|
|
4c10d42fbf | ||
|
|
7fd0467aef | ||
|
|
696b75ee37 | ||
|
|
f20f371a61 | ||
|
|
24c6e7d819 | ||
|
|
acaacd8ab1 | ||
|
|
12c5cf361d | ||
|
|
50d0cd363c | ||
|
|
5bf22422d9 | ||
|
|
c17d7c0281 | ||
|
|
951cae2156 | ||
|
|
4f339265d3 | ||
|
|
ea4181308d | ||
|
|
030631607e | ||
|
|
beefe37260 | ||
|
|
5a73d99c6f | ||
|
|
e4646fc3d2 | ||
|
|
bb554e89d9 | ||
|
|
fd205bfa8d | ||
|
|
e7e1400126 | ||
|
|
117cdd8b54 | ||
|
|
c830b8aaf7 | ||
|
|
1db3e4583b | ||
|
|
4f8a5a5f54 | ||
|
|
303f6e4567 | ||
|
|
0d90a93645 | ||
|
|
40c9829328 | ||
|
|
4051ea522a | ||
|
|
cc7823dad8 | ||
|
|
d6a1af23a7 | ||
|
|
313493cc94 | ||
|
|
4b9fdacbad | ||
|
|
13b7ab8da3 | ||
|
|
de61e81ff7 | ||
|
|
4eb13a73bf | ||
|
|
fd5b537ab1 | ||
|
|
28794c62c4 | ||
|
|
e263518f01 | ||
|
|
345061a7cc | ||
|
|
a05016a5da | ||
|
|
9e3589d638 | ||
|
|
fc03bd2f0d | ||
|
|
0e228765fc | ||
|
|
f45ccc0761 | ||
|
|
9f4cd646c2 | ||
|
|
a9ecc627e6 | ||
|
|
50286678bf | ||
|
|
917c5fdd80 | ||
|
|
1457f83530 | ||
|
|
5ab8154e7e | ||
|
|
09be5cbc99 | ||
|
|
0738e18100 | ||
|
|
40f40f6d24 | ||
|
|
ad5bc51c77 | ||
|
|
75c16f9b87 | ||
|
|
d96d7651ca | ||
|
|
a5f25a2246 | ||
|
|
2b4741fbc7 | ||
|
|
f317baa8de | ||
|
|
5678131591 | ||
|
|
10f8ba4434 | ||
|
|
cacfefad4b | ||
|
|
0d4e57cb21 | ||
|
|
063836fe5d | ||
|
|
7b3c9e94e6 | ||
|
|
be3d121ec6 | ||
|
|
59fd3cffe3 | ||
|
|
39eda257a7 | ||
|
|
d3fea909e9 | ||
|
|
7eb70aeb4d | ||
|
|
846bdfa812 | ||
|
|
0b6ae6ffb8 | ||
|
|
71922dd0b1 | ||
|
|
5eb8958ff2 | ||
|
|
ac2506154f | ||
|
|
43bdc76f87 | ||
|
|
3195c678c7 | ||
|
|
bd43eca09d | ||
|
|
c504985b99 | ||
|
|
4243a74284 | ||
|
|
e749c7e492 | ||
|
|
c3ee921d30 | ||
|
|
df69a31e62 | ||
|
|
b7c02a5923 | ||
|
|
bfb6caeeaf | ||
|
|
30a913aad6 | ||
|
|
00e361c5ac | ||
|
|
56edd8f671 | ||
|
|
2b52809d2c | ||
|
|
5c3a9b1dfc | ||
|
|
fe88f0e437 | ||
|
|
87877d1b80 | ||
|
|
1bc3c16b59 | ||
|
|
ed1e7e32c7 | ||
|
|
5da9ccaa98 | ||
|
|
fd7ecc004f | ||
|
|
3ae4014b39 | ||
|
|
a50339bd5f | ||
|
|
7df1c26942 | ||
|
|
fc82a32a48 | ||
|
|
adf0ff588f | ||
|
|
b840eae4c6 | ||
|
|
619f34119e | ||
|
|
6d1c62bbf0 | ||
|
|
5dd883e790 | ||
|
|
a2b43faa0b | ||
|
|
8861eaf903 | ||
|
|
107e3e7630 | ||
|
|
314c0bb34b | ||
|
|
89a097faa8 | ||
|
|
df01582996 | ||
|
|
8ff56b5bb8 | ||
|
|
2f8f139f7c | ||
|
|
b2280c85b7 | ||
|
|
002b8af94a | ||
|
|
99b274acbc | ||
|
|
d4ececae20 | ||
|
|
ff2071c1da | ||
|
|
189b7b9c5f | ||
|
|
a878254662 | ||
|
|
3566542d0e | ||
|
|
ca84ab1a94 | ||
|
|
d84f88b50f | ||
|
|
e3b69b8ae2 | ||
|
|
91a7ffaad2 | ||
|
|
16fadd2441 | ||
|
|
cff7df164f | ||
|
|
de38fa882c | ||
|
|
bd703b8ff2 | ||
|
|
72df27be44 | ||
|
|
f3e23b1128 | ||
|
|
19f7220c0b | ||
|
|
3249572dc1 | ||
|
|
ba09139bd7 | ||
|
|
90bf158e9f | ||
|
|
d1539e6c07 | ||
|
|
c893e3c462 | ||
|
|
b56e73a02a | ||
|
|
40f5c5b987 | ||
|
|
d48517b29d | ||
|
|
3b472f786e | ||
|
|
f3743fc7f9 | ||
|
|
56ed9019a6 | ||
|
|
3e0bd65135 | ||
|
|
72d0948224 | ||
|
|
4542fc0991 | ||
|
|
914bc8a3e9 | ||
|
|
11f0983e5c | ||
|
|
89d7b8138a | ||
|
|
eae1f05e88 | ||
|
|
367a287153 | ||
|
|
06b5121d9e | ||
|
|
82517e6ba8 | ||
|
|
0b4662e4b7 | ||
|
|
288899a473 | ||
|
|
5af7f4e847 | ||
|
|
d2ae94f20b | ||
|
|
d56a439a74 | ||
|
|
9c08e936f9 | ||
|
|
284b01ca38 | ||
|
|
2e94531c72 | ||
|
|
e1a5b93cce | ||
|
|
7fd5902e6b | ||
|
|
143fe84b8e | ||
|
|
80408855ac | ||
|
|
c80dd5d738 | ||
|
|
b3db113b1b | ||
|
|
dceb8ee535 | ||
|
|
31d3614060 | ||
|
|
5fdfde6a07 | ||
|
|
81c832ef9e | ||
|
|
012e448562 | ||
|
|
44d8a14629 | ||
|
|
7ad37ca0e3 | ||
|
|
f0ff6546e4 | ||
|
|
77c10d90f3 | ||
|
|
e0248faebd | ||
|
|
feedc9ec66 | ||
|
|
7754b46dc4 | ||
|
|
90d0ef033b | ||
|
|
5702d28cda | ||
|
|
0bb5568de9 | ||
|
|
37b02b18f7 | ||
|
|
cd9e9cd2c1 | ||
|
|
234a4bfc93 | ||
|
|
fad1a08378 | ||
|
|
04886761a2 | ||
|
|
823f59b5c7 | ||
|
|
974332c0cc | ||
|
|
8b9813079b | ||
|
|
fe4acebb8b | ||
|
|
69bf434e2c | ||
|
|
e867497315 | ||
|
|
3ec23c1fc5 | ||
|
|
d27340867f | ||
|
|
7eb16a098a | ||
|
|
f0bc68585a | ||
|
|
092e53586e | ||
|
|
41e3571e1d | ||
|
|
e58294198c | ||
|
|
0619c75276 | ||
|
|
78b4b11f26 | ||
|
|
8d9eb1e534 | ||
|
|
d2a5376cb8 | ||
|
|
f8295a02fd | ||
|
|
3d833ef6a8 | ||
|
|
1c7e011f87 | ||
|
|
9e7eaf720f | ||
|
|
6399347a63 | ||
|
|
23e3f12e88 | ||
|
|
985b884d85 | ||
|
|
93b48a94fc | ||
|
|
080d316059 | ||
|
|
0c384b1e42 | ||
|
|
324c0bde7d | ||
|
|
9e57e7d29b | ||
|
|
20658f6eac | ||
|
|
822ba5f0b5 | ||
|
|
e6011301b2 | ||
|
|
947ad9b308 | ||
|
|
d1337f39ed | ||
|
|
c6843d6a2c | ||
|
|
f2634250a6 | ||
|
|
9bd70e1366 | ||
|
|
1025101954 | ||
|
|
80d6ca8ef9 | ||
|
|
5858384631 | ||
|
|
5c1404f78e | ||
|
|
7be6751650 | ||
|
|
e86567ead2 | ||
|
|
c1f0ed18ef | ||
|
|
0e1bdb07d4 | ||
|
|
25d6ad220d | ||
|
|
90ea6ab278 | ||
|
|
36ea09eff4 | ||
|
|
460cc240b0 | ||
|
|
c34a0ef8f0 | ||
|
|
061f83d92a | ||
|
|
edf318bae0 | ||
|
|
e860497c0c | ||
|
|
d2d8c0115c | ||
|
|
5ec686df08 | ||
|
|
7c54775ddc | ||
|
|
425bc692ad | ||
|
|
ffcd672ebf | ||
|
|
7e3e38d054 | ||
|
|
6bc915526f | ||
|
|
4af94df142 | ||
|
|
2e12ceeaed | ||
|
|
33bc7914e9 | ||
|
|
0404e35be8 | ||
|
|
fbaa323ad4 | ||
|
|
4ee267ca7e | ||
|
|
1d3e9f4889 | ||
|
|
3d643cb95a | ||
|
|
22862f20cc | ||
|
|
2e87c6f4da | ||
|
|
fb1c0aa387 | ||
|
|
1701e4715d | ||
|
|
0d07cf40b8 | ||
|
|
41a05d96a5 | ||
|
|
4cea3125e6 | ||
|
|
997663a4ad | ||
|
|
b632575e39 | ||
|
|
59ab4fe745 | ||
|
|
147400fbe0 | ||
|
|
ac381736a5 | ||
|
|
08a1f10af4 | ||
|
|
8822349f94 | ||
|
|
27635ea027 | ||
|
|
429a03d986 | ||
|
|
518c31dd0e | ||
|
|
16769865e4 | ||
|
|
9d8c3b0a3b | ||
|
|
f16ebf9bfe | ||
|
|
f29329fe80 | ||
|
|
8cf14bb67e | ||
|
|
2bba8aa14a | ||
|
|
5b23b979df | ||
|
|
78e5d3229e | ||
|
|
0ab73a9beb | ||
|
|
7ee6809257 | ||
|
|
3cf865e5f0 | ||
|
|
9fc1fc4cfe | ||
|
|
d80fcb77f6 | ||
|
|
5a2ed71bd9 | ||
|
|
9729c2e440 | ||
|
|
c5d1e20a64 | ||
|
|
da65f8f935 | ||
|
|
582ac28728 | ||
|
|
262d3295d1 | ||
|
|
8dbc5e2100 | ||
|
|
941dd6c76d | ||
|
|
fdc9c01df1 | ||
|
|
b538aa6ca2 | ||
|
|
1d1841f7aa | ||
|
|
1b527fd494 | ||
|
|
73e16c912f | ||
|
|
9ac4738ef9 | ||
|
|
cbec564af9 | ||
|
|
c5d1db7905 | ||
|
|
ad263f7229 | ||
|
|
f63acc0202 | ||
|
|
f572e7fba8 | ||
|
|
ed210ee403 | ||
|
|
92129b33e7 | ||
|
|
ee6b974c18 | ||
|
|
2d73bcb951 | ||
|
|
2d7538aca6 | ||
|
|
aef87b29ba | ||
|
|
5f493fbcfb | ||
|
|
071e8488a8 | ||
|
|
22ed13b9df | ||
|
|
1a0932c210 | ||
|
|
bc74c943b8 | ||
|
|
cc6429722a | ||
|
|
3b57a923fd | ||
|
|
7efd692bbc | ||
|
|
d773d335a2 | ||
|
|
78ae8815c2 | ||
|
|
8f61b0e180 | ||
|
|
a974e810c2 | ||
|
|
599ce784d2 | ||
|
|
db973de7bd | ||
|
|
5f7053c519 | ||
|
|
84a334dd3a | ||
|
|
7d15ce2b33 | ||
|
|
37791acb59 | ||
|
|
96f0254a48 | ||
|
|
8b4499e461 | ||
|
|
6a3e28c384 | ||
|
|
b05cf14b98 | ||
|
|
a6b816b1c6 | ||
|
|
bb9ad6cac0 | ||
|
|
b9d48f4115 | ||
|
|
84299606f4 | ||
|
|
8efb699231 | ||
|
|
3c088b33a2 | ||
|
|
4362dfacc9 | ||
|
|
05b9071ca6 | ||
|
|
117228fa8c | ||
|
|
3a3d88c668 | ||
|
|
54a7f52fe3 | ||
|
|
1479b449df | ||
|
|
fef5ad780d | ||
|
|
aa3c1ac623 | ||
|
|
b5a8f0fce1 | ||
|
|
d9cfdc3242 | ||
|
|
b73382f60a | ||
|
|
9e96d70840 | ||
|
|
d28c3b50e3 | ||
|
|
2f203330e4 | ||
|
|
7d222b1b71 | ||
|
|
d85d8ac13f | ||
|
|
7979eb654f | ||
|
|
2577dd3af4 | ||
|
|
daa332e7b0 | ||
|
|
288c0c27d6 | ||
|
|
832dae3421 | ||
|
|
fe7c1a2cdb | ||
|
|
e8e4288d85 | ||
|
|
6901afb406 | ||
|
|
f260d8cf01 | ||
|
|
575c1d4129 | ||
|
|
17c9d507be | ||
|
|
8c3557e96b | ||
|
|
228990472d | ||
|
|
09e7866a5c | ||
|
|
665ba7f9f1 | ||
|
|
ee3038d5e4 | ||
|
|
885ee7a820 | ||
|
|
ef303b11f2 | ||
|
|
a82ce85707 | ||
|
|
5bfe7ba169 | ||
|
|
ceac5bfaa4 | ||
|
|
b0638cfc49 | ||
|
|
96220aa8ea | ||
|
|
8ff476a3a1 | ||
|
|
261b6e8dce | ||
|
|
2b9141e0e5 | ||
|
|
55255faa52 | ||
|
|
d42e3f74ad | ||
|
|
81a8a63861 | ||
|
|
c3a61e2db5 | ||
|
|
bffe47a974 | ||
|
|
4314b37d04 | ||
|
|
cf93f69f40 | ||
|
|
55f626424f | ||
|
|
431d52f250 | ||
|
|
c1f24d8f0e | ||
|
|
fc5a3cf80c | ||
|
|
e1e999180a | ||
|
|
8755618910 | ||
|
|
aede97571f | ||
|
|
01bc84db02 | ||
|
|
3564e96a00 | ||
|
|
f6f8f27668 | ||
|
|
dff54464c6 | ||
|
|
e987cdaaae | ||
|
|
6cd0e58fd0 | ||
|
|
f794c090a5 | ||
|
|
0d3197e437 | ||
|
|
150bf7fc65 | ||
|
|
51004b14d9 | ||
|
|
ea7e15b447 | ||
|
|
8e637a2ec7 | ||
|
|
96d886380a | ||
|
|
981c69040f | ||
|
|
de90c276af | ||
|
|
0129a8579f | ||
|
|
11ed4a56bd | ||
|
|
d75a0e69a0 | ||
|
|
1faad73381 | ||
|
|
d2499cd69d | ||
|
|
98df77439c | ||
|
|
81bbbe4eec | ||
|
|
9f530525d7 | ||
|
|
129283066f | ||
|
|
0dc6a726c1 | ||
|
|
4636499439 | ||
|
|
9a16eb2895 | ||
|
|
270a080b55 | ||
|
|
1cf9a55e3e | ||
|
|
6bcd91a801 | ||
|
|
7ed25ddc74 | ||
|
|
ae557c30d3 | ||
|
|
5a1800d642 | ||
|
|
d8fe7a52d6 | ||
|
|
791ecfbb32 | ||
|
|
5ff4473083 | ||
|
|
d1e88a30cb | ||
|
|
7eae7756f5 | ||
|
|
4e3cd01aad | ||
|
|
dbaee284e4 | ||
|
|
8253bfe2e0 | ||
|
|
828b5ad8bb | ||
|
|
fedad26c13 | ||
|
|
a526bb70ea | ||
|
|
5f6de610e1 | ||
|
|
02397868fc | ||
|
|
265a6b9b68 | ||
|
|
10e7c533d7 | ||
|
|
0ed3c5a5ec | ||
|
|
c2b06a02bf | ||
|
|
e0458a8fde | ||
|
|
21fb5f75b8 | ||
|
|
fb99412193 | ||
|
|
fdd327d58d | ||
|
|
0dfe696300 | ||
|
|
c0ba798708 | ||
|
|
67d7e53f7a | ||
|
|
e6366f7442 | ||
|
|
89d9cb0539 | ||
|
|
0d300a3540 | ||
|
|
7c59916c22 | ||
|
|
8f515ecc05 | ||
|
|
34f62a0919 | ||
|
|
0207a7ac96 | ||
|
|
bf619d8586 | ||
|
|
d48f9c2a6c | ||
|
|
90a5aa609a | ||
|
|
4fe7a463c5 | ||
|
|
7f49c91267 | ||
|
|
f6bf9c0857 | ||
|
|
da24810da2 | ||
|
|
ee3213c28f | ||
|
|
233eeb0b38 | ||
|
|
6c3b973748 | ||
|
|
9b8e2d9343 | ||
|
|
24fd577767 | ||
|
|
42b85de83e | ||
|
|
62266010ac | ||
|
|
0d7a57fa9d | ||
|
|
f909b3c0dc | ||
|
|
8b518161a3 | ||
|
|
20fafdca65 | ||
|
|
fd96efd456 | ||
|
|
7c21768e99 | ||
|
|
6a5a94f48f | ||
|
|
33d41338ef | ||
|
|
2d3b9364bf | ||
|
|
fa49fd7ba2 | ||
|
|
c3d72f6883 | ||
|
|
af99b52527 | ||
|
|
f241e1f81a | ||
|
|
90acce7fa1 | ||
|
|
7286391883 | ||
|
|
a1eab125ee | ||
|
|
1d4af2d92b | ||
|
|
d6cf2a837f | ||
|
|
d6b80acfbc | ||
|
|
1cad615b25 | ||
|
|
73fa79bf3f | ||
|
|
d79c13064e | ||
|
|
427a377c2a | ||
|
|
9feb4d6668 | ||
|
|
a366e9a4b5 | ||
|
|
cbdf33c42c | ||
|
|
9ceaf20584 | ||
|
|
54fee7bd3a | ||
|
|
414d8f2162 | ||
|
|
86cf1dd54b | ||
|
|
d099375200 | ||
|
|
9536372cfb | ||
|
|
630a17cf90 | ||
|
|
0a7b7894bd | ||
|
|
3a9fc39cd9 | ||
|
|
1181fd4560 | ||
|
|
b8a60261ef | ||
|
|
db68d55a0e | ||
|
|
574efb4526 | ||
|
|
03b0252589 | ||
|
|
ed09df4e13 | ||
|
|
f89ecd97d6 | ||
|
|
3093fc4f33 | ||
|
|
984fca4726 | ||
|
|
cc42d787d4 | ||
|
|
e2e0fd4eba | ||
|
|
bad9f2e6dc | ||
|
|
68bf6f16ac | ||
|
|
cca701c641 | ||
|
|
09ec7c8a62 | ||
|
|
68f312288d | ||
|
|
191243a1d2 | ||
|
|
b0fed73236 | ||
|
|
f125e1ce9e | ||
|
|
e2216b7824 | ||
|
|
7632827177 | ||
|
|
b0e76ec791 | ||
|
|
a82745f544 | ||
|
|
cbb8ef5dfe | ||
|
|
a181e35865 | ||
|
|
014537e1ea | ||
|
|
9b50f56e7c | ||
|
|
9cbca162a0 | ||
|
|
f73f32e41c | ||
|
|
cfc30753af | ||
|
|
081e94c738 | ||
|
|
5dd57bab67 | ||
|
|
492a731ec1 | ||
|
|
0b1aff5759 | ||
|
|
8f1475d5d0 | ||
|
|
c6b84b0f20 | ||
|
|
02ba78ab90 | ||
|
|
57db8dfe23 | ||
|
|
8e16738465 | ||
|
|
db6b2b7702 | ||
|
|
603d0809b4 | ||
|
|
614cc93cac | ||
|
|
1cb75350e2 | ||
|
|
42ef4fedfa | ||
|
|
2284acce94 | ||
|
|
919daf0dbb | ||
|
|
6d824c8745 | ||
|
|
1d94546902 | ||
|
|
ad7508f203 | ||
|
|
d391fda051 | ||
|
|
fe0f2d9ef9 | ||
|
|
b9110c164d | ||
|
|
6c8631d5cc | ||
|
|
61734e5cac | ||
|
|
77fb9a9c01 | ||
|
|
af28b99b2a | ||
|
|
4f79bb7931 | ||
|
|
644abcf071 | ||
|
|
183f2d974c | ||
|
|
e914317bef | ||
|
|
5e20fedf5f | ||
|
|
54337ecdf3 | ||
|
|
c7de0e0253 | ||
|
|
b72219c06a | ||
|
|
64b23257db | ||
|
|
c57f17d094 | ||
|
|
cd44901e90 | ||
|
|
766d08a8eb | ||
|
|
c3ef05b257 | ||
|
|
093453582f | ||
|
|
767aa182b9 | ||
|
|
ad11a2b813 | ||
|
|
dafecebdc0 | ||
|
|
e7174866e5 | ||
|
|
fdaa6a22a4 | ||
|
|
fd0c71a485 | ||
|
|
3c1f9a9953 | ||
|
|
3ef81afc76 | ||
|
|
03d0c8620e | ||
|
|
63b5387164 | ||
|
|
2af758e5f1 | ||
|
|
2c44b4e170 | ||
|
|
7906fbfee6 | ||
|
|
17565ec93b | ||
|
|
26acaee424 | ||
|
|
9b6e56a65e | ||
|
|
7fa3d3aa0b | ||
|
|
1120c8185d | ||
|
|
41af94ea66 | ||
|
|
36539bb670 | ||
|
|
8e88e0b9f5 | ||
|
|
097f3e250c | ||
|
|
9c2972afb0 | ||
|
|
7aae781569 | ||
|
|
92f71fd25f | ||
|
|
f44ba26f0c | ||
|
|
73140ab826 | ||
|
|
4971b9d804 | ||
|
|
654e76d91e | ||
|
|
984bf27d9b | ||
|
|
546b2bc24b | ||
|
|
d4e4f6d2d7 | ||
|
|
b047ca0294 | ||
|
|
2b1e69153b | ||
|
|
ae8d42fb82 | ||
|
|
89ae640487 | ||
|
|
6e0c3a368f | ||
|
|
033f902ace | ||
|
|
6b1a4385b2 | ||
|
|
e552b5475f | ||
|
|
8b631f11b8 | ||
|
|
1a9104c003 | ||
|
|
872a28a5eb | ||
|
|
c7557b8e48 | ||
|
|
c6fed3e97f | ||
|
|
ed17478961 | ||
|
|
b674983034 | ||
|
|
a22b1cd69e | ||
|
|
f1be9b3f4a | ||
|
|
534282839c | ||
|
|
8dd7632d0a | ||
|
|
51e9f3598e | ||
|
|
76caab19bf | ||
|
|
234f7dbd3b | ||
|
|
e404695a0d | ||
|
|
75cd72385a | ||
|
|
d9fa051dd8 | ||
|
|
98394095e4 | ||
|
|
c58400572c | ||
|
|
3b291d3fbf | ||
|
|
15a8d7c473 | ||
|
|
67b9314693 | ||
|
|
99f7c4f821 | ||
|
|
0cb594dd5d | ||
|
|
bd431fbf49 | ||
|
|
8c0168d3a8 | ||
|
|
7ae3e78b15 | ||
|
|
d61a5af335 | ||
|
|
f90066f286 | ||
|
|
463da578dd | ||
|
|
1eefa71e1f | ||
|
|
969c235490 | ||
|
|
f35ff24d0c | ||
|
|
94f990da31 | ||
|
|
d6931ec491 | ||
|
|
19b403da86 | ||
|
|
6ecd1c31e5 | ||
|
|
a7233f6036 | ||
|
|
898f10ca96 | ||
|
|
87d2d08a8f | ||
|
|
928dcf9af9 | ||
|
|
e4f762822a | ||
|
|
573216befb | ||
|
|
30f93debc4 | ||
|
|
a1b6d6050f | ||
|
|
eceea72a56 | ||
|
|
888c233e9c | ||
|
|
8db030d36e | ||
|
|
d8db25ee89 | ||
|
|
e1af1abcc2 | ||
|
|
787e5ea28d | ||
|
|
7bb5da3005 | ||
|
|
efcb278f61 | ||
|
|
72a67ac534 | ||
|
|
7f1b7e7521 | ||
|
|
0c61057551 | ||
|
|
0c146bd04c | ||
|
|
7ca4b64a2b | ||
|
|
aa6fa7f1e3 | ||
|
|
40da1911d9 | ||
|
|
c6ecbb25dc | ||
|
|
00939da40f | ||
|
|
7513761540 | ||
|
|
ec234ac0a8 | ||
|
|
31095e4a8c | ||
|
|
dd60baf9d4 | ||
|
|
4ef99294e7 | ||
|
|
47df97322d | ||
|
|
f100ce6a04 | ||
|
|
cae9cf44cf | ||
|
|
495033270c | ||
|
|
4a0d097fe9 | ||
|
|
8e5dbc7382 | ||
|
|
c2d1f71305 | ||
|
|
81bef30ae0 | ||
|
|
e4926c8364 | ||
|
|
b3794ffdd8 | ||
|
|
394889258c | ||
|
|
38a85272c2 | ||
|
|
dbffbca6f5 | ||
|
|
cd42e9832c | ||
|
|
cb0c9e5caf | ||
|
|
aaf534427e | ||
|
|
5d7fd47cf9 | ||
|
|
42721f3b75 | ||
|
|
836615aac9 | ||
|
|
e745755a46 | ||
|
|
20eb168315 | ||
|
|
17922dc857 | ||
|
|
fda8857ec8 | ||
|
|
bad7340a4e | ||
|
|
7beb09153e | ||
|
|
90f95d7c78 | ||
|
|
92cc268209 | ||
|
|
ab3fce29ab | ||
|
|
ecdde647b1 | ||
|
|
304b4d9bcb | ||
|
|
4d12ed491c | ||
|
|
9afcb7071f | ||
|
|
2c48d2da3f | ||
|
|
87b9e3d977 | ||
|
|
1dbefc40c8 | ||
|
|
6c76312e5c | ||
|
|
20b0af9a03 | ||
|
|
9e6b4dca97 | ||
|
|
99dfa4c73a | ||
|
|
8e8cddf462 | ||
|
|
e9c9d17a9b | ||
|
|
2c09ce44f6 | ||
|
|
89d5695b7f | ||
|
|
8fb2c68722 | ||
|
|
c4c7c56684 | ||
|
|
76340cc99c | ||
|
|
eecd8fff71 | ||
|
|
36b3581389 | ||
|
|
eb07aafce8 | ||
|
|
8ab70d76e7 | ||
|
|
f92f34bb20 | ||
|
|
ae722bb1a0 | ||
|
|
ee5c4cb83b | ||
|
|
bf31abee22 | ||
|
|
2fc37501f5 | ||
|
|
7308c6c2a9 | ||
|
|
99f84b8a66 | ||
|
|
2ff0f94262 | ||
|
|
affc453b6e | ||
|
|
526ac3906d | ||
|
|
cd95cf4849 | ||
|
|
4af4935e7e | ||
|
|
9442880a5a | ||
|
|
9d7a78e1ef | ||
|
|
54c2fa98b4 | ||
|
|
54cad53f5f | ||
|
|
cfd03a99c2 | ||
|
|
991de009be | ||
|
|
2fef329319 | ||
|
|
db7623968d | ||
|
|
7c80c88feb | ||
|
|
2c7153cd7a | ||
|
|
d730feecb4 | ||
|
|
1fdd1f702e | ||
|
|
34c91e5fe0 | ||
|
|
6d40de2179 | ||
|
|
6ca14c814e | ||
|
|
545cbeeec0 | ||
|
|
431dcfa914 | ||
|
|
4d30788738 | ||
|
|
e4364cc985 | ||
|
|
99ede63a9a | ||
|
|
291b5be986 | ||
|
|
a7944f1369 | ||
|
|
7e10d78d53 | ||
|
|
fd0580bfdd | ||
|
|
5737fbc23c | ||
|
|
e026ac6a2a | ||
|
|
e7bb1f42b1 | ||
|
|
a22000c41b | ||
|
|
0336435ebc | ||
|
|
154fbb34ea | ||
|
|
3e47bfacf0 | ||
|
|
9316c1293e | ||
|
|
f6f02bb5eb | ||
|
|
84967ace53 | ||
|
|
c7362fce9c | ||
|
|
8cb67b6480 | ||
|
|
3ae4285702 | ||
|
|
998d407d44 | ||
|
|
520cc807d6 | ||
|
|
7404bfdc44 | ||
|
|
e8d4f8ae7b | ||
|
|
f7610ce2ad | ||
|
|
516c219580 | ||
|
|
5d0efb5472 | ||
|
|
9d9bd245f3 | ||
|
|
53928eb895 | ||
|
|
8dda9fdb70 | ||
|
|
cf7520ec22 | ||
|
|
68d7a6da7f | ||
|
|
09c53e7cb7 | ||
|
|
0f24c2f849 | ||
|
|
88116d9032 | ||
|
|
6ba82c6d85 | ||
|
|
5816dc2955 | ||
|
|
f4251e58a5 | ||
|
|
2fef00d2a8 | ||
|
|
2f992e9863 | ||
|
|
13111081be | ||
|
|
5de043acc6 | ||
|
|
7d230139a0 | ||
|
|
0a6c848c9e | ||
|
|
074fee2b48 | ||
|
|
7f588935ea | ||
|
|
4b72ae7aab | ||
|
|
09b4a7ff15 | ||
|
|
7944522188 | ||
|
|
ae4d114802 | ||
|
|
07f3cd2ae5 | ||
|
|
035d878a9f | ||
|
|
913ed62095 | ||
|
|
8c135e4a91 | ||
|
|
5bcfe1a6c6 | ||
|
|
2ccef31f75 | ||
|
|
2c4783ff8b | ||
|
|
7cc1c1b561 | ||
|
|
d309c6311d | ||
|
|
e7f9072911 | ||
|
|
fe298bd53f | ||
|
|
6fe7f4641e | ||
|
|
9ae0bd9c2b | ||
|
|
dca98b7aa1 | ||
|
|
c0fc5d142f | ||
|
|
a973a6c7d2 | ||
|
|
a454a7f736 | ||
|
|
bae61a8152 | ||
|
|
0c984644b4 | ||
|
|
921b2c3aa4 | ||
|
|
8ba7ce73d8 | ||
|
|
76a8fe3839 | ||
|
|
1e6f0f28f6 | ||
|
|
6040803b60 | ||
|
|
04ae812a11 | ||
|
|
a0ad12c45b | ||
|
|
9cc7fdaca9 | ||
|
|
545a79d406 | ||
|
|
7c34964f87 | ||
|
|
6a97ab9ecb | ||
|
|
ad6336231c | ||
|
|
2f36c9d66d | ||
|
|
ae966833a4 | ||
|
|
3b037acb01 | ||
|
|
8771fa5c17 | ||
|
|
bccc6aa8d1 | ||
|
|
da27be6de5 | ||
|
|
838c5c7770 | ||
|
|
02395413ba | ||
|
|
4c1682b365 | ||
|
|
e7613e4f8b | ||
|
|
685fd49dd7 | ||
|
|
6061f3d4fa | ||
|
|
d55025ecae | ||
|
|
e3e0e9796b | ||
|
|
ecb2a5f3c6 | ||
|
|
76ccebf099 | ||
|
|
78100aa963 | ||
|
|
0b56fc7598 | ||
|
|
c1199f1a8a | ||
|
|
c8c078e78a | ||
|
|
d36f9c2ac8 | ||
|
|
e1dd4ac9e7 | ||
|
|
e6a35199e0 | ||
|
|
3cd1c92162 | ||
|
|
be5ce6249f | ||
|
|
0321fe93cf | ||
|
|
2cbfac2c89 | ||
|
|
0a6705f43e | ||
|
|
97e14337e3 | ||
|
|
5e7d644efd | ||
|
|
40ae019e1d | ||
|
|
efbde4a179 | ||
|
|
f565edd76d | ||
|
|
a3b8c9c233 | ||
|
|
de92bc0234 | ||
|
|
e6377eac9b | ||
|
|
22726c1de8 | ||
|
|
bce3aeb218 | ||
|
|
81722610d5 | ||
|
|
5bfad04b41 | ||
|
|
880664c6ab | ||
|
|
8f0c61ed14 | ||
|
|
7d524668e0 | ||
|
|
75680c5866 | ||
|
|
a1d008e6f0 | ||
|
|
d5d62a4ffd | ||
|
|
b72bd5bb37 | ||
|
|
7fecd20a1d | ||
|
|
f586f22ce3 | ||
|
|
21848d6bf1 | ||
|
|
28c57c4144 | ||
|
|
4a6ebff473 | ||
|
|
5c8d955f61 | ||
|
|
baaf509637 | ||
|
|
db3e1b9ed5 | ||
|
|
1a1e3345f4 | ||
|
|
527fc2790b | ||
|
|
cd7d9fc4f5 | ||
|
|
a61685ce01 | ||
|
|
b9e63d3f7d | ||
|
|
cc3a9dd553 | ||
|
|
6a89cc15c3 | ||
|
|
fc50392ec7 | ||
|
|
59cd89a9c9 | ||
|
|
d6ff5f7d96 | ||
|
|
8e4dfbd10d | ||
|
|
b2d1cea759 | ||
|
|
6fe1766c83 | ||
|
|
e59c35a308 | ||
|
|
b50071ed37 | ||
|
|
28c7de6185 | ||
|
|
6fb4ebba15 | ||
|
|
d00d83abd4 | ||
|
|
e6d16e458f | ||
|
|
ae42d35184 | ||
|
|
ce8929d153 | ||
|
|
cc2a775271 | ||
|
|
83d719cf79 | ||
|
|
4643b5835e | ||
|
|
a991bf9045 | ||
|
|
3fd3d83029 | ||
|
|
24419551a9 | ||
|
|
c83eb2e0c9 | ||
|
|
929b1675e3 | ||
|
|
db54b438e6 | ||
|
|
967254d9ca | ||
|
|
2d806df9b9 | ||
|
|
4fe798ec3b | ||
|
|
3555ff5f4e | ||
|
|
05ca819823 | ||
|
|
c8b8b60b93 | ||
|
|
287986d524 | ||
|
|
4c25f5e73b | ||
|
|
cbc217e80a | ||
|
|
fe348e89c5 | ||
|
|
e1e1984d3e | ||
|
|
99662b616f | ||
|
|
857d6e419f | ||
|
|
a298b9ea01 | ||
|
|
61097d0826 | ||
|
|
2ee0f634e6 | ||
|
|
61b3b4f775 | ||
|
|
dc4b9753d3 | ||
|
|
f1ef6c2096 | ||
|
|
872c915cf7 | ||
|
|
fb9f09c97f | ||
|
|
884db8a8b5 | ||
|
|
ee21b7bc37 | ||
|
|
32c53b9584 | ||
|
|
4e5f3fbe84 | ||
|
|
2ce193877b | ||
|
|
e52d599326 | ||
|
|
2cf66f41cb | ||
|
|
a06b387acc | ||
|
|
03520e0d6f | ||
|
|
a6a72a5b54 | ||
|
|
85db58aeb5 | ||
|
|
596bf32caa | ||
|
|
2b2644a76f | ||
|
|
02684a868f | ||
|
|
1924b308fd | ||
|
|
0d62e42c50 | ||
|
|
d3193cf8b7 | ||
|
|
f7538568c0 | ||
|
|
4629ecb8ee | ||
|
|
5bcea37d59 | ||
|
|
6decaef050 | ||
|
|
248578086f | ||
|
|
87553c6aa0 | ||
|
|
a2aa267e43 | ||
|
|
a563e9375e | ||
|
|
9a4be1fbec | ||
|
|
80f48518ca | ||
|
|
16c4b55e31 | ||
|
|
023a96a6d3 | ||
|
|
39394e49ae | ||
|
|
b54ddc3aa9 | ||
|
|
97537bd185 | ||
|
|
1225173a43 | ||
|
|
096bb8d439 | ||
|
|
df1f6e2b99 | ||
|
|
d1f5bef25d | ||
|
|
d426db43ec | ||
|
|
3bace07948 | ||
|
|
24e31d0a40 | ||
|
|
fb623c0929 | ||
|
|
4f641ce12d | ||
|
|
8cd1e40fb3 | ||
|
|
8a7027e8d6 | ||
|
|
5bbf73e3b5 | ||
|
|
106a58779d | ||
|
|
fa5b5ca02d | ||
|
|
ba6163574e | ||
|
|
37eca8af24 | ||
|
|
421c91a58c | ||
|
|
c90bf1c6e2 | ||
|
|
5b1de296af | ||
|
|
f4414566d3 | ||
|
|
db4f3eda55 | ||
|
|
f3b76df13b | ||
|
|
bb79272020 | ||
|
|
926ef9e33d | ||
|
|
ead21f37d7 | ||
|
|
49a2602329 | ||
|
|
e88bddc24f | ||
|
|
a5821e5785 | ||
|
|
4e4d741075 | ||
|
|
bec66e9e69 | ||
|
|
50832aab47 | ||
|
|
643fdd0bce | ||
|
|
d1565bb46f | ||
|
|
8fa66c13a9 | ||
|
|
c0ffa06b95 | ||
|
|
3b53f5bca3 | ||
|
|
2c80155c6f | ||
|
|
8a9b3b3d59 | ||
|
|
5dd691aa95 | ||
|
|
27ceae580a | ||
|
|
b6b6413d04 | ||
|
|
2095f4f670 | ||
|
|
606e8948c0 | ||
|
|
3b6fc1c496 | ||
|
|
f96bf65557 | ||
|
|
804cff8c55 | ||
|
|
633b9c0426 | ||
|
|
7d6991dd65 | ||
|
|
95247154d6 | ||
|
|
be6142aa43 | ||
|
|
0069513780 | ||
|
|
0c9a23a53c | ||
|
|
0035fc2313 | ||
|
|
6f62d4d5c1 | ||
|
|
51f9b34a7c | ||
|
|
337be9124f | ||
|
|
dd4e4d7559 | ||
|
|
0f29c267be | ||
|
|
d38ceb78c9 | ||
|
|
0c354c748a | ||
|
|
3a8e7c8899 | ||
|
|
261b8a1d06 | ||
|
|
01d8b224db | ||
|
|
e9a7e104c0 | ||
|
|
b4503908df | ||
|
|
fd48c6df8a | ||
|
|
cd7134e309 | ||
|
|
5fa6777239 | ||
|
|
908d0b0007 | ||
|
|
8e6989758e | ||
|
|
29b72df14c | ||
|
|
f100a33d98 | ||
|
|
7a64c432b1 | ||
|
|
2301b909d2 | ||
|
|
89680de12b | ||
|
|
a03af85a6b | ||
|
|
fbca37c42b | ||
|
|
4a57917783 | ||
|
|
cdc7d449a6 | ||
|
|
daf0b23805 | ||
|
|
d8ac82be36 | ||
|
|
a6c144038b | ||
|
|
980454beb2 | ||
|
|
63922f86a2 | ||
|
|
22414ce399 | ||
|
|
7496d9c114 | ||
|
|
c63dd62ed2 | ||
|
|
ff01d845b4 | ||
|
|
57592ee840 | ||
|
|
432c4c2cf1 | ||
|
|
98b7377643 | ||
|
|
287ec7e851 | ||
|
|
8a2d1ec5a7 | ||
|
|
afb2364ca2 | ||
|
|
9711390c18 | ||
|
|
bffb0573a6 | ||
|
|
17cbbb5bf0 | ||
|
|
b3b5f17e03 | ||
|
|
88acf8e098 | ||
|
|
f87144f84b | ||
|
|
1333f1fd47 | ||
|
|
8fa6bd1743 | ||
|
|
02d3468516 | ||
|
|
f657ac97f6 | ||
|
|
57dfaf135d | ||
|
|
9df42d7b98 | ||
|
|
b5928c36a3 | ||
|
|
910e7fed97 | ||
|
|
a9839abd4c | ||
|
|
78c7b6259c | ||
|
|
a6f7e1472b | ||
|
|
e03fcd24dd | ||
|
|
cd99b2e795 | ||
|
|
b5b06ea49c | ||
|
|
f7fb5840cf | ||
|
|
3b96d54369 | ||
|
|
f390b9cf2f | ||
|
|
1c65a2c1b4 | ||
|
|
2d2b75a4bf | ||
|
|
dcbe25c3ae | ||
|
|
46d23d9b86 | ||
|
|
fd9c4cbfa5 | ||
|
|
5c410b8df4 | ||
|
|
8c58d8a8ad | ||
|
|
a0a2eb2106 | ||
|
|
b7d976796a | ||
|
|
2e22c712af | ||
|
|
c7f83d3ff1 | ||
|
|
62474e0ed6 | ||
|
|
62226e8b3d | ||
|
|
8144373725 | ||
|
|
e9d8dd09ac | ||
|
|
6fc62da7ae | ||
|
|
4f75201a98 | ||
|
|
ba884c29bd | ||
|
|
2fe271f19f | ||
|
|
cf5709aab1 | ||
|
|
654cdf3d5b | ||
|
|
6c79d9e63b | ||
|
|
0aefa3be85 | ||
|
|
bc5ab3120f | ||
|
|
df8e129fc6 | ||
|
|
84caee94af | ||
|
|
1d9e320087 | ||
|
|
2a3c4c1a33 | ||
|
|
8c0fbb3665 | ||
|
|
9ea09b2b94 | ||
|
|
db81db5363 | ||
|
|
e715ccbdd5 | ||
|
|
bc94c50783 | ||
|
|
b4b9ef2362 | ||
|
|
dd6f7e3701 | ||
|
|
01e382285d | ||
|
|
4b1d4a3e20 | ||
|
|
562819e3ca | ||
|
|
551283c16e | ||
|
|
cd53e2d4a7 | ||
|
|
a58234f0cd | ||
|
|
c8d7243b5b | ||
|
|
6b1ca7b07c | ||
|
|
b80e7c3c92 | ||
|
|
0da09c5ddd | ||
|
|
17c081a40c | ||
|
|
0647cee02a | ||
|
|
423850a7aa | ||
|
|
896d30b151 | ||
|
|
495fd191f2 | ||
|
|
ae76daf393 | ||
|
|
8056b5573b | ||
|
|
516623cbbb | ||
|
|
a5ae2e891c | ||
|
|
90b40a8e5a | ||
|
|
7f40645934 | ||
|
|
6c204d2b77 | ||
|
|
ed988dcdc5 | ||
|
|
7b44cde4bd | ||
|
|
c7bad89af3 | ||
|
|
21a91e88a1 | ||
|
|
76d2838721 | ||
|
|
9b1fe9f466 | ||
|
|
9976800a35 | ||
|
|
f542351404 | ||
|
|
a13dedb6e4 | ||
|
|
d47ce79a24 | ||
|
|
cce42b4b83 | ||
|
|
142d17ebad | ||
|
|
30ca59dab7 | ||
|
|
c89b1f0e96 | ||
|
|
59bd11a3a7 | ||
|
|
3880c3c1be | ||
|
|
efa4b9e0b8 | ||
|
|
8c6e205c5a | ||
|
|
d478728cb7 | ||
|
|
5b07d7b776 | ||
|
|
18d62c4a17 | ||
|
|
02830e0ad6 | ||
|
|
6d89bddf29 | ||
|
|
dbbd499349 | ||
|
|
d3562ce394 | ||
|
|
d5973cf8a6 | ||
|
|
1d3cc36eef | ||
|
|
8fcfecbed1 | ||
|
|
7c1b878c3f | ||
|
|
4ea4221380 | ||
|
|
b8b3c9ef9f | ||
|
|
f00dc69bb6 | ||
|
|
23f286f24e | ||
|
|
16f8f77f5d | ||
|
|
dfc0ec995c | ||
|
|
8b848b62bb | ||
|
|
2dc62024fe | ||
|
|
994e85425f | ||
|
|
1880a485f8 | ||
|
|
03645fb235 | ||
|
|
eb8431255d | ||
|
|
e5a81b6c35 | ||
|
|
0eecd11fdc | ||
|
|
9c8e39827f | ||
|
|
586dec5ba3 | ||
|
|
6db7c800d5 | ||
|
|
2a8e1778ad | ||
|
|
a3425c0e78 | ||
|
|
7300c917dc | ||
|
|
dc3e144b6a | ||
|
|
75d339392b | ||
|
|
901a47318d | ||
|
|
dbadf37823 | ||
|
|
3321ac95ca | ||
|
|
c0bd4af120 | ||
|
|
d78b2b1cfb | ||
|
|
3e20912339 | ||
|
|
b2d7149a95 | ||
|
|
64be213b66 | ||
|
|
68b28ed530 | ||
|
|
3eacce9a66 | ||
|
|
6dadc2357a | ||
|
|
698d8ca701 | ||
|
|
1a4b00c70e | ||
|
|
64552fbd00 | ||
|
|
7c8d8f56e1 | ||
|
|
93ada8989f | ||
|
|
4b4c3dc41e | ||
|
|
b699fb046b | ||
|
|
ae08d13de4 | ||
|
|
1d784231b0 | ||
|
|
5fd79890e7 | ||
|
|
53b2a480ef | ||
|
|
943137de3b | ||
|
|
2d3aad573e | ||
|
|
409cd4f6a1 | ||
|
|
bd526ad0a1 | ||
|
|
4673d2093a | ||
|
|
94a765ee31 | ||
|
|
dcd2417fce | ||
|
|
4c5853e5e7 | ||
|
|
52f4cb599a | ||
|
|
90f6cc233c | ||
|
|
de264c42a8 | ||
|
|
c2469162fb | ||
|
|
19b7c7f52a | ||
|
|
e20d01a679 | ||
|
|
9a5c0a4b6d | ||
|
|
1b0d09068b | ||
|
|
3373b62b02 | ||
|
|
508e257543 | ||
|
|
7b0cd14b00 | ||
|
|
22fb219ad8 | ||
|
|
c34c5ff1f9 | ||
|
|
4e5bdec13a | ||
|
|
fbd43d9947 | ||
|
|
5dab89c9ec | ||
|
|
2a24effac0 | ||
|
|
972d3f1d39 | ||
|
|
a7aa5fd523 | ||
|
|
b9d8b69889 | ||
|
|
dedb9122df | ||
|
|
0e5bf0c27e | ||
|
|
a46436f61a | ||
|
|
6106adc6a5 | ||
|
|
c8bc11d61d | ||
|
|
f29b54898f | ||
|
|
fc693bc257 | ||
|
|
bba5c2cc8a | ||
|
|
0fb0e490f8 | ||
|
|
023e3d0c41 | ||
|
|
c11a359761 | ||
|
|
0da49bd92b | ||
|
|
b9ef713dd7 | ||
|
|
4948f3f213 | ||
|
|
7b1427b843 | ||
|
|
77a3c1c3ae | ||
|
|
2c236387b7 | ||
|
|
66e5136ba0 | ||
|
|
f748e3632d | ||
|
|
90688b238a | ||
|
|
986c91b5c8 | ||
|
|
8c13426492 | ||
|
|
fefd9b7427 | ||
|
|
8a55208c62 | ||
|
|
1f8b54a92d | ||
|
|
8d74a86bf1 | ||
|
|
6c82e98bbc | ||
|
|
94246104b8 | ||
|
|
347e5e9606 | ||
|
|
e4138c3e1e | ||
|
|
f2b5ae6894 | ||
|
|
0a89107b8b | ||
|
|
2a323f77ce | ||
|
|
59edcf33bd | ||
|
|
35506e179a | ||
|
|
6ce3805719 | ||
|
|
c1a82f2fae | ||
|
|
4f9478a336 | ||
|
|
e1dc2681f1 | ||
|
|
ce77c3fd8b | ||
|
|
9f1194056a | ||
|
|
b82c9ba190 | ||
|
|
6857b05039 | ||
|
|
abbbcb02c0 | ||
|
|
ec6144250d | ||
|
|
89d1222b8f | ||
|
|
de4985a9b6 | ||
|
|
6dd8cf6c0a | ||
|
|
6b2eae36f2 | ||
|
|
13445d815b | ||
|
|
e2d71abecd | ||
|
|
ddf1c74091 | ||
|
|
1bcc916807 | ||
|
|
c06b48af0e | ||
|
|
7e9549c05a | ||
|
|
3e2b08f9d0 | ||
|
|
fb85691fb9 | ||
|
|
1684756b79 | ||
|
|
88e4a9a755 | ||
|
|
d411394482 | ||
|
|
827d5289bc | ||
|
|
b133bc58f0 | ||
|
|
82c9a1a2bb | ||
|
|
e1ec4a2502 | ||
|
|
b6dc539105 | ||
|
|
6e8d8befb8 | ||
|
|
6995e98181 | ||
|
|
4597ed49cf | ||
|
|
ef2f8317c7 | ||
|
|
9b89ff9f2d | ||
|
|
4f291fa513 | ||
|
|
22b9befbda | ||
|
|
a9694fcdc0 | ||
|
|
d823dde43c | ||
|
|
d69e0bce4a | ||
|
|
7f197ede51 | ||
|
|
af97922e94 | ||
|
|
db94dc76b4 | ||
|
|
99effb051b | ||
|
|
425b6e0dc0 | ||
|
|
2516169f61 | ||
|
|
a3281712e2 | ||
|
|
bf079742cb | ||
|
|
98f4f4d6c4 | ||
|
|
42e489e199 | ||
|
|
d3b88d1b4f | ||
|
|
ec318f1cc5 | ||
|
|
6cfae6919f | ||
|
|
b23a071050 | ||
|
|
732e82e3d0 | ||
|
|
fecbc7a091 | ||
|
|
4b39362039 | ||
|
|
835cab58cf | ||
|
|
6e058f8581 | ||
|
|
9317dd610b | ||
|
|
8dc56b56ad | ||
|
|
4611fbfe0c | ||
|
|
b725c91b05 | ||
|
|
482062376e | ||
|
|
32fc990c68 | ||
|
|
3946d771e5 | ||
|
|
5940f62794 | ||
|
|
71cad51e8f | ||
|
|
dfeb901417 | ||
|
|
02933ae568 | ||
|
|
4ca2d4146b | ||
|
|
5d97a7f9ca | ||
|
|
6eab1f158a | ||
|
|
65a289e16f | ||
|
|
637707e58f | ||
|
|
95e602bf3b | ||
|
|
4ac192f520 | ||
|
|
473d0f74bd | ||
|
|
93ea1248e3 | ||
|
|
97270dcbe0 | ||
|
|
50105f0559 | ||
|
|
50cc274b2e | ||
|
|
3867329ef3 | ||
|
|
6648793e40 | ||
|
|
2899a126fc | ||
|
|
5391425123 | ||
|
|
1e7af0bbc7 | ||
|
|
dd67a8c8ba | ||
|
|
28ba9c5efa | ||
|
|
bb413ece49 | ||
|
|
31f4d20477 | ||
|
|
95e3a88608 | ||
|
|
bec4df7b12 | ||
|
|
93400cf44d | ||
|
|
57a15088c2 | ||
|
|
be6d55e5c4 | ||
|
|
09419d88af | ||
|
|
9c4bae6f23 | ||
|
|
b74320008a | ||
|
|
35b87e79a7 | ||
|
|
9be70f67ca | ||
|
|
bb86098235 | ||
|
|
dec32da262 | ||
|
|
a33e511c12 | ||
|
|
d71a2ce61e | ||
|
|
133bb2319f | ||
|
|
7d84a47683 | ||
|
|
38e6b81d07 | ||
|
|
143c5de51d | ||
|
|
3e424dea7b | ||
|
|
a794819869 | ||
|
|
b0fd50453a | ||
|
|
fe3ad3724c | ||
|
|
e1c6142851 | ||
|
|
6e7002dbd3 | ||
|
|
6a4063af0d | ||
|
|
6b636c051a | ||
|
|
9a035d3c51 | ||
|
|
850c52d07c | ||
|
|
10f8f5dd7b | ||
|
|
4e272ff066 | ||
|
|
a73e690172 | ||
|
|
be8d63ba8f | ||
|
|
3b90e18047 | ||
|
|
947d9d4560 | ||
|
|
179bc6ecdf | ||
|
|
fbabcfce94 | ||
|
|
3a92ad47e7 | ||
|
|
92a20a5362 | ||
|
|
9565b5194c | ||
|
|
23b2f3b971 | ||
|
|
f93dd6052e | ||
|
|
80df572b18 | ||
|
|
0c64d7e56a | ||
|
|
a8ce283727 | ||
|
|
ab8e9e7d7a | ||
|
|
dbce268692 | ||
|
|
fef9f95e65 | ||
|
|
f0952b55d0 | ||
|
|
8c7c8f4374 | ||
|
|
60e1947ed2 | ||
|
|
5b35822945 | ||
|
|
0a76876764 | ||
|
|
e382496e4c | ||
|
|
0c91a4e0f3 | ||
|
|
65a8e8f59c | ||
|
|
5497adaba1 | ||
|
|
56fae0b1f5 | ||
|
|
aaf08dadff | ||
|
|
557297ac9a | ||
|
|
baee951657 | ||
|
|
253dc24e40 | ||
|
|
503b1efd8a | ||
|
|
50f2ecbcb0 | ||
|
|
97e158989f | ||
|
|
e732fbb414 | ||
|
|
f8a168e64d | ||
|
|
e599621a32 | ||
|
|
59ab2083aa | ||
|
|
2d7c4eda66 | ||
|
|
3cc1870aee | ||
|
|
8eec86232c | ||
|
|
77a1e3a653 | ||
|
|
27e1d6cdae | ||
|
|
91c22b16bf | ||
|
|
fc5c9b931b | ||
|
|
8ce9737f3d | ||
|
|
6b44178108 | ||
|
|
6664547f43 | ||
|
|
10383e2701 | ||
|
|
f4b9f2965f | ||
|
|
2ba933d16a | ||
|
|
669961e496 | ||
|
|
f979491013 | ||
|
|
0d55b28805 | ||
|
|
9c70e649ca | ||
|
|
8c079bf5bc | ||
|
|
2cdf4a0532 | ||
|
|
4ba34ce672 | ||
|
|
637f1b5aed | ||
|
|
56a87125e0 | ||
|
|
6fedc8d942 | ||
|
|
dbb834d964 | ||
|
|
449946cc15 | ||
|
|
c3671a154d | ||
|
|
6874fb785b | ||
|
|
5141ddc96e | ||
|
|
6a03371731 | ||
|
|
b658bb415b | ||
|
|
85405a54c7 | ||
|
|
30a0834e72 | ||
|
|
109a76e1fc | ||
|
|
c231fd1466 | ||
|
|
c1a99b9be4 | ||
|
|
bf55428954 | ||
|
|
5e55d6b08f | ||
|
|
21098d2627 | ||
|
|
8da67ba61c | ||
|
|
54a0947bb4 | ||
|
|
a562b249a2 | ||
|
|
5af17f70b4 | ||
|
|
ca5bb91977 | ||
|
|
bbac54433e | ||
|
|
b6a5ec6490 | ||
|
|
aaf700f0b5 | ||
|
|
2ce89aca1e | ||
|
|
efdf69022a | ||
|
|
d4d1d4cc2a | ||
|
|
a8c4900891 | ||
|
|
930a7af8e7 | ||
|
|
77acd4ba8d | ||
|
|
625c4a1079 | ||
|
|
341ef19099 | ||
|
|
2563b20019 | ||
|
|
1b3b5b4dfe | ||
|
|
2e6bdc5636 | ||
|
|
be298cfa16 | ||
|
|
277e71b26a | ||
|
|
f7c903a586 | ||
|
|
ff4a5bef9b | ||
|
|
d8dc44e786 | ||
|
|
c968104a19 | ||
|
|
fbb27b84d1 | ||
|
|
f7481ecadf | ||
|
|
85c37b473a | ||
|
|
e0c5a85314 | ||
|
|
2fa1a5c4b9 | ||
|
|
23bc231df3 | ||
|
|
2146b605f7 | ||
|
|
8853e97b40 | ||
|
|
06d75da257 | ||
|
|
099aa1e3c2 | ||
|
|
63fdb348db | ||
|
|
81ee44f6c0 | ||
|
|
130a3a261d | ||
|
|
94368f43eb | ||
|
|
9a55213ddc | ||
|
|
5055542d61 | ||
|
|
23063ae0b9 | ||
|
|
a7f9aa909a | ||
|
|
15ecc451f3 | ||
|
|
186a4cfdf3 | ||
|
|
220ef9e2e2 | ||
|
|
7079116aa8 | ||
|
|
b9e6de45e6 | ||
|
|
d3503ff940 | ||
|
|
c3f4e1ba2e | ||
|
|
695fb64fa8 | ||
|
|
d32ab9ce74 | ||
|
|
94648989b8 | ||
|
|
07522d3c2e | ||
|
|
c14c07d2e3 | ||
|
|
9511ccfe47 | ||
|
|
ed17a1bf23 | ||
|
|
2a4f2f3942 | ||
|
|
3254eaf51c | ||
|
|
7941bae141 | ||
|
|
35a6666a84 | ||
|
|
73d5042774 | ||
|
|
9126cbab91 | ||
|
|
f8366f6e42 | ||
|
|
100c9b94ba | ||
|
|
8343c3597e | ||
|
|
d31adafa11 | ||
|
|
1acc6759e9 | ||
|
|
e995003c27 | ||
|
|
9edee2435c | ||
|
|
5d337b75f9 | ||
|
|
2188fad9c1 | ||
|
|
edc73f3f33 | ||
|
|
ade424cbb4 | ||
|
|
6e03773134 | ||
|
|
4ad0294655 | ||
|
|
43d3a0c8ea | ||
|
|
c045a4f2a7 | ||
|
|
20611eb8dc | ||
|
|
8ff7e180a4 | ||
|
|
3827e00b54 | ||
|
|
c52e689d0d | ||
|
|
cb517cb529 | ||
|
|
50bb620aa1 | ||
|
|
c745ea63b2 | ||
|
|
8e959bd245 | ||
|
|
298ca42369 | ||
|
|
ed9b9ce3c5 | ||
|
|
1298d2f8b6 | ||
|
|
6e84f685ce | ||
|
|
1ad87cfec9 | ||
|
|
9e9f459c0e | ||
|
|
fa3e0c726e | ||
|
|
3b038310ab | ||
|
|
6709936a8f | ||
|
|
04e5d02ab9 | ||
|
|
09d49bac95 | ||
|
|
3360839fe3 | ||
|
|
1af39cb228 | ||
|
|
c95735f083 | ||
|
|
c1285adbf8 | ||
|
|
fa2e6be05d | ||
|
|
4092a7c84b | ||
|
|
58d299c737 | ||
|
|
11ddac2b5f | ||
|
|
1f95c74f1e | ||
|
|
a197fbd4b5 | ||
|
|
708b8beadf | ||
|
|
0e1601e5b6 | ||
|
|
c7355510a2 | ||
|
|
1faa172944 | ||
|
|
7a8c98cd90 | ||
|
|
13e907bbd0 | ||
|
|
39e7832676 | ||
|
|
9b999e72ce | ||
|
|
e1a61503e4 | ||
|
|
9272d02149 | ||
|
|
067c02aba1 | ||
|
|
d0268bb9a2 | ||
|
|
fb4872ff7f | ||
|
|
2044458df9 | ||
|
|
d6df026550 | ||
|
|
7858ca6cc5 | ||
|
|
ac36473d13 | ||
|
|
72fb153fe0 | ||
|
|
527a602eba | ||
|
|
a71fd3b4df | ||
|
|
2ebc0383b5 | ||
|
|
9d2fc976e2 | ||
|
|
7431001ed6 | ||
|
|
149b4b5b43 | ||
|
|
c0eb9aac1c | ||
|
|
7f41f94fff | ||
|
|
d1f0dac302 | ||
|
|
afb3e00067 | ||
|
|
79469fc8d6 | ||
|
|
9a31ad6151 | ||
|
|
09cc6b69e3 | ||
|
|
948700eed6 | ||
|
|
3ab82849d4 | ||
|
|
0f43a19fdb | ||
|
|
cc1c1340a3 | ||
|
|
fe25ae83df | ||
|
|
c787bbe0e5 | ||
|
|
7aff9aac82 | ||
|
|
8b09db5f7f | ||
|
|
b5623602f5 | ||
|
|
16b27b3a1f | ||
|
|
8b00be9039 | ||
|
|
fa9e27c5e4 | ||
|
|
8603ac40a1 | ||
|
|
f4d9384603 | ||
|
|
c4408612b3 | ||
|
|
0742f7db26 | ||
|
|
891c2fe899 | ||
|
|
b831eb178b | ||
|
|
962ceaa89e | ||
|
|
d52b00bd34 | ||
|
|
aa0d174ccb | ||
|
|
b8e9c3d55a | ||
|
|
0b4c498c93 | ||
|
|
efc7c82cac | ||
|
|
b384449717 | ||
|
|
63917aa020 | ||
|
|
5016f529af | ||
|
|
5bd5f1bfda | ||
|
|
d4dcbce9cb | ||
|
|
da7ffc0da9 | ||
|
|
df8196a68c | ||
|
|
c1631759fc | ||
|
|
9e9c3c810f | ||
|
|
463101aec1 | ||
|
|
2072964701 | ||
|
|
aded1b78b5 | ||
|
|
ca9c859059 | ||
|
|
55811dae32 | ||
|
|
7136d145f8 | ||
|
|
2fbbf7519f | ||
|
|
5dd94c8298 | ||
|
|
663bf4fbb0 | ||
|
|
f0a22a4a4c | ||
|
|
4ab91520bd | ||
|
|
412b44a981 | ||
|
|
980d8a2641 | ||
|
|
a95d439852 | ||
|
|
a08e39faec | ||
|
|
b3295262c1 | ||
|
|
27aa026568 | ||
|
|
9969e1706e | ||
|
|
fb58595d44 | ||
|
|
bdfa16ca6f | ||
|
|
b307bcb4a9 | ||
|
|
f26941091b | ||
|
|
6cd5769ed7 | ||
|
|
41adfa65b3 | ||
|
|
3fbb7c7a2d | ||
|
|
0aa82c04ea | ||
|
|
5c6f2694c7 | ||
|
|
eca7615f08 | ||
|
|
52d559bb38 | ||
|
|
259736390a | ||
|
|
7db07630a7 | ||
|
|
d617b0f447 | ||
|
|
80ff5917f7 | ||
|
|
b401da5eba | ||
|
|
05b25c334f | ||
|
|
2c5a47a275 | ||
|
|
b2605a9012 | ||
|
|
b929a19f48 | ||
|
|
4b04faa88b | ||
|
|
5fee0b5bf1 | ||
|
|
27120fb0f5 | ||
|
|
0cf539fb82 | ||
|
|
26a38bd8de | ||
|
|
ebbce4d061 | ||
|
|
5acd2f6c3a | ||
|
|
fe2bc903b8 | ||
|
|
658f1f5cda | ||
|
|
5ccc047fe4 | ||
|
|
6d704b9cd1 | ||
|
|
5f957b5cf9 | ||
|
|
8681728b8d | ||
|
|
45a02e3439 | ||
|
|
aef4dd3fe7 | ||
|
|
6a92c6af4e | ||
|
|
e010940b61 | ||
|
|
2c9a4d276a | ||
|
|
4dfba73e5c | ||
|
|
c282d662ca | ||
|
|
b3d7594813 |
83
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
83
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
name: Bug report
|
||||||
|
description: Create a report to help us improve
|
||||||
|
title: "[Bug] "
|
||||||
|
labels: ["bug"]
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Verify steps
|
||||||
|
description: "
|
||||||
|
在提交之前,请确认
|
||||||
|
Please verify that you've followed these steps
|
||||||
|
"
|
||||||
|
options:
|
||||||
|
- label: "
|
||||||
|
确保你使用的是**本仓库**最新的的 mihomo 或 mihomo Alpha 版本
|
||||||
|
Ensure you are using the latest version of Mihomo or Mihomo Alpha from **this repository**.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
如果你可以自己 debug 并解决的话,提交 PR 吧
|
||||||
|
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
||||||
|
"
|
||||||
|
required: false
|
||||||
|
- label: "
|
||||||
|
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
||||||
|
I have searched on the [issue tracker](……/) for a related issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经使用 Alpha 分支版本测试过,问题依旧存在
|
||||||
|
I have tested using the dev branch, and the issue still exists.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法自行解决问题
|
||||||
|
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
这是 Mihomo 核心的问题,并非我所使用的 Mihomo 衍生版本(如 OpenMihomo、KoolMihomo 等)的特定问题
|
||||||
|
This is an issue of the Mihomo core *per se*, not to the derivatives of Mihomo, like OpenMihomo or KoolMihomo.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- type: input
|
||||||
|
attributes:
|
||||||
|
label: Mihomo version
|
||||||
|
description: "use `mihomo -v`"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: dropdown
|
||||||
|
id: os
|
||||||
|
attributes:
|
||||||
|
label: What OS are you seeing the problem on?
|
||||||
|
multiple: true
|
||||||
|
options:
|
||||||
|
- macOS
|
||||||
|
- Windows
|
||||||
|
- Linux
|
||||||
|
- OpenBSD/FreeBSD
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: yaml
|
||||||
|
label: "Mihomo config"
|
||||||
|
description: "
|
||||||
|
在下方附上 Mihomo core 配置文件,请确保配置文件中没有敏感信息(比如:服务器地址,密码,端口等)
|
||||||
|
Paste the Mihomo core configuration file below, please make sure that there is no sensitive information in the configuration file (e.g., server address/url, password, port)
|
||||||
|
"
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
render: shell
|
||||||
|
label: Mihomo log
|
||||||
|
description: "
|
||||||
|
在下方附上 Mihomo Core 的日志,log level 使用 DEBUG
|
||||||
|
Paste the Mihomo core log below with the log level set to `DEBUG`.
|
||||||
|
"
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
5
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
blank_issues_enabled: false
|
||||||
|
contact_links:
|
||||||
|
- name: mihomo Community Support
|
||||||
|
url: https://github.com/MetaCubeX/mihomo/discussions
|
||||||
|
about: Please ask and answer questions about mihomo here.
|
||||||
37
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
37
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
name: Feature request
|
||||||
|
description: Suggest an idea for this project
|
||||||
|
title: "[Feature] "
|
||||||
|
labels: ["enhancement"]
|
||||||
|
body:
|
||||||
|
- type: checkboxes
|
||||||
|
id: ensure
|
||||||
|
attributes:
|
||||||
|
label: Verify steps
|
||||||
|
description: "
|
||||||
|
在提交之前,请确认
|
||||||
|
Please verify that you've followed these steps
|
||||||
|
"
|
||||||
|
options:
|
||||||
|
- label: "
|
||||||
|
我已经在 [Issue Tracker](……/) 中找过我要提出的请求
|
||||||
|
I have searched on the [issue tracker](……/) for a related feature request.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- label: "
|
||||||
|
我已经仔细看过 [Documentation](https://wiki.metacubex.one/) 并无法找到这个功能
|
||||||
|
I have read the [documentation](https://wiki.metacubex.one/) and was unable to solve the issue.
|
||||||
|
"
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Description
|
||||||
|
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Mihomo Core 的行为是什麽?
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
- type: textarea
|
||||||
|
attributes:
|
||||||
|
label: Possible Solution
|
||||||
|
description: "
|
||||||
|
此项非必须,但是如果你有想法的话欢迎提出。
|
||||||
|
Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
|
||||||
|
"
|
||||||
32
.github/genReleaseNote.sh
vendored
Executable file
32
.github/genReleaseNote.sh
vendored
Executable file
@@ -0,0 +1,32 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
while getopts "v:" opt; do
|
||||||
|
case $opt in
|
||||||
|
v)
|
||||||
|
version_range=$OPTARG
|
||||||
|
;;
|
||||||
|
\?)
|
||||||
|
echo "Invalid option: -$OPTARG" >&2
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -z "$version_range" ]; then
|
||||||
|
echo "Please provide the version range using -v option. Example: ./genReleashNote.sh -v v1.14.1...v1.14.2"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "## What's Changed" > release.md
|
||||||
|
git log --pretty=format:"* %h %s by @%an" --grep="^feat" -i $version_range | sort -f | uniq >> release.md
|
||||||
|
echo "" >> release.md
|
||||||
|
|
||||||
|
echo "## BUG & Fix" >> release.md
|
||||||
|
git log --pretty=format:"* %h %s by @%an" --grep="^fix" -i $version_range | sort -f | uniq >> release.md
|
||||||
|
echo "" >> release.md
|
||||||
|
|
||||||
|
echo "## Maintenance" >> release.md
|
||||||
|
git log --pretty=format:"* %h %s by @%an" --grep="^chore\|^docs\|^refactor" -i $version_range | sort -f | uniq >> release.md
|
||||||
|
echo "" >> release.md
|
||||||
|
|
||||||
|
echo "**Full Changelog**: https://github.com/MetaCubeX/mihomo/compare/$version_range" >> release.md
|
||||||
182
.github/patch/go1.21.patch
vendored
Normal file
182
.github/patch/go1.21.patch
vendored
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
Subject: [PATCH] Revert "[release-branch.go1.21] crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -15,7 +15,7 @@
|
||||||
|
// available, /dev/urandom otherwise.
|
||||||
|
// On OpenBSD and macOS, Reader uses getentropy(2).
|
||||||
|
// On other Unix-like systems, Reader reads from /dev/urandom.
|
||||||
|
-// On Windows systems, Reader uses the ProcessPrng API.
|
||||||
|
+// On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// On JS/Wasm, Reader uses the Web Crypto API.
|
||||||
|
// On WASIP1/Wasm, Reader uses random_get from wasi_snapshot_preview1.
|
||||||
|
var Reader io.Reader
|
||||||
|
Index: src/crypto/rand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
--- a/src/crypto/rand/rand_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -15,8 +15,11 @@
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
- if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
+func (r *rngReader) Read(b []byte) (n int, err error) {
|
||||||
|
+ // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
+ // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
+ // and 64-bit systems.
|
||||||
|
+ if err := batched(windows.RtlGenRandom, 1<<31-1)(b); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -384,7 +384,7 @@
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
//sys RtlLookupFunctionEntry(pc uintptr, baseAddress *uintptr, table *byte) (ret uintptr) = kernel32.RtlLookupFunctionEntry
|
||||||
|
//sys RtlVirtualUnwind(handlerType uint32, baseAddress uintptr, pc uintptr, entry uintptr, ctxt uintptr, data *uintptr, frame *uintptr, ctxptrs *byte) (ret uintptr) = kernel32.RtlVirtualUnwind
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -37,14 +37,13 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
- modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
- modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
- modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
- modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
- modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
- moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
- modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
+ modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
+ modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
+ modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
+ moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
+ modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
|
||||||
|
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||||
|
procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
|
||||||
|
@@ -53,7 +52,7 @@
|
||||||
|
procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -149,12 +148,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 8bba868de983dd7bf55fcd121495ba8d6e2734e7)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision 7e6c963d81e14ee394402671d4044b2940c8d2c1)
|
||||||
|
@@ -127,8 +127,15 @@
|
||||||
|
_AddVectoredContinueHandler,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
+ // This approach has been recommended by Microsoft (see issue
|
||||||
|
+ // 15589 for details).
|
||||||
|
+ // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
+ // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
+ // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
+ // when building executable as Cgo. So load SystemFunction036
|
||||||
|
+ // manually during runtime startup.
|
||||||
|
+ _RtlGenRandom stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -145,12 +152,12 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
- bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
- kernel32dll = [...]uint16{'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ws2_32dll = [...]uint16{'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ advapi32dll = [...]uint16{'a', 'd', 'v', 'a', 'p', 'i', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ kernel32dll = [...]uint16{'k', 'e', 'r', 'n', 'e', 'l', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
+ ws2_32dll = [...]uint16{'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
@@ -249,11 +256,11 @@
|
||||||
|
}
|
||||||
|
_AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll[:])
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
|
||||||
|
n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
if n32 == 0 {
|
||||||
|
@@ -610,7 +617,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func getRandomData(r []byte) {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
extendRandom(r, n)
|
||||||
645
.github/patch/go1.22.patch
vendored
Normal file
645
.github/patch/go1.22.patch
vendored
Normal file
@@ -0,0 +1,645 @@
|
|||||||
|
Subject: [PATCH] Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -15,7 +15,7 @@
|
||||||
|
// available, /dev/urandom otherwise.
|
||||||
|
// On OpenBSD and macOS, Reader uses getentropy(2).
|
||||||
|
// On other Unix-like systems, Reader reads from /dev/urandom.
|
||||||
|
-// On Windows systems, Reader uses the ProcessPrng API.
|
||||||
|
+// On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// On JS/Wasm, Reader uses the Web Crypto API.
|
||||||
|
// On WASIP1/Wasm, Reader uses random_get from wasi_snapshot_preview1.
|
||||||
|
var Reader io.Reader
|
||||||
|
Index: src/crypto/rand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
--- a/src/crypto/rand/rand_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -15,8 +15,11 @@
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
- if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
+func (r *rngReader) Read(b []byte) (n int, err error) {
|
||||||
|
+ // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
+ // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
+ // and 64-bit systems.
|
||||||
|
+ if err := batched(windows.RtlGenRandom, 1<<31-1)(b); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -384,7 +384,7 @@
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
@@ -37,14 +37,13 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
- modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
- modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
- modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
- modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
- modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
- moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
- modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
+ modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
+ modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
+ modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
+ modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
+ modpsapi = syscall.NewLazyDLL(sysdll.Add("psapi.dll"))
|
||||||
|
+ moduserenv = syscall.NewLazyDLL(sysdll.Add("userenv.dll"))
|
||||||
|
+ modws2_32 = syscall.NewLazyDLL(sysdll.Add("ws2_32.dll"))
|
||||||
|
|
||||||
|
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||||
|
procDuplicateTokenEx = modadvapi32.NewProc("DuplicateTokenEx")
|
||||||
|
@@ -56,7 +55,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -180,12 +179,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision cb4eee693c382bea4222f20837e26501d40ed892)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision 83ff9782e024cb328b690cbf0da4e7848a327f4f)
|
||||||
|
@@ -40,8 +40,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._RaiseFailFastException RaiseFailFastException%3 "kernel32.dll"
|
||||||
|
@@ -74,7 +74,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -98,8 +97,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_RaiseFailFastException,
|
||||||
|
@@ -127,8 +126,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ stdFunction
|
||||||
|
+
|
||||||
|
+ // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
+ // This approach has been recommended by Microsoft (see issue
|
||||||
|
+ // 15589 for details).
|
||||||
|
+ // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
+ // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
+ // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
+ // when building executable as Cgo. So load SystemFunction036
|
||||||
|
+ // manually during runtime startup.
|
||||||
|
+ _RtlGenRandom stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -143,14 +157,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ws2_32dll = [...]uint16{'w', 's', '2', '_', '3', '2', '.', 'd', 'l', 'l', 0}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -239,25 +245,51 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
_RtlGetCurrentPeb = windowsFindfunc(n32, []byte("RtlGetCurrentPeb\000"))
|
||||||
|
_RtlGetNtVersionNumbers = windowsFindfunc(n32, []byte("RtlGetNtVersionNumbers\000"))
|
||||||
|
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
}
|
||||||
|
@@ -267,7 +299,8 @@
|
||||||
|
throw("timeBegin/EndPeriod not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
- ws232 := windowsLoadSystemLib(ws2_32dll[:])
|
||||||
|
+ var ws232dll = []byte("ws2_32.dll\000")
|
||||||
|
+ ws232 := windowsLoadSystemLib(ws232dll)
|
||||||
|
if ws232 == 0 {
|
||||||
|
throw("ws2_32.dll not found")
|
||||||
|
}
|
||||||
|
@@ -286,7 +319,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -360,6 +393,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -507,7 +556,6 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
|
||||||
|
ncpu = getproccount()
|
||||||
|
@@ -524,7 +572,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/hook_windows.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// Placeholders for socket system calls.
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error) = syscall.Socket
|
||||||
|
wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
|
||||||
|
connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
|
||||||
|
listenFunc func(syscall.Handle, int) error = syscall.Listen
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build !js && !plan9 && !wasip1 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// Copyright 2015 The Go Authors. All rights reserved.
|
||||||
|
+// Use of this source code is governed by a BSD-style
|
||||||
|
+// license that can be found in the LICENSE file.
|
||||||
|
+
|
||||||
|
+package socktest_test
|
||||||
|
+
|
||||||
|
+import "syscall"
|
||||||
|
+
|
||||||
|
+var (
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error)
|
||||||
|
+ closeFunc func(syscall.Handle) error
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
+ closeFunc = sw.Closesocket
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func uninstallTestHooks() {
|
||||||
|
+ socketFunc = syscall.Socket
|
||||||
|
+ closeFunc = syscall.Closesocket
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
+// Socket wraps [syscall.Socket].
|
||||||
|
+func (sw *Switch) Socket(family, sotype, proto int) (s syscall.Handle, err error) {
|
||||||
|
+ sw.once.Do(sw.init)
|
||||||
|
+
|
||||||
|
+ so := &Status{Cookie: cookie(family, sotype, proto)}
|
||||||
|
+ sw.fmu.RLock()
|
||||||
|
+ f, _ := sw.fltab[FilterSocket]
|
||||||
|
+ sw.fmu.RUnlock()
|
||||||
|
+
|
||||||
|
+ af, err := f.apply(so)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+ s, so.Err = syscall.Socket(family, sotype, proto)
|
||||||
|
+ if err = af.apply(so); err != nil {
|
||||||
|
+ if so.Err == nil {
|
||||||
|
+ syscall.Closesocket(s)
|
||||||
|
+ }
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ sw.smu.Lock()
|
||||||
|
+ defer sw.smu.Unlock()
|
||||||
|
+ if so.Err != nil {
|
||||||
|
+ sw.stats.getLocked(so.Cookie).OpenFailed++
|
||||||
|
+ return syscall.InvalidHandle, so.Err
|
||||||
|
+ }
|
||||||
|
+ nso := sw.addLocked(s, family, sotype, proto)
|
||||||
|
+ sw.stats.getLocked(nso.Cookie).Opened++
|
||||||
|
+ return s, nil
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// WSASocket wraps [syscall.WSASocket].
|
||||||
|
func (sw *Switch) WSASocket(family, sotype, proto int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (s syscall.Handle, err error) {
|
||||||
|
sw.once.Do(sw.init)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -8,6 +8,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -17,6 +18,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -26,6 +28,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/net/sock_windows.go (revision ef0606261340e608017860b423ffae5c1ce78239)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
|
||||||
|
s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
|
||||||
|
nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
|
||||||
|
+ if err == nil {
|
||||||
|
+ return s, nil
|
||||||
|
+ }
|
||||||
|
+ // WSA_FLAG_NO_HANDLE_INHERIT flag is not supported on some
|
||||||
|
+ // old versions of Windows, see
|
||||||
|
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
|
||||||
|
+ // for details. Just use syscall.Socket, if windows.WSASocket failed.
|
||||||
|
+
|
||||||
|
+ // See ../syscall/exec_unix.go for description of ForkLock.
|
||||||
|
+ syscall.ForkLock.RLock()
|
||||||
|
+ s, err = socketFunc(family, sotype, proto)
|
||||||
|
+ if err == nil {
|
||||||
|
+ syscall.CloseOnExec(s)
|
||||||
|
+ }
|
||||||
|
+ syscall.ForkLock.RUnlock()
|
||||||
|
if err != nil {
|
||||||
|
return syscall.InvalidHandle, os.NewSyscallError("socket", err)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 9779155f18b6556a034f7bb79fb7fb2aad1e26a9)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision 7f83badcb925a7e743188041cb6e561fc9b5b642)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -317,6 +316,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ var maj, min, build uint32
|
||||||
|
+ rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
+ isWin7 := maj < 6 || (maj == 6 && min <= 1)
|
||||||
|
+ // NT kernel handles are divisible by 4, with the bottom 3 bits left as
|
||||||
|
+ // a tag. The fully set tag correlates with the types of handles we're
|
||||||
|
+ // concerned about here. Except, the kernel will interpret some
|
||||||
|
+ // special handle values, like -1, -2, and so forth, so kernelbase.dll
|
||||||
|
+ // checks to see that those bottom three bits are checked, but that top
|
||||||
|
+ // bit is not checked.
|
||||||
|
+ isLegacyWin7ConsoleHandle := func(handle Handle) bool { return isWin7 && handle&0x10000003 == 3 }
|
||||||
|
+
|
||||||
|
p, _ := GetCurrentProcess()
|
||||||
|
parentProcess := p
|
||||||
|
if sys.ParentProcess != 0 {
|
||||||
|
@@ -325,7 +335,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ destinationProcessHandle := parentProcess
|
||||||
|
+
|
||||||
|
+ // On Windows 7, console handles aren't real handles, and can only be duplicated
|
||||||
|
+ // into the current process, not a parent one, which amounts to the same thing.
|
||||||
|
+ if parentProcess != p && isLegacyWin7ConsoleHandle(Handle(attr.Files[i])) {
|
||||||
|
+ destinationProcessHandle = p
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ err := DuplicateHandle(p, Handle(attr.Files[i]), destinationProcessHandle, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +374,14 @@
|
||||||
|
|
||||||
|
fd = append(fd, sys.AdditionalInheritedHandles...)
|
||||||
|
|
||||||
|
+ // On Windows 7, console handles aren't real handles, so don't pass them
|
||||||
|
+ // through to PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
|
||||||
|
+ for i := range fd {
|
||||||
|
+ if isLegacyWin7ConsoleHandle(fd[i]) {
|
||||||
|
+ fd[i] = 0
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
// The presence of a NULL handle in the list is enough to cause PROC_THREAD_ATTRIBUTE_HANDLE_LIST
|
||||||
|
// to treat the entire list as empty, so remove NULL handles.
|
||||||
|
j := 0
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision 7f83badcb925a7e743188041cb6e561fc9b5b642)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision 83ff9782e024cb328b690cbf0da4e7848a327f4f)
|
||||||
|
@@ -413,23 +413,36 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
//go:nosplit
|
||||||
|
//go:cgo_unsafe_args
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
lockOSThread()
|
||||||
|
c := &getg().m.syscall
|
||||||
|
- c.fn = getLoadLibraryEx()
|
||||||
|
- c.n = 3
|
||||||
|
- args := struct {
|
||||||
|
- lpFileName *uint16
|
||||||
|
- hFile uintptr // always 0
|
||||||
|
- flags uint32
|
||||||
|
- }{filename, 0, _LOAD_LIBRARY_SEARCH_SYSTEM32}
|
||||||
|
- c.args = uintptr(noescape(unsafe.Pointer(&args)))
|
||||||
|
+
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ c.fn = getLoadLibraryEx()
|
||||||
|
+ c.n = 3
|
||||||
|
+ args := struct {
|
||||||
|
+ lpFileName *uint16
|
||||||
|
+ hFile uintptr // always 0
|
||||||
|
+ flags uint32
|
||||||
|
+ }{filename, 0, _LOAD_LIBRARY_SEARCH_SYSTEM32}
|
||||||
|
+ c.args = uintptr(noescape(unsafe.Pointer(&args)))
|
||||||
|
+ } else {
|
||||||
|
+ c.fn = getLoadLibrary()
|
||||||
|
+ c.n = 1
|
||||||
|
+ c.args = uintptr(noescape(unsafe.Pointer(&absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
|
||||||
|
cgocall(asmstdcallAddr, unsafe.Pointer(c))
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
handle = c.r1
|
||||||
|
if handle == 0 {
|
||||||
|
err = c.err
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision 7f83badcb925a7e743188041cb6e561fc9b5b642)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision 83ff9782e024cb328b690cbf0da4e7848a327f4f)
|
||||||
|
@@ -44,7 +44,7 @@
|
||||||
|
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -53,6 +53,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -69,7 +72,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
643
.github/patch/go1.23.patch
vendored
Normal file
643
.github/patch/go1.23.patch
vendored
Normal file
@@ -0,0 +1,643 @@
|
|||||||
|
Subject: [PATCH] Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -16,7 +16,7 @@
|
||||||
|
// - On macOS and iOS, Reader uses arc4random_buf(3).
|
||||||
|
// - On OpenBSD and NetBSD, Reader uses getentropy(2).
|
||||||
|
// - On other Unix-like systems, Reader reads from /dev/urandom.
|
||||||
|
-// - On Windows, Reader uses the ProcessPrng API.
|
||||||
|
+// - On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// - On js/wasm, Reader uses the Web Crypto API.
|
||||||
|
// - On wasip1/wasm, Reader uses random_get from wasi_snapshot_preview1.
|
||||||
|
var Reader io.Reader
|
||||||
|
Index: src/crypto/rand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand_windows.go b/src/crypto/rand/rand_windows.go
|
||||||
|
--- a/src/crypto/rand/rand_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/crypto/rand/rand_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -15,8 +15,11 @@
|
||||||
|
|
||||||
|
type rngReader struct{}
|
||||||
|
|
||||||
|
-func (r *rngReader) Read(b []byte) (int, error) {
|
||||||
|
- if err := windows.ProcessPrng(b); err != nil {
|
||||||
|
+func (r *rngReader) Read(b []byte) (n int, err error) {
|
||||||
|
+ // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
+ // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
+ // and 64-bit systems.
|
||||||
|
+ if err := batched(windows.RtlGenRandom, 1<<31-1)(b); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -414,7 +414,7 @@
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
@@ -38,7 +38,6 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
@@ -57,7 +56,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -183,12 +182,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 6885bad7dd86880be6929c02085e5c7a67ff2887)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision 69e2eed6dd0f6d815ebf15797761c13f31213dd6)
|
||||||
|
@@ -39,8 +39,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceFrequency QueryPerformanceFrequency%1 "kernel32.dll"
|
||||||
|
@@ -74,7 +74,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -97,8 +96,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_QueryPerformanceFrequency,
|
||||||
|
@@ -127,8 +126,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ stdFunction
|
||||||
|
+
|
||||||
|
+ // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
+ // This approach has been recommended by Microsoft (see issue
|
||||||
|
+ // 15589 for details).
|
||||||
|
+ // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
+ // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
+ // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
+ // when building executable as Cgo. So load SystemFunction036
|
||||||
|
+ // manually during runtime startup.
|
||||||
|
+ _RtlGenRandom stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -145,13 +159,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -244,8 +251,18 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname windows_QueryPerformanceCounter internal/syscall/windows.QueryPerformanceCounter
|
||||||
|
@@ -263,13 +280,28 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
@@ -298,7 +330,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -357,6 +389,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -430,7 +478,8 @@
|
||||||
|
// Only load winmm.dll if we need it.
|
||||||
|
// This avoids a dependency on winmm.dll for Go programs
|
||||||
|
// that run on new Windows versions.
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
print("runtime: LoadLibraryExW failed; errno=", getlasterror(), "\n")
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
@@ -471,6 +520,28 @@
|
||||||
|
canUseLongPaths = true
|
||||||
|
}
|
||||||
|
|
||||||
|
+var osVersionInfo struct {
|
||||||
|
+ majorVersion uint32
|
||||||
|
+ minorVersion uint32
|
||||||
|
+ buildNumber uint32
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func initOsVersionInfo() {
|
||||||
|
+ info := _OSVERSIONINFOW{}
|
||||||
|
+ info.osVersionInfoSize = uint32(unsafe.Sizeof(info))
|
||||||
|
+ stdcall1(_RtlGetVersion, uintptr(unsafe.Pointer(&info)))
|
||||||
|
+ osVersionInfo.majorVersion = info.majorVersion
|
||||||
|
+ osVersionInfo.minorVersion = info.minorVersion
|
||||||
|
+ osVersionInfo.buildNumber = info.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) {
|
||||||
|
+ *majorVersion = osVersionInfo.majorVersion
|
||||||
|
+ *minorVersion = osVersionInfo.minorVersion
|
||||||
|
+ *buildNumber = osVersionInfo.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
func osinit() {
|
||||||
|
asmstdcallAddr = unsafe.Pointer(abi.FuncPCABI0(asmstdcall))
|
||||||
|
|
||||||
|
@@ -483,8 +554,8 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
+ initOsVersionInfo()
|
||||||
|
|
||||||
|
ncpu = getproccount()
|
||||||
|
|
||||||
|
@@ -500,7 +571,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/hook_windows.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// Placeholders for socket system calls.
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error) = syscall.Socket
|
||||||
|
wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
|
||||||
|
connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
|
||||||
|
listenFunc func(syscall.Handle, int) error = syscall.Listen
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build !js && !plan9 && !wasip1 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// Copyright 2015 The Go Authors. All rights reserved.
|
||||||
|
+// Use of this source code is governed by a BSD-style
|
||||||
|
+// license that can be found in the LICENSE file.
|
||||||
|
+
|
||||||
|
+package socktest_test
|
||||||
|
+
|
||||||
|
+import "syscall"
|
||||||
|
+
|
||||||
|
+var (
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error)
|
||||||
|
+ closeFunc func(syscall.Handle) error
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
+ closeFunc = sw.Closesocket
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func uninstallTestHooks() {
|
||||||
|
+ socketFunc = syscall.Socket
|
||||||
|
+ closeFunc = syscall.Closesocket
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
+// Socket wraps [syscall.Socket].
|
||||||
|
+func (sw *Switch) Socket(family, sotype, proto int) (s syscall.Handle, err error) {
|
||||||
|
+ sw.once.Do(sw.init)
|
||||||
|
+
|
||||||
|
+ so := &Status{Cookie: cookie(family, sotype, proto)}
|
||||||
|
+ sw.fmu.RLock()
|
||||||
|
+ f, _ := sw.fltab[FilterSocket]
|
||||||
|
+ sw.fmu.RUnlock()
|
||||||
|
+
|
||||||
|
+ af, err := f.apply(so)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+ s, so.Err = syscall.Socket(family, sotype, proto)
|
||||||
|
+ if err = af.apply(so); err != nil {
|
||||||
|
+ if so.Err == nil {
|
||||||
|
+ syscall.Closesocket(s)
|
||||||
|
+ }
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ sw.smu.Lock()
|
||||||
|
+ defer sw.smu.Unlock()
|
||||||
|
+ if so.Err != nil {
|
||||||
|
+ sw.stats.getLocked(so.Cookie).OpenFailed++
|
||||||
|
+ return syscall.InvalidHandle, so.Err
|
||||||
|
+ }
|
||||||
|
+ nso := sw.addLocked(s, family, sotype, proto)
|
||||||
|
+ sw.stats.getLocked(nso.Cookie).Opened++
|
||||||
|
+ return s, nil
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// WSASocket wraps [syscall.WSASocket].
|
||||||
|
func (sw *Switch) WSASocket(family, sotype, proto int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (s syscall.Handle, err error) {
|
||||||
|
sw.once.Do(sw.init)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -8,6 +8,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -17,6 +18,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -26,6 +28,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/net/sock_windows.go (revision 21290de8a4c91408de7c2b5b68757b1e90af49dd)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
|
||||||
|
s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
|
||||||
|
nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
|
||||||
|
+ if err == nil {
|
||||||
|
+ return s, nil
|
||||||
|
+ }
|
||||||
|
+ // WSA_FLAG_NO_HANDLE_INHERIT flag is not supported on some
|
||||||
|
+ // old versions of Windows, see
|
||||||
|
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
|
||||||
|
+ // for details. Just use syscall.Socket, if windows.WSASocket failed.
|
||||||
|
+
|
||||||
|
+ // See ../syscall/exec_unix.go for description of ForkLock.
|
||||||
|
+ syscall.ForkLock.RLock()
|
||||||
|
+ s, err = socketFunc(family, sotype, proto)
|
||||||
|
+ if err == nil {
|
||||||
|
+ syscall.CloseOnExec(s)
|
||||||
|
+ }
|
||||||
|
+ syscall.ForkLock.RUnlock()
|
||||||
|
if err != nil {
|
||||||
|
return syscall.InvalidHandle, os.NewSyscallError("socket", err)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 9ac42137ef6730e8b7daca016ece831297a1d75b)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision 6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -254,6 +253,9 @@
|
||||||
|
var zeroProcAttr ProcAttr
|
||||||
|
var zeroSysProcAttr SysProcAttr
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
|
||||||
|
if len(argv0) == 0 {
|
||||||
|
return 0, 0, EWINDOWS
|
||||||
|
@@ -317,6 +319,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ var maj, min, build uint32
|
||||||
|
+ rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
+ isWin7 := maj < 6 || (maj == 6 && min <= 1)
|
||||||
|
+ // NT kernel handles are divisible by 4, with the bottom 3 bits left as
|
||||||
|
+ // a tag. The fully set tag correlates with the types of handles we're
|
||||||
|
+ // concerned about here. Except, the kernel will interpret some
|
||||||
|
+ // special handle values, like -1, -2, and so forth, so kernelbase.dll
|
||||||
|
+ // checks to see that those bottom three bits are checked, but that top
|
||||||
|
+ // bit is not checked.
|
||||||
|
+ isLegacyWin7ConsoleHandle := func(handle Handle) bool { return isWin7 && handle&0x10000003 == 3 }
|
||||||
|
+
|
||||||
|
p, _ := GetCurrentProcess()
|
||||||
|
parentProcess := p
|
||||||
|
if sys.ParentProcess != 0 {
|
||||||
|
@@ -325,7 +338,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ destinationProcessHandle := parentProcess
|
||||||
|
+
|
||||||
|
+ // On Windows 7, console handles aren't real handles, and can only be duplicated
|
||||||
|
+ // into the current process, not a parent one, which amounts to the same thing.
|
||||||
|
+ if parentProcess != p && isLegacyWin7ConsoleHandle(Handle(attr.Files[i])) {
|
||||||
|
+ destinationProcessHandle = p
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ err := DuplicateHandle(p, Handle(attr.Files[i]), destinationProcessHandle, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +377,14 @@
|
||||||
|
|
||||||
|
fd = append(fd, sys.AdditionalInheritedHandles...)
|
||||||
|
|
||||||
|
+ // On Windows 7, console handles aren't real handles, so don't pass them
|
||||||
|
+ // through to PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
|
||||||
|
+ for i := range fd {
|
||||||
|
+ if isLegacyWin7ConsoleHandle(fd[i]) {
|
||||||
|
+ fd[i] = 0
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
// The presence of a NULL handle in the list is enough to cause PROC_THREAD_ATTRIBUTE_HANDLE_LIST
|
||||||
|
// to treat the entire list as empty, so remove NULL handles.
|
||||||
|
j := 0
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision 6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision 69e2eed6dd0f6d815ebf15797761c13f31213dd6)
|
||||||
|
@@ -413,10 +413,20 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
- handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryW)), uintptr(unsafe.Pointer(absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
if handle != 0 {
|
||||||
|
err = 0
|
||||||
|
}
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision 6a31d3fa8e47ddabc10bd97bff10d9a85f4cfb76)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision 69e2eed6dd0f6d815ebf15797761c13f31213dd6)
|
||||||
|
@@ -44,7 +44,7 @@
|
||||||
|
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -53,6 +53,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -69,7 +72,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
657
.github/patch/go1.24.patch
vendored
Normal file
657
.github/patch/go1.24.patch
vendored
Normal file
@@ -0,0 +1,657 @@
|
|||||||
|
Subject: [PATCH] Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/internal/sysrand/rand_windows.go b/src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
--- a/src/crypto/internal/sysrand/rand_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/crypto/internal/sysrand/rand_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -7,5 +7,26 @@
|
||||||
|
import "internal/syscall/windows"
|
||||||
|
|
||||||
|
func read(b []byte) error {
|
||||||
|
- return windows.ProcessPrng(b)
|
||||||
|
+ // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
+ // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
+ // and 64-bit systems.
|
||||||
|
+ return batched(windows.RtlGenRandom, 1<<31-1)(b)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// batched returns a function that calls f to populate a []byte by chunking it
|
||||||
|
+// into subslices of, at most, readMax bytes.
|
||||||
|
+func batched(f func([]byte) error, readMax int) func([]byte) error {
|
||||||
|
+ return func(out []byte) error {
|
||||||
|
+ for len(out) > 0 {
|
||||||
|
+ read := len(out)
|
||||||
|
+ if read > readMax {
|
||||||
|
+ read = readMax
|
||||||
|
+ }
|
||||||
|
+ if err := f(out[:read]); err != nil {
|
||||||
|
+ return err
|
||||||
|
+ }
|
||||||
|
+ out = out[read:]
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -22,7 +22,7 @@
|
||||||
|
// - On legacy Linux (< 3.17), Reader opens /dev/urandom on first use.
|
||||||
|
// - On macOS, iOS, and OpenBSD Reader, uses arc4random_buf(3).
|
||||||
|
// - On NetBSD, Reader uses the kern.arandom sysctl.
|
||||||
|
-// - On Windows, Reader uses the ProcessPrng API.
|
||||||
|
+// - On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// - On js/wasm, Reader uses the Web Crypto API.
|
||||||
|
// - On wasip1/wasm, Reader uses random_get.
|
||||||
|
//
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -416,7 +416,7 @@
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
@@ -38,7 +38,6 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
@@ -63,7 +62,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procGetACP = modkernel32.NewProc("GetACP")
|
||||||
|
@@ -236,12 +235,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 3901409b5d0fb7c85a3e6730a59943cc93b2835c)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision ac3e93c061779dfefc0dd13a5b6e6f764a25621e)
|
||||||
|
@@ -40,8 +40,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceFrequency QueryPerformanceFrequency%1 "kernel32.dll"
|
||||||
|
@@ -75,7 +75,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -98,8 +97,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_QueryPerformanceFrequency,
|
||||||
|
@@ -128,8 +127,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ stdFunction
|
||||||
|
+
|
||||||
|
+ // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
+ // This approach has been recommended by Microsoft (see issue
|
||||||
|
+ // 15589 for details).
|
||||||
|
+ // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
+ // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
+ // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
+ // when building executable as Cgo. So load SystemFunction036
|
||||||
|
+ // manually during runtime startup.
|
||||||
|
+ _RtlGenRandom stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -146,13 +160,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -245,8 +252,18 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname windows_QueryPerformanceCounter internal/syscall/windows.QueryPerformanceCounter
|
||||||
|
@@ -264,13 +281,28 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
@@ -299,7 +331,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -358,6 +390,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -431,7 +479,8 @@
|
||||||
|
// Only load winmm.dll if we need it.
|
||||||
|
// This avoids a dependency on winmm.dll for Go programs
|
||||||
|
// that run on new Windows versions.
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
print("runtime: LoadLibraryExW failed; errno=", getlasterror(), "\n")
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
@@ -472,6 +521,28 @@
|
||||||
|
canUseLongPaths = true
|
||||||
|
}
|
||||||
|
|
||||||
|
+var osVersionInfo struct {
|
||||||
|
+ majorVersion uint32
|
||||||
|
+ minorVersion uint32
|
||||||
|
+ buildNumber uint32
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func initOsVersionInfo() {
|
||||||
|
+ info := _OSVERSIONINFOW{}
|
||||||
|
+ info.osVersionInfoSize = uint32(unsafe.Sizeof(info))
|
||||||
|
+ stdcall1(_RtlGetVersion, uintptr(unsafe.Pointer(&info)))
|
||||||
|
+ osVersionInfo.majorVersion = info.majorVersion
|
||||||
|
+ osVersionInfo.minorVersion = info.minorVersion
|
||||||
|
+ osVersionInfo.buildNumber = info.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) {
|
||||||
|
+ *majorVersion = osVersionInfo.majorVersion
|
||||||
|
+ *minorVersion = osVersionInfo.minorVersion
|
||||||
|
+ *buildNumber = osVersionInfo.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
func osinit() {
|
||||||
|
asmstdcallAddr = unsafe.Pointer(abi.FuncPCABI0(asmstdcall))
|
||||||
|
|
||||||
|
@@ -484,8 +555,8 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
+ initOsVersionInfo()
|
||||||
|
|
||||||
|
ncpu = getproccount()
|
||||||
|
|
||||||
|
@@ -501,7 +572,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/hook_windows.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// Placeholders for socket system calls.
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error) = syscall.Socket
|
||||||
|
wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
|
||||||
|
connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
|
||||||
|
listenFunc func(syscall.Handle, int) error = syscall.Listen
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build !js && !plan9 && !wasip1 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// Copyright 2015 The Go Authors. All rights reserved.
|
||||||
|
+// Use of this source code is governed by a BSD-style
|
||||||
|
+// license that can be found in the LICENSE file.
|
||||||
|
+
|
||||||
|
+package socktest_test
|
||||||
|
+
|
||||||
|
+import "syscall"
|
||||||
|
+
|
||||||
|
+var (
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error)
|
||||||
|
+ closeFunc func(syscall.Handle) error
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
+ closeFunc = sw.Closesocket
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func uninstallTestHooks() {
|
||||||
|
+ socketFunc = syscall.Socket
|
||||||
|
+ closeFunc = syscall.Closesocket
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
+// Socket wraps [syscall.Socket].
|
||||||
|
+func (sw *Switch) Socket(family, sotype, proto int) (s syscall.Handle, err error) {
|
||||||
|
+ sw.once.Do(sw.init)
|
||||||
|
+
|
||||||
|
+ so := &Status{Cookie: cookie(family, sotype, proto)}
|
||||||
|
+ sw.fmu.RLock()
|
||||||
|
+ f, _ := sw.fltab[FilterSocket]
|
||||||
|
+ sw.fmu.RUnlock()
|
||||||
|
+
|
||||||
|
+ af, err := f.apply(so)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+ s, so.Err = syscall.Socket(family, sotype, proto)
|
||||||
|
+ if err = af.apply(so); err != nil {
|
||||||
|
+ if so.Err == nil {
|
||||||
|
+ syscall.Closesocket(s)
|
||||||
|
+ }
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ sw.smu.Lock()
|
||||||
|
+ defer sw.smu.Unlock()
|
||||||
|
+ if so.Err != nil {
|
||||||
|
+ sw.stats.getLocked(so.Cookie).OpenFailed++
|
||||||
|
+ return syscall.InvalidHandle, so.Err
|
||||||
|
+ }
|
||||||
|
+ nso := sw.addLocked(s, family, sotype, proto)
|
||||||
|
+ sw.stats.getLocked(nso.Cookie).Opened++
|
||||||
|
+ return s, nil
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// WSASocket wraps [syscall.WSASocket].
|
||||||
|
func (sw *Switch) WSASocket(family, sotype, proto int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (s syscall.Handle, err error) {
|
||||||
|
sw.once.Do(sw.init)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -8,6 +8,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -17,6 +18,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -26,6 +28,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/net/sock_windows.go (revision 7b1fd7d39c6be0185fbe1d929578ab372ac5c632)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
|
||||||
|
s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
|
||||||
|
nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
|
||||||
|
+ if err == nil {
|
||||||
|
+ return s, nil
|
||||||
|
+ }
|
||||||
|
+ // WSA_FLAG_NO_HANDLE_INHERIT flag is not supported on some
|
||||||
|
+ // old versions of Windows, see
|
||||||
|
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
|
||||||
|
+ // for details. Just use syscall.Socket, if windows.WSASocket failed.
|
||||||
|
+
|
||||||
|
+ // See ../syscall/exec_unix.go for description of ForkLock.
|
||||||
|
+ syscall.ForkLock.RLock()
|
||||||
|
+ s, err = socketFunc(family, sotype, proto)
|
||||||
|
+ if err == nil {
|
||||||
|
+ syscall.CloseOnExec(s)
|
||||||
|
+ }
|
||||||
|
+ syscall.ForkLock.RUnlock()
|
||||||
|
if err != nil {
|
||||||
|
return syscall.InvalidHandle, os.NewSyscallError("socket", err)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 2a406dc9f1ea7323d6ca9fccb2fe9ddebb6b1cc8)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision 979d6d8bab3823ff572ace26767fd2ce3cf351ae)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -254,6 +253,9 @@
|
||||||
|
var zeroProcAttr ProcAttr
|
||||||
|
var zeroSysProcAttr SysProcAttr
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
|
||||||
|
if len(argv0) == 0 {
|
||||||
|
return 0, 0, EWINDOWS
|
||||||
|
@@ -317,6 +319,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ var maj, min, build uint32
|
||||||
|
+ rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
+ isWin7 := maj < 6 || (maj == 6 && min <= 1)
|
||||||
|
+ // NT kernel handles are divisible by 4, with the bottom 3 bits left as
|
||||||
|
+ // a tag. The fully set tag correlates with the types of handles we're
|
||||||
|
+ // concerned about here. Except, the kernel will interpret some
|
||||||
|
+ // special handle values, like -1, -2, and so forth, so kernelbase.dll
|
||||||
|
+ // checks to see that those bottom three bits are checked, but that top
|
||||||
|
+ // bit is not checked.
|
||||||
|
+ isLegacyWin7ConsoleHandle := func(handle Handle) bool { return isWin7 && handle&0x10000003 == 3 }
|
||||||
|
+
|
||||||
|
p, _ := GetCurrentProcess()
|
||||||
|
parentProcess := p
|
||||||
|
if sys.ParentProcess != 0 {
|
||||||
|
@@ -325,7 +338,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ destinationProcessHandle := parentProcess
|
||||||
|
+
|
||||||
|
+ // On Windows 7, console handles aren't real handles, and can only be duplicated
|
||||||
|
+ // into the current process, not a parent one, which amounts to the same thing.
|
||||||
|
+ if parentProcess != p && isLegacyWin7ConsoleHandle(Handle(attr.Files[i])) {
|
||||||
|
+ destinationProcessHandle = p
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ err := DuplicateHandle(p, Handle(attr.Files[i]), destinationProcessHandle, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +377,14 @@
|
||||||
|
|
||||||
|
fd = append(fd, sys.AdditionalInheritedHandles...)
|
||||||
|
|
||||||
|
+ // On Windows 7, console handles aren't real handles, so don't pass them
|
||||||
|
+ // through to PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
|
||||||
|
+ for i := range fd {
|
||||||
|
+ if isLegacyWin7ConsoleHandle(fd[i]) {
|
||||||
|
+ fd[i] = 0
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
// The presence of a NULL handle in the list is enough to cause PROC_THREAD_ATTRIBUTE_HANDLE_LIST
|
||||||
|
// to treat the entire list as empty, so remove NULL handles.
|
||||||
|
j := 0
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision 979d6d8bab3823ff572ace26767fd2ce3cf351ae)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision ac3e93c061779dfefc0dd13a5b6e6f764a25621e)
|
||||||
|
@@ -413,10 +413,20 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
- handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryW)), uintptr(unsafe.Pointer(absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
if handle != 0 {
|
||||||
|
err = 0
|
||||||
|
}
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision 979d6d8bab3823ff572ace26767fd2ce3cf351ae)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision ac3e93c061779dfefc0dd13a5b6e6f764a25621e)
|
||||||
|
@@ -45,7 +45,7 @@
|
||||||
|
//go:noescape
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -54,6 +54,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -70,7 +73,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
884
.github/patch/go1.25.patch
vendored
Normal file
884
.github/patch/go1.25.patch
vendored
Normal file
@@ -0,0 +1,884 @@
|
|||||||
|
Subject: [PATCH] Revert "os: remove 5ms sleep on Windows in (*Process).Wait"
|
||||||
|
Fix os.RemoveAll not working on Windows7
|
||||||
|
Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/internal/sysrand/rand_windows.go b/src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
--- a/src/crypto/internal/sysrand/rand_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/crypto/internal/sysrand/rand_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -7,5 +7,26 @@
|
||||||
|
import "internal/syscall/windows"
|
||||||
|
|
||||||
|
func read(b []byte) error {
|
||||||
|
- return windows.ProcessPrng(b)
|
||||||
|
+ // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
+ // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
+ // and 64-bit systems.
|
||||||
|
+ return batched(windows.RtlGenRandom, 1<<31-1)(b)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// batched returns a function that calls f to populate a []byte by chunking it
|
||||||
|
+// into subslices of, at most, readMax bytes.
|
||||||
|
+func batched(f func([]byte) error, readMax int) func([]byte) error {
|
||||||
|
+ return func(out []byte) error {
|
||||||
|
+ for len(out) > 0 {
|
||||||
|
+ read := len(out)
|
||||||
|
+ if read > readMax {
|
||||||
|
+ read = readMax
|
||||||
|
+ }
|
||||||
|
+ if err := f(out[:read]); err != nil {
|
||||||
|
+ return err
|
||||||
|
+ }
|
||||||
|
+ out = out[read:]
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -22,7 +22,7 @@
|
||||||
|
// - On legacy Linux (< 3.17), Reader opens /dev/urandom on first use.
|
||||||
|
// - On macOS, iOS, and OpenBSD Reader, uses arc4random_buf(3).
|
||||||
|
// - On NetBSD, Reader uses the kern.arandom sysctl.
|
||||||
|
-// - On Windows, Reader uses the ProcessPrng API.
|
||||||
|
+// - On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// - On js/wasm, Reader uses the Web Crypto API.
|
||||||
|
// - On wasip1/wasm, Reader uses random_get.
|
||||||
|
//
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -419,7 +419,7 @@
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
@@ -38,7 +38,6 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
@@ -63,7 +62,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort")
|
||||||
|
@@ -242,12 +241,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.Syscall(procProcessPrng.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
+ r1, _, e1 := syscall.Syscall(procSystemFunction036.Addr(), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision 6e676ab2b809d46623acb5988248d95d1eb7939c)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
@@ -39,8 +39,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceFrequency QueryPerformanceFrequency%1 "kernel32.dll"
|
||||||
|
@@ -74,7 +74,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -97,8 +96,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
_LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_QueryPerformanceFrequency,
|
||||||
|
@@ -127,8 +126,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ stdFunction
|
||||||
|
+
|
||||||
|
+ // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
+ // This approach has been recommended by Microsoft (see issue
|
||||||
|
+ // 15589 for details).
|
||||||
|
+ // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
+ // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
+ // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
+ // when building executable as Cgo. So load SystemFunction036
|
||||||
|
+ // manually during runtime startup.
|
||||||
|
+ _RtlGenRandom stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -145,13 +159,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -244,8 +251,18 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- return stdcall3(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall3(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname windows_QueryPerformanceCounter internal/syscall/windows.QueryPerformanceCounter
|
||||||
|
@@ -263,13 +280,28 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall1(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
@@ -298,7 +330,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -357,6 +389,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -430,7 +478,8 @@
|
||||||
|
// Only load winmm.dll if we need it.
|
||||||
|
// This avoids a dependency on winmm.dll for Go programs
|
||||||
|
// that run on new Windows versions.
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
print("runtime: LoadLibraryExW failed; errno=", getlasterror(), "\n")
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
@@ -471,6 +520,28 @@
|
||||||
|
canUseLongPaths = true
|
||||||
|
}
|
||||||
|
|
||||||
|
+var osVersionInfo struct {
|
||||||
|
+ majorVersion uint32
|
||||||
|
+ minorVersion uint32
|
||||||
|
+ buildNumber uint32
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func initOsVersionInfo() {
|
||||||
|
+ info := _OSVERSIONINFOW{}
|
||||||
|
+ info.osVersionInfoSize = uint32(unsafe.Sizeof(info))
|
||||||
|
+ stdcall1(_RtlGetVersion, uintptr(unsafe.Pointer(&info)))
|
||||||
|
+ osVersionInfo.majorVersion = info.majorVersion
|
||||||
|
+ osVersionInfo.minorVersion = info.minorVersion
|
||||||
|
+ osVersionInfo.buildNumber = info.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) {
|
||||||
|
+ *majorVersion = osVersionInfo.majorVersion
|
||||||
|
+ *minorVersion = osVersionInfo.minorVersion
|
||||||
|
+ *buildNumber = osVersionInfo.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
func osinit() {
|
||||||
|
asmstdcallAddr = unsafe.Pointer(abi.FuncPCABI0(asmstdcall))
|
||||||
|
|
||||||
|
@@ -483,8 +554,8 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
+ initOsVersionInfo()
|
||||||
|
|
||||||
|
numCPUStartup = getCPUCount()
|
||||||
|
|
||||||
|
@@ -500,7 +571,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall2(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall2(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/hook_windows.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// Placeholders for socket system calls.
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error) = syscall.Socket
|
||||||
|
wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
|
||||||
|
connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
|
||||||
|
listenFunc func(syscall.Handle, int) error = syscall.Listen
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build !js && !plan9 && !wasip1 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// Copyright 2015 The Go Authors. All rights reserved.
|
||||||
|
+// Use of this source code is governed by a BSD-style
|
||||||
|
+// license that can be found in the LICENSE file.
|
||||||
|
+
|
||||||
|
+package socktest_test
|
||||||
|
+
|
||||||
|
+import "syscall"
|
||||||
|
+
|
||||||
|
+var (
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error)
|
||||||
|
+ closeFunc func(syscall.Handle) error
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
+ closeFunc = sw.Closesocket
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func uninstallTestHooks() {
|
||||||
|
+ socketFunc = syscall.Socket
|
||||||
|
+ closeFunc = syscall.Closesocket
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
+// Socket wraps [syscall.Socket].
|
||||||
|
+func (sw *Switch) Socket(family, sotype, proto int) (s syscall.Handle, err error) {
|
||||||
|
+ sw.once.Do(sw.init)
|
||||||
|
+
|
||||||
|
+ so := &Status{Cookie: cookie(family, sotype, proto)}
|
||||||
|
+ sw.fmu.RLock()
|
||||||
|
+ f, _ := sw.fltab[FilterSocket]
|
||||||
|
+ sw.fmu.RUnlock()
|
||||||
|
+
|
||||||
|
+ af, err := f.apply(so)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+ s, so.Err = syscall.Socket(family, sotype, proto)
|
||||||
|
+ if err = af.apply(so); err != nil {
|
||||||
|
+ if so.Err == nil {
|
||||||
|
+ syscall.Closesocket(s)
|
||||||
|
+ }
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ sw.smu.Lock()
|
||||||
|
+ defer sw.smu.Unlock()
|
||||||
|
+ if so.Err != nil {
|
||||||
|
+ sw.stats.getLocked(so.Cookie).OpenFailed++
|
||||||
|
+ return syscall.InvalidHandle, so.Err
|
||||||
|
+ }
|
||||||
|
+ nso := sw.addLocked(s, family, sotype, proto)
|
||||||
|
+ sw.stats.getLocked(nso.Cookie).Opened++
|
||||||
|
+ return s, nil
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// WSASocket wraps [syscall.WSASocket].
|
||||||
|
func (sw *Switch) WSASocket(family, sotype, proto int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (s syscall.Handle, err error) {
|
||||||
|
sw.once.Do(sw.init)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -12,6 +12,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -21,6 +22,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -30,6 +32,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/net/sock_windows.go (revision 6788c4c6f9fafb56729bad6b660f7ee2272d699f)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
|
||||||
|
s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
|
||||||
|
nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
|
||||||
|
+ if err == nil {
|
||||||
|
+ return s, nil
|
||||||
|
+ }
|
||||||
|
+ // WSA_FLAG_NO_HANDLE_INHERIT flag is not supported on some
|
||||||
|
+ // old versions of Windows, see
|
||||||
|
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
|
||||||
|
+ // for details. Just use syscall.Socket, if windows.WSASocket failed.
|
||||||
|
+
|
||||||
|
+ // See ../syscall/exec_unix.go for description of ForkLock.
|
||||||
|
+ syscall.ForkLock.RLock()
|
||||||
|
+ s, err = socketFunc(family, sotype, proto)
|
||||||
|
+ if err == nil {
|
||||||
|
+ syscall.CloseOnExec(s)
|
||||||
|
+ }
|
||||||
|
+ syscall.ForkLock.RUnlock()
|
||||||
|
if err != nil {
|
||||||
|
return syscall.InvalidHandle, os.NewSyscallError("socket", err)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision 8cb5472d94c34b88733a81091bd328e70ee565a4)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision a5b2168bb836ed9d6601c626f95e56c07923f906)
|
||||||
|
@@ -14,7 +14,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -254,6 +253,9 @@
|
||||||
|
var zeroProcAttr ProcAttr
|
||||||
|
var zeroSysProcAttr SysProcAttr
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
|
||||||
|
if len(argv0) == 0 {
|
||||||
|
return 0, 0, EWINDOWS
|
||||||
|
@@ -317,6 +319,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ var maj, min, build uint32
|
||||||
|
+ rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
+ isWin7 := maj < 6 || (maj == 6 && min <= 1)
|
||||||
|
+ // NT kernel handles are divisible by 4, with the bottom 3 bits left as
|
||||||
|
+ // a tag. The fully set tag correlates with the types of handles we're
|
||||||
|
+ // concerned about here. Except, the kernel will interpret some
|
||||||
|
+ // special handle values, like -1, -2, and so forth, so kernelbase.dll
|
||||||
|
+ // checks to see that those bottom three bits are checked, but that top
|
||||||
|
+ // bit is not checked.
|
||||||
|
+ isLegacyWin7ConsoleHandle := func(handle Handle) bool { return isWin7 && handle&0x10000003 == 3 }
|
||||||
|
+
|
||||||
|
p, _ := GetCurrentProcess()
|
||||||
|
parentProcess := p
|
||||||
|
if sys.ParentProcess != 0 {
|
||||||
|
@@ -325,7 +338,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ destinationProcessHandle := parentProcess
|
||||||
|
+
|
||||||
|
+ // On Windows 7, console handles aren't real handles, and can only be duplicated
|
||||||
|
+ // into the current process, not a parent one, which amounts to the same thing.
|
||||||
|
+ if parentProcess != p && isLegacyWin7ConsoleHandle(Handle(attr.Files[i])) {
|
||||||
|
+ destinationProcessHandle = p
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ err := DuplicateHandle(p, Handle(attr.Files[i]), destinationProcessHandle, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -356,6 +377,14 @@
|
||||||
|
|
||||||
|
fd = append(fd, sys.AdditionalInheritedHandles...)
|
||||||
|
|
||||||
|
+ // On Windows 7, console handles aren't real handles, so don't pass them
|
||||||
|
+ // through to PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
|
||||||
|
+ for i := range fd {
|
||||||
|
+ if isLegacyWin7ConsoleHandle(fd[i]) {
|
||||||
|
+ fd[i] = 0
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
// The presence of a NULL handle in the list is enough to cause PROC_THREAD_ATTRIBUTE_HANDLE_LIST
|
||||||
|
// to treat the entire list as empty, so remove NULL handles.
|
||||||
|
j := 0
|
||||||
|
Index: src/runtime/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/syscall_windows.go b/src/runtime/syscall_windows.go
|
||||||
|
--- a/src/runtime/syscall_windows.go (revision a5b2168bb836ed9d6601c626f95e56c07923f906)
|
||||||
|
+++ b/src/runtime/syscall_windows.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
@@ -413,10 +413,20 @@
|
||||||
|
|
||||||
|
const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
-func syscall_loadsystemlibrary(filename *uint16) (handle, err uintptr) {
|
||||||
|
- handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryExW)), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ handle, _, err = syscall_SyscallN(uintptr(unsafe.Pointer(_LoadLibraryW)), uintptr(unsafe.Pointer(absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
if handle != 0 {
|
||||||
|
err = 0
|
||||||
|
}
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision a5b2168bb836ed9d6601c626f95e56c07923f906)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
@@ -45,7 +45,7 @@
|
||||||
|
//go:noescape
|
||||||
|
func SyscallN(trap uintptr, args ...uintptr) (r1, r2 uintptr, err Errno)
|
||||||
|
func loadlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
-func loadsystemlibrary(filename *uint16) (handle uintptr, err Errno)
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (proc uintptr, err Errno)
|
||||||
|
|
||||||
|
// A DLL implements access to a single DLL.
|
||||||
|
@@ -54,6 +54,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -70,7 +73,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
|
Index: src/os/removeall_at.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/removeall_at.go b/src/os/removeall_at.go
|
||||||
|
--- a/src/os/removeall_at.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
+++ b/src/os/removeall_at.go (revision 0a52622d2331ff975fb0442617ec19bc352bb2ed)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build unix || wasip1 || windows
|
||||||
|
+//go:build unix || wasip1
|
||||||
|
|
||||||
|
package os
|
||||||
|
|
||||||
|
@@ -175,3 +175,25 @@
|
||||||
|
}
|
||||||
|
return newDirFile(fd, name)
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+func rootRemoveAll(r *Root, name string) error {
|
||||||
|
+ // Consistency with os.RemoveAll: Strip trailing /s from the name,
|
||||||
|
+ // so RemoveAll("not_a_directory/") succeeds.
|
||||||
|
+ for len(name) > 0 && IsPathSeparator(name[len(name)-1]) {
|
||||||
|
+ name = name[:len(name)-1]
|
||||||
|
+ }
|
||||||
|
+ if endsWithDot(name) {
|
||||||
|
+ // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
+ }
|
||||||
|
+ _, err := doInRoot(r, name, nil, func(parent sysfdType, name string) (struct{}, error) {
|
||||||
|
+ return struct{}{}, removeAllFrom(parent, name)
|
||||||
|
+ })
|
||||||
|
+ if IsNotExist(err) {
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
+ if err != nil {
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
+ }
|
||||||
|
+ return err
|
||||||
|
+}
|
||||||
|
Index: src/os/removeall_noat.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/removeall_noat.go b/src/os/removeall_noat.go
|
||||||
|
--- a/src/os/removeall_noat.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
+++ b/src/os/removeall_noat.go (revision 0a52622d2331ff975fb0442617ec19bc352bb2ed)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build (js && wasm) || plan9
|
||||||
|
+//go:build (js && wasm) || plan9 || windows
|
||||||
|
|
||||||
|
package os
|
||||||
|
|
||||||
|
@@ -140,3 +140,22 @@
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+func rootRemoveAll(r *Root, name string) error {
|
||||||
|
+ if endsWithDot(name) {
|
||||||
|
+ // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
+ }
|
||||||
|
+ if err := checkPathEscapesLstat(r, name); err != nil {
|
||||||
|
+ if err == syscall.ENOTDIR {
|
||||||
|
+ // Some intermediate path component is not a directory.
|
||||||
|
+ // RemoveAll treats this as success (since the target doesn't exist).
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: err}
|
||||||
|
+ }
|
||||||
|
+ if err := RemoveAll(joinPath(r.root.name, name)); err != nil {
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+}
|
||||||
|
Index: src/os/root_noopenat.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/root_noopenat.go b/src/os/root_noopenat.go
|
||||||
|
--- a/src/os/root_noopenat.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
+++ b/src/os/root_noopenat.go (revision 0a52622d2331ff975fb0442617ec19bc352bb2ed)
|
||||||
|
@@ -11,7 +11,6 @@
|
||||||
|
"internal/filepathlite"
|
||||||
|
"internal/stringslite"
|
||||||
|
"sync/atomic"
|
||||||
|
- "syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
@@ -185,25 +184,6 @@
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
-
|
||||||
|
-func rootRemoveAll(r *Root, name string) error {
|
||||||
|
- if endsWithDot(name) {
|
||||||
|
- // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
- }
|
||||||
|
- if err := checkPathEscapesLstat(r, name); err != nil {
|
||||||
|
- if err == syscall.ENOTDIR {
|
||||||
|
- // Some intermediate path component is not a directory.
|
||||||
|
- // RemoveAll treats this as success (since the target doesn't exist).
|
||||||
|
- return nil
|
||||||
|
- }
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: err}
|
||||||
|
- }
|
||||||
|
- if err := RemoveAll(joinPath(r.root.name, name)); err != nil {
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
- }
|
||||||
|
- return nil
|
||||||
|
-}
|
||||||
|
|
||||||
|
func rootReadlink(r *Root, name string) (string, error) {
|
||||||
|
if err := checkPathEscapesLstat(r, name); err != nil {
|
||||||
|
Index: src/os/root_openat.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/root_openat.go b/src/os/root_openat.go
|
||||||
|
--- a/src/os/root_openat.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
+++ b/src/os/root_openat.go (revision 0a52622d2331ff975fb0442617ec19bc352bb2ed)
|
||||||
|
@@ -194,28 +194,6 @@
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
-func rootRemoveAll(r *Root, name string) error {
|
||||||
|
- // Consistency with os.RemoveAll: Strip trailing /s from the name,
|
||||||
|
- // so RemoveAll("not_a_directory/") succeeds.
|
||||||
|
- for len(name) > 0 && IsPathSeparator(name[len(name)-1]) {
|
||||||
|
- name = name[:len(name)-1]
|
||||||
|
- }
|
||||||
|
- if endsWithDot(name) {
|
||||||
|
- // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
- }
|
||||||
|
- _, err := doInRoot(r, name, nil, func(parent sysfdType, name string) (struct{}, error) {
|
||||||
|
- return struct{}{}, removeAllFrom(parent, name)
|
||||||
|
- })
|
||||||
|
- if IsNotExist(err) {
|
||||||
|
- return nil
|
||||||
|
- }
|
||||||
|
- if err != nil {
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
- }
|
||||||
|
- return err
|
||||||
|
-}
|
||||||
|
-
|
||||||
|
func rootRename(r *Root, oldname, newname string) error {
|
||||||
|
_, err := doInRoot(r, oldname, nil, func(oldparent sysfdType, oldname string) (struct{}, error) {
|
||||||
|
_, err := doInRoot(r, newname, nil, func(newparent sysfdType, newname string) (struct{}, error) {
|
||||||
|
Index: src/os/root_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/root_windows.go b/src/os/root_windows.go
|
||||||
|
--- a/src/os/root_windows.go (revision f56f1e23507e646c85243a71bde7b9629b2f970c)
|
||||||
|
+++ b/src/os/root_windows.go (revision 0a52622d2331ff975fb0442617ec19bc352bb2ed)
|
||||||
|
@@ -402,3 +402,14 @@
|
||||||
|
}
|
||||||
|
return fi.Mode(), nil
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+func checkPathEscapes(r *Root, name string) error {
|
||||||
|
+ if !filepathlite.IsLocal(name) {
|
||||||
|
+ return errPathEscapes
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func checkPathEscapesLstat(r *Root, name string) error {
|
||||||
|
+ return checkPathEscapes(r, name)
|
||||||
|
+}
|
||||||
|
Index: src/os/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/exec_windows.go b/src/os/exec_windows.go
|
||||||
|
--- a/src/os/exec_windows.go (revision 0a52622d2331ff975fb0442617ec19bc352bb2ed)
|
||||||
|
+++ b/src/os/exec_windows.go (revision fb3d09a67fe97008ad76fea97ae88170072cbdbb)
|
||||||
|
@@ -10,6 +10,7 @@
|
||||||
|
"runtime"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
+ _ "unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Note that Process.handle is never nil because Windows always requires
|
||||||
|
@@ -49,9 +50,23 @@
|
||||||
|
// than statusDone.
|
||||||
|
p.doRelease(statusReleased)
|
||||||
|
|
||||||
|
+ var maj, min, build uint32
|
||||||
|
+ rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
+ if maj < 10 {
|
||||||
|
+ // NOTE(brainman): It seems that sometimes process is not dead
|
||||||
|
+ // when WaitForSingleObject returns. But we do not know any
|
||||||
|
+ // other way to wait for it. Sleeping for a while seems to do
|
||||||
|
+ // the trick sometimes.
|
||||||
|
+ // See https://golang.org/issue/25965 for details.
|
||||||
|
+ time.Sleep(5 * time.Millisecond)
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
return &ProcessState{p.Pid, syscall.WaitStatus{ExitCode: ec}, &u}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func (p *Process) signal(sig Signal) error {
|
||||||
|
handle, status := p.handleTransientAcquire()
|
||||||
|
switch status {
|
||||||
883
.github/patch/go1.26.patch
vendored
Normal file
883
.github/patch/go1.26.patch
vendored
Normal file
@@ -0,0 +1,883 @@
|
|||||||
|
Subject: [PATCH] Revert "os: remove 5ms sleep on Windows in (*Process).Wait"
|
||||||
|
Fix os.RemoveAll not working on Windows7
|
||||||
|
Revert "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
Revert "syscall: remove Windows 7 console handle workaround"
|
||||||
|
Revert "net: remove sysSocket fallback for Windows 7"
|
||||||
|
Revert "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
---
|
||||||
|
Index: src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/internal/sysrand/rand_windows.go b/src/crypto/internal/sysrand/rand_windows.go
|
||||||
|
--- a/src/crypto/internal/sysrand/rand_windows.go (revision c599a8f2385849a225d02843b3c6389dbfc5aa69)
|
||||||
|
+++ b/src/crypto/internal/sysrand/rand_windows.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
@@ -7,5 +7,26 @@
|
||||||
|
import "internal/syscall/windows"
|
||||||
|
|
||||||
|
func read(b []byte) error {
|
||||||
|
- return windows.ProcessPrng(b)
|
||||||
|
+ // RtlGenRandom only returns 1<<32-1 bytes at a time. We only read at
|
||||||
|
+ // most 1<<31-1 bytes at a time so that this works the same on 32-bit
|
||||||
|
+ // and 64-bit systems.
|
||||||
|
+ return batched(windows.RtlGenRandom, 1<<31-1)(b)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+// batched returns a function that calls f to populate a []byte by chunking it
|
||||||
|
+// into subslices of, at most, readMax bytes.
|
||||||
|
+func batched(f func([]byte) error, readMax int) func([]byte) error {
|
||||||
|
+ return func(out []byte) error {
|
||||||
|
+ for len(out) > 0 {
|
||||||
|
+ read := len(out)
|
||||||
|
+ if read > readMax {
|
||||||
|
+ read = readMax
|
||||||
|
+ }
|
||||||
|
+ if err := f(out[:read]); err != nil {
|
||||||
|
+ return err
|
||||||
|
+ }
|
||||||
|
+ out = out[read:]
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
}
|
||||||
|
Index: src/crypto/rand/rand.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/crypto/rand/rand.go b/src/crypto/rand/rand.go
|
||||||
|
--- a/src/crypto/rand/rand.go (revision c599a8f2385849a225d02843b3c6389dbfc5aa69)
|
||||||
|
+++ b/src/crypto/rand/rand.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
@@ -25,7 +25,7 @@
|
||||||
|
// - On legacy Linux (< 3.17), Reader opens /dev/urandom on first use.
|
||||||
|
// - On macOS, iOS, and OpenBSD Reader, uses arc4random_buf(3).
|
||||||
|
// - On NetBSD, Reader uses the kern.arandom sysctl.
|
||||||
|
-// - On Windows, Reader uses the ProcessPrng API.
|
||||||
|
+// - On Windows systems, Reader uses the RtlGenRandom API.
|
||||||
|
// - On js/wasm, Reader uses the Web Crypto API.
|
||||||
|
// - On wasip1/wasm, Reader uses random_get.
|
||||||
|
//
|
||||||
|
Index: src/internal/syscall/windows/syscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/syscall_windows.go b/src/internal/syscall/windows/syscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/syscall_windows.go (revision c599a8f2385849a225d02843b3c6389dbfc5aa69)
|
||||||
|
+++ b/src/internal/syscall/windows/syscall_windows.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
@@ -421,7 +421,7 @@
|
||||||
|
//sys DestroyEnvironmentBlock(block *uint16) (err error) = userenv.DestroyEnvironmentBlock
|
||||||
|
//sys CreateEvent(eventAttrs *SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle syscall.Handle, err error) = kernel32.CreateEventW
|
||||||
|
|
||||||
|
-//sys ProcessPrng(buf []byte) (err error) = bcryptprimitives.ProcessPrng
|
||||||
|
+//sys RtlGenRandom(buf []byte) (err error) = advapi32.SystemFunction036
|
||||||
|
|
||||||
|
type FILE_ID_BOTH_DIR_INFO struct {
|
||||||
|
NextEntryOffset uint32
|
||||||
|
Index: src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/internal/syscall/windows/zsyscall_windows.go b/src/internal/syscall/windows/zsyscall_windows.go
|
||||||
|
--- a/src/internal/syscall/windows/zsyscall_windows.go (revision c599a8f2385849a225d02843b3c6389dbfc5aa69)
|
||||||
|
+++ b/src/internal/syscall/windows/zsyscall_windows.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
@@ -38,7 +38,6 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
modadvapi32 = syscall.NewLazyDLL(sysdll.Add("advapi32.dll"))
|
||||||
|
- modbcryptprimitives = syscall.NewLazyDLL(sysdll.Add("bcryptprimitives.dll"))
|
||||||
|
modiphlpapi = syscall.NewLazyDLL(sysdll.Add("iphlpapi.dll"))
|
||||||
|
modkernel32 = syscall.NewLazyDLL(sysdll.Add("kernel32.dll"))
|
||||||
|
modnetapi32 = syscall.NewLazyDLL(sysdll.Add("netapi32.dll"))
|
||||||
|
@@ -63,7 +62,7 @@
|
||||||
|
procQueryServiceStatus = modadvapi32.NewProc("QueryServiceStatus")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procSetTokenInformation = modadvapi32.NewProc("SetTokenInformation")
|
||||||
|
- procProcessPrng = modbcryptprimitives.NewProc("ProcessPrng")
|
||||||
|
+ procSystemFunction036 = modadvapi32.NewProc("SystemFunction036")
|
||||||
|
procGetAdaptersAddresses = modiphlpapi.NewProc("GetAdaptersAddresses")
|
||||||
|
procCreateEventW = modkernel32.NewProc("CreateEventW")
|
||||||
|
procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort")
|
||||||
|
@@ -244,12 +243,12 @@
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
-func ProcessPrng(buf []byte) (err error) {
|
||||||
|
+func RtlGenRandom(buf []byte) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(buf) > 0 {
|
||||||
|
_p0 = &buf[0]
|
||||||
|
}
|
||||||
|
- r1, _, e1 := syscall.SyscallN(procProcessPrng.Addr(), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)))
|
||||||
|
+ r1, _, e1 := syscall.SyscallN(procSystemFunction036.Addr(), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
err = errnoErr(e1)
|
||||||
|
}
|
||||||
|
Index: src/runtime/os_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/runtime/os_windows.go b/src/runtime/os_windows.go
|
||||||
|
--- a/src/runtime/os_windows.go (revision c599a8f2385849a225d02843b3c6389dbfc5aa69)
|
||||||
|
+++ b/src/runtime/os_windows.go (revision ea2726a6fa25fbfa1092e696e522eafca544d24c)
|
||||||
|
@@ -40,7 +40,8 @@
|
||||||
|
//go:cgo_import_dynamic runtime._GetSystemInfo GetSystemInfo%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._GetThreadContext GetThreadContext%2 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._SetThreadContext SetThreadContext%2 "kernel32.dll"
|
||||||
|
-//go:cgo_import_dynamic runtime._LoadLibraryExW LoadLibraryExW%3 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryW LoadLibraryW%1 "kernel32.dll"
|
||||||
|
+//go:cgo_import_dynamic runtime._LoadLibraryA LoadLibraryA%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._PostQueuedCompletionStatus PostQueuedCompletionStatus%4 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceCounter QueryPerformanceCounter%1 "kernel32.dll"
|
||||||
|
//go:cgo_import_dynamic runtime._QueryPerformanceFrequency QueryPerformanceFrequency%1 "kernel32.dll"
|
||||||
|
@@ -74,7 +75,6 @@
|
||||||
|
// Following syscalls are available on every Windows PC.
|
||||||
|
// All these variables are set by the Windows executable
|
||||||
|
// loader before the Go program starts.
|
||||||
|
- _AddVectoredContinueHandler,
|
||||||
|
_AddVectoredExceptionHandler,
|
||||||
|
_CloseHandle,
|
||||||
|
_CreateEventA,
|
||||||
|
@@ -97,7 +97,8 @@
|
||||||
|
_GetSystemInfo,
|
||||||
|
_GetThreadContext,
|
||||||
|
_SetThreadContext,
|
||||||
|
- _LoadLibraryExW,
|
||||||
|
+ _LoadLibraryW,
|
||||||
|
+ _LoadLibraryA,
|
||||||
|
_PostQueuedCompletionStatus,
|
||||||
|
_QueryPerformanceCounter,
|
||||||
|
_QueryPerformanceFrequency,
|
||||||
|
@@ -126,8 +127,23 @@
|
||||||
|
_WriteFile,
|
||||||
|
_ stdFunction
|
||||||
|
|
||||||
|
- // Use ProcessPrng to generate cryptographically random data.
|
||||||
|
- _ProcessPrng stdFunction
|
||||||
|
+ // Following syscalls are only available on some Windows PCs.
|
||||||
|
+ // We will load syscalls, if available, before using them.
|
||||||
|
+ _AddDllDirectory,
|
||||||
|
+ _AddVectoredContinueHandler,
|
||||||
|
+ _LoadLibraryExA,
|
||||||
|
+ _LoadLibraryExW,
|
||||||
|
+ _ stdFunction
|
||||||
|
+
|
||||||
|
+ // Use RtlGenRandom to generate cryptographically random data.
|
||||||
|
+ // This approach has been recommended by Microsoft (see issue
|
||||||
|
+ // 15589 for details).
|
||||||
|
+ // The RtlGenRandom is not listed in advapi32.dll, instead
|
||||||
|
+ // RtlGenRandom function can be found by searching for SystemFunction036.
|
||||||
|
+ // Also some versions of Mingw cannot link to SystemFunction036
|
||||||
|
+ // when building executable as Cgo. So load SystemFunction036
|
||||||
|
+ // manually during runtime startup.
|
||||||
|
+ _RtlGenRandom stdFunction
|
||||||
|
|
||||||
|
// Load ntdll.dll manually during startup, otherwise Mingw
|
||||||
|
// links wrong printf function to cgo executable (see issue
|
||||||
|
@@ -144,13 +160,6 @@
|
||||||
|
_ stdFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
-var (
|
||||||
|
- bcryptprimitivesdll = [...]uint16{'b', 'c', 'r', 'y', 'p', 't', 'p', 'r', 'i', 'm', 'i', 't', 'i', 'v', 'e', 's', '.', 'd', 'l', 'l', 0}
|
||||||
|
- ntdlldll = [...]uint16{'n', 't', 'd', 'l', 'l', '.', 'd', 'l', 'l', 0}
|
||||||
|
- powrprofdll = [...]uint16{'p', 'o', 'w', 'r', 'p', 'r', 'o', 'f', '.', 'd', 'l', 'l', 0}
|
||||||
|
- winmmdll = [...]uint16{'w', 'i', 'n', 'm', 'm', '.', 'd', 'l', 'l', 0}
|
||||||
|
-)
|
||||||
|
-
|
||||||
|
// Function to be called by windows CreateThread
|
||||||
|
// to start new os thread.
|
||||||
|
func tstart_stdcall(newm *m)
|
||||||
|
@@ -242,9 +251,40 @@
|
||||||
|
return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
-func windowsLoadSystemLib(name []uint16) uintptr {
|
||||||
|
- const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
- return stdcall(_LoadLibraryExW, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+//go:linkname syscall_getSystemDirectory syscall.getSystemDirectory
|
||||||
|
+func syscall_getSystemDirectory() string {
|
||||||
|
+ return unsafe.String(&sysDirectory[0], sysDirectoryLen)
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func windowsLoadSystemLib(name []byte) uintptr {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ return stdcall(_LoadLibraryExA, uintptr(unsafe.Pointer(&name[0])), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ absName := append(sysDirectory[:sysDirectoryLen], name...)
|
||||||
|
+ return stdcall(_LoadLibraryA, uintptr(unsafe.Pointer(&absName[0])))
|
||||||
|
+ }
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
+
|
||||||
|
+// When available, this function will use LoadLibraryEx with the filename
|
||||||
|
+// parameter and the important SEARCH_SYSTEM32 argument. But on systems that
|
||||||
|
+// do not have that option, absoluteFilepath should contain a fallback
|
||||||
|
+// to the full path inside of system32 for use with vanilla LoadLibrary.
|
||||||
|
+//
|
||||||
|
+//go:linkname syscall_loadsystemlibrary syscall.loadsystemlibrary
|
||||||
|
+func syscall_loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle, err uintptr) {
|
||||||
|
+ if useLoadLibraryEx {
|
||||||
|
+ handle, _, err = syscall_syscalln(uintptr(unsafe.Pointer(_LoadLibraryExW)), 3, uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
+ } else {
|
||||||
|
+ handle, _, err = syscall_syscalln(uintptr(unsafe.Pointer(_LoadLibraryW)), 1, uintptr(unsafe.Pointer(absoluteFilepath)))
|
||||||
|
+ }
|
||||||
|
+ KeepAlive(filename)
|
||||||
|
+ KeepAlive(absoluteFilepath)
|
||||||
|
+ if handle != 0 {
|
||||||
|
+ err = 0
|
||||||
|
+ }
|
||||||
|
+ return
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname windows_QueryPerformanceCounter internal/syscall/windows.QueryPerformanceCounter
|
||||||
|
@@ -262,13 +302,28 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOptionalSyscalls() {
|
||||||
|
- bcryptPrimitives := windowsLoadSystemLib(bcryptprimitivesdll[:])
|
||||||
|
- if bcryptPrimitives == 0 {
|
||||||
|
- throw("bcryptprimitives.dll not found")
|
||||||
|
+ var kernel32dll = []byte("kernel32.dll\000")
|
||||||
|
+ k32 := stdcall(_LoadLibraryA, uintptr(unsafe.Pointer(&kernel32dll[0])))
|
||||||
|
+ if k32 == 0 {
|
||||||
|
+ throw("kernel32.dll not found")
|
||||||
|
}
|
||||||
|
- _ProcessPrng = windowsFindfunc(bcryptPrimitives, []byte("ProcessPrng\000"))
|
||||||
|
+ _AddDllDirectory = windowsFindfunc(k32, []byte("AddDllDirectory\000"))
|
||||||
|
+ _AddVectoredContinueHandler = windowsFindfunc(k32, []byte("AddVectoredContinueHandler\000"))
|
||||||
|
+ _LoadLibraryExA = windowsFindfunc(k32, []byte("LoadLibraryExA\000"))
|
||||||
|
+ _LoadLibraryExW = windowsFindfunc(k32, []byte("LoadLibraryExW\000"))
|
||||||
|
+ useLoadLibraryEx = (_LoadLibraryExW != nil && _LoadLibraryExA != nil && _AddDllDirectory != nil)
|
||||||
|
+
|
||||||
|
+ initSysDirectory()
|
||||||
|
|
||||||
|
- n32 := windowsLoadSystemLib(ntdlldll[:])
|
||||||
|
+ var advapi32dll = []byte("advapi32.dll\000")
|
||||||
|
+ a32 := windowsLoadSystemLib(advapi32dll)
|
||||||
|
+ if a32 == 0 {
|
||||||
|
+ throw("advapi32.dll not found")
|
||||||
|
+ }
|
||||||
|
+ _RtlGenRandom = windowsFindfunc(a32, []byte("SystemFunction036\000"))
|
||||||
|
+
|
||||||
|
+ var ntdll = []byte("ntdll.dll\000")
|
||||||
|
+ n32 := windowsLoadSystemLib(ntdll)
|
||||||
|
if n32 == 0 {
|
||||||
|
throw("ntdll.dll not found")
|
||||||
|
}
|
||||||
|
@@ -297,7 +352,7 @@
|
||||||
|
context uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
- powrprof := windowsLoadSystemLib(powrprofdll[:])
|
||||||
|
+ powrprof := windowsLoadSystemLib([]byte("powrprof.dll\000"))
|
||||||
|
if powrprof == 0 {
|
||||||
|
return // Running on Windows 7, where we don't need it anyway.
|
||||||
|
}
|
||||||
|
@@ -351,6 +406,22 @@
|
||||||
|
// in sys_windows_386.s and sys_windows_amd64.s:
|
||||||
|
func getlasterror() uint32
|
||||||
|
|
||||||
|
+// When loading DLLs, we prefer to use LoadLibraryEx with
|
||||||
|
+// LOAD_LIBRARY_SEARCH_* flags, if available. LoadLibraryEx is not
|
||||||
|
+// available on old Windows, though, and the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags are not available on some versions of Windows without a
|
||||||
|
+// security patch.
|
||||||
|
+//
|
||||||
|
+// https://msdn.microsoft.com/en-us/library/ms684179(v=vs.85).aspx says:
|
||||||
|
+// "Windows 7, Windows Server 2008 R2, Windows Vista, and Windows
|
||||||
|
+// Server 2008: The LOAD_LIBRARY_SEARCH_* flags are available on
|
||||||
|
+// systems that have KB2533623 installed. To determine whether the
|
||||||
|
+// flags are available, use GetProcAddress to get the address of the
|
||||||
|
+// AddDllDirectory, RemoveDllDirectory, or SetDefaultDllDirectories
|
||||||
|
+// function. If GetProcAddress succeeds, the LOAD_LIBRARY_SEARCH_*
|
||||||
|
+// flags can be used with LoadLibraryEx."
|
||||||
|
+var useLoadLibraryEx bool
|
||||||
|
+
|
||||||
|
var timeBeginPeriodRetValue uint32
|
||||||
|
|
||||||
|
// osRelaxMinNS indicates that sysmon shouldn't osRelax if the next
|
||||||
|
@@ -417,7 +488,8 @@
|
||||||
|
// Only load winmm.dll if we need it.
|
||||||
|
// This avoids a dependency on winmm.dll for Go programs
|
||||||
|
// that run on new Windows versions.
|
||||||
|
- m32 := windowsLoadSystemLib(winmmdll[:])
|
||||||
|
+ var winmmdll = []byte("winmm.dll\000")
|
||||||
|
+ m32 := windowsLoadSystemLib(winmmdll)
|
||||||
|
if m32 == 0 {
|
||||||
|
print("runtime: LoadLibraryExW failed; errno=", getlasterror(), "\n")
|
||||||
|
throw("winmm.dll not found")
|
||||||
|
@@ -458,6 +530,28 @@
|
||||||
|
canUseLongPaths = true
|
||||||
|
}
|
||||||
|
|
||||||
|
+var osVersionInfo struct {
|
||||||
|
+ majorVersion uint32
|
||||||
|
+ minorVersion uint32
|
||||||
|
+ buildNumber uint32
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func initOsVersionInfo() {
|
||||||
|
+ info := windows.OSVERSIONINFOW{}
|
||||||
|
+ info.OSVersionInfoSize = uint32(unsafe.Sizeof(info))
|
||||||
|
+ stdcall(_RtlGetVersion, uintptr(unsafe.Pointer(&info)))
|
||||||
|
+ osVersionInfo.majorVersion = info.MajorVersion
|
||||||
|
+ osVersionInfo.minorVersion = info.MinorVersion
|
||||||
|
+ osVersionInfo.buildNumber = info.BuildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32) {
|
||||||
|
+ *majorVersion = osVersionInfo.majorVersion
|
||||||
|
+ *minorVersion = osVersionInfo.minorVersion
|
||||||
|
+ *buildNumber = osVersionInfo.buildNumber
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
func osinit() {
|
||||||
|
asmstdcallAddr = unsafe.Pointer(windows.AsmStdCallAddr())
|
||||||
|
|
||||||
|
@@ -470,8 +564,8 @@
|
||||||
|
initHighResTimer()
|
||||||
|
timeBeginPeriodRetValue = osRelax(false)
|
||||||
|
|
||||||
|
- initSysDirectory()
|
||||||
|
initLongPathSupport()
|
||||||
|
+ initOsVersionInfo()
|
||||||
|
|
||||||
|
numCPUStartup = getCPUCount()
|
||||||
|
|
||||||
|
@@ -487,7 +581,7 @@
|
||||||
|
//go:nosplit
|
||||||
|
func readRandom(r []byte) int {
|
||||||
|
n := 0
|
||||||
|
- if stdcall(_ProcessPrng, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
+ if stdcall(_RtlGenRandom, uintptr(unsafe.Pointer(&r[0])), uintptr(len(r)))&0xff != 0 {
|
||||||
|
n = len(r)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
Index: src/net/hook_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/hook_windows.go b/src/net/hook_windows.go
|
||||||
|
--- a/src/net/hook_windows.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
+++ b/src/net/hook_windows.go (revision 44e76f7cf1bc6e04b5da724e0b2e48f393713506)
|
||||||
|
@@ -13,6 +13,7 @@
|
||||||
|
hostsFilePath = windows.GetSystemDirectory() + "/Drivers/etc/hosts"
|
||||||
|
|
||||||
|
// Placeholders for socket system calls.
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error) = syscall.Socket
|
||||||
|
wsaSocketFunc func(int32, int32, int32, *syscall.WSAProtocolInfo, uint32, uint32) (syscall.Handle, error) = windows.WSASocket
|
||||||
|
connectFunc func(syscall.Handle, syscall.Sockaddr) error = syscall.Connect
|
||||||
|
listenFunc func(syscall.Handle, int) error = syscall.Listen
|
||||||
|
Index: src/net/internal/socktest/main_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_test.go b/src/net/internal/socktest/main_test.go
|
||||||
|
--- a/src/net/internal/socktest/main_test.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
+++ b/src/net/internal/socktest/main_test.go (revision 44e76f7cf1bc6e04b5da724e0b2e48f393713506)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build !js && !plan9 && !wasip1 && !windows
|
||||||
|
+//go:build !js && !plan9 && !wasip1
|
||||||
|
|
||||||
|
package socktest_test
|
||||||
|
|
||||||
|
Index: src/net/internal/socktest/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/main_windows_test.go b/src/net/internal/socktest/main_windows_test.go
|
||||||
|
new file mode 100644
|
||||||
|
--- /dev/null (revision 44e76f7cf1bc6e04b5da724e0b2e48f393713506)
|
||||||
|
+++ b/src/net/internal/socktest/main_windows_test.go (revision 44e76f7cf1bc6e04b5da724e0b2e48f393713506)
|
||||||
|
@@ -0,0 +1,22 @@
|
||||||
|
+// Copyright 2015 The Go Authors. All rights reserved.
|
||||||
|
+// Use of this source code is governed by a BSD-style
|
||||||
|
+// license that can be found in the LICENSE file.
|
||||||
|
+
|
||||||
|
+package socktest_test
|
||||||
|
+
|
||||||
|
+import "syscall"
|
||||||
|
+
|
||||||
|
+var (
|
||||||
|
+ socketFunc func(int, int, int) (syscall.Handle, error)
|
||||||
|
+ closeFunc func(syscall.Handle) error
|
||||||
|
+)
|
||||||
|
+
|
||||||
|
+func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
+ closeFunc = sw.Closesocket
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func uninstallTestHooks() {
|
||||||
|
+ socketFunc = syscall.Socket
|
||||||
|
+ closeFunc = syscall.Closesocket
|
||||||
|
+}
|
||||||
|
Index: src/net/internal/socktest/sys_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/internal/socktest/sys_windows.go b/src/net/internal/socktest/sys_windows.go
|
||||||
|
--- a/src/net/internal/socktest/sys_windows.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
+++ b/src/net/internal/socktest/sys_windows.go (revision 44e76f7cf1bc6e04b5da724e0b2e48f393713506)
|
||||||
|
@@ -9,6 +9,38 @@
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
+// Socket wraps [syscall.Socket].
|
||||||
|
+func (sw *Switch) Socket(family, sotype, proto int) (s syscall.Handle, err error) {
|
||||||
|
+ sw.once.Do(sw.init)
|
||||||
|
+
|
||||||
|
+ so := &Status{Cookie: cookie(family, sotype, proto)}
|
||||||
|
+ sw.fmu.RLock()
|
||||||
|
+ f, _ := sw.fltab[FilterSocket]
|
||||||
|
+ sw.fmu.RUnlock()
|
||||||
|
+
|
||||||
|
+ af, err := f.apply(so)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+ s, so.Err = syscall.Socket(family, sotype, proto)
|
||||||
|
+ if err = af.apply(so); err != nil {
|
||||||
|
+ if so.Err == nil {
|
||||||
|
+ syscall.Closesocket(s)
|
||||||
|
+ }
|
||||||
|
+ return syscall.InvalidHandle, err
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ sw.smu.Lock()
|
||||||
|
+ defer sw.smu.Unlock()
|
||||||
|
+ if so.Err != nil {
|
||||||
|
+ sw.stats.getLocked(so.Cookie).OpenFailed++
|
||||||
|
+ return syscall.InvalidHandle, so.Err
|
||||||
|
+ }
|
||||||
|
+ nso := sw.addLocked(s, family, sotype, proto)
|
||||||
|
+ sw.stats.getLocked(nso.Cookie).Opened++
|
||||||
|
+ return s, nil
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
// WSASocket wraps [syscall.WSASocket].
|
||||||
|
func (sw *Switch) WSASocket(family, sotype, proto int32, protinfo *syscall.WSAProtocolInfo, group uint32, flags uint32) (s syscall.Handle, err error) {
|
||||||
|
sw.once.Do(sw.init)
|
||||||
|
Index: src/net/main_windows_test.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/main_windows_test.go b/src/net/main_windows_test.go
|
||||||
|
--- a/src/net/main_windows_test.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
+++ b/src/net/main_windows_test.go (revision 44e76f7cf1bc6e04b5da724e0b2e48f393713506)
|
||||||
|
@@ -12,6 +12,7 @@
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Placeholders for saving original socket system calls.
|
||||||
|
+ origSocket = socketFunc
|
||||||
|
origWSASocket = wsaSocketFunc
|
||||||
|
origClosesocket = poll.CloseFunc
|
||||||
|
origConnect = connectFunc
|
||||||
|
@@ -21,6 +22,7 @@
|
||||||
|
)
|
||||||
|
|
||||||
|
func installTestHooks() {
|
||||||
|
+ socketFunc = sw.Socket
|
||||||
|
wsaSocketFunc = sw.WSASocket
|
||||||
|
poll.CloseFunc = sw.Closesocket
|
||||||
|
connectFunc = sw.Connect
|
||||||
|
@@ -30,6 +32,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
func uninstallTestHooks() {
|
||||||
|
+ socketFunc = origSocket
|
||||||
|
wsaSocketFunc = origWSASocket
|
||||||
|
poll.CloseFunc = origClosesocket
|
||||||
|
connectFunc = origConnect
|
||||||
|
Index: src/net/sock_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/net/sock_windows.go b/src/net/sock_windows.go
|
||||||
|
--- a/src/net/sock_windows.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
+++ b/src/net/sock_windows.go (revision 44e76f7cf1bc6e04b5da724e0b2e48f393713506)
|
||||||
|
@@ -20,6 +20,21 @@
|
||||||
|
func sysSocket(family, sotype, proto int) (syscall.Handle, error) {
|
||||||
|
s, err := wsaSocketFunc(int32(family), int32(sotype), int32(proto),
|
||||||
|
nil, 0, windows.WSA_FLAG_OVERLAPPED|windows.WSA_FLAG_NO_HANDLE_INHERIT)
|
||||||
|
+ if err == nil {
|
||||||
|
+ return s, nil
|
||||||
|
+ }
|
||||||
|
+ // WSA_FLAG_NO_HANDLE_INHERIT flag is not supported on some
|
||||||
|
+ // old versions of Windows, see
|
||||||
|
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
|
||||||
|
+ // for details. Just use syscall.Socket, if windows.WSASocket failed.
|
||||||
|
+
|
||||||
|
+ // See ../syscall/exec_unix.go for description of ForkLock.
|
||||||
|
+ syscall.ForkLock.RLock()
|
||||||
|
+ s, err = socketFunc(family, sotype, proto)
|
||||||
|
+ if err == nil {
|
||||||
|
+ syscall.CloseOnExec(s)
|
||||||
|
+ }
|
||||||
|
+ syscall.ForkLock.RUnlock()
|
||||||
|
if err != nil {
|
||||||
|
return syscall.InvalidHandle, os.NewSyscallError("socket", err)
|
||||||
|
}
|
||||||
|
Index: src/syscall/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/exec_windows.go b/src/syscall/exec_windows.go
|
||||||
|
--- a/src/syscall/exec_windows.go (revision b0d48afabb9fd14976c27221cb525c5d2ebbfe79)
|
||||||
|
+++ b/src/syscall/exec_windows.go (revision b4aece36e51ecce81c3ee9fe03e31db552e90018)
|
||||||
|
@@ -15,7 +15,6 @@
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
-// ForkLock is not used on Windows.
|
||||||
|
var ForkLock sync.RWMutex
|
||||||
|
|
||||||
|
// EscapeArg rewrites command line argument s as prescribed
|
||||||
|
@@ -304,6 +303,9 @@
|
||||||
|
var zeroProcAttr ProcAttr
|
||||||
|
var zeroSysProcAttr SysProcAttr
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
|
||||||
|
if len(argv0) == 0 {
|
||||||
|
return 0, 0, EWINDOWS
|
||||||
|
@@ -367,6 +369,17 @@
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
+ var maj, min, build uint32
|
||||||
|
+ rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
+ isWin7 := maj < 6 || (maj == 6 && min <= 1)
|
||||||
|
+ // NT kernel handles are divisible by 4, with the bottom 3 bits left as
|
||||||
|
+ // a tag. The fully set tag correlates with the types of handles we're
|
||||||
|
+ // concerned about here. Except, the kernel will interpret some
|
||||||
|
+ // special handle values, like -1, -2, and so forth, so kernelbase.dll
|
||||||
|
+ // checks to see that those bottom three bits are checked, but that top
|
||||||
|
+ // bit is not checked.
|
||||||
|
+ isLegacyWin7ConsoleHandle := func(handle Handle) bool { return isWin7 && handle&0x10000003 == 3 }
|
||||||
|
+
|
||||||
|
p, _ := GetCurrentProcess()
|
||||||
|
parentProcess := p
|
||||||
|
if sys.ParentProcess != 0 {
|
||||||
|
@@ -375,7 +388,15 @@
|
||||||
|
fd := make([]Handle, len(attr.Files))
|
||||||
|
for i := range attr.Files {
|
||||||
|
if attr.Files[i] > 0 {
|
||||||
|
- err := DuplicateHandle(p, Handle(attr.Files[i]), parentProcess, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
+ destinationProcessHandle := parentProcess
|
||||||
|
+
|
||||||
|
+ // On Windows 7, console handles aren't real handles, and can only be duplicated
|
||||||
|
+ // into the current process, not a parent one, which amounts to the same thing.
|
||||||
|
+ if parentProcess != p && isLegacyWin7ConsoleHandle(Handle(attr.Files[i])) {
|
||||||
|
+ destinationProcessHandle = p
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
+ err := DuplicateHandle(p, Handle(attr.Files[i]), destinationProcessHandle, &fd[i], 0, true, DUPLICATE_SAME_ACCESS)
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
@@ -406,6 +427,14 @@
|
||||||
|
|
||||||
|
fd = append(fd, sys.AdditionalInheritedHandles...)
|
||||||
|
|
||||||
|
+ // On Windows 7, console handles aren't real handles, so don't pass them
|
||||||
|
+ // through to PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
|
||||||
|
+ for i := range fd {
|
||||||
|
+ if isLegacyWin7ConsoleHandle(fd[i]) {
|
||||||
|
+ fd[i] = 0
|
||||||
|
+ }
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
// The presence of a NULL handle in the list is enough to cause PROC_THREAD_ATTRIBUTE_HANDLE_LIST
|
||||||
|
// to treat the entire list as empty, so remove NULL handles.
|
||||||
|
j := 0
|
||||||
|
Index: src/syscall/dll_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/syscall/dll_windows.go b/src/syscall/dll_windows.go
|
||||||
|
--- a/src/syscall/dll_windows.go (revision b4aece36e51ecce81c3ee9fe03e31db552e90018)
|
||||||
|
+++ b/src/syscall/dll_windows.go (revision ea2726a6fa25fbfa1092e696e522eafca544d24c)
|
||||||
|
@@ -119,14 +119,7 @@
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:linkname loadsystemlibrary
|
||||||
|
-func loadsystemlibrary(filename *uint16) (uintptr, Errno) {
|
||||||
|
- const _LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
|
||||||
|
- handle, _, err := SyscallN(uintptr(__LoadLibraryExW), uintptr(unsafe.Pointer(filename)), 0, _LOAD_LIBRARY_SEARCH_SYSTEM32)
|
||||||
|
- if handle != 0 {
|
||||||
|
- err = 0
|
||||||
|
- }
|
||||||
|
- return handle, err
|
||||||
|
-}
|
||||||
|
+func loadsystemlibrary(filename *uint16, absoluteFilepath *uint16) (handle uintptr, err Errno)
|
||||||
|
|
||||||
|
//go:linkname getprocaddress
|
||||||
|
func getprocaddress(handle uintptr, procname *uint8) (uintptr, Errno) {
|
||||||
|
@@ -143,6 +136,9 @@
|
||||||
|
Handle Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname getSystemDirectory
|
||||||
|
+func getSystemDirectory() string // Implemented in runtime package.
|
||||||
|
+
|
||||||
|
// LoadDLL loads the named DLL file into memory.
|
||||||
|
//
|
||||||
|
// If name is not an absolute path and is not a known system DLL used by
|
||||||
|
@@ -159,7 +155,11 @@
|
||||||
|
var h uintptr
|
||||||
|
var e Errno
|
||||||
|
if sysdll.IsSystemDLL[name] {
|
||||||
|
- h, e = loadsystemlibrary(namep)
|
||||||
|
+ absoluteFilepathp, err := UTF16PtrFromString(getSystemDirectory() + name)
|
||||||
|
+ if err != nil {
|
||||||
|
+ return nil, err
|
||||||
|
+ }
|
||||||
|
+ h, e = loadsystemlibrary(namep, absoluteFilepathp)
|
||||||
|
} else {
|
||||||
|
h, e = loadlibrary(namep)
|
||||||
|
}
|
||||||
|
Index: src/os/removeall_at.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/removeall_at.go b/src/os/removeall_at.go
|
||||||
|
--- a/src/os/removeall_at.go (revision ea2726a6fa25fbfa1092e696e522eafca544d24c)
|
||||||
|
+++ b/src/os/removeall_at.go (revision d47e0d22130d597dcf9daa6b41fd9501274f0cb2)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build unix || wasip1 || windows
|
||||||
|
+//go:build unix || wasip1
|
||||||
|
|
||||||
|
package os
|
||||||
|
|
||||||
|
@@ -175,3 +175,25 @@
|
||||||
|
}
|
||||||
|
return newDirFile(fd, name)
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+func rootRemoveAll(r *Root, name string) error {
|
||||||
|
+ // Consistency with os.RemoveAll: Strip trailing /s from the name,
|
||||||
|
+ // so RemoveAll("not_a_directory/") succeeds.
|
||||||
|
+ for len(name) > 0 && IsPathSeparator(name[len(name)-1]) {
|
||||||
|
+ name = name[:len(name)-1]
|
||||||
|
+ }
|
||||||
|
+ if endsWithDot(name) {
|
||||||
|
+ // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
+ }
|
||||||
|
+ _, err := doInRoot(r, name, nil, func(parent sysfdType, name string) (struct{}, error) {
|
||||||
|
+ return struct{}{}, removeAllFrom(parent, name)
|
||||||
|
+ })
|
||||||
|
+ if IsNotExist(err) {
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
+ if err != nil {
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
+ }
|
||||||
|
+ return err
|
||||||
|
+}
|
||||||
|
Index: src/os/removeall_noat.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/removeall_noat.go b/src/os/removeall_noat.go
|
||||||
|
--- a/src/os/removeall_noat.go (revision ea2726a6fa25fbfa1092e696e522eafca544d24c)
|
||||||
|
+++ b/src/os/removeall_noat.go (revision d47e0d22130d597dcf9daa6b41fd9501274f0cb2)
|
||||||
|
@@ -2,7 +2,7 @@
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
-//go:build (js && wasm) || plan9
|
||||||
|
+//go:build (js && wasm) || plan9 || windows
|
||||||
|
|
||||||
|
package os
|
||||||
|
|
||||||
|
@@ -140,3 +140,22 @@
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+func rootRemoveAll(r *Root, name string) error {
|
||||||
|
+ if endsWithDot(name) {
|
||||||
|
+ // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
+ }
|
||||||
|
+ if err := checkPathEscapesLstat(r, name); err != nil {
|
||||||
|
+ if err == syscall.ENOTDIR {
|
||||||
|
+ // Some intermediate path component is not a directory.
|
||||||
|
+ // RemoveAll treats this as success (since the target doesn't exist).
|
||||||
|
+ return nil
|
||||||
|
+ }
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: err}
|
||||||
|
+ }
|
||||||
|
+ if err := RemoveAll(joinPath(r.root.name, name)); err != nil {
|
||||||
|
+ return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+}
|
||||||
|
Index: src/os/root_noopenat.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/root_noopenat.go b/src/os/root_noopenat.go
|
||||||
|
--- a/src/os/root_noopenat.go (revision ea2726a6fa25fbfa1092e696e522eafca544d24c)
|
||||||
|
+++ b/src/os/root_noopenat.go (revision d47e0d22130d597dcf9daa6b41fd9501274f0cb2)
|
||||||
|
@@ -11,7 +11,6 @@
|
||||||
|
"internal/filepathlite"
|
||||||
|
"internal/stringslite"
|
||||||
|
"sync/atomic"
|
||||||
|
- "syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
@@ -185,25 +184,6 @@
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
-
|
||||||
|
-func rootRemoveAll(r *Root, name string) error {
|
||||||
|
- if endsWithDot(name) {
|
||||||
|
- // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
- }
|
||||||
|
- if err := checkPathEscapesLstat(r, name); err != nil {
|
||||||
|
- if err == syscall.ENOTDIR {
|
||||||
|
- // Some intermediate path component is not a directory.
|
||||||
|
- // RemoveAll treats this as success (since the target doesn't exist).
|
||||||
|
- return nil
|
||||||
|
- }
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: err}
|
||||||
|
- }
|
||||||
|
- if err := RemoveAll(joinPath(r.root.name, name)); err != nil {
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
- }
|
||||||
|
- return nil
|
||||||
|
-}
|
||||||
|
|
||||||
|
func rootReadlink(r *Root, name string) (string, error) {
|
||||||
|
if err := checkPathEscapesLstat(r, name); err != nil {
|
||||||
|
Index: src/os/root_openat.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/root_openat.go b/src/os/root_openat.go
|
||||||
|
--- a/src/os/root_openat.go (revision ea2726a6fa25fbfa1092e696e522eafca544d24c)
|
||||||
|
+++ b/src/os/root_openat.go (revision d47e0d22130d597dcf9daa6b41fd9501274f0cb2)
|
||||||
|
@@ -196,28 +196,6 @@
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
-func rootRemoveAll(r *Root, name string) error {
|
||||||
|
- // Consistency with os.RemoveAll: Strip trailing /s from the name,
|
||||||
|
- // so RemoveAll("not_a_directory/") succeeds.
|
||||||
|
- for len(name) > 0 && IsPathSeparator(name[len(name)-1]) {
|
||||||
|
- name = name[:len(name)-1]
|
||||||
|
- }
|
||||||
|
- if endsWithDot(name) {
|
||||||
|
- // Consistency with os.RemoveAll: Return EINVAL when trying to remove .
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: syscall.EINVAL}
|
||||||
|
- }
|
||||||
|
- _, err := doInRoot(r, name, nil, func(parent sysfdType, name string) (struct{}, error) {
|
||||||
|
- return struct{}{}, removeAllFrom(parent, name)
|
||||||
|
- })
|
||||||
|
- if IsNotExist(err) {
|
||||||
|
- return nil
|
||||||
|
- }
|
||||||
|
- if err != nil {
|
||||||
|
- return &PathError{Op: "RemoveAll", Path: name, Err: underlyingError(err)}
|
||||||
|
- }
|
||||||
|
- return err
|
||||||
|
-}
|
||||||
|
-
|
||||||
|
func rootRename(r *Root, oldname, newname string) error {
|
||||||
|
_, err := doInRoot(r, oldname, nil, func(oldparent sysfdType, oldname string) (struct{}, error) {
|
||||||
|
_, err := doInRoot(r, newname, nil, func(newparent sysfdType, newname string) (struct{}, error) {
|
||||||
|
Index: src/os/root_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/root_windows.go b/src/os/root_windows.go
|
||||||
|
--- a/src/os/root_windows.go (revision ea2726a6fa25fbfa1092e696e522eafca544d24c)
|
||||||
|
+++ b/src/os/root_windows.go (revision d47e0d22130d597dcf9daa6b41fd9501274f0cb2)
|
||||||
|
@@ -402,3 +402,14 @@
|
||||||
|
}
|
||||||
|
return fi.Mode(), nil
|
||||||
|
}
|
||||||
|
+
|
||||||
|
+func checkPathEscapes(r *Root, name string) error {
|
||||||
|
+ if !filepathlite.IsLocal(name) {
|
||||||
|
+ return errPathEscapes
|
||||||
|
+ }
|
||||||
|
+ return nil
|
||||||
|
+}
|
||||||
|
+
|
||||||
|
+func checkPathEscapesLstat(r *Root, name string) error {
|
||||||
|
+ return checkPathEscapes(r, name)
|
||||||
|
+}
|
||||||
|
Index: src/os/exec_windows.go
|
||||||
|
IDEA additional info:
|
||||||
|
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
|
||||||
|
<+>UTF-8
|
||||||
|
===================================================================
|
||||||
|
diff --git a/src/os/exec_windows.go b/src/os/exec_windows.go
|
||||||
|
--- a/src/os/exec_windows.go (revision d47e0d22130d597dcf9daa6b41fd9501274f0cb2)
|
||||||
|
+++ b/src/os/exec_windows.go (revision 00e8daec9a4d88f44a8dc55d3bdb71878e525b41)
|
||||||
|
@@ -10,6 +10,7 @@
|
||||||
|
"runtime"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
+ _ "unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Note that Process.handle is never nil because Windows always requires
|
||||||
|
@@ -49,9 +50,23 @@
|
||||||
|
// than statusDone.
|
||||||
|
p.doRelease(statusReleased)
|
||||||
|
|
||||||
|
+ var maj, min, build uint32
|
||||||
|
+ rtlGetNtVersionNumbers(&maj, &min, &build)
|
||||||
|
+ if maj < 10 {
|
||||||
|
+ // NOTE(brainman): It seems that sometimes process is not dead
|
||||||
|
+ // when WaitForSingleObject returns. But we do not know any
|
||||||
|
+ // other way to wait for it. Sleeping for a while seems to do
|
||||||
|
+ // the trick sometimes.
|
||||||
|
+ // See https://golang.org/issue/25965 for details.
|
||||||
|
+ time.Sleep(5 * time.Millisecond)
|
||||||
|
+ }
|
||||||
|
+
|
||||||
|
return &ProcessState{p.Pid, syscall.WaitStatus{ExitCode: ec}, &u}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
+//go:linkname rtlGetNtVersionNumbers syscall.rtlGetNtVersionNumbers
|
||||||
|
+func rtlGetNtVersionNumbers(majorVersion *uint32, minorVersion *uint32, buildNumber *uint32)
|
||||||
|
+
|
||||||
|
func (p *Process) signal(sig Signal) error {
|
||||||
|
handle, status := p.handleTransientAcquire()
|
||||||
|
switch status {
|
||||||
26
.github/release.sh
vendored
Normal file
26
.github/release.sh
vendored
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ ! ($FILENAME =~ ".exe" || $FILENAME =~ ".sh")]];then
|
||||||
|
gzip -S ".gz" $FILENAME
|
||||||
|
elif [[ $FILENAME =~ ".exe" ]];then
|
||||||
|
zip -m ${FILENAME%.*}.zip $FILENAME
|
||||||
|
else echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ $FILENAME =~ ".zip" ]];then
|
||||||
|
echo "rename $FILENAME"
|
||||||
|
mv $FILENAME ${FILENAME%.*}-${VERSION}.zip
|
||||||
|
elif [[ $FILENAME =~ ".gz" ]];then
|
||||||
|
echo "rename $FILENAME"
|
||||||
|
mv $FILENAME ${FILENAME%.*}-${VERSION}.gz
|
||||||
|
else
|
||||||
|
echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
||||||
18
.github/release/.fpm_systemd
vendored
Normal file
18
.github/release/.fpm_systemd
vendored
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
-s dir
|
||||||
|
--name mihomo
|
||||||
|
--category net
|
||||||
|
--license GPL-3.0-or-later
|
||||||
|
--description "The universal proxy platform."
|
||||||
|
--url "https://wiki.metacubex.one/"
|
||||||
|
--maintainer "MetaCubeX <none@example.com>"
|
||||||
|
--deb-field "Bug: https://github.com/MetaCubeX/mihomo/issues"
|
||||||
|
--no-deb-generate-changes
|
||||||
|
--config-files /etc/mihomo/config.yaml
|
||||||
|
|
||||||
|
.github/release/config.yaml=/etc/mihomo/config.yaml
|
||||||
|
|
||||||
|
.github/release/mihomo.service=/usr/lib/systemd/system/mihomo.service
|
||||||
|
.github/release/mihomo@.service=/usr/lib/systemd/system/mihomo@.service
|
||||||
|
|
||||||
|
|
||||||
|
LICENSE=/usr/share/licenses/mihomo/LICENSE
|
||||||
15
.github/release/config.yaml
vendored
Normal file
15
.github/release/config.yaml
vendored
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
mixed-port: 7890
|
||||||
|
|
||||||
|
dns:
|
||||||
|
enable: true
|
||||||
|
ipv6: true
|
||||||
|
enhanced-mode: fake-ip
|
||||||
|
fake-ip-filter:
|
||||||
|
- "*"
|
||||||
|
- "+.lan"
|
||||||
|
- "+.local"
|
||||||
|
nameserver:
|
||||||
|
- system
|
||||||
|
|
||||||
|
rules:
|
||||||
|
- MATCH,DIRECT
|
||||||
17
.github/release/mihomo.service
vendored
Normal file
17
.github/release/mihomo.service
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=mihomo Daemon, Another Clash Kernel.
|
||||||
|
Documentation=https://wiki.metacubex.one
|
||||||
|
After=network.target nss-lookup.target network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
ExecStart=/usr/bin/mihomo -d /etc/mihomo
|
||||||
|
ExecReload=/bin/kill -HUP $MAINPID
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=10
|
||||||
|
LimitNOFILE=infinity
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
17
.github/release/mihomo@.service
vendored
Normal file
17
.github/release/mihomo@.service
vendored
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=mihomo Daemon, Another Clash Kernel.
|
||||||
|
Documentation=https://wiki.metacubex.one
|
||||||
|
After=network.target nss-lookup.target network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SYS_TIME CAP_SYS_PTRACE CAP_DAC_READ_SEARCH CAP_DAC_OVERRIDE
|
||||||
|
ExecStart=/usr/bin/mihomo -d /etc/mihomo
|
||||||
|
ExecReload=/bin/kill -HUP $MAINPID
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=10
|
||||||
|
LimitNOFILE=infinity
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
35
.github/rename-cgo.sh
vendored
Normal file
35
.github/rename-cgo.sh
vendored
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ $FILENAME =~ "darwin-10.16-arm64" ]];then
|
||||||
|
echo "rename darwin-10.16-arm64 $FILENAME"
|
||||||
|
mv $FILENAME mihomo-darwin-arm64-cgo
|
||||||
|
elif [[ $FILENAME =~ "darwin-10.16-amd64" ]];then
|
||||||
|
echo "rename darwin-10.16-amd64 $FILENAME"
|
||||||
|
mv $FILENAME mihomo-darwin-amd64-cgo
|
||||||
|
elif [[ $FILENAME =~ "windows-4.0-386" ]];then
|
||||||
|
echo "rename windows 386 $FILENAME"
|
||||||
|
mv $FILENAME mihomo-windows-386-cgo.exe
|
||||||
|
elif [[ $FILENAME =~ "windows-4.0-amd64" ]];then
|
||||||
|
echo "rename windows amd64 $FILENAME"
|
||||||
|
mv $FILENAME mihomo-windows-amd64-cgo.exe
|
||||||
|
elif [[ $FILENAME =~ "mihomo-linux-arm-5" ]];then
|
||||||
|
echo "rename mihomo-linux-arm-5 $FILENAME"
|
||||||
|
mv $FILENAME mihomo-linux-armv5-cgo
|
||||||
|
elif [[ $FILENAME =~ "mihomo-linux-arm-6" ]];then
|
||||||
|
echo "rename mihomo-linux-arm-6 $FILENAME"
|
||||||
|
mv $FILENAME mihomo-linux-armv6-cgo
|
||||||
|
elif [[ $FILENAME =~ "mihomo-linux-arm-7" ]];then
|
||||||
|
echo "rename mihomo-linux-arm-7 $FILENAME"
|
||||||
|
mv $FILENAME mihomo-linux-armv7-cgo
|
||||||
|
elif [[ $FILENAME =~ "linux" ]];then
|
||||||
|
echo "rename linux $FILENAME"
|
||||||
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
elif [[ $FILENAME =~ "android" ]];then
|
||||||
|
echo "rename android $FILENAME"
|
||||||
|
mv $FILENAME $FILENAME-cgo
|
||||||
|
else echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
||||||
12
.github/rename-go120.sh
vendored
Normal file
12
.github/rename-go120.sh
vendored
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
FILENAMES=$(ls)
|
||||||
|
for FILENAME in $FILENAMES
|
||||||
|
do
|
||||||
|
if [[ ! ($FILENAME =~ ".exe" || $FILENAME =~ ".sh")]];then
|
||||||
|
mv $FILENAME ${FILENAME}-go120
|
||||||
|
elif [[ $FILENAME =~ ".exe" ]];then
|
||||||
|
mv $FILENAME ${FILENAME%.*}-go120.exe
|
||||||
|
else echo "skip $FILENAME"
|
||||||
|
fi
|
||||||
|
done
|
||||||
20
.github/workflows/build.yaml
vendored
20
.github/workflows/build.yaml
vendored
@@ -1,20 +0,0 @@
|
|||||||
name: Build All
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Set up Go
|
|
||||||
uses: actions/setup-go@v1
|
|
||||||
with:
|
|
||||||
go-version: 1.18
|
|
||||||
- name: Check out code
|
|
||||||
uses: actions/checkout@v1
|
|
||||||
- name: Build
|
|
||||||
run: make all
|
|
||||||
- name: Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
||||||
596
.github/workflows/build.yml
vendored
Normal file
596
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,596 @@
|
|||||||
|
name: Build
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version:
|
||||||
|
description: "Tag version to release"
|
||||||
|
required: true
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "docs/**"
|
||||||
|
- "README.md"
|
||||||
|
- ".github/ISSUE_TEMPLATE/**"
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
concurrency:
|
||||||
|
group: "${{ github.workflow }}-${{ github.ref }}"
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: docker.io
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
jobs:
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-compatible } # old style file name will be removed in next released
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-v1 }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v2, output: amd64-v2 }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-v3 }
|
||||||
|
- { goos: darwin, goarch: arm64, output: arm64 }
|
||||||
|
|
||||||
|
- { goos: linux, goarch: '386', go386: sse2, output: '386', debian: i386, rpm: i386}
|
||||||
|
- { goos: linux, goarch: '386', go386: softfloat, output: '386-softfloat' }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-compatible} # old style file name will be removed in next released
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64, debian: amd64, rpm: x86_64, pacman: x86_64}
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-v1, debian: amd64, rpm: x86_64, pacman: x86_64, test: test }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v2, output: amd64-v2, debian: amd64, rpm: x86_64, pacman: x86_64}
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-v3, debian: amd64, rpm: x86_64, pacman: x86_64}
|
||||||
|
- { goos: linux, goarch: arm64, output: arm64, debian: arm64, rpm: aarch64, pacman: aarch64}
|
||||||
|
- { goos: linux, goarch: arm, goarm: '5', output: armv5 }
|
||||||
|
- { goos: linux, goarch: arm, goarm: '6', output: armv6, debian: armel, rpm: armv6hl}
|
||||||
|
- { goos: linux, goarch: arm, goarm: '7', output: armv7, debian: armhf, rpm: armv7hl, pacman: armv7hl}
|
||||||
|
- { goos: linux, goarch: mips, gomips: hardfloat, output: mips-hardfloat }
|
||||||
|
- { goos: linux, goarch: mips, gomips: softfloat, output: mips-softfloat }
|
||||||
|
- { goos: linux, goarch: mipsle, gomips: hardfloat, output: mipsle-hardfloat }
|
||||||
|
- { goos: linux, goarch: mipsle, gomips: softfloat, output: mipsle-softfloat }
|
||||||
|
- { goos: linux, goarch: mips64, output: mips64 }
|
||||||
|
- { goos: linux, goarch: mips64le, output: mips64le, debian: mips64el, rpm: mips64el }
|
||||||
|
- { goos: linux, goarch: loong64, output: loong64-abi1, abi: '1', debian: loongarch64, rpm: loongarch64 }
|
||||||
|
- { goos: linux, goarch: loong64, output: loong64-abi2, abi: '2', debian: loong64, rpm: loong64 }
|
||||||
|
- { goos: linux, goarch: riscv64, output: riscv64, debian: riscv64, rpm: riscv64 }
|
||||||
|
- { goos: linux, goarch: s390x, output: s390x, debian: s390x, rpm: s390x }
|
||||||
|
- { goos: linux, goarch: ppc64le, output: ppc64le, debian: ppc64el, rpm: ppc64le }
|
||||||
|
|
||||||
|
# Go 1.26 with special patch can work on Windows 7
|
||||||
|
# https://github.com/MetaCubeX/go/commits/release-branch.go1.26/
|
||||||
|
- { goos: windows, goarch: '386', output: '386' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-compatible } # old style file name will be removed in next released
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1 }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2 }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3 }
|
||||||
|
- { goos: windows, goarch: arm64, output: arm64 }
|
||||||
|
|
||||||
|
- { goos: freebsd, goarch: '386', output: '386' }
|
||||||
|
- { goos: freebsd, goarch: amd64, goamd64: v1, output: amd64-compatible } # old style file name will be removed in next released
|
||||||
|
- { goos: freebsd, goarch: amd64, goamd64: v3, output: amd64 }
|
||||||
|
- { goos: freebsd, goarch: amd64, goamd64: v1, output: amd64-v1 }
|
||||||
|
- { goos: freebsd, goarch: amd64, goamd64: v2, output: amd64-v2 }
|
||||||
|
- { goos: freebsd, goarch: amd64, goamd64: v3, output: amd64-v3 }
|
||||||
|
- { goos: freebsd, goarch: arm64, output: arm64 }
|
||||||
|
|
||||||
|
- { goos: android, goarch: '386', ndk: i686-linux-android34, output: '386' }
|
||||||
|
- { goos: android, goarch: amd64, ndk: x86_64-linux-android34, output: amd64 }
|
||||||
|
- { goos: android, goarch: arm, ndk: armv7a-linux-androideabi34, output: armv7 }
|
||||||
|
- { goos: android, goarch: arm64, ndk: aarch64-linux-android34, output: arm64-v8 }
|
||||||
|
|
||||||
|
# Go 1.25 with special patch can work on Windows 7
|
||||||
|
# https://github.com/MetaCubeX/go/commits/release-branch.go1.25/
|
||||||
|
- { goos: windows, goarch: '386', output: '386-go125', goversion: '1.25' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go125, goversion: '1.25' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go125, goversion: '1.25' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go125, goversion: '1.25' }
|
||||||
|
|
||||||
|
# Go 1.24 with special patch can work on Windows 7
|
||||||
|
# https://github.com/MetaCubeX/go/commits/release-branch.go1.24/
|
||||||
|
- { goos: windows, goarch: '386', output: '386-go124', goversion: '1.24' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go124, goversion: '1.24' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go124, goversion: '1.24' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go124, goversion: '1.24' }
|
||||||
|
|
||||||
|
# Go 1.23 with special patch can work on Windows 7
|
||||||
|
# https://github.com/MetaCubeX/go/commits/release-branch.go1.23/
|
||||||
|
- { goos: windows, goarch: '386', output: '386-go123', goversion: '1.23' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go123, goversion: '1.23' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go123, goversion: '1.23' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go123, goversion: '1.23' }
|
||||||
|
|
||||||
|
# Go 1.22 with special patch can work on Windows 7
|
||||||
|
# https://github.com/MetaCubeX/go/commits/release-branch.go1.22/
|
||||||
|
- { goos: windows, goarch: '386', output: '386-go122', goversion: '1.22' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go122, goversion: '1.22' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go122, goversion: '1.22' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go122, goversion: '1.22' }
|
||||||
|
|
||||||
|
# Go 1.21 can revert commit `9e4385` to work on Windows 7
|
||||||
|
# https://github.com/golang/go/issues/64622#issuecomment-1847475161
|
||||||
|
# (OR we can just use golang1.21.4 which unneeded any patch)
|
||||||
|
- { goos: windows, goarch: '386', output: '386-go121', goversion: '1.21' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go121, goversion: '1.21' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go121, goversion: '1.21' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go121, goversion: '1.21' }
|
||||||
|
|
||||||
|
# Go 1.20 is the last release that will run on any release of Windows 7, 8, Server 2008 and Server 2012. Go 1.21 will require at least Windows 10 or Server 2016.
|
||||||
|
- { goos: windows, goarch: '386', output: '386-go120', goversion: '1.20' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v1, output: amd64-v1-go120, goversion: '1.20' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v2, output: amd64-v2-go120, goversion: '1.20' }
|
||||||
|
- { goos: windows, goarch: amd64, goamd64: v3, output: amd64-v3-go120, goversion: '1.20' }
|
||||||
|
|
||||||
|
# Go 1.24 is the last release that will run on macOS 11 Big Sur. Go 1.25 will require macOS 12 Monterey or later.
|
||||||
|
- { goos: darwin, goarch: arm64, output: arm64-go124, goversion: '1.24' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-v1-go124, goversion: '1.24' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v2, output: amd64-v2-go124, goversion: '1.24' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-v3-go124, goversion: '1.24' }
|
||||||
|
|
||||||
|
# Go 1.22 is the last release that will run on macOS 10.15 Catalina. Go 1.23 will require macOS 11 Big Sur or later.
|
||||||
|
- { goos: darwin, goarch: arm64, output: arm64-go122, goversion: '1.22' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-v1-go122, goversion: '1.22' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v2, output: amd64-v2-go122, goversion: '1.22' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-v3-go122, goversion: '1.22' }
|
||||||
|
|
||||||
|
# Go 1.20 is the last release that will run on macOS 10.13 High Sierra or 10.14 Mojave. Go 1.21 will require macOS 10.15 Catalina or later.
|
||||||
|
- { goos: darwin, goarch: arm64, output: arm64-go120, goversion: '1.20' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v1, output: amd64-v1-go120, goversion: '1.20' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v2, output: amd64-v2-go120, goversion: '1.20' }
|
||||||
|
- { goos: darwin, goarch: amd64, goamd64: v3, output: amd64-v3-go120, goversion: '1.20' }
|
||||||
|
|
||||||
|
# Go 1.23 is the last release that requires Linux kernel version 2.6.32 or later. Go 1.24 will require Linux kernel version 3.2 or later.
|
||||||
|
- { goos: linux, goarch: '386', output: '386-go123', goversion: '1.23' }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-v1-go123, goversion: '1.23', test: test }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v2, output: amd64-v2-go123, goversion: '1.23' }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-v3-go123, goversion: '1.23' }
|
||||||
|
|
||||||
|
# only for test
|
||||||
|
- { goos: linux, goarch: '386', output: '386-go120', goversion: '1.20' }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v1, output: amd64-v1-go120, goversion: '1.20', test: test }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v2, output: amd64-v2-go120, goversion: '1.20' }
|
||||||
|
- { goos: linux, goarch: amd64, goamd64: v3, output: amd64-v3-go120, goversion: '1.20' }
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
if: ${{ matrix.jobs.goversion == '' && matrix.jobs.abi != '1' }}
|
||||||
|
uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version: '1.26'
|
||||||
|
check-latest: true # Always check for the latest patch release
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
if: ${{ matrix.jobs.goversion != '' && matrix.jobs.abi != '1' }}
|
||||||
|
uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version: ${{ matrix.jobs.goversion }}
|
||||||
|
check-latest: true # Always check for the latest patch release
|
||||||
|
|
||||||
|
- name: Set up Go1.25 loongarch abi1
|
||||||
|
if: ${{ matrix.jobs.goarch == 'loong64' && matrix.jobs.abi == '1' }}
|
||||||
|
run: |
|
||||||
|
wget -q https://github.com/MetaCubeX/loongarch64-golang/releases/download/1.25.5/go1.25.5.linux-amd64-abi1.tar.gz
|
||||||
|
sudo tar zxf go1.25.5.linux-amd64-abi1.tar.gz -C /usr/local
|
||||||
|
echo "/usr/local/go/bin" >> $GITHUB_PATH
|
||||||
|
|
||||||
|
# this patch file only works on golang1.26.x
|
||||||
|
# that means after golang1.27 release it must be changed
|
||||||
|
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.26/
|
||||||
|
# revert:
|
||||||
|
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||||
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
|
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
# f0894a00f4b756d4b9b4078af2e686b359493583: "os: remove 5ms sleep on Windows in (*Process).Wait"
|
||||||
|
# sepical fix:
|
||||||
|
# - os.RemoveAll not working on Windows7
|
||||||
|
- name: Revert Golang1.26 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.26.patch
|
||||||
|
|
||||||
|
# this patch file only works on golang1.25.x
|
||||||
|
# that means after golang1.26 release it must be changed
|
||||||
|
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.25/
|
||||||
|
# revert:
|
||||||
|
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||||
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
|
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
# f0894a00f4b756d4b9b4078af2e686b359493583: "os: remove 5ms sleep on Windows in (*Process).Wait"
|
||||||
|
# sepical fix:
|
||||||
|
# - os.RemoveAll not working on Windows7
|
||||||
|
- name: Revert Golang1.25 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.25' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.25.patch
|
||||||
|
|
||||||
|
# this patch file only works on golang1.24.x
|
||||||
|
# that means after golang1.25 release it must be changed
|
||||||
|
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.24/
|
||||||
|
# revert:
|
||||||
|
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||||
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
|
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
- name: Revert Golang1.24 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.24' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.24.patch
|
||||||
|
|
||||||
|
# this patch file only works on golang1.23.x
|
||||||
|
# that means after golang1.24 release it must be changed
|
||||||
|
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.23/
|
||||||
|
# revert:
|
||||||
|
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||||
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
|
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
- name: Revert Golang1.23 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.23' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.23.patch
|
||||||
|
|
||||||
|
# this patch file only works on golang1.22.x
|
||||||
|
# that means after golang1.23 release it must be changed
|
||||||
|
# see: https://github.com/MetaCubeX/go/commits/release-branch.go1.22/
|
||||||
|
# revert:
|
||||||
|
# 693def151adff1af707d82d28f55dba81ceb08e1: "crypto/rand,runtime: switch RtlGenRandom for ProcessPrng"
|
||||||
|
# 7c1157f9544922e96945196b47b95664b1e39108: "net: remove sysSocket fallback for Windows 7"
|
||||||
|
# 48042aa09c2f878c4faa576948b07fe625c4707a: "syscall: remove Windows 7 console handle workaround"
|
||||||
|
# a17d959debdb04cd550016a3501dd09d50cd62e7: "runtime: always use LoadLibraryEx to load system libraries"
|
||||||
|
- name: Revert Golang1.22 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.22' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.22.patch
|
||||||
|
|
||||||
|
# modify from https://github.com/restic/restic/issues/4636#issuecomment-1896455557
|
||||||
|
- name: Revert Golang1.21 commit for Windows7/8
|
||||||
|
if: ${{ matrix.jobs.goos == 'windows' && matrix.jobs.goversion == '1.21' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go1.21.patch
|
||||||
|
|
||||||
|
- name: Set variables
|
||||||
|
run: |
|
||||||
|
VERSION="${GITHUB_REF_NAME,,}-$(git rev-parse --short HEAD)"
|
||||||
|
VERSION="${VERSION//\//-}"
|
||||||
|
PackageVersion="$(curl -s "https://api.github.com/repos/MetaCubeX/mihomo/releases/latest" | jq -r '.tag_name' | sed 's/v//g' | awk -F '.' '{$NF = $NF + 1; print}' OFS='.').${VERSION/-/.}"
|
||||||
|
if [ -n "${{ github.event.inputs.version }}" ]; then
|
||||||
|
VERSION=${{ github.event.inputs.version }}
|
||||||
|
PackageVersion="${VERSION#v}"
|
||||||
|
fi
|
||||||
|
echo "VERSION=${VERSION}" >> $GITHUB_ENV
|
||||||
|
echo "PackageVersion=${PackageVersion}" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
echo "BUILDTIME=$(date)" >> $GITHUB_ENV
|
||||||
|
echo "CGO_ENABLED=0" >> $GITHUB_ENV
|
||||||
|
echo "BUILDTAG=-extldflags --static" >> $GITHUB_ENV
|
||||||
|
echo "GOTOOLCHAIN=local" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Setup NDK
|
||||||
|
if: ${{ matrix.jobs.goos == 'android' }}
|
||||||
|
uses: nttld/setup-ndk@v1
|
||||||
|
id: setup-ndk
|
||||||
|
with:
|
||||||
|
ndk-version: r29-beta1
|
||||||
|
|
||||||
|
- name: Set NDK path
|
||||||
|
if: ${{ matrix.jobs.goos == 'android' }}
|
||||||
|
run: |
|
||||||
|
echo "CC=${{steps.setup-ndk.outputs.ndk-path}}/toolchains/llvm/prebuilt/linux-x86_64/bin/${{matrix.jobs.ndk}}-clang" >> $GITHUB_ENV
|
||||||
|
echo "CGO_ENABLED=1" >> $GITHUB_ENV
|
||||||
|
echo "BUILDTAG=" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
if: ${{ matrix.jobs.test == 'test' }}
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
echo "---test with_gvisor---"
|
||||||
|
go test ./... -tags "with_gvisor" -count=1
|
||||||
|
|
||||||
|
- name: Update CA
|
||||||
|
run: |
|
||||||
|
sudo apt-get update && sudo apt-get install ca-certificates
|
||||||
|
sudo update-ca-certificates
|
||||||
|
cp -f /etc/ssl/certs/ca-certificates.crt component/ca/ca-certificates.crt
|
||||||
|
|
||||||
|
- name: Build core
|
||||||
|
env:
|
||||||
|
GOOS: ${{matrix.jobs.goos}}
|
||||||
|
GOARCH: ${{matrix.jobs.goarch}}
|
||||||
|
GOAMD64: ${{matrix.jobs.goamd64}}
|
||||||
|
GO386: ${{matrix.jobs.go386}}
|
||||||
|
GOARM: ${{matrix.jobs.goarm}}
|
||||||
|
GOMIPS: ${{matrix.jobs.gomips}}
|
||||||
|
run: |
|
||||||
|
go env
|
||||||
|
go build -v -tags "with_gvisor" -trimpath -ldflags "${BUILDTAG} -X 'github.com/metacubex/mihomo/constant.Version=${VERSION}' -X 'github.com/metacubex/mihomo/constant.BuildTime=${BUILDTIME}' -w -s -buildid="
|
||||||
|
if [ "${{matrix.jobs.goos}}" = "windows" ]; then
|
||||||
|
cp mihomo.exe mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
||||||
|
zip -r mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.zip mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}.exe
|
||||||
|
else
|
||||||
|
cp mihomo mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
||||||
|
gzip -c mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}} > mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.gz
|
||||||
|
rm mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Package DEB
|
||||||
|
if: matrix.jobs.debian != ''
|
||||||
|
run: |
|
||||||
|
set -xeuo pipefail
|
||||||
|
sudo gem install fpm
|
||||||
|
cp .github/release/.fpm_systemd .fpm
|
||||||
|
|
||||||
|
fpm -t deb \
|
||||||
|
-v "${PackageVersion}" \
|
||||||
|
-p "mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.deb" \
|
||||||
|
--architecture ${{ matrix.jobs.debian }} \
|
||||||
|
mihomo=/usr/bin/mihomo
|
||||||
|
|
||||||
|
- name: Package RPM
|
||||||
|
if: matrix.jobs.rpm != ''
|
||||||
|
run: |
|
||||||
|
set -xeuo pipefail
|
||||||
|
sudo gem install fpm
|
||||||
|
cp .github/release/.fpm_systemd .fpm
|
||||||
|
|
||||||
|
fpm -t rpm \
|
||||||
|
-v "${PackageVersion}" \
|
||||||
|
-p "mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.rpm" \
|
||||||
|
--architecture ${{ matrix.jobs.rpm }} \
|
||||||
|
mihomo=/usr/bin/mihomo
|
||||||
|
|
||||||
|
- name: Package Pacman
|
||||||
|
if: matrix.jobs.pacman != ''
|
||||||
|
run: |
|
||||||
|
set -xeuo pipefail
|
||||||
|
sudo gem install fpm
|
||||||
|
sudo apt-get update && sudo apt-get install -y libarchive-tools
|
||||||
|
cp .github/release/.fpm_systemd .fpm
|
||||||
|
|
||||||
|
fpm -t pacman \
|
||||||
|
-v "${PackageVersion}" \
|
||||||
|
-p "mihomo-${{matrix.jobs.goos}}-${{matrix.jobs.output}}-${VERSION}.pkg.tar.zst" \
|
||||||
|
--architecture ${{ matrix.jobs.pacman }} \
|
||||||
|
mihomo=/usr/bin/mihomo
|
||||||
|
|
||||||
|
- name: Save version
|
||||||
|
run: |
|
||||||
|
echo ${VERSION} > version.txt
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Archive production artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: "${{ matrix.jobs.goos }}-${{ matrix.jobs.output }}"
|
||||||
|
path: |
|
||||||
|
mihomo*.gz
|
||||||
|
mihomo*.deb
|
||||||
|
mihomo*.rpm
|
||||||
|
mihomo*.pkg.tar.zst
|
||||||
|
mihomo*.zip
|
||||||
|
version.txt
|
||||||
|
checksums.txt
|
||||||
|
|
||||||
|
Upload-Prerelease:
|
||||||
|
permissions: write-all
|
||||||
|
if: ${{ github.event_name != 'workflow_dispatch' && github.ref_type == 'branch' && !startsWith(github.event_name, 'pull_request') }}
|
||||||
|
needs: [build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Download all workflow run artifacts
|
||||||
|
uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Calculate checksums
|
||||||
|
run: |
|
||||||
|
cd bin/
|
||||||
|
find . -type f -not -name "checksums.*" -not -name "version.txt" | sort | xargs sha256sum > checksums.txt
|
||||||
|
cat checksums.txt
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Delete current release assets
|
||||||
|
uses: 8Mi-Tech/delete-release-assets-action@main
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
- name: Set Env
|
||||||
|
run: |
|
||||||
|
echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
- name: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- run: |
|
||||||
|
cat > release.txt << 'EOF'
|
||||||
|
Release created at ${{ env.BUILDTIME }}
|
||||||
|
Synchronize ${{ github.ref_name }} branch code updates, keeping only the latest version
|
||||||
|
<br>
|
||||||
|
[我应该下载哪个文件? / Which file should I download?](https://github.com/MetaCubeX/mihomo/wiki/FAQ)
|
||||||
|
[二进制文件筛选 / Binary file selector](https://metacubex.github.io/Meta-Docs/startup/#_1)
|
||||||
|
[查看文档 / Docs](https://metacubex.github.io/Meta-Docs/)
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Upload Prerelease
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
files: |
|
||||||
|
bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
||||||
|
body_path: release.txt
|
||||||
|
|
||||||
|
Upload-Release:
|
||||||
|
permissions: write-all
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
|
needs: [build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
ref: Meta
|
||||||
|
fetch-depth: '0'
|
||||||
|
fetch-tags: 'true'
|
||||||
|
|
||||||
|
- name: Get tags
|
||||||
|
run: |
|
||||||
|
echo "CURRENTVERSION=${{ github.event.inputs.version }}" >> $GITHUB_ENV
|
||||||
|
git fetch --tags
|
||||||
|
echo "PREVERSION=$(git describe --tags --abbrev=0 HEAD)" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Force push Alpha branch to Meta
|
||||||
|
run: |
|
||||||
|
git config --global user.email "github-actions[bot]@users.noreply.github.com"
|
||||||
|
git config --global user.name "github-actions[bot]"
|
||||||
|
git fetch origin Alpha:Alpha
|
||||||
|
git push origin Alpha:Meta --force
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Tag the commit on Alpha
|
||||||
|
run: |
|
||||||
|
git checkout Alpha
|
||||||
|
git tag ${{ github.event.inputs.version }}
|
||||||
|
git push origin ${{ github.event.inputs.version }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Generate release notes
|
||||||
|
run: |
|
||||||
|
cp ./.github/genReleaseNote.sh ./
|
||||||
|
bash ./genReleaseNote.sh -v ${PREVERSION}...${CURRENTVERSION}
|
||||||
|
rm ./genReleaseNote.sh
|
||||||
|
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Upload Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.event.inputs.version }}
|
||||||
|
files: bin/*
|
||||||
|
body_path: release.md
|
||||||
|
|
||||||
|
Docker:
|
||||||
|
if: ${{ !startsWith(github.event_name, 'pull_request') }}
|
||||||
|
permissions: write-all
|
||||||
|
needs: [build]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v5
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: bin/
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Display structure of downloaded files
|
||||||
|
run: ls -R
|
||||||
|
working-directory: bin
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: Setup Docker buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
if: ${{ github.event_name != 'workflow_dispatch' }}
|
||||||
|
id: meta_alpha
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: '${{ env.REGISTRY }}/${{ github.repository }}'
|
||||||
|
|
||||||
|
# Extract metadata (tags, labels) for Docker
|
||||||
|
# https://github.com/docker/metadata-action
|
||||||
|
- name: Extract Docker metadata
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
|
id: meta_release
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: '${{ env.REGISTRY }}/${{ github.repository }}'
|
||||||
|
tags: |
|
||||||
|
${{ github.event.inputs.version }}
|
||||||
|
flavor: |
|
||||||
|
latest=true
|
||||||
|
labels: org.opencontainers.image.version=${{ github.event.inputs.version }}
|
||||||
|
|
||||||
|
- name: Show files
|
||||||
|
run: |
|
||||||
|
ls .
|
||||||
|
ls bin/
|
||||||
|
|
||||||
|
- name: login to docker REGISTRY
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.REGISTRY }}
|
||||||
|
username: ${{ secrets.DOCKER_HUB_USER }}
|
||||||
|
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||||
|
|
||||||
|
# Build and push Docker image with Buildx (don't push on PR)
|
||||||
|
# https://github.com/docker/build-push-action
|
||||||
|
- name: Build and push Docker image
|
||||||
|
if: ${{ github.event_name != 'workflow_dispatch' }}
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
platforms: |
|
||||||
|
linux/386
|
||||||
|
linux/amd64
|
||||||
|
linux/arm64
|
||||||
|
linux/arm/v7
|
||||||
|
tags: ${{ steps.meta_alpha.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta_alpha.outputs.labels }}
|
||||||
|
|
||||||
|
- name: Build and push Docker image
|
||||||
|
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.version != '' }}
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
file: ./Dockerfile
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
platforms: |
|
||||||
|
linux/386
|
||||||
|
linux/amd64
|
||||||
|
linux/arm64
|
||||||
|
linux/arm/v7
|
||||||
|
tags: ${{ steps.meta_release.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta_release.outputs.labels }}
|
||||||
61
.github/workflows/docker.yaml
vendored
61
.github/workflows/docker.yaml
vendored
@@ -1,61 +0,0 @@
|
|||||||
name: Docker
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Beta
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
env:
|
|
||||||
REGISTRY: docker.io
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
# Extract metadata (tags, labels) for Docker
|
|
||||||
# https://github.com/docker/metadata-action
|
|
||||||
- name: Extract Docker metadata
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v3
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY }}/${{ secrets.DOCKERHUB_ACCOUNT }}/${{secrets.DOCKERHUB_REPO}}
|
|
||||||
|
|
||||||
- name: Log into registry
|
|
||||||
if: github.event_name != 'pull_request'
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ${{ env.REGISTRY }}
|
|
||||||
username: ${{ secrets.DOCKER_HUB_USER }}
|
|
||||||
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
|
||||||
|
|
||||||
# Build and push Docker image with Buildx (don't push on PR)
|
|
||||||
# https://github.com/docker/build-push-action
|
|
||||||
- name: Build and push Docker image
|
|
||||||
id: build-and-push
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
file: ./Dockerfile
|
|
||||||
push: ${{ github.event_name != 'pull_request' }}
|
|
||||||
platforms: |
|
|
||||||
linux/386
|
|
||||||
linux/amd64
|
|
||||||
linux/arm64/v8
|
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
|
||||||
70
.github/workflows/prerelease.yml
vendored
70
.github/workflows/prerelease.yml
vendored
@@ -1,70 +0,0 @@
|
|||||||
name: Prerelease
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- Alpha
|
|
||||||
- Beta
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/go/pkg/mod
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
if: ${{env.GITHUB_REF_NAME=='Beta'}}
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j releases
|
|
||||||
|
|
||||||
- name: Delete current release assets
|
|
||||||
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
|
||||||
with:
|
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
tag: Prerelease-${{env.GITHUB_REF_NAME}}
|
|
||||||
deleteOnlyFromDrafts: false
|
|
||||||
|
|
||||||
- name: Tag Repo
|
|
||||||
uses: richardsimko/update-tag@v1
|
|
||||||
with:
|
|
||||||
tag_name: Prerelease-${{env.GITHUB_REF_NAME}}
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Upload Alpha
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() }}
|
|
||||||
with:
|
|
||||||
tag: ${{env.GITHUB_REF_NAME}}
|
|
||||||
tag_name: Prerelease-${{env.GITHUB_REF_NAME}}
|
|
||||||
files: bin/*
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
44
.github/workflows/release.yaml
vendored
44
.github/workflows/release.yaml
vendored
@@ -1,44 +0,0 @@
|
|||||||
name: Release
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- "v*"
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Get latest go version
|
|
||||||
id: version
|
|
||||||
run: |
|
|
||||||
echo ::set-output name=go_version::$(curl -s https://raw.githubusercontent.com/actions/go-versions/main/versions-manifest.json | grep -oE '"version": "[0-9]{1}.[0-9]{1,}(.[0-9]{1,})?"' | head -1 | cut -d':' -f2 | sed 's/ //g; s/"//g')
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: ${{ steps.version.outputs.go_version }}
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/go/pkg/mod
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
- name: Test
|
|
||||||
run: |
|
|
||||||
go test ./...
|
|
||||||
- name: Build
|
|
||||||
if: success()
|
|
||||||
env:
|
|
||||||
NAME: Clash.Meta
|
|
||||||
BINDIR: bin
|
|
||||||
run: make -j releases
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: ${{ success() && startsWith(github.ref, 'refs/tags/')}}
|
|
||||||
with:
|
|
||||||
tag: ${{ github.ref }}
|
|
||||||
files: bin/*
|
|
||||||
generate_release_notes: true
|
|
||||||
68
.github/workflows/test.yml
vendored
Normal file
68
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
name: Test
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "docs/**"
|
||||||
|
- "README.md"
|
||||||
|
- ".github/ISSUE_TEMPLATE/**"
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os:
|
||||||
|
- 'ubuntu-latest' # amd64 linux
|
||||||
|
- 'windows-latest' # amd64 windows
|
||||||
|
- 'macos-latest' # arm64 macos
|
||||||
|
- 'ubuntu-24.04-arm' # arm64 linux
|
||||||
|
- 'macos-15-intel' # amd64 macos
|
||||||
|
go-version:
|
||||||
|
- '1.26'
|
||||||
|
- '1.25'
|
||||||
|
- '1.24'
|
||||||
|
- '1.23'
|
||||||
|
- '1.22'
|
||||||
|
- '1.21'
|
||||||
|
- '1.20'
|
||||||
|
fail-fast: false
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
CGO_ENABLED: 0
|
||||||
|
GOTOOLCHAIN: local
|
||||||
|
# Fix mingw trying to be smart and converting paths https://github.com/moby/moby/issues/24029#issuecomment-250412919
|
||||||
|
MSYS_NO_PATHCONV: true
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v5
|
||||||
|
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v6
|
||||||
|
with:
|
||||||
|
go-version: ${{ matrix.go-version }}
|
||||||
|
check-latest: true # Always check for the latest patch release
|
||||||
|
|
||||||
|
- name: Revert Golang commit for Windows7/8
|
||||||
|
if: ${{ runner.os == 'Windows' && matrix.go-version != '1.20' }}
|
||||||
|
run: |
|
||||||
|
cd $(go env GOROOT)
|
||||||
|
patch --verbose -p 1 < $GITHUB_WORKSPACE/.github/patch/go${{matrix.go-version}}.patch
|
||||||
|
|
||||||
|
- name: Remove inbound test for macOS
|
||||||
|
if: ${{ runner.os == 'macOS' }}
|
||||||
|
run: |
|
||||||
|
rm -rf listener/inbound/*_test.go
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: go test ./... -v -count=1
|
||||||
|
|
||||||
|
- name: Test with tag with_gvisor
|
||||||
|
run: go test ./... -v -count=1 -tags "with_gvisor"
|
||||||
30
.github/workflows/trigger-cmfa-update.yml
vendored
Normal file
30
.github/workflows/trigger-cmfa-update.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
name: Trigger CMFA Update
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
paths-ignore:
|
||||||
|
- "docs/**"
|
||||||
|
- "README.md"
|
||||||
|
- ".github/ISSUE_TEMPLATE/**"
|
||||||
|
branches:
|
||||||
|
- Alpha
|
||||||
|
tags:
|
||||||
|
- "v*"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
# Send "core-updated" to MetaCubeX/ClashMetaForAndroid to trigger update-dependencies
|
||||||
|
trigger-CMFA-update:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: tibdex/github-app-token@v1
|
||||||
|
id: generate-token
|
||||||
|
with:
|
||||||
|
app_id: ${{ secrets.MAINTAINER_APPID }}
|
||||||
|
private_key: ${{ secrets.MAINTAINER_APP_PRIVATE_KEY }}
|
||||||
|
|
||||||
|
- name: Trigger update-dependencies
|
||||||
|
run: |
|
||||||
|
curl -X POST https://api.github.com/repos/MetaCubeX/ClashMetaForAndroid/dispatches \
|
||||||
|
-H "Accept: application/vnd.github.everest-preview+json" \
|
||||||
|
-H "Authorization: token ${{ steps.generate-token.outputs.token }}" \
|
||||||
|
-d '{"event_type": "core-updated"}'
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -24,4 +24,5 @@ vendor
|
|||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
/output
|
/output
|
||||||
/.vscode
|
.vscode/
|
||||||
|
.fleet/
|
||||||
@@ -8,9 +8,10 @@ linters:
|
|||||||
|
|
||||||
linters-settings:
|
linters-settings:
|
||||||
gci:
|
gci:
|
||||||
|
custom-order: true
|
||||||
sections:
|
sections:
|
||||||
- standard
|
- standard
|
||||||
- prefix(github.com/Dreamacro/clash)
|
- prefix(github.com/metacubex/mihomo)
|
||||||
- default
|
- default
|
||||||
staticcheck:
|
staticcheck:
|
||||||
go: '1.18'
|
go: '1.19'
|
||||||
|
|||||||
40
Dockerfile
40
Dockerfile
@@ -1,26 +1,26 @@
|
|||||||
FROM golang:alpine as builder
|
FROM alpine:latest as builder
|
||||||
|
ARG TARGETPLATFORM
|
||||||
|
RUN echo "I'm building for $TARGETPLATFORM"
|
||||||
|
|
||||||
RUN apk add --no-cache make git && \
|
RUN apk add --no-cache gzip && \
|
||||||
mkdir /clash-config && \
|
mkdir /mihomo-config && \
|
||||||
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
wget -O /mihomo-config/geoip.metadb https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.metadb && \
|
||||||
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
wget -O /mihomo-config/geosite.dat https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geosite.dat && \
|
||||||
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
wget -O /mihomo-config/geoip.dat https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/geoip.dat
|
||||||
|
|
||||||
|
|
||||||
COPY . /clash-src
|
|
||||||
WORKDIR /clash-src
|
|
||||||
RUN go mod download &&\
|
|
||||||
make docker &&\
|
|
||||||
mv ./bin/Clash.Meta-docker /clash
|
|
||||||
|
|
||||||
|
COPY docker/file-name.sh /mihomo/file-name.sh
|
||||||
|
WORKDIR /mihomo
|
||||||
|
COPY bin/ bin/
|
||||||
|
RUN FILE_NAME=`sh file-name.sh` && echo $FILE_NAME && \
|
||||||
|
FILE_NAME=`ls bin/ | egrep "$FILE_NAME.gz"|awk NR==1` && echo $FILE_NAME && \
|
||||||
|
mv bin/$FILE_NAME mihomo.gz && gzip -d mihomo.gz && chmod +x mihomo && echo "$FILE_NAME" > /mihomo-config/test
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/mihomo"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata
|
RUN apk add --no-cache ca-certificates tzdata iptables
|
||||||
|
|
||||||
VOLUME ["/root/.config/clash/"]
|
VOLUME ["/root/.config/mihomo/"]
|
||||||
|
|
||||||
COPY --from=builder /clash-config/ /root/.config/clash/
|
COPY --from=builder /mihomo-config/ /root/.config/mihomo/
|
||||||
COPY --from=builder /clash /clash
|
COPY --from=builder /mihomo/mihomo /mihomo
|
||||||
RUN chmod +x /clash
|
ENTRYPOINT [ "/mihomo" ]
|
||||||
ENTRYPOINT [ "/clash" ]
|
|
||||||
|
|||||||
104
Makefile
104
Makefile
@@ -1,29 +1,35 @@
|
|||||||
NAME=Clash.Meta
|
NAME=mihomo
|
||||||
BINDIR=bin
|
BINDIR=bin
|
||||||
BRANCH=$(shell git branch --show-current)
|
BRANCH=$(shell git branch --show-current)
|
||||||
ifeq ($(BRANCH),Alpha)
|
ifeq ($(BRANCH),Alpha)
|
||||||
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
||||||
else ifeq ($(BRANCH),Beta)
|
else ifeq ($(BRANCH),Beta)
|
||||||
VERSION=beta-$(shell git rev-parse --short HEAD)
|
VERSION=beta-$(shell git rev-parse --short HEAD)
|
||||||
else ifeq ($(BRANCH),HEAD)
|
else ifeq ($(BRANCH),)
|
||||||
VERSION=$(shell git describe --tags)
|
VERSION=$(shell git describe --tags)
|
||||||
else
|
else
|
||||||
VERSION=unknown
|
VERSION=$(shell git rev-parse --short HEAD)
|
||||||
endif
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
GOBUILD=CGO_ENABLED=0 go build -tags with_gvisor -trimpath -ldflags '-X "github.com/metacubex/mihomo/constant.Version=$(VERSION)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-X "github.com/metacubex/mihomo/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-w -s -buildid='
|
-w -s -buildid='
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64v1 \
|
darwin-386 \
|
||||||
darwin-amd64v2 \
|
darwin-amd64-compatible \
|
||||||
darwin-amd64v3 \
|
darwin-amd64 \
|
||||||
|
darwin-amd64-v1 \
|
||||||
|
darwin-amd64-v2 \
|
||||||
|
darwin-amd64-v3 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64v1 \
|
linux-386 \
|
||||||
linux-amd64v2 \
|
linux-amd64-compatible \
|
||||||
linux-amd64v3 \
|
linux-amd64 \
|
||||||
|
linux-amd64-v1 \
|
||||||
|
linux-amd64-v2 \
|
||||||
|
linux-amd64-v3 \
|
||||||
linux-armv5 \
|
linux-armv5 \
|
||||||
linux-armv6 \
|
linux-armv6 \
|
||||||
linux-armv7 \
|
linux-armv7 \
|
||||||
@@ -34,6 +40,8 @@ PLATFORM_LIST = \
|
|||||||
linux-mips-hardfloat \
|
linux-mips-hardfloat \
|
||||||
linux-mipsle-softfloat \
|
linux-mipsle-softfloat \
|
||||||
linux-mipsle-hardfloat \
|
linux-mipsle-hardfloat \
|
||||||
|
linux-riscv64 \
|
||||||
|
linux-loong64 \
|
||||||
android-arm64 \
|
android-arm64 \
|
||||||
freebsd-386 \
|
freebsd-386 \
|
||||||
freebsd-amd64 \
|
freebsd-amd64 \
|
||||||
@@ -41,27 +49,41 @@ PLATFORM_LIST = \
|
|||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
windows-386 \
|
windows-386 \
|
||||||
windows-amd64v1 \
|
windows-amd64-compatible \
|
||||||
windows-amd64v2 \
|
windows-amd64 \
|
||||||
windows-amd64v3 \
|
windows-amd64-v1 \
|
||||||
|
windows-amd64-v2 \
|
||||||
|
windows-amd64-v3 \
|
||||||
windows-arm64 \
|
windows-arm64 \
|
||||||
windows-arm32v7
|
windows-arm32v7
|
||||||
|
|
||||||
all:linux-amd64 linux-arm64\
|
all:linux-amd64-v3 linux-arm64\
|
||||||
darwin-amd64 darwin-arm64\
|
darwin-amd64-v3 darwin-arm64\
|
||||||
windows-amd64 windows-arm64\
|
windows-amd64-v3 windows-arm64\
|
||||||
|
|
||||||
|
|
||||||
|
darwin-all: darwin-amd64-v3 darwin-arm64
|
||||||
|
|
||||||
docker:
|
docker:
|
||||||
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v3:
|
darwin-386:
|
||||||
|
GOARCH=386 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-amd64-compatible:
|
||||||
|
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-amd64:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v2:
|
darwin-amd64-v1:
|
||||||
|
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
darwin-amd64-v2:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-amd64v1:
|
darwin-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=darwin GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@@ -69,14 +91,20 @@ darwin-arm64:
|
|||||||
linux-386:
|
linux-386:
|
||||||
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64v3:
|
linux-amd64-compatible:
|
||||||
|
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-amd64:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64v2:
|
linux-amd64-v1:
|
||||||
|
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-amd64-v2:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64v1:
|
linux-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=linux GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-arm64:
|
linux-arm64:
|
||||||
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
@@ -108,6 +136,12 @@ linux-mips64:
|
|||||||
linux-mips64le:
|
linux-mips64le:
|
||||||
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-riscv64:
|
||||||
|
GOARCH=riscv64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-loong64:
|
||||||
|
GOARCH=loong64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
android-arm64:
|
android-arm64:
|
||||||
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
@@ -123,14 +157,20 @@ freebsd-arm64:
|
|||||||
windows-386:
|
windows-386:
|
||||||
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v3:
|
windows-amd64-compatible:
|
||||||
|
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v2:
|
windows-amd64-v1:
|
||||||
|
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-amd64-v2:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-amd64v1:
|
windows-amd64-v3:
|
||||||
GOARCH=amd64 GOOS=windows GOAMD64=v1 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
windows-arm64:
|
windows-arm64:
|
||||||
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
@@ -160,3 +200,7 @@ lint:
|
|||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm $(BINDIR)/*
|
rm $(BINDIR)/*
|
||||||
|
|
||||||
|
CLANG ?= clang-14
|
||||||
|
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
||||||
|
|
||||||
|
|||||||
289
README.md
289
README.md
@@ -3,17 +3,17 @@
|
|||||||
<br>Meta Kernel<br>
|
<br>Meta Kernel<br>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h3 align="center">Another Clash Kernel.</h3>
|
<h3 align="center">Another Mihomo Kernel.</h3>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
<a href="https://goreportcard.com/report/github.com/MetaCubeX/mihomo">
|
||||||
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?style=flat-square">
|
<img src="https://goreportcard.com/badge/github.com/MetaCubeX/mihomo?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<img src="https://img.shields.io/github/go-mod/go-version/Dreamacro/clash?style=flat-square">
|
<img src="https://img.shields.io/github/go-mod/go-version/MetaCubeX/mihomo/Alpha?style=flat-square">
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
<a href="https://github.com/MetaCubeX/mihomo/releases">
|
||||||
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/MetaCubeX/mihomo/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/Clash-Mini/Clash.Meta">
|
<a href="https://github.com/MetaCubeX/mihomo">
|
||||||
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
@@ -21,199 +21,55 @@
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Local HTTP/HTTPS/SOCKS server with authentication support
|
- Local HTTP/HTTPS/SOCKS server with authentication support
|
||||||
- VMess, Shadowsocks, Trojan, Snell protocol support for remote connections
|
- VMess, VLESS, Shadowsocks, Trojan, Snell, TUIC, Hysteria protocol support
|
||||||
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
- Built-in DNS server that aims to minimize DNS pollution attack impact, supports DoH/DoT upstream and fake IP.
|
||||||
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
- Rules based off domains, GEOIP, IPCIDR or Process to forward packets to different nodes
|
||||||
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node based off latency
|
- Remote groups allow users to implement powerful rules. Supports automatic fallback, load balancing or auto select node
|
||||||
- Remote providers, allowing users to get node lists remotely instead of hardcoding in config
|
based off latency
|
||||||
- Netfilter TCP redirecting. Deploy Clash on your Internet gateway with `iptables`.
|
- Remote providers, allowing users to get node lists remotely instead of hard-coding in config
|
||||||
|
- Netfilter TCP redirecting. Deploy Mihomo on your Internet gateway with `iptables`.
|
||||||
- Comprehensive HTTP RESTful API controller
|
- Comprehensive HTTP RESTful API controller
|
||||||
|
|
||||||
## Getting Started
|
## Dashboard
|
||||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
|
||||||
|
|
||||||
## Advanced usage for this branch
|
A web dashboard with first-class support for this project has been created; it can be checked out at [metacubexd](https://github.com/MetaCubeX/metacubexd).
|
||||||
|
|
||||||
### DNS configuration
|
## Configration example
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Configuration example is located at [/docs/config.yaml](https://github.com/MetaCubeX/mihomo/blob/Alpha/docs/config.yaml).
|
||||||
|
|
||||||
Restore `Redir remote resolution`.
|
## Docs
|
||||||
|
|
||||||
Support resolve ip with a `Proxy Tunnel`.
|
Documentation can be found in [mihomo Docs](https://wiki.metacubex.one/).
|
||||||
|
|
||||||
```yaml
|
## For development
|
||||||
proxy-groups:
|
|
||||||
|
|
||||||
- name: DNS
|
Requirements:
|
||||||
type: url-test
|
[Go 1.20 or newer](https://go.dev/dl/)
|
||||||
use:
|
|
||||||
- HK
|
Build mihomo:
|
||||||
url: http://cp.cloudflare.com
|
|
||||||
interval: 180
|
```shell
|
||||||
lazy: true
|
git clone https://github.com/MetaCubeX/mihomo.git
|
||||||
```
|
cd mihomo && go mod download
|
||||||
```yaml
|
go build
|
||||||
dns:
|
|
||||||
enable: true
|
|
||||||
use-hosts: true
|
|
||||||
ipv6: false
|
|
||||||
enhanced-mode: redir-host
|
|
||||||
fake-ip-range: 198.18.0.1/16
|
|
||||||
listen: 127.0.0.1:6868
|
|
||||||
default-nameserver:
|
|
||||||
- 119.29.29.29
|
|
||||||
- 114.114.114.114
|
|
||||||
nameserver:
|
|
||||||
- https://doh.pub/dns-query
|
|
||||||
- tls://223.5.5.5:853
|
|
||||||
fallback:
|
|
||||||
- 'https://1.0.0.1/dns-query#DNS' # append the proxy adapter name or group name to the end of DNS URL with '#' prefix.
|
|
||||||
- 'tls://8.8.4.4:853#DNS'
|
|
||||||
fallback-filter:
|
|
||||||
geoip: false
|
|
||||||
geosite:
|
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to unsafe DNS providers.
|
|
||||||
domain:
|
|
||||||
- +.example.com
|
|
||||||
ipcidr:
|
|
||||||
- 0.0.0.0/32
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### TUN configuration
|
Set go proxy if a connection to GitHub is not possible:
|
||||||
|
|
||||||
Supports macOS, Linux and Windows.
|
```shell
|
||||||
|
go env -w GOPROXY=https://goproxy.io,direct
|
||||||
Built-in [Wintun](https://www.wintun.net) driver.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
# Enable the TUN listener
|
|
||||||
tun:
|
|
||||||
enable: true
|
|
||||||
stack: gvisor # only gvisor
|
|
||||||
dns-hijack:
|
|
||||||
- 0.0.0.0:53 # additional dns server listen on TUN
|
|
||||||
auto-route: true # auto set global route
|
|
||||||
```
|
|
||||||
### Rules configuration
|
|
||||||
- Support rule `GEOSITE`.
|
|
||||||
- Support rule-providers `RULE-SET`.
|
|
||||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
|
||||||
- Support `network` condition for all rules.
|
|
||||||
- Support source IPCIDR condition for all rules, just append to the end.
|
|
||||||
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
|
||||||
```yaml
|
|
||||||
rules:
|
|
||||||
|
|
||||||
# network(tcp/udp) condition for all rules
|
|
||||||
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
|
||||||
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
|
||||||
|
|
||||||
# rule GEOSITE
|
|
||||||
- GEOSITE,category-ads-all,REJECT
|
|
||||||
- GEOSITE,icloud@cn,DIRECT
|
|
||||||
- GEOSITE,apple@cn,DIRECT
|
|
||||||
- GEOSITE,apple-cn,DIRECT
|
|
||||||
- GEOSITE,microsoft@cn,DIRECT
|
|
||||||
- GEOSITE,facebook,PROXY
|
|
||||||
- GEOSITE,youtube,PROXY
|
|
||||||
- GEOSITE,geolocation-cn,DIRECT
|
|
||||||
- GEOSITE,geolocation-!cn,PROXY
|
|
||||||
|
|
||||||
# source IPCIDR condition for all rules in gateway proxy
|
|
||||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
|
||||||
|
|
||||||
- GEOIP,telegram,PROXY,no-resolve
|
|
||||||
- GEOIP,private,DIRECT,no-resolve
|
|
||||||
- GEOIP,cn,DIRECT
|
|
||||||
|
|
||||||
- MATCH,PROXY
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Build with gvisor tun stack:
|
||||||
|
|
||||||
### Proxies configuration
|
```shell
|
||||||
|
go build -tags with_gvisor
|
||||||
Active health detection `urltest / fallback` (based on tcp handshake, multiple failures within a limited time will actively trigger health detection to use the node)
|
|
||||||
|
|
||||||
Support `Policy Group Filter`
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
proxy-groups:
|
|
||||||
|
|
||||||
- name: 🚀 HK Group
|
|
||||||
type: select
|
|
||||||
use:
|
|
||||||
- ALL
|
|
||||||
filter: 'HK'
|
|
||||||
|
|
||||||
- name: 🚀 US Group
|
|
||||||
type: select
|
|
||||||
use:
|
|
||||||
- ALL
|
|
||||||
filter: 'US'
|
|
||||||
|
|
||||||
proxy-providers:
|
|
||||||
ALL:
|
|
||||||
type: http
|
|
||||||
url: "xxxxx"
|
|
||||||
interval: 3600
|
|
||||||
path: "xxxxx"
|
|
||||||
health-check:
|
|
||||||
enable: true
|
|
||||||
interval: 600
|
|
||||||
url: http://www.gstatic.com/generate_204
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Support outbound transport protocol `VLESS`.
|
|
||||||
|
|
||||||
The XTLS support (TCP/UDP) transport by the XRAY-CORE.
|
|
||||||
```yaml
|
|
||||||
proxies:
|
|
||||||
- name: "vless"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
servername: example.com # AKA SNI
|
|
||||||
# flow: xtls-rprx-direct # xtls-rprx-origin # enable XTLS
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
- name: "vless-ws"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
tls: true
|
|
||||||
udp: true
|
|
||||||
network: ws
|
|
||||||
servername: example.com # priority over wss host
|
|
||||||
# skip-cert-verify: true
|
|
||||||
ws-opts:
|
|
||||||
path: /path
|
|
||||||
headers: { Host: example.com, Edge: "12a00c4.fm.huawei.com:82897" }
|
|
||||||
|
|
||||||
- name: "vless-grpc"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
tls: true
|
|
||||||
udp: true
|
|
||||||
network: grpc
|
|
||||||
servername: example.com # priority over wss host
|
|
||||||
# skip-cert-verify: true
|
|
||||||
grpc-opts:
|
|
||||||
grpc-service-name: grpcname
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### IPTABLES configuration
|
### IPTABLES configuration
|
||||||
Work on Linux OS who's supported `iptables`
|
|
||||||
|
Work on Linux OS which supported `iptables`
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# Enable the TPROXY listener
|
# Enable the TPROXY listener
|
||||||
@@ -224,75 +80,22 @@ iptables:
|
|||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
|
||||||
### General installation guide for Linux
|
Check [wiki](https://wiki.metacubex.one/api/#debug) to get an instruction on using debug
|
||||||
+ Create user given name `clash-meta`
|
API.
|
||||||
|
|
||||||
+ Download and decompress pre-built binaries from [releases](https://github.com/MetaCubeX/Clash.Meta/releases)
|
|
||||||
|
|
||||||
+ Rename executable file to `Clash-Meta` and move to `/usr/local/bin/`
|
|
||||||
|
|
||||||
+ Create folder `/etc/Clash-Meta/` as working directory
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Run Meta Kernel by user `clash-meta` as a daemon.
|
|
||||||
|
|
||||||
Create the systemd configuration file at `/etc/systemd/system/Clash-Meta.service`:
|
|
||||||
|
|
||||||
```
|
|
||||||
[Unit]
|
|
||||||
Description=Clash-Meta Daemon, Another Clash Kernel.
|
|
||||||
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
User=clash-meta
|
|
||||||
Group=clash-meta
|
|
||||||
LimitNPROC=500
|
|
||||||
LimitNOFILE=1000000
|
|
||||||
CapabilityBoundingSet=cap_net_admin
|
|
||||||
AmbientCapabilities=cap_net_admin
|
|
||||||
Restart=always
|
|
||||||
ExecStartPre=/usr/bin/sleep 1s
|
|
||||||
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
```
|
|
||||||
Launch clashd on system startup with:
|
|
||||||
```shell
|
|
||||||
$ systemctl enable Clash-Meta
|
|
||||||
```
|
|
||||||
Launch clashd immediately with:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ systemctl start Clash-Meta
|
|
||||||
```
|
|
||||||
|
|
||||||
### Display Process name
|
|
||||||
|
|
||||||
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
|
||||||
|
|
||||||
To display process name in GUI please use [Dashboard For Meta](https://github.com/Clash-Mini/Dashboard).
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
If you want to build an application that uses clash as a library, check out the
|
|
||||||
the [GitHub Wiki](https://github.com/Dreamacro/clash/wiki/use-clash-as-a-library)
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
* [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
- [Dreamacro/clash](https://github.com/Dreamacro/clash)
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
- [SagerNet/sing-box](https://github.com/SagerNet/sing-box)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
- [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
- [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
- [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
|
- [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
This software is released under the GPL-3.0 license.
|
This software is released under the GPL-3.0 license.
|
||||||
|
|
||||||
[](https://app.fossa.io/projects/git%2Bgithub.com%2FDreamacro%2Fclash?ref=badge_large)
|
**In addition, any downstream projects not affiliated with `MetaCubeX` shall not contain the word `mihomo` in their names.**
|
||||||
@@ -5,61 +5,62 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/netip"
|
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/common/queue"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
"github.com/metacubex/mihomo/common/xsync"
|
||||||
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"github.com/metacubex/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
var UnifiedDelay = atomic.NewBool(false)
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
|
|
||||||
type Proxy struct {
|
const (
|
||||||
C.ProxyAdapter
|
defaultHistoriesNum = 10
|
||||||
|
)
|
||||||
|
|
||||||
|
type internalProxyState struct {
|
||||||
|
alive atomic.Bool
|
||||||
history *queue.Queue[C.DelayHistory]
|
history *queue.Queue[C.DelayHistory]
|
||||||
alive *atomic.Bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Alive implements C.Proxy
|
type Proxy struct {
|
||||||
func (p *Proxy) Alive() bool {
|
C.ProxyAdapter
|
||||||
|
alive atomic.Bool
|
||||||
|
history *queue.Queue[C.DelayHistory]
|
||||||
|
extra xsync.Map[string, *internalProxyState]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adapter implements C.Proxy
|
||||||
|
func (p *Proxy) Adapter() C.ProxyAdapter {
|
||||||
|
return p.ProxyAdapter
|
||||||
|
}
|
||||||
|
|
||||||
|
// AliveForTestUrl implements C.Proxy
|
||||||
|
func (p *Proxy) AliveForTestUrl(url string) bool {
|
||||||
|
if state, ok := p.extra.Load(url); ok {
|
||||||
|
return state.alive.Load()
|
||||||
|
}
|
||||||
|
|
||||||
return p.alive.Load()
|
return p.alive.Load()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dial implements C.Proxy
|
|
||||||
func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTCPTimeout)
|
|
||||||
defer cancel()
|
|
||||||
return p.DialContext(ctx, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (p *Proxy) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata)
|
||||||
wasCancel := false
|
|
||||||
if err != nil {
|
|
||||||
wasCancel = strings.Contains(err.Error(), "operation was canceled")
|
|
||||||
}
|
|
||||||
p.alive.Store(err == nil || wasCancel)
|
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialUDP implements C.ProxyAdapter
|
|
||||||
func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultUDPTimeout)
|
|
||||||
defer cancel()
|
|
||||||
return p.ListenPacketContext(ctx, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (p *Proxy) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata)
|
||||||
p.alive.Store(err == nil)
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,17 +74,60 @@ func (p *Proxy) DelayHistory() []C.DelayHistory {
|
|||||||
return histories
|
return histories
|
||||||
}
|
}
|
||||||
|
|
||||||
// LastDelay return last history record. if proxy is not alive, return the max value of uint16.
|
// DelayHistoryForTestUrl implements C.Proxy
|
||||||
|
func (p *Proxy) DelayHistoryForTestUrl(url string) []C.DelayHistory {
|
||||||
|
var queueM []C.DelayHistory
|
||||||
|
|
||||||
|
if state, ok := p.extra.Load(url); ok {
|
||||||
|
queueM = state.history.Copy()
|
||||||
|
}
|
||||||
|
histories := []C.DelayHistory{}
|
||||||
|
for _, item := range queueM {
|
||||||
|
histories = append(histories, item)
|
||||||
|
}
|
||||||
|
return histories
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExtraDelayHistories return all delay histories for each test URL
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) LastDelay() (delay uint16) {
|
func (p *Proxy) ExtraDelayHistories() map[string]C.ProxyState {
|
||||||
var max uint16 = 0xffff
|
histories := map[string]C.ProxyState{}
|
||||||
if !p.alive.Load() {
|
|
||||||
return max
|
p.extra.Range(func(k string, v *internalProxyState) bool {
|
||||||
|
testUrl := k
|
||||||
|
state := v
|
||||||
|
|
||||||
|
queueM := state.history.Copy()
|
||||||
|
var history []C.DelayHistory
|
||||||
|
|
||||||
|
for _, item := range queueM {
|
||||||
|
history = append(history, item)
|
||||||
|
}
|
||||||
|
|
||||||
|
histories[testUrl] = C.ProxyState{
|
||||||
|
Alive: state.alive.Load(),
|
||||||
|
History: history,
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
return histories
|
||||||
|
}
|
||||||
|
|
||||||
|
// LastDelayForTestUrl return last history record of the specified URL. if proxy is not alive, return the max value of uint16.
|
||||||
|
// implements C.Proxy
|
||||||
|
func (p *Proxy) LastDelayForTestUrl(url string) (delay uint16) {
|
||||||
|
var maxDelay uint16 = 0xffff
|
||||||
|
|
||||||
|
alive := false
|
||||||
|
var history C.DelayHistory
|
||||||
|
|
||||||
|
if state, ok := p.extra.Load(url); ok {
|
||||||
|
alive = state.alive.Load()
|
||||||
|
history = state.history.Last()
|
||||||
}
|
}
|
||||||
|
|
||||||
history := p.history.Last()
|
if !alive || history.Delay == 0 {
|
||||||
if history.Delay == 0 {
|
return maxDelay
|
||||||
return max
|
|
||||||
}
|
}
|
||||||
return history.Delay
|
return history.Delay
|
||||||
}
|
}
|
||||||
@@ -98,24 +142,61 @@ func (p *Proxy) MarshalJSON() ([]byte, error) {
|
|||||||
mapping := map[string]any{}
|
mapping := map[string]any{}
|
||||||
_ = json.Unmarshal(inner, &mapping)
|
_ = json.Unmarshal(inner, &mapping)
|
||||||
mapping["history"] = p.DelayHistory()
|
mapping["history"] = p.DelayHistory()
|
||||||
|
mapping["extra"] = p.ExtraDelayHistories()
|
||||||
|
mapping["alive"] = p.alive.Load()
|
||||||
mapping["name"] = p.Name()
|
mapping["name"] = p.Name()
|
||||||
mapping["udp"] = p.SupportUDP()
|
mapping["udp"] = p.SupportUDP()
|
||||||
|
mapping["uot"] = p.SupportUOT()
|
||||||
|
|
||||||
|
proxyInfo := p.ProxyInfo()
|
||||||
|
mapping["xudp"] = proxyInfo.XUDP
|
||||||
|
mapping["tfo"] = proxyInfo.TFO
|
||||||
|
mapping["mptcp"] = proxyInfo.MPTCP
|
||||||
|
mapping["smux"] = proxyInfo.SMUX
|
||||||
|
mapping["interface"] = proxyInfo.Interface
|
||||||
|
mapping["routing-mark"] = proxyInfo.RoutingMark
|
||||||
|
mapping["provider-name"] = proxyInfo.ProviderName
|
||||||
|
mapping["dialer-proxy"] = proxyInfo.DialerProxy
|
||||||
|
|
||||||
return json.Marshal(mapping)
|
return json.Marshal(mapping)
|
||||||
}
|
}
|
||||||
|
|
||||||
// URLTest get the delay for the specified URL
|
// URLTest get the delay for the specified URL
|
||||||
// implements C.Proxy
|
// implements C.Proxy
|
||||||
func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
func (p *Proxy) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (t uint16, err error) {
|
||||||
|
var satisfied bool
|
||||||
|
|
||||||
defer func() {
|
defer func() {
|
||||||
p.alive.Store(err == nil)
|
alive := err == nil
|
||||||
record := C.DelayHistory{Time: time.Now()}
|
record := C.DelayHistory{Time: time.Now()}
|
||||||
if err == nil {
|
if alive {
|
||||||
record.Delay = t
|
record.Delay = t
|
||||||
}
|
}
|
||||||
|
|
||||||
|
p.alive.Store(alive)
|
||||||
p.history.Put(record)
|
p.history.Put(record)
|
||||||
if p.history.Len() > 10 {
|
if p.history.Len() > defaultHistoriesNum {
|
||||||
p.history.Pop()
|
p.history.Pop()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
state, _ := p.extra.LoadOrStoreFn(url, func() *internalProxyState {
|
||||||
|
return &internalProxyState{
|
||||||
|
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
||||||
|
alive: atomic.NewBool(true),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if !satisfied {
|
||||||
|
record.Delay = 0
|
||||||
|
alive = false
|
||||||
|
}
|
||||||
|
|
||||||
|
state.alive.Store(alive)
|
||||||
|
state.history.Put(record)
|
||||||
|
if state.history.Len() > defaultHistoriesNum {
|
||||||
|
state.history.Pop()
|
||||||
|
}
|
||||||
|
|
||||||
}()
|
}()
|
||||||
|
|
||||||
unifiedDelay := UnifiedDelay.Load()
|
unifiedDelay := UnifiedDelay.Load()
|
||||||
@@ -140,6 +221,11 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
req = req.WithContext(ctx)
|
req = req.WithContext(ctx)
|
||||||
|
|
||||||
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{})
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
transport := &http.Transport{
|
transport := &http.Transport{
|
||||||
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
||||||
return instance, nil
|
return instance, nil
|
||||||
@@ -149,34 +235,55 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
IdleConnTimeout: 90 * time.Second,
|
IdleConnTimeout: 90 * time.Second,
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
TLSHandshakeTimeout: 10 * time.Second,
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
ExpectContinueTimeout: 1 * time.Second,
|
||||||
|
TLSClientConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
client := http.Client{
|
client := http.Client{
|
||||||
|
Timeout: 30 * time.Second,
|
||||||
Transport: transport,
|
Transport: transport,
|
||||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||||
return http.ErrUseLastResponse
|
return http.ErrUseLastResponse
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
defer client.CloseIdleConnections()
|
defer client.CloseIdleConnections()
|
||||||
|
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
|
||||||
if unifiedDelay {
|
if unifiedDelay {
|
||||||
start = time.Now()
|
second := time.Now()
|
||||||
resp, err = client.Do(req)
|
var ignoredErr error
|
||||||
if err != nil {
|
var secondResp *http.Response
|
||||||
return
|
secondResp, ignoredErr = client.Do(req)
|
||||||
|
if ignoredErr == nil {
|
||||||
|
resp = secondResp
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
start = second
|
||||||
|
} else {
|
||||||
|
if strings.HasPrefix(url, "http://") {
|
||||||
|
log.Errorln("%s failed to get the second response from %s: %v", p.Name(), url, ignoredErr)
|
||||||
|
log.Warnln("It is recommended to use HTTPS for provider.health-check.url and group.url to ensure better reliability. Due to some proxy providers hijacking test addresses and not being compatible with repeated HEAD requests, using HTTP may result in failed tests.")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ = resp.Body.Close()
|
|
||||||
|
satisfied = resp != nil && (expectedStatus == nil || expectedStatus.Check(uint16(resp.StatusCode)))
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
func NewProxy(adapter C.ProxyAdapter) *Proxy {
|
||||||
return &Proxy{adapter, queue.New[C.DelayHistory](10), atomic.NewBool(true)}
|
return &Proxy{
|
||||||
|
ProxyAdapter: adapter,
|
||||||
|
history: queue.New[C.DelayHistory](defaultHistoriesNum),
|
||||||
|
alive: atomic.NewBool(true),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
||||||
@@ -198,11 +305,6 @@ func urlToMetadata(rawURL string) (addr C.Metadata, err error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
addr = C.Metadata{
|
err = addr.SetRemoteAddress(net.JoinHostPort(u.Hostname(), port))
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: u.Hostname(),
|
|
||||||
DstIP: netip.Addr{},
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
73
adapter/inbound/addition.go
Normal file
73
adapter/inbound/addition.go
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Addition func(metadata *C.Metadata)
|
||||||
|
|
||||||
|
func ApplyAdditions(metadata *C.Metadata, additions ...Addition) {
|
||||||
|
for _, addition := range additions {
|
||||||
|
addition(metadata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithInName(name string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.InName = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithInUser(user string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.InUser = user
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSpecialRules(specialRules string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.SpecialRules = specialRules
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSpecialProxy(specialProxy string) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.SpecialProxy = specialProxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithDstAddr(addr net.Addr) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
_ = metadata.SetRemoteAddr(addr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSrcAddr(addr net.Addr) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
m := C.Metadata{}
|
||||||
|
if err := m.SetRemoteAddr(addr); err == nil {
|
||||||
|
metadata.SrcIP = m.DstIP
|
||||||
|
metadata.SrcPort = m.DstPort
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithInAddr(addr net.Addr) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
m := C.Metadata{}
|
||||||
|
if err := m.SetRemoteAddr(addr); err == nil {
|
||||||
|
metadata.InIP = m.DstIP
|
||||||
|
metadata.InPort = m.DstPort
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithDSCP(dscp uint8) Addition {
|
||||||
|
return func(metadata *C.Metadata) {
|
||||||
|
metadata.DSCP = dscp
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Placeholder(metadata *C.Metadata) {}
|
||||||
38
adapter/inbound/auth.go
Normal file
38
adapter/inbound/auth.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var skipAuthPrefixes []netip.Prefix
|
||||||
|
|
||||||
|
func SetSkipAuthPrefixes(prefixes []netip.Prefix) {
|
||||||
|
skipAuthPrefixes = prefixes
|
||||||
|
}
|
||||||
|
|
||||||
|
func SkipAuthPrefixes() []netip.Prefix {
|
||||||
|
return skipAuthPrefixes
|
||||||
|
}
|
||||||
|
|
||||||
|
func SkipAuthRemoteAddr(addr net.Addr) bool {
|
||||||
|
m := C.Metadata{}
|
||||||
|
if err := m.SetRemoteAddr(addr); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return skipAuth(m.AddrPort().Addr())
|
||||||
|
}
|
||||||
|
|
||||||
|
func SkipAuthRemoteAddress(addr string) bool {
|
||||||
|
m := C.Metadata{}
|
||||||
|
if err := m.SetRemoteAddress(addr); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return skipAuth(m.AddrPort().Addr())
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipAuth(addr netip.Addr) bool {
|
||||||
|
return prefixesContains(skipAuthPrefixes, addr)
|
||||||
|
}
|
||||||
@@ -3,19 +3,18 @@ package inbound
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTP receive normal http request and return HTTPContext
|
// NewHTTP receive normal http request and return HTTPContext
|
||||||
func NewHTTP(target socks5.Addr, source net.Addr, conn net.Conn) *context.ConnContext {
|
func NewHTTP(target socks5.Addr, srcConn net.Conn, conn net.Conn, additions ...Addition) (net.Conn, *C.Metadata) {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = C.HTTP
|
metadata.Type = C.HTTP
|
||||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
metadata.RawSrcAddr = srcConn.RemoteAddr()
|
||||||
metadata.SrcIP = ip
|
metadata.RawDstAddr = srcConn.LocalAddr()
|
||||||
metadata.SrcPort = port
|
ApplyAdditions(metadata, WithSrcAddr(srcConn.RemoteAddr()), WithInAddr(srcConn.LocalAddr()))
|
||||||
}
|
ApplyAdditions(metadata, additions...)
|
||||||
return context.NewConnContext(conn, metadata)
|
return conn, metadata
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,19 +2,19 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
|
||||||
|
"github.com/metacubex/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewHTTPS receive CONNECT request and return ConnContext
|
// NewHTTPS receive CONNECT request and return ConnContext
|
||||||
func NewHTTPS(request *http.Request, conn net.Conn) *context.ConnContext {
|
func NewHTTPS(request *http.Request, conn net.Conn, additions ...Addition) (net.Conn, *C.Metadata) {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPCONNECT
|
metadata.Type = C.HTTPS
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
metadata.RawSrcAddr = conn.RemoteAddr()
|
||||||
metadata.SrcIP = ip
|
metadata.RawDstAddr = conn.LocalAddr()
|
||||||
metadata.SrcPort = port
|
ApplyAdditions(metadata, WithSrcAddr(conn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
||||||
}
|
ApplyAdditions(metadata, additions...)
|
||||||
return context.NewConnContext(conn, metadata)
|
return conn, metadata
|
||||||
}
|
}
|
||||||
|
|||||||
47
adapter/inbound/ipfilter.go
Normal file
47
adapter/inbound/ipfilter.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
var lanAllowedIPs []netip.Prefix
|
||||||
|
var lanDisAllowedIPs []netip.Prefix
|
||||||
|
|
||||||
|
func SetAllowedIPs(prefixes []netip.Prefix) {
|
||||||
|
lanAllowedIPs = prefixes
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetDisAllowedIPs(prefixes []netip.Prefix) {
|
||||||
|
lanDisAllowedIPs = prefixes
|
||||||
|
}
|
||||||
|
|
||||||
|
func AllowedIPs() []netip.Prefix {
|
||||||
|
return lanAllowedIPs
|
||||||
|
}
|
||||||
|
|
||||||
|
func DisAllowedIPs() []netip.Prefix {
|
||||||
|
return lanDisAllowedIPs
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsRemoteAddrDisAllowed(addr net.Addr) bool {
|
||||||
|
m := C.Metadata{}
|
||||||
|
if err := m.SetRemoteAddr(addr); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
ipAddr := m.AddrPort().Addr()
|
||||||
|
if ipAddr.IsValid() {
|
||||||
|
return isAllowed(ipAddr) && !isDisAllowed(ipAddr)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isAllowed(addr netip.Addr) bool {
|
||||||
|
return prefixesContains(lanAllowedIPs, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDisAllowed(addr netip.Addr) bool {
|
||||||
|
return prefixesContains(lanDisAllowedIPs, addr)
|
||||||
|
}
|
||||||
107
adapter/inbound/listen.go
Normal file
107
adapter/inbound/listen.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/keepalive"
|
||||||
|
"github.com/metacubex/mihomo/component/mptcp"
|
||||||
|
|
||||||
|
"github.com/metacubex/tfo-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
lc = tfo.ListenConfig{
|
||||||
|
DisableTFO: true,
|
||||||
|
}
|
||||||
|
mutex sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func SetTfo(open bool) {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
|
lc.DisableTFO = !open
|
||||||
|
}
|
||||||
|
|
||||||
|
func Tfo() bool {
|
||||||
|
mutex.RLock()
|
||||||
|
defer mutex.RUnlock()
|
||||||
|
return !lc.DisableTFO
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetMPTCP(open bool) {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
|
mptcp.SetNetListenConfig(&lc.ListenConfig, open)
|
||||||
|
}
|
||||||
|
|
||||||
|
func MPTCP() bool {
|
||||||
|
mutex.RLock()
|
||||||
|
defer mutex.RUnlock()
|
||||||
|
return mptcp.GetNetListenConfig(&lc.ListenConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
func preResolve(network, address string) (string, error) {
|
||||||
|
switch network { // like net.Resolver.internetAddrList but filter domain to avoid call net.Resolver.lookupIPAddr
|
||||||
|
case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "ip", "ip4", "ip6":
|
||||||
|
if host, port, err := net.SplitHostPort(address); err == nil {
|
||||||
|
switch host {
|
||||||
|
case "localhost":
|
||||||
|
switch network {
|
||||||
|
case "tcp6", "udp6", "ip6":
|
||||||
|
address = net.JoinHostPort("::1", port)
|
||||||
|
default:
|
||||||
|
address = net.JoinHostPort("127.0.0.1", port)
|
||||||
|
}
|
||||||
|
case "": // internetAddrList can handle this special case
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
if _, err := netip.ParseAddr(host); err != nil { // not ip
|
||||||
|
return "", fmt.Errorf("invalid network address: %s", address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return address, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenContext(ctx context.Context, network, address string) (net.Listener, error) {
|
||||||
|
address, err := preResolve(network, address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
mutex.RLock()
|
||||||
|
defer mutex.RUnlock()
|
||||||
|
return lc.Listen(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Listen(network, address string) (net.Listener, error) {
|
||||||
|
return ListenContext(context.Background(), network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenPacketContext(ctx context.Context, network, address string) (net.PacketConn, error) {
|
||||||
|
address, err := preResolve(network, address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
mutex.RLock()
|
||||||
|
defer mutex.RUnlock()
|
||||||
|
return lc.ListenPacket(ctx, network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListenPacket(network, address string) (net.PacketConn, error) {
|
||||||
|
return ListenPacketContext(context.Background(), network, address)
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
keepalive.SetDisableKeepAliveCallback.Register(func(b bool) {
|
||||||
|
mutex.Lock()
|
||||||
|
defer mutex.Unlock()
|
||||||
|
keepalive.SetNetListenConfig(&lc.ListenConfig)
|
||||||
|
})
|
||||||
|
}
|
||||||
14
adapter/inbound/listen_notwindows.go
Normal file
14
adapter/inbound/listen_notwindows.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
const SupportNamedPipe = false
|
||||||
|
|
||||||
|
func ListenNamedPipe(path string) (net.Listener, error) {
|
||||||
|
return nil, os.ErrInvalid
|
||||||
|
}
|
||||||
32
adapter/inbound/listen_windows.go
Normal file
32
adapter/inbound/listen_windows.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package inbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/metacubex/wireguard-go/ipc/namedpipe"
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
const SupportNamedPipe = true
|
||||||
|
|
||||||
|
// windowsSDDL is the Security Descriptor set on the namedpipe.
|
||||||
|
// It provides read/write access to all users and the local system.
|
||||||
|
const windowsSDDL = "D:PAI(A;OICI;GWGR;;;BU)(A;OICI;GWGR;;;SY)"
|
||||||
|
|
||||||
|
func ListenNamedPipe(path string) (net.Listener, error) {
|
||||||
|
sddl := os.Getenv("LISTEN_NAMEDPIPE_SDDL")
|
||||||
|
if sddl == "" {
|
||||||
|
sddl = windowsSDDL
|
||||||
|
}
|
||||||
|
securityDescriptor, err := windows.SecurityDescriptorFromString(sddl)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
namedpipeLC := namedpipe.ListenConfig{
|
||||||
|
SecurityDescriptor: securityDescriptor,
|
||||||
|
InputBufferSize: 256 * 1024,
|
||||||
|
OutputBufferSize: 256 * 1024,
|
||||||
|
}
|
||||||
|
return namedpipeLC.Listen(path)
|
||||||
|
}
|
||||||
@@ -1,33 +1,22 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PacketAdapter is a UDP Packet adapter for socks/redir/tun
|
|
||||||
type PacketAdapter struct {
|
|
||||||
C.UDPPacket
|
|
||||||
metadata *C.Metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// Metadata returns destination metadata
|
|
||||||
func (s *PacketAdapter) Metadata() *C.Metadata {
|
|
||||||
return s.metadata
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewPacket is PacketAdapter generator
|
// NewPacket is PacketAdapter generator
|
||||||
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type) *PacketAdapter {
|
func NewPacket(target socks5.Addr, packet C.UDPPacket, source C.Type, additions ...Addition) (C.UDPPacket, *C.Metadata) {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.UDP
|
metadata.NetWork = C.UDP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
if ip, port, err := parseAddr(packet.LocalAddr().String()); err == nil {
|
metadata.RawSrcAddr = packet.LocalAddr()
|
||||||
metadata.SrcIP = ip
|
metadata.RawDstAddr = metadata.UDPAddr()
|
||||||
metadata.SrcPort = port
|
ApplyAdditions(metadata, WithSrcAddr(packet.LocalAddr()))
|
||||||
|
if p, ok := packet.(C.UDPPacketInAddr); ok {
|
||||||
|
ApplyAdditions(metadata, WithInAddr(p.InAddr()))
|
||||||
}
|
}
|
||||||
|
ApplyAdditions(metadata, additions...)
|
||||||
|
|
||||||
return &PacketAdapter{
|
return packet, metadata
|
||||||
UDPPacket: packet,
|
|
||||||
metadata: metadata,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,50 +2,17 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewSocket receive TCP inbound and return ConnContext
|
// NewSocket receive TCP inbound and return ConnContext
|
||||||
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnContext {
|
func NewSocket(target socks5.Addr, conn net.Conn, source C.Type, additions ...Addition) (net.Conn, *C.Metadata) {
|
||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
remoteAddr := conn.RemoteAddr()
|
ApplyAdditions(metadata, WithSrcAddr(conn.RemoteAddr()), WithInAddr(conn.LocalAddr()))
|
||||||
// Filter when net.Addr interface is nil
|
ApplyAdditions(metadata, additions...)
|
||||||
if remoteAddr != nil {
|
return conn, metadata
|
||||||
if ip, port, err := parseAddr(remoteAddr.String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewInner(conn net.Conn, dst string, host string) *context.ConnContext {
|
|
||||||
metadata := &C.Metadata{}
|
|
||||||
metadata.NetWork = C.TCP
|
|
||||||
metadata.Type = C.INNER
|
|
||||||
metadata.DNSMode = C.DNSMapping
|
|
||||||
metadata.Host = host
|
|
||||||
metadata.AddrType = C.AtypDomainName
|
|
||||||
metadata.Process = C.ClashName
|
|
||||||
if h, port, err := net.SplitHostPort(dst); err == nil {
|
|
||||||
metadata.DstPort = port
|
|
||||||
if host == "" {
|
|
||||||
if ip, err := netip.ParseAddr(h); err == nil {
|
|
||||||
metadata.DstIP = ip
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
if ip.Is6() {
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.NewConnContext(conn, metadata)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,33 +2,31 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
|
"github.com/metacubex/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{}
|
||||||
AddrType: int(target[0]),
|
|
||||||
}
|
|
||||||
|
|
||||||
switch target[0] {
|
switch target[0] {
|
||||||
case socks5.AtypDomainName:
|
case socks5.AtypDomainName:
|
||||||
// trim for FQDN
|
// trim for FQDN
|
||||||
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
|
metadata.Host = strings.TrimRight(string(target[2:2+target[1]]), ".")
|
||||||
metadata.DstPort = strconv.Itoa((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
metadata.DstPort = uint16((int(target[2+target[1]]) << 8) | int(target[2+target[1]+1]))
|
||||||
case socks5.AtypIPv4:
|
case socks5.AtypIPv4:
|
||||||
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
metadata.DstIP, _ = netip.AddrFromSlice(target[1 : 1+net.IPv4len])
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
metadata.DstPort = uint16((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
||||||
case socks5.AtypIPv6:
|
case socks5.AtypIPv6:
|
||||||
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv6len]))
|
metadata.DstIP, _ = netip.AddrFromSlice(target[1 : 1+net.IPv6len])
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
metadata.DstPort = uint16((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
}
|
}
|
||||||
|
metadata.DstIP = metadata.DstIP.Unmap()
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
@@ -43,34 +41,23 @@ func parseHTTPAddr(request *http.Request) *C.Metadata {
|
|||||||
// trim FQDN (#737)
|
// trim FQDN (#737)
|
||||||
host = strings.TrimRight(host, ".")
|
host = strings.TrimRight(host, ".")
|
||||||
|
|
||||||
metadata := &C.Metadata{
|
metadata := &C.Metadata{}
|
||||||
NetWork: C.TCP,
|
_ = metadata.SetRemoteAddress(net.JoinHostPort(host, port))
|
||||||
AddrType: C.AtypDomainName,
|
|
||||||
Host: host,
|
|
||||||
DstIP: netip.Addr{},
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
|
||||||
if err == nil {
|
|
||||||
switch {
|
|
||||||
case ip.Is6():
|
|
||||||
metadata.AddrType = C.AtypIPv6
|
|
||||||
default:
|
|
||||||
metadata.AddrType = C.AtypIPv4
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
return metadata
|
return metadata
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseAddr(addr string) (netip.Addr, string, error) {
|
func prefixesContains(prefixes []netip.Prefix, addr netip.Addr) bool {
|
||||||
host, port, err := net.SplitHostPort(addr)
|
if len(prefixes) == 0 {
|
||||||
if err != nil {
|
return false
|
||||||
return netip.Addr{}, "", err
|
|
||||||
}
|
}
|
||||||
|
if !addr.IsValid() {
|
||||||
ip, err := netip.ParseAddr(host)
|
return false
|
||||||
return ip, port, err
|
}
|
||||||
|
addr = addr.Unmap().WithZone("") // netip.Prefix.Contains returns false if ip has an IPv6 zone
|
||||||
|
for _, prefix := range prefixes {
|
||||||
|
if prefix.Contains(addr) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|||||||
137
adapter/outbound/anytls.go
Normal file
137
adapter/outbound/anytls.go
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/transport/anytls"
|
||||||
|
"github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
"github.com/metacubex/sing/common/uot"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AnyTLS struct {
|
||||||
|
*Base
|
||||||
|
client *anytls.Client
|
||||||
|
option *AnyTLSOption
|
||||||
|
}
|
||||||
|
|
||||||
|
type AnyTLSOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
IdleSessionCheckInterval int `proxy:"idle-session-check-interval,omitempty"`
|
||||||
|
IdleSessionTimeout int `proxy:"idle-session-timeout,omitempty"`
|
||||||
|
MinIdleSession int `proxy:"min-idle-session,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *AnyTLS) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := t.client.CreateProxy(ctx, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(c, t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *AnyTLS) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if err = t.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// create tcp
|
||||||
|
c, err := t.client.CreateProxy(ctx, uot.RequestDestination(2))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// create uot on tcp
|
||||||
|
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (t *AnyTLS) SupportUOT() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (t *AnyTLS) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := t.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = t.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (t *AnyTLS) Close() error {
|
||||||
|
return t.client.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAnyTLS(option AnyTLSOption) (*AnyTLS, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
outbound := &AnyTLS{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.AnyTLS,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: option.UDP,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
singDialer := proxydialer.NewSingDialer(outbound.dialer)
|
||||||
|
|
||||||
|
tOption := anytls.ClientConfig{
|
||||||
|
Password: option.Password,
|
||||||
|
Server: M.ParseSocksaddrHostPort(option.Server, uint16(option.Port)),
|
||||||
|
Dialer: singDialer,
|
||||||
|
IdleSessionCheckInterval: time.Duration(option.IdleSessionCheckInterval) * time.Second,
|
||||||
|
IdleSessionTimeout: time.Duration(option.IdleSessionTimeout) * time.Second,
|
||||||
|
MinIdleSession: option.MinIdleSession,
|
||||||
|
}
|
||||||
|
echConfig, err := option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tlsConfig := &vmess.TLSConfig{
|
||||||
|
Host: option.SNI,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
NextProtos: option.ALPN,
|
||||||
|
FingerPrint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
ECH: echConfig,
|
||||||
|
}
|
||||||
|
if tlsConfig.Host == "" {
|
||||||
|
tlsConfig.Host = option.Server
|
||||||
|
}
|
||||||
|
tOption.TLSConfig = tlsConfig
|
||||||
|
|
||||||
|
client := anytls.NewClient(context.TODO(), tOption)
|
||||||
|
outbound.client = client
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
@@ -2,24 +2,42 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/sha1"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"regexp"
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type ProxyAdapter interface {
|
||||||
|
C.ProxyAdapter
|
||||||
|
DialOptions() []dialer.Option
|
||||||
|
ResolveUDP(ctx context.Context, metadata *C.Metadata) error
|
||||||
|
}
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
name string
|
name string
|
||||||
addr string
|
addr string
|
||||||
iface string
|
tp C.AdapterType
|
||||||
tp C.AdapterType
|
pdName string
|
||||||
udp bool
|
udp bool
|
||||||
rmark int
|
xudp bool
|
||||||
|
tfo bool
|
||||||
|
mpTcp bool
|
||||||
|
iface string
|
||||||
|
rmark int
|
||||||
|
prefer C.DNSPrefer
|
||||||
|
dialer C.Dialer
|
||||||
|
id string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implements C.ProxyAdapter
|
// Name implements C.ProxyAdapter
|
||||||
@@ -27,24 +45,27 @@ func (b *Base) Name() string {
|
|||||||
return b.name
|
return b.name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Id implements C.ProxyAdapter
|
||||||
|
func (b *Base) Id() string {
|
||||||
|
if b.id == "" {
|
||||||
|
b.id = utils.NewUUIDV6().String()
|
||||||
|
}
|
||||||
|
|
||||||
|
return b.id
|
||||||
|
}
|
||||||
|
|
||||||
// Type implements C.ProxyAdapter
|
// Type implements C.ProxyAdapter
|
||||||
func (b *Base) Type() C.AdapterType {
|
func (b *Base) Type() C.AdapterType {
|
||||||
return b.tp
|
return b.tp
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
return nil, C.ErrNotSupport
|
||||||
return c, errors.New("no support")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, C.ErrNotSupport
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (b *Base) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
return nil, errors.New("no support")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@@ -57,10 +78,28 @@ func (b *Base) SupportUDP() bool {
|
|||||||
return b.udp
|
return b.udp
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (b *Base) ProxyInfo() (info C.ProxyInfo) {
|
||||||
|
info.XUDP = b.xudp
|
||||||
|
info.TFO = b.tfo
|
||||||
|
info.MPTCP = b.mpTcp
|
||||||
|
info.SMUX = false
|
||||||
|
info.Interface = b.iface
|
||||||
|
info.RoutingMark = b.rmark
|
||||||
|
info.ProviderName = b.pdName
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (b *Base) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (b *Base) MarshalJSON() ([]byte, error) {
|
func (b *Base) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]string{
|
return json.Marshal(map[string]string{
|
||||||
"type": b.Type().String(),
|
"type": b.Type().String(),
|
||||||
|
"id": b.Id(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,12 +109,12 @@ func (b *Base) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (b *Base) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialOptions return []dialer.Option from struct
|
// DialOptions return []dialer.Option from struct
|
||||||
func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
func (b *Base) DialOptions() (opts []dialer.Option) {
|
||||||
if b.iface != "" {
|
if b.iface != "" {
|
||||||
opts = append(opts, dialer.WithInterface(b.iface))
|
opts = append(opts, dialer.WithInterface(b.iface))
|
||||||
}
|
}
|
||||||
@@ -84,12 +123,69 @@ func (b *Base) DialOptions(opts ...dialer.Option) []dialer.Option {
|
|||||||
opts = append(opts, dialer.WithRoutingMark(b.rmark))
|
opts = append(opts, dialer.WithRoutingMark(b.rmark))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
switch b.prefer {
|
||||||
|
case C.IPv4Only:
|
||||||
|
opts = append(opts, dialer.WithOnlySingleStack(true))
|
||||||
|
case C.IPv6Only:
|
||||||
|
opts = append(opts, dialer.WithOnlySingleStack(false))
|
||||||
|
case C.IPv4Prefer:
|
||||||
|
opts = append(opts, dialer.WithPreferIPv4())
|
||||||
|
case C.IPv6Prefer:
|
||||||
|
opts = append(opts, dialer.WithPreferIPv6())
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.tfo {
|
||||||
|
opts = append(opts, dialer.WithTFO(true))
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.mpTcp {
|
||||||
|
opts = append(opts, dialer.WithMPTCP(true))
|
||||||
|
}
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *Base) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(ctx, metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't resolve ip: %w", err)
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Base) Close() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
TFO bool `proxy:"tfo,omitempty"`
|
||||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
MPTCP bool `proxy:"mptcp,omitempty"`
|
||||||
|
Interface string `proxy:"interface-name,omitempty"`
|
||||||
|
RoutingMark int `proxy:"routing-mark,omitempty"`
|
||||||
|
IPVersion C.DNSPrefer `proxy:"ip-version,omitempty"`
|
||||||
|
DialerProxy string `proxy:"dialer-proxy,omitempty"` // don't apply this option into groups, but can set a group name in a proxy
|
||||||
|
|
||||||
|
//
|
||||||
|
// The following parameters are used internally, assign value by the structure decoder are disallowed
|
||||||
|
//
|
||||||
|
DialerForAPI C.Dialer `proxy:"-"` // the dialer used for API usage has higher priority than all the above configurations.
|
||||||
|
ProviderName string `proxy:"-"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BasicOption) NewDialer(opts []dialer.Option) C.Dialer {
|
||||||
|
cDialer := b.DialerForAPI
|
||||||
|
if cDialer == nil {
|
||||||
|
if b.DialerProxy != "" {
|
||||||
|
cDialer = proxydialer.NewByName(b.DialerProxy)
|
||||||
|
} else {
|
||||||
|
cDialer = dialer.NewDialer(opts...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cDialer
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaseOption struct {
|
type BaseOption struct {
|
||||||
@@ -97,24 +193,47 @@ type BaseOption struct {
|
|||||||
Addr string
|
Addr string
|
||||||
Type C.AdapterType
|
Type C.AdapterType
|
||||||
UDP bool
|
UDP bool
|
||||||
|
XUDP bool
|
||||||
|
TFO bool
|
||||||
|
MPTCP bool
|
||||||
Interface string
|
Interface string
|
||||||
RoutingMark int
|
RoutingMark int
|
||||||
|
Prefer C.DNSPrefer
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBase(opt BaseOption) *Base {
|
func NewBase(opt BaseOption) *Base {
|
||||||
return &Base{
|
return &Base{
|
||||||
name: opt.Name,
|
name: opt.Name,
|
||||||
addr: opt.Addr,
|
addr: opt.Addr,
|
||||||
tp: opt.Type,
|
tp: opt.Type,
|
||||||
udp: opt.UDP,
|
udp: opt.UDP,
|
||||||
iface: opt.Interface,
|
xudp: opt.XUDP,
|
||||||
rmark: opt.RoutingMark,
|
tfo: opt.TFO,
|
||||||
|
mpTcp: opt.MPTCP,
|
||||||
|
iface: opt.Interface,
|
||||||
|
rmark: opt.RoutingMark,
|
||||||
|
prefer: opt.Prefer,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
net.Conn
|
N.ExtendedConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
pdChain C.Chain
|
||||||
|
adapterAddr string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) RemoteDestination() string {
|
||||||
|
if remoteAddr := c.RemoteAddr(); remoteAddr != nil {
|
||||||
|
m := C.Metadata{}
|
||||||
|
if err := m.SetRemoteAddr(remoteAddr); err == nil {
|
||||||
|
if m.Valid() {
|
||||||
|
return m.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
host, _, _ := net.SplitHostPort(c.adapterAddr)
|
||||||
|
return host
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@@ -122,18 +241,59 @@ func (c *conn) Chains() C.Chain {
|
|||||||
return c.chain
|
return c.chain
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProviderChains implements C.Connection
|
||||||
|
func (c *conn) ProviderChains() C.Chain {
|
||||||
|
return c.pdChain
|
||||||
|
}
|
||||||
|
|
||||||
// AppendToChains implements C.Connection
|
// AppendToChains implements C.Connection
|
||||||
func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
|
c.pdChain = append(c.pdChain, a.ProxyInfo().ProviderName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) Upstream() any {
|
||||||
|
return c.ExtendedConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) AddRef(ref any) {
|
||||||
|
c.ExtendedConn = N.NewRefConn(c.ExtendedConn, ref) // add ref for autoCloseProxyAdapter
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
func NewConn(c net.Conn, a C.ProxyAdapter) C.Conn {
|
||||||
return &conn{c, []string{a.Name()}}
|
if _, ok := c.(syscall.Conn); !ok { // exclusion system conn like *net.TCPConn
|
||||||
|
c = N.NewDeadlineConn(c) // most conn from outbound can't handle readDeadline correctly
|
||||||
|
}
|
||||||
|
cc := &conn{N.NewExtendedConn(c), nil, nil, a.Addr()}
|
||||||
|
cc.AppendToChains(a)
|
||||||
|
return cc
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
net.PacketConn
|
N.EnhancePacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
pdChain C.Chain
|
||||||
|
adapterName string
|
||||||
|
connID string
|
||||||
|
adapterAddr string
|
||||||
|
resolveUDP func(ctx context.Context, metadata *C.Metadata) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||||
|
return c.resolveUDP(ctx, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) RemoteDestination() string {
|
||||||
|
host, _, _ := net.SplitHostPort(c.adapterAddr)
|
||||||
|
return host
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@@ -141,36 +301,94 @@ func (c *packetConn) Chains() C.Chain {
|
|||||||
return c.chain
|
return c.chain
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProviderChains implements C.Connection
|
||||||
|
func (c *packetConn) ProviderChains() C.Chain {
|
||||||
|
return c.pdChain
|
||||||
|
}
|
||||||
|
|
||||||
// AppendToChains implements C.Connection
|
// AppendToChains implements C.Connection
|
||||||
func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
|
c.pdChain = append(c.pdChain, a.ProxyInfo().ProviderName)
|
||||||
}
|
}
|
||||||
|
|
||||||
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func (c *packetConn) LocalAddr() net.Addr {
|
||||||
return &packetConn{pc, []string{a.Name()}}
|
lAddr := c.EnhancePacketConn.LocalAddr()
|
||||||
|
return N.NewCustomAddr(c.adapterName, c.connID, lAddr) // make quic-go's connMultiplexer happy
|
||||||
}
|
}
|
||||||
|
|
||||||
func uuidMap(str string) string {
|
func (c *packetConn) Upstream() any {
|
||||||
match, _ := regexp.MatchString(`[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$`, str)
|
return c.EnhancePacketConn
|
||||||
if !match {
|
}
|
||||||
var Nil [16]byte
|
|
||||||
h := sha1.New()
|
func (c *packetConn) WriterReplaceable() bool {
|
||||||
h.Write(Nil[:])
|
return true
|
||||||
h.Write([]byte(str))
|
}
|
||||||
u := h.Sum(nil)[:16]
|
|
||||||
u[6] = (u[6] & 0x0f) | (5 << 4)
|
func (c *packetConn) ReaderReplaceable() bool {
|
||||||
u[8] = u[8]&(0xff>>2) | (0x02 << 6)
|
return true
|
||||||
buf := make([]byte, 36)
|
}
|
||||||
hex.Encode(buf[0:8], u[0:4])
|
|
||||||
buf[8] = '-'
|
func (c *packetConn) AddRef(ref any) {
|
||||||
hex.Encode(buf[9:13], u[4:6])
|
c.EnhancePacketConn = N.NewRefPacketConn(c.EnhancePacketConn, ref) // add ref for autoCloseProxyAdapter
|
||||||
buf[13] = '-'
|
}
|
||||||
hex.Encode(buf[14:18], u[6:8])
|
|
||||||
buf[18] = '-'
|
func newPacketConn(pc net.PacketConn, a ProxyAdapter) C.PacketConn {
|
||||||
hex.Encode(buf[19:23], u[8:10])
|
epc := N.NewEnhancePacketConn(pc)
|
||||||
buf[23] = '-'
|
if _, ok := pc.(syscall.Conn); !ok { // exclusion system conn like *net.UDPConn
|
||||||
hex.Encode(buf[24:], u[10:])
|
epc = N.NewDeadlineEnhancePacketConn(epc) // most conn from outbound can't handle readDeadline correctly
|
||||||
return string(buf)
|
|
||||||
}
|
}
|
||||||
return str
|
cpc := &packetConn{epc, nil, nil, a.Name(), utils.NewUUIDV4().String(), a.Addr(), a.ResolveUDP}
|
||||||
|
cpc.AppendToChains(a)
|
||||||
|
return cpc
|
||||||
|
}
|
||||||
|
|
||||||
|
type AddRef interface {
|
||||||
|
AddRef(ref any)
|
||||||
|
}
|
||||||
|
|
||||||
|
type autoCloseProxyAdapter struct {
|
||||||
|
ProxyAdapter
|
||||||
|
closeOnce sync.Once
|
||||||
|
closeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *autoCloseProxyAdapter) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := p.ProxyAdapter.DialContext(ctx, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if c, ok := c.(AddRef); ok {
|
||||||
|
c.AddRef(p)
|
||||||
|
}
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *autoCloseProxyAdapter) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pc, ok := pc.(AddRef); ok {
|
||||||
|
pc.AddRef(p)
|
||||||
|
}
|
||||||
|
return pc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *autoCloseProxyAdapter) Close() error {
|
||||||
|
p.closeOnce.Do(func() {
|
||||||
|
log.Debugln("Closing outdated proxy [%s]", p.Name())
|
||||||
|
runtime.SetFinalizer(p, nil)
|
||||||
|
p.closeErr = p.ProxyAdapter.Close()
|
||||||
|
})
|
||||||
|
return p.closeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAutoCloseProxyAdapter(adapter ProxyAdapter) ProxyAdapter {
|
||||||
|
proxy := &autoCloseProxyAdapter{
|
||||||
|
ProxyAdapter: adapter,
|
||||||
|
}
|
||||||
|
// auto close ProxyAdapter
|
||||||
|
runtime.SetFinalizer(proxy, (*autoCloseProxyAdapter).Close)
|
||||||
|
return proxy
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,67 +2,105 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"fmt"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/loopback"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Direct struct {
|
type Direct struct {
|
||||||
*Base
|
*Base
|
||||||
|
loopBack *loopback.Detector
|
||||||
|
}
|
||||||
|
|
||||||
|
type DirectOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
opts = append(opts, dialer.WithDirect())
|
if err := d.loopBack.CheckConn(metadata); err != nil {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), d.Base.DialOptions(opts...)...)
|
return nil, err
|
||||||
|
}
|
||||||
|
opts := d.DialOptions()
|
||||||
|
opts = append(opts, dialer.WithResolver(resolver.DirectHostResolver))
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", metadata.RemoteAddress(), opts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
return d.loopBack.NewConn(NewConn(c, d)), nil
|
||||||
return NewConn(c, d), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
opts = append(opts, dialer.WithDirect())
|
if err := d.loopBack.CheckPacketConn(metadata); err != nil {
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := d.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pc, err := dialer.NewDialer(d.DialOptions()...).ListenPacket(ctx, "udp", "", metadata.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return newPacketConn(&directPacketConn{pc}, d), nil
|
return d.loopBack.NewPacketConn(newPacketConn(pc, d)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type directPacketConn struct {
|
func (d *Direct) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||||
net.PacketConn
|
if (!metadata.Resolved() || resolver.DirectHostResolver != resolver.DefaultResolver) && metadata.Host != "" {
|
||||||
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, resolver.DirectHostResolver)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't resolve ip: %w", err)
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Direct) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return true // tell DNSDialer don't send domain to DialContext, avoid lookback to DefaultResolver
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDirectWithOption(option DirectOption) *Direct {
|
||||||
|
return &Direct{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Direct,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
loopBack: loopback.NewDetector(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirect() *Direct {
|
func NewDirect() *Direct {
|
||||||
return &Direct{
|
return &Direct{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "DIRECT",
|
name: "DIRECT",
|
||||||
tp: C.Direct,
|
tp: C.Direct,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCompatible() *Direct {
|
func NewCompatible() *Direct {
|
||||||
return &Direct{
|
return &Direct{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "COMPATIBLE",
|
name: "COMPATIBLE",
|
||||||
tp: C.Compatible,
|
tp: C.Compatible,
|
||||||
udp: true,
|
udp: true,
|
||||||
},
|
prefer: C.DualStack,
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewPass() *Direct {
|
|
||||||
return &Direct{
|
|
||||||
Base: &Base{
|
|
||||||
name: "PASS",
|
|
||||||
tp: C.Pass,
|
|
||||||
udp: true,
|
|
||||||
},
|
},
|
||||||
|
loopBack: loopback.NewDetector(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
170
adapter/outbound/dns.go
Normal file
170
adapter/outbound/dns.go
Normal file
@@ -0,0 +1,170 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Dns struct {
|
||||||
|
*Base
|
||||||
|
}
|
||||||
|
|
||||||
|
type DnsOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (d *Dns) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
left, right := N.Pipe()
|
||||||
|
go resolver.RelayDnsConn(context.Background(), right, 0)
|
||||||
|
return NewConn(left, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (d *Dns) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
log.Debugln("[DNS] hijack udp:%s from %s", metadata.RemoteAddress(), metadata.SourceAddrPort())
|
||||||
|
if err := d.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
|
return newPacketConn(&dnsPacketConn{
|
||||||
|
response: make(chan dnsPacket, 1),
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
}, d), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Dns) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
metadata.DstIP = netip.AddrFrom4([4]byte{127, 0, 0, 2})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type dnsPacket struct {
|
||||||
|
data []byte
|
||||||
|
put func()
|
||||||
|
addr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
// dnsPacketConn implements net.PacketConn
|
||||||
|
type dnsPacketConn struct {
|
||||||
|
response chan dnsPacket
|
||||||
|
ctx context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
select {
|
||||||
|
case packet := <-d.response:
|
||||||
|
return packet.data, packet.put, packet.addr, nil
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return nil, nil, nil, net.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
select {
|
||||||
|
case packet := <-d.response:
|
||||||
|
n = copy(p, packet.data)
|
||||||
|
if packet.put != nil {
|
||||||
|
packet.put()
|
||||||
|
}
|
||||||
|
return n, packet.addr, nil
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return 0, nil, net.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
select {
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
return 0, net.ErrClosed
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(p) > resolver.SafeDnsPacketSize {
|
||||||
|
// wtf???
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := pool.Get(resolver.SafeDnsPacketSize)
|
||||||
|
put := func() { _ = pool.Put(buf) }
|
||||||
|
copy(buf, p) // avoid p be changed after WriteTo returned
|
||||||
|
|
||||||
|
go func() { // don't block the WriteTo function
|
||||||
|
ctx, cancel := context.WithTimeout(d.ctx, resolver.DefaultDnsRelayTimeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
buf, err = resolver.RelayDnsPacket(ctx, buf[:len(p)], buf)
|
||||||
|
if err != nil {
|
||||||
|
put()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
packet := dnsPacket{
|
||||||
|
data: buf,
|
||||||
|
put: put,
|
||||||
|
addr: addr,
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case d.response <- packet:
|
||||||
|
break
|
||||||
|
case <-d.ctx.Done():
|
||||||
|
put()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dnsPacketConn) Close() error {
|
||||||
|
d.cancel()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) LocalAddr() net.Addr {
|
||||||
|
return &net.UDPAddr{
|
||||||
|
IP: net.IPv4(127, 0, 0, 1),
|
||||||
|
Port: 53,
|
||||||
|
Zone: "",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetReadDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*dnsPacketConn) SetWriteDeadline(t time.Time) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDnsWithOption(option DnsOption) *Dns {
|
||||||
|
return &Dns{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
tp: C.Dns,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
41
adapter/outbound/ech.go
Normal file
41
adapter/outbound/ech.go
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/ech"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ECHOptions struct {
|
||||||
|
Enable bool `proxy:"enable,omitempty" obfs:"enable,omitempty"`
|
||||||
|
Config string `proxy:"config,omitempty" obfs:"config,omitempty"`
|
||||||
|
|
||||||
|
QueryServerName string `proxy:"query-server-name,omitempty" obfs:"query-server-name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o ECHOptions) Parse() (*ech.Config, error) {
|
||||||
|
if !o.Enable {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
echConfig := &ech.Config{}
|
||||||
|
if o.Config != "" {
|
||||||
|
list, err := base64.StdEncoding.DecodeString(o.Config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("base64 decode ech config string failed: %v", err)
|
||||||
|
}
|
||||||
|
echConfig.GetEncryptedClientHelloConfigList = func(ctx context.Context, serverName string) ([]byte, error) {
|
||||||
|
return list, nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
echConfig.GetEncryptedClientHelloConfigList = func(ctx context.Context, serverName string) ([]byte, error) {
|
||||||
|
if o.QueryServerName != "" { // overrides the domain name used for ECH HTTPS record queries
|
||||||
|
serverName = o.QueryServerName
|
||||||
|
}
|
||||||
|
return resolver.ResolveECHWithResolver(ctx, serverName, resolver.ProxyServerHostResolver)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return echConfig, nil
|
||||||
|
}
|
||||||
@@ -3,18 +3,18 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
|
"github.com/metacubex/http"
|
||||||
|
"github.com/metacubex/tls"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Http struct {
|
type Http struct {
|
||||||
@@ -35,37 +35,41 @@ type HttpOption struct {
|
|||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (h *Http) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (h *Http) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if h.tlsConfig != nil {
|
if h.tlsConfig != nil {
|
||||||
cc := tls.Client(c, h.tlsConfig)
|
cc := tls.Client(c, h.tlsConfig)
|
||||||
err := cc.Handshake()
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.shakeHand(metadata, c); err != nil {
|
if err := h.shakeHandContext(ctx, c, metadata); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", h.addr, h.Base.DialOptions(opts...)...)
|
c, err := h.dialer.DialContext(ctx, "tcp", h.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", h.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = h.StreamConn(c, metadata)
|
c, err = h.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -73,36 +77,50 @@ func (h *Http) DialContext(ctx context.Context, metadata *C.Metadata, opts ...di
|
|||||||
return NewConn(c, h), nil
|
return NewConn(c, h), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
addr := metadata.RemoteAddress()
|
func (h *Http) ProxyInfo() C.ProxyInfo {
|
||||||
req := &http.Request{
|
info := h.Base.ProxyInfo()
|
||||||
Method: http.MethodConnect,
|
info.DialerProxy = h.option.DialerProxy
|
||||||
URL: &url.URL{
|
return info
|
||||||
Host: addr,
|
}
|
||||||
},
|
|
||||||
Host: addr,
|
func (h *Http) shakeHandContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (err error) {
|
||||||
Header: http.Header{
|
if ctx.Done() != nil {
|
||||||
"Proxy-Connection": []string{"Keep-Alive"},
|
done := N.SetupContextForConn(ctx, c)
|
||||||
},
|
defer done(&err)
|
||||||
}
|
}
|
||||||
|
|
||||||
//增加headers
|
addr := metadata.RemoteAddress()
|
||||||
if len(h.option.Headers) != 0 {
|
HeaderString := "CONNECT " + addr + " HTTP/1.1\r\n"
|
||||||
for key, value := range h.option.Headers {
|
tempHeaders := map[string]string{
|
||||||
req.Header.Add(key, value)
|
"Host": addr,
|
||||||
}
|
"User-Agent": "Go-http-client/1.1",
|
||||||
|
"Proxy-Connection": "Keep-Alive",
|
||||||
|
}
|
||||||
|
|
||||||
|
for key, value := range h.option.Headers {
|
||||||
|
tempHeaders[key] = value
|
||||||
}
|
}
|
||||||
|
|
||||||
if h.user != "" && h.pass != "" {
|
if h.user != "" && h.pass != "" {
|
||||||
auth := h.user + ":" + h.pass
|
auth := h.user + ":" + h.pass
|
||||||
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
tempHeaders["Proxy-Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := req.Write(rw); err != nil {
|
for key, value := range tempHeaders {
|
||||||
|
HeaderString += key + ": " + value + "\r\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
HeaderString += "\r\n"
|
||||||
|
|
||||||
|
_, err = c.Write([]byte(HeaderString))
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := http.ReadResponse(bufio.NewReader(rw), req)
|
resp, err := http.ReadResponse(bufio.NewReader(c), nil)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -126,30 +144,45 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
return fmt.Errorf("can not connect remote err code: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHttp(option HttpOption) *Http {
|
func NewHttp(option HttpOption) (*Http, error) {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
sni := option.Server
|
sni := option.Server
|
||||||
if option.SNI != "" {
|
if option.SNI != "" {
|
||||||
sni = option.SNI
|
sni = option.SNI
|
||||||
}
|
}
|
||||||
tlsConfig = &tls.Config{
|
var err error
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
ServerName: sni,
|
TLSConfig: &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Http{
|
outbound := &Http{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Http,
|
tp: C.Http,
|
||||||
iface: option.Interface,
|
pdName: option.ProviderName,
|
||||||
rmark: option.RoutingMark,
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|||||||
324
adapter/outbound/hysteria.go
Normal file
324
adapter/outbound/hysteria.go
Normal file
@@ -0,0 +1,324 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/ech"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
hyCongestion "github.com/metacubex/mihomo/transport/hysteria/congestion"
|
||||||
|
"github.com/metacubex/mihomo/transport/hysteria/core"
|
||||||
|
"github.com/metacubex/mihomo/transport/hysteria/obfs"
|
||||||
|
"github.com/metacubex/mihomo/transport/hysteria/pmtud_fix"
|
||||||
|
"github.com/metacubex/mihomo/transport/hysteria/transport"
|
||||||
|
"github.com/metacubex/mihomo/transport/hysteria/utils"
|
||||||
|
|
||||||
|
"github.com/metacubex/tls"
|
||||||
|
|
||||||
|
"github.com/metacubex/quic-go"
|
||||||
|
"github.com/metacubex/quic-go/congestion"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
mbpsToBps = 125000
|
||||||
|
|
||||||
|
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
||||||
|
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
||||||
|
|
||||||
|
DefaultALPN = "hysteria"
|
||||||
|
DefaultProtocol = "udp"
|
||||||
|
DefaultHopInterval = 10
|
||||||
|
)
|
||||||
|
|
||||||
|
type Hysteria struct {
|
||||||
|
*Base
|
||||||
|
|
||||||
|
option *HysteriaOption
|
||||||
|
client *core.Client
|
||||||
|
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
echConfig *ech.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
tcpConn, err := h.client.DialTCP(metadata.String(), metadata.DstPort, h.genHdc(ctx))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(tcpConn, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
if err := h.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
udpConn, err := h.client.DialUDP(h.genHdc(ctx))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) genHdc(ctx context.Context) utils.PacketDialer {
|
||||||
|
return &hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func(network string, rAddr net.Addr) (net.PacketConn, error) {
|
||||||
|
rAddrPort, _ := netip.ParseAddrPort(rAddr.String())
|
||||||
|
return h.dialer.ListenPacket(ctx, network, "", rAddrPort)
|
||||||
|
},
|
||||||
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
|
udpAddr, err := resolveUDPAddr(ctx, "udp", addr, h.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err = h.echConfig.ClientHandle(ctx, h.tlsConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return udpAddr, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (h *Hysteria) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := h.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = h.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
type HysteriaOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port,omitempty"`
|
||||||
|
Ports string `proxy:"ports,omitempty"`
|
||||||
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
|
ObfsProtocol string `proxy:"obfs-protocol,omitempty"` // compatible with Stash
|
||||||
|
Up string `proxy:"up"`
|
||||||
|
UpSpeed int `proxy:"up-speed,omitempty"` // compatible with Stash
|
||||||
|
Down string `proxy:"down"`
|
||||||
|
DownSpeed int `proxy:"down-speed,omitempty"` // compatible with Stash
|
||||||
|
Auth string `proxy:"auth,omitempty"`
|
||||||
|
AuthString string `proxy:"auth-str,omitempty"`
|
||||||
|
Obfs string `proxy:"obfs,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
|
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||||
|
HopInterval int `proxy:"hop-interval,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *HysteriaOption) Speed() (uint64, uint64, error) {
|
||||||
|
var up, down uint64
|
||||||
|
up = StringToBps(c.Up)
|
||||||
|
if up == 0 {
|
||||||
|
return 0, 0, fmt.Errorf("invaild upload speed: %s", c.Up)
|
||||||
|
}
|
||||||
|
|
||||||
|
down = StringToBps(c.Down)
|
||||||
|
if down == 0 {
|
||||||
|
return 0, 0, fmt.Errorf("invaild download speed: %s", c.Down)
|
||||||
|
}
|
||||||
|
|
||||||
|
return up, down, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHysteria(option HysteriaOption) (*Hysteria, error) {
|
||||||
|
clientTransport := &transport.ClientTransport{}
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
ports := option.Ports
|
||||||
|
|
||||||
|
serverName := option.Server
|
||||||
|
if option.SNI != "" {
|
||||||
|
serverName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
ServerName: serverName,
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
|
tlsConfig.NextProtos = option.ALPN
|
||||||
|
} else {
|
||||||
|
tlsConfig.NextProtos = []string{DefaultALPN}
|
||||||
|
}
|
||||||
|
|
||||||
|
echConfig, err := option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tlsClientConfig := tlsConfig
|
||||||
|
|
||||||
|
quicConfig := &quic.Config{
|
||||||
|
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
KeepAlivePeriod: 10 * time.Second,
|
||||||
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
|
EnableDatagrams: true,
|
||||||
|
}
|
||||||
|
if option.ObfsProtocol != "" {
|
||||||
|
option.Protocol = option.ObfsProtocol
|
||||||
|
}
|
||||||
|
if option.Protocol == "" {
|
||||||
|
option.Protocol = DefaultProtocol
|
||||||
|
}
|
||||||
|
if option.HopInterval == 0 {
|
||||||
|
option.HopInterval = DefaultHopInterval
|
||||||
|
}
|
||||||
|
hopInterval := time.Duration(int64(option.HopInterval)) * time.Second
|
||||||
|
if option.ReceiveWindow == 0 {
|
||||||
|
quicConfig.InitialStreamReceiveWindow = DefaultStreamReceiveWindow / 10
|
||||||
|
quicConfig.MaxStreamReceiveWindow = DefaultStreamReceiveWindow
|
||||||
|
}
|
||||||
|
if option.ReceiveWindow == 0 {
|
||||||
|
quicConfig.InitialConnectionReceiveWindow = DefaultConnectionReceiveWindow / 10
|
||||||
|
quicConfig.MaxConnectionReceiveWindow = DefaultConnectionReceiveWindow
|
||||||
|
}
|
||||||
|
if !quicConfig.DisablePathMTUDiscovery && pmtud_fix.DisablePathMTUDiscovery {
|
||||||
|
log.Infoln("hysteria: Path MTU Discovery is not yet supported on this platform")
|
||||||
|
}
|
||||||
|
|
||||||
|
var auth = []byte(option.AuthString)
|
||||||
|
if option.Auth != "" {
|
||||||
|
auth, err = base64.StdEncoding.DecodeString(option.Auth)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var obfuscator obfs.Obfuscator
|
||||||
|
if len(option.Obfs) > 0 {
|
||||||
|
obfuscator = obfs.NewXPlusObfuscator([]byte(option.Obfs))
|
||||||
|
}
|
||||||
|
|
||||||
|
up, down, err := option.Speed()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if option.UpSpeed != 0 {
|
||||||
|
up = uint64(option.UpSpeed * mbpsToBps)
|
||||||
|
}
|
||||||
|
if option.DownSpeed != 0 {
|
||||||
|
down = uint64(option.DownSpeed * mbpsToBps)
|
||||||
|
}
|
||||||
|
client, err := core.NewClient(
|
||||||
|
addr, ports, option.Protocol, auth, tlsClientConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
||||||
|
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
||||||
|
}, obfuscator, hopInterval, option.FastOpen,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||||
|
}
|
||||||
|
outbound := &Hysteria{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Hysteria,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.FastOpen,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
client: client,
|
||||||
|
tlsConfig: tlsClientConfig,
|
||||||
|
echConfig: echConfig,
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (h *Hysteria) Close() error {
|
||||||
|
if h.client != nil {
|
||||||
|
return h.client.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type hyPacketConn struct {
|
||||||
|
core.UDPConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *hyPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
|
||||||
|
b, addrStr, err := c.UDPConn.ReadFrom()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n = copy(p, b)
|
||||||
|
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *hyPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
b, addrStr, err := c.UDPConn.ReadFrom()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
data = b
|
||||||
|
addr = M.ParseSocksaddr(addrStr).UDPAddr()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *hyPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) {
|
||||||
|
err = c.UDPConn.WriteTo(p, M.SocksaddrFromNet(addr).String())
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n = len(p)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
type hyDialerWithContext struct {
|
||||||
|
hyDialer func(network string, rAddr net.Addr) (net.PacketConn, error)
|
||||||
|
ctx context.Context
|
||||||
|
remoteAddr func(host string) (net.Addr, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) ListenPacket(rAddr net.Addr) (net.PacketConn, error) {
|
||||||
|
network := "udp"
|
||||||
|
if addrPort, err := netip.ParseAddrPort(rAddr.String()); err == nil {
|
||||||
|
network = dialer.ParseNetwork(network, addrPort.Addr())
|
||||||
|
}
|
||||||
|
return h.hyDialer(network, rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) Context() context.Context {
|
||||||
|
return h.ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) RemoteAddr(host string) (net.Addr, error) {
|
||||||
|
return h.remoteAddr(host)
|
||||||
|
}
|
||||||
236
adapter/outbound/hysteria2.go
Normal file
236
adapter/outbound/hysteria2.go
Normal file
@@ -0,0 +1,236 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
tuicCommon "github.com/metacubex/mihomo/transport/tuic/common"
|
||||||
|
|
||||||
|
"github.com/metacubex/quic-go"
|
||||||
|
"github.com/metacubex/sing-quic/hysteria2"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
"github.com/metacubex/tls"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
hysteria2.SetCongestionController = tuicCommon.SetCongestionController
|
||||||
|
}
|
||||||
|
|
||||||
|
const minHopInterval = 5
|
||||||
|
const defaultHopInterval = 30
|
||||||
|
|
||||||
|
type Hysteria2 struct {
|
||||||
|
*Base
|
||||||
|
|
||||||
|
option *Hysteria2Option
|
||||||
|
client *hysteria2.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
type Hysteria2Option struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port,omitempty"`
|
||||||
|
Ports string `proxy:"ports,omitempty"`
|
||||||
|
HopInterval int `proxy:"hop-interval,omitempty"`
|
||||||
|
Up string `proxy:"up,omitempty"`
|
||||||
|
Down string `proxy:"down,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
Obfs string `proxy:"obfs,omitempty"`
|
||||||
|
ObfsPassword string `proxy:"obfs-password,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
|
UdpMTU int `proxy:"udp-mtu,omitempty"`
|
||||||
|
|
||||||
|
// quic-go special config
|
||||||
|
InitialStreamReceiveWindow uint64 `proxy:"initial-stream-receive-window,omitempty"`
|
||||||
|
MaxStreamReceiveWindow uint64 `proxy:"max-stream-receive-window,omitempty"`
|
||||||
|
InitialConnectionReceiveWindow uint64 `proxy:"initial-connection-receive-window,omitempty"`
|
||||||
|
MaxConnectionReceiveWindow uint64 `proxy:"max-connection-receive-window,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria2) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := h.client.DialConn(ctx, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(c, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria2) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if err = h.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pc, err := h.client.ListenPacket(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pc == nil {
|
||||||
|
return nil, errors.New("packetConn is nil")
|
||||||
|
}
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(pc), h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (h *Hysteria2) Close() error {
|
||||||
|
if h.client != nil {
|
||||||
|
return h.client.CloseWithError(errors.New("proxy removed"))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (h *Hysteria2) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := h.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = h.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHysteria2(option Hysteria2Option) (*Hysteria2, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
outbound := &Hysteria2{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Hysteria2,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: true,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
singDialer := proxydialer.NewSingDialer(outbound.dialer)
|
||||||
|
|
||||||
|
var salamanderPassword string
|
||||||
|
if len(option.Obfs) > 0 {
|
||||||
|
if option.ObfsPassword == "" {
|
||||||
|
return nil, errors.New("missing obfs password")
|
||||||
|
}
|
||||||
|
switch option.Obfs {
|
||||||
|
case hysteria2.ObfsTypeSalamander:
|
||||||
|
salamanderPassword = option.ObfsPassword
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown obfs type: %s", option.Obfs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
serverName := option.Server
|
||||||
|
if option.SNI != "" {
|
||||||
|
serverName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
ServerName: serverName,
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
|
tlsConfig.NextProtos = option.ALPN
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsClientConfig := tlsConfig
|
||||||
|
echConfig, err := option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.UdpMTU == 0 {
|
||||||
|
// "1200" from quic-go's MaxDatagramSize
|
||||||
|
// "-3" from quic-go's DatagramFrame.MaxDataLen
|
||||||
|
option.UdpMTU = 1200 - 3
|
||||||
|
}
|
||||||
|
|
||||||
|
quicConfig := &quic.Config{
|
||||||
|
InitialStreamReceiveWindow: option.InitialStreamReceiveWindow,
|
||||||
|
MaxStreamReceiveWindow: option.MaxStreamReceiveWindow,
|
||||||
|
InitialConnectionReceiveWindow: option.InitialConnectionReceiveWindow,
|
||||||
|
MaxConnectionReceiveWindow: option.MaxConnectionReceiveWindow,
|
||||||
|
}
|
||||||
|
|
||||||
|
clientOptions := hysteria2.ClientOptions{
|
||||||
|
Context: context.TODO(),
|
||||||
|
Dialer: singDialer,
|
||||||
|
Logger: log.SingLogger,
|
||||||
|
SendBPS: StringToBps(option.Up),
|
||||||
|
ReceiveBPS: StringToBps(option.Down),
|
||||||
|
SalamanderPassword: salamanderPassword,
|
||||||
|
Password: option.Password,
|
||||||
|
TLSConfig: tlsClientConfig,
|
||||||
|
QUICConfig: quicConfig,
|
||||||
|
UDPDisabled: false,
|
||||||
|
CWND: option.CWND,
|
||||||
|
UdpMTU: option.UdpMTU,
|
||||||
|
ServerAddress: func(ctx context.Context) (*net.UDPAddr, error) {
|
||||||
|
udpAddr, err := resolveUDPAddr(ctx, "udp", addr, option.IPVersion)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err = echConfig.ClientHandle(ctx, tlsClientConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return udpAddr, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
var ranges utils.IntRanges[uint16]
|
||||||
|
var serverPorts []uint16
|
||||||
|
if option.Ports != "" {
|
||||||
|
ranges, err = utils.NewUnsignedRanges[uint16](option.Ports)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ranges.Range(func(port uint16) bool {
|
||||||
|
serverPorts = append(serverPorts, port)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if len(serverPorts) > 0 {
|
||||||
|
if option.HopInterval == 0 {
|
||||||
|
option.HopInterval = defaultHopInterval
|
||||||
|
} else if option.HopInterval < minHopInterval {
|
||||||
|
option.HopInterval = minHopInterval
|
||||||
|
}
|
||||||
|
clientOptions.HopInterval = time.Duration(option.HopInterval) * time.Second
|
||||||
|
clientOptions.ServerPorts = serverPorts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option.Port == 0 && len(serverPorts) == 0 {
|
||||||
|
return nil, errors.New("invalid port")
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := hysteria2.NewClient(clientOptions)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
outbound.client = client
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
397
adapter/outbound/masque.go
Normal file
397
adapter/outbound/masque.go
Normal file
@@ -0,0 +1,397 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
|
"github.com/metacubex/mihomo/common/contextutils"
|
||||||
|
"github.com/metacubex/mihomo/common/pool"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/dns"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
"github.com/metacubex/mihomo/transport/masque"
|
||||||
|
"github.com/metacubex/mihomo/transport/tuic/common"
|
||||||
|
|
||||||
|
connectip "github.com/metacubex/connect-ip-go"
|
||||||
|
"github.com/metacubex/quic-go"
|
||||||
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
"github.com/metacubex/tls"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Masque struct {
|
||||||
|
*Base
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
quicConfig *quic.Config
|
||||||
|
tunDevice wireguard.Device
|
||||||
|
resolver resolver.Resolver
|
||||||
|
uri string
|
||||||
|
|
||||||
|
runCtx context.Context
|
||||||
|
runCancel context.CancelFunc
|
||||||
|
runMutex sync.Mutex
|
||||||
|
running atomic.Bool
|
||||||
|
runDevice atomic.Bool
|
||||||
|
|
||||||
|
option MasqueOption
|
||||||
|
}
|
||||||
|
|
||||||
|
type MasqueOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
PrivateKey string `proxy:"private-key"`
|
||||||
|
PublicKey string `proxy:"public-key"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
|
URI string `proxy:"uri,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
|
||||||
|
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||||
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
|
|
||||||
|
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||||
|
Dns []string `proxy:"dns,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (option MasqueOption) Prefixes() ([]netip.Prefix, error) {
|
||||||
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
|
if len(option.Ip) > 0 {
|
||||||
|
if !strings.Contains(option.Ip, "/") {
|
||||||
|
option.Ip = option.Ip + "/32"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ip); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("ip address parse error: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(option.Ipv6) > 0 {
|
||||||
|
if !strings.Contains(option.Ipv6, "/") {
|
||||||
|
option.Ipv6 = option.Ipv6 + "/128"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ipv6); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("ipv6 address parse error: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(localPrefixes) == 0 {
|
||||||
|
return nil, errors.New("missing local address")
|
||||||
|
}
|
||||||
|
return localPrefixes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMasque(option MasqueOption) (*Masque, error) {
|
||||||
|
outbound := &Masque{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.Masque,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
outbound.runCtx = ctx
|
||||||
|
outbound.runCancel = cancel
|
||||||
|
|
||||||
|
privKeyB64, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode private key: %v", err)
|
||||||
|
}
|
||||||
|
privKey, err := x509.ParseECPrivateKey(privKeyB64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse private key: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
endpointPubKeyB64, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to decode public key: %v", err)
|
||||||
|
}
|
||||||
|
pubKey, err := x509.ParsePKIXPublicKey(endpointPubKeyB64)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to parse public key: %v", err)
|
||||||
|
}
|
||||||
|
ecPubKey, ok := pubKey.(*ecdsa.PublicKey)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("failed to assert public key as ECDSA")
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := option.URI
|
||||||
|
if uri == "" {
|
||||||
|
uri = masque.ConnectURI
|
||||||
|
}
|
||||||
|
outbound.uri = uri
|
||||||
|
|
||||||
|
sni := option.SNI
|
||||||
|
if sni == "" {
|
||||||
|
sni = masque.ConnectSNI
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig, err := masque.PrepareTlsConfig(privKey, ecPubKey, sni)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to prepare TLS config: %v\n", err)
|
||||||
|
}
|
||||||
|
outbound.tlsConfig = tlsConfig
|
||||||
|
|
||||||
|
outbound.quicConfig = &quic.Config{
|
||||||
|
EnableDatagrams: true,
|
||||||
|
InitialPacketSize: 1242,
|
||||||
|
KeepAlivePeriod: 30 * time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
prefixes, err := option.Prefixes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
outbound.option = option
|
||||||
|
|
||||||
|
mtu := option.MTU
|
||||||
|
if mtu == 0 {
|
||||||
|
mtu = 1280
|
||||||
|
}
|
||||||
|
if len(prefixes) == 0 {
|
||||||
|
return nil, errors.New("missing local address")
|
||||||
|
}
|
||||||
|
outbound.tunDevice, err = wireguard.NewStackDevice(prefixes, uint32(mtu))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create device: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var has6 bool
|
||||||
|
for _, address := range prefixes {
|
||||||
|
if !address.Addr().Unmap().Is4() {
|
||||||
|
has6 = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.RemoteDnsResolve && len(option.Dns) > 0 {
|
||||||
|
nss, err := dns.ParseNameServer(option.Dns)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range nss {
|
||||||
|
nss[i].ProxyAdapter = outbound
|
||||||
|
}
|
||||||
|
outbound.resolver = dns.NewResolver(dns.Config{
|
||||||
|
Main: nss,
|
||||||
|
IPv6: has6,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Masque) run(ctx context.Context) error {
|
||||||
|
if w.running.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
w.runMutex.Lock()
|
||||||
|
defer w.runMutex.Unlock()
|
||||||
|
// double-check like sync.Once
|
||||||
|
if w.running.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if w.runCtx.Err() != nil {
|
||||||
|
return w.runCtx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
if !w.runDevice.Load() {
|
||||||
|
err := w.tunDevice.Start()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
w.runDevice.Store(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr, err := resolveUDPAddr(ctx, "udp", w.addr, w.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := w.dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
quicConn, err := quic.Dial(ctx, pc, udpAddr, w.tlsConfig, w.quicConfig)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
common.SetCongestionController(quicConn, w.option.CongestionController, w.option.CWND)
|
||||||
|
|
||||||
|
tr, ipConn, err := masque.ConnectTunnel(ctx, quicConn, w.uri)
|
||||||
|
if err != nil {
|
||||||
|
_ = pc.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
w.running.Store(true)
|
||||||
|
|
||||||
|
runCtx, runCancel := context.WithCancel(w.runCtx)
|
||||||
|
contextutils.AfterFunc(runCtx, func() {
|
||||||
|
w.running.Store(false)
|
||||||
|
_ = ipConn.Close()
|
||||||
|
_ = tr.Close()
|
||||||
|
_ = pc.Close()
|
||||||
|
})
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer runCancel()
|
||||||
|
buf := pool.Get(pool.UDPBufferSize)
|
||||||
|
defer pool.Put(buf)
|
||||||
|
bufs := [][]byte{buf}
|
||||||
|
sizes := []int{0}
|
||||||
|
for runCtx.Err() == nil {
|
||||||
|
_, err := w.tunDevice.Read(bufs, sizes, 0)
|
||||||
|
if err != nil {
|
||||||
|
log.Errorln("[Masque](%s) error reading from TUN device: %v", w.name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
icmp, err := ipConn.WritePacket(buf[:sizes[0]])
|
||||||
|
if err != nil {
|
||||||
|
if errors.As(err, new(*connectip.CloseError)) {
|
||||||
|
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Warnln("[Masque](%s) error writing to IP connection: %v, continuing...", w.name, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(icmp) > 0 {
|
||||||
|
if _, err := w.tunDevice.Write([][]byte{icmp}, 0); err != nil {
|
||||||
|
log.Warnln("[Masque](%s) error writing ICMP to TUN device: %v, continuing...", w.name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer runCancel()
|
||||||
|
buf := pool.Get(pool.UDPBufferSize)
|
||||||
|
defer pool.Put(buf)
|
||||||
|
for runCtx.Err() == nil {
|
||||||
|
n, err := ipConn.ReadPacket(buf)
|
||||||
|
if err != nil {
|
||||||
|
if errors.As(err, new(*connectip.CloseError)) {
|
||||||
|
log.Errorln("[Masque](%s) connection closed while writing to IP connection: %v", w.name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Warnln("[Masque](%s) error reading from IP connection: %v, continuing...", w.name, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := w.tunDevice.Write([][]byte{buf[:n]}, 0); err != nil {
|
||||||
|
log.Errorln("[Masque](%s) error writing to TUN device: %v", w.name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (w *Masque) Close() error {
|
||||||
|
w.runCancel()
|
||||||
|
if w.tunDevice != nil {
|
||||||
|
w.tunDevice.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Masque) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
var conn net.Conn
|
||||||
|
if err = w.run(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !metadata.Resolved() || w.resolver != nil {
|
||||||
|
r := resolver.DefaultResolver
|
||||||
|
if w.resolver != nil {
|
||||||
|
r = w.resolver
|
||||||
|
}
|
||||||
|
options := w.DialOptions()
|
||||||
|
options = append(options, dialer.WithResolver(r))
|
||||||
|
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
||||||
|
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
|
} else {
|
||||||
|
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if conn == nil {
|
||||||
|
return nil, errors.New("conn is nil")
|
||||||
|
}
|
||||||
|
return NewConn(conn, w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Masque) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
var pc net.PacketConn
|
||||||
|
if err = w.run(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = w.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pc == nil {
|
||||||
|
return nil, errors.New("packetConn is nil")
|
||||||
|
}
|
||||||
|
return newPacketConn(pc, w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *Masque) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||||
|
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
||||||
|
r := resolver.DefaultResolver
|
||||||
|
if w.resolver != nil {
|
||||||
|
r = w.resolver
|
||||||
|
}
|
||||||
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, r)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't resolve ip: %w", err)
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (w *Masque) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := w.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = w.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (w *Masque) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
370
adapter/outbound/mieru.go
Normal file
370
adapter/outbound/mieru.go
Normal file
@@ -0,0 +1,370 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
|
mieruclient "github.com/enfein/mieru/v3/apis/client"
|
||||||
|
mierucommon "github.com/enfein/mieru/v3/apis/common"
|
||||||
|
mierumodel "github.com/enfein/mieru/v3/apis/model"
|
||||||
|
mierutp "github.com/enfein/mieru/v3/apis/trafficpattern"
|
||||||
|
mierupb "github.com/enfein/mieru/v3/pkg/appctl/appctlpb"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Mieru struct {
|
||||||
|
*Base
|
||||||
|
option *MieruOption
|
||||||
|
client mieruclient.Client
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
type MieruOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port,omitempty"`
|
||||||
|
PortRange string `proxy:"port-range,omitempty"`
|
||||||
|
Transport string `proxy:"transport"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
UserName string `proxy:"username"`
|
||||||
|
Password string `proxy:"password"`
|
||||||
|
Multiplexing string `proxy:"multiplexing,omitempty"`
|
||||||
|
HandshakeMode string `proxy:"handshake-mode,omitempty"`
|
||||||
|
TrafficPattern string `proxy:"traffic-pattern,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type mieruPacketDialer struct {
|
||||||
|
C.Dialer
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ mierucommon.PacketDialer = (*mieruPacketDialer)(nil)
|
||||||
|
|
||||||
|
func (pd mieruPacketDialer) ListenPacket(ctx context.Context, network, laddr, raddr string) (net.PacketConn, error) {
|
||||||
|
rAddrPort, err := netip.ParseAddrPort(raddr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid address %s: %w", raddr, err)
|
||||||
|
}
|
||||||
|
return pd.Dialer.ListenPacket(ctx, network, laddr, rAddrPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
type mieruDNSResolver struct {
|
||||||
|
prefer C.DNSPrefer
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ mierucommon.DNSResolver = (*mieruDNSResolver)(nil)
|
||||||
|
|
||||||
|
func (dr mieruDNSResolver) LookupIP(ctx context.Context, network, host string) (_ []net.IP, err error) {
|
||||||
|
var ip netip.Addr
|
||||||
|
switch dr.prefer {
|
||||||
|
case C.IPv4Only:
|
||||||
|
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
case C.IPv6Only:
|
||||||
|
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
case C.IPv6Prefer:
|
||||||
|
ip, err = resolver.ResolveIPPrefer6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
default:
|
||||||
|
ip, err = resolver.ResolveIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
||||||
|
}
|
||||||
|
// TODO: handle IP4P (due to interface limitations, it's currently impossible to modify the port here)
|
||||||
|
return []net.IP{ip.AsSlice()}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (m *Mieru) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
if err := m.ensureClientIsRunning(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
addr := metadataToMieruNetAddrSpec(metadata)
|
||||||
|
c, err := m.client.DialContext(ctx, addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("dial to %s failed: %w", addr, err)
|
||||||
|
}
|
||||||
|
return NewConn(c, m), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (m *Mieru) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if err = m.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := m.ensureClientIsRunning(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c, err := m.client.DialContext(ctx, metadata.UDPAddr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("dial to %s failed: %w", metadata.UDPAddr(), err)
|
||||||
|
}
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(mierucommon.NewUDPAssociateWrapper(mierucommon.NewPacketOverStreamTunnel(c))), m), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (m *Mieru) SupportUOT() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (m *Mieru) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := m.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = m.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Mieru) ensureClientIsRunning() error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
|
||||||
|
if m.client.IsRunning() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a dialer and add it to the client config, before starting the client.
|
||||||
|
config, err := m.client.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
config.Dialer = m.dialer
|
||||||
|
config.PacketDialer = mieruPacketDialer{Dialer: m.dialer}
|
||||||
|
config.Resolver = mieruDNSResolver{prefer: m.prefer}
|
||||||
|
if err := m.client.Store(config); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := m.client.Start(); err != nil {
|
||||||
|
return fmt.Errorf("failed to start mieru client: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMieru(option MieruOption) (*Mieru, error) {
|
||||||
|
config, err := buildMieruClientConfig(option)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to build mieru client config: %w", err)
|
||||||
|
}
|
||||||
|
c := mieruclient.NewClient()
|
||||||
|
if err := c.Store(config); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to store mieru client config: %w", err)
|
||||||
|
}
|
||||||
|
// Client is started lazily on the first use.
|
||||||
|
|
||||||
|
var addr string
|
||||||
|
if option.Port != 0 {
|
||||||
|
addr = net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
} else {
|
||||||
|
beginPort, _, _ := beginAndEndPortFromPortRange(option.PortRange)
|
||||||
|
addr = net.JoinHostPort(option.Server, strconv.Itoa(beginPort))
|
||||||
|
}
|
||||||
|
outbound := &Mieru{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Mieru,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: option.UDP,
|
||||||
|
xudp: false,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
client: c,
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (m *Mieru) Close() error {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
if m.client != nil && m.client.IsRunning() {
|
||||||
|
return m.client.Stop()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func metadataToMieruNetAddrSpec(metadata *C.Metadata) mierumodel.NetAddrSpec {
|
||||||
|
spec := mierumodel.NetAddrSpec{
|
||||||
|
Net: metadata.NetWork.String(),
|
||||||
|
}
|
||||||
|
if metadata.Host != "" {
|
||||||
|
spec.AddrSpec = mierumodel.AddrSpec{
|
||||||
|
FQDN: metadata.Host,
|
||||||
|
Port: int(metadata.DstPort),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
spec.AddrSpec = mierumodel.AddrSpec{
|
||||||
|
IP: metadata.DstIP.AsSlice(),
|
||||||
|
Port: int(metadata.DstPort),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return spec
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildMieruClientConfig(option MieruOption) (*mieruclient.ClientConfig, error) {
|
||||||
|
if err := validateMieruOption(option); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to validate mieru option: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var transportProtocol = mierupb.TransportProtocol_UNKNOWN_TRANSPORT_PROTOCOL.Enum()
|
||||||
|
switch option.Transport {
|
||||||
|
case "TCP":
|
||||||
|
transportProtocol = mierupb.TransportProtocol_TCP.Enum()
|
||||||
|
case "UDP":
|
||||||
|
transportProtocol = mierupb.TransportProtocol_UDP.Enum()
|
||||||
|
}
|
||||||
|
var server *mierupb.ServerEndpoint
|
||||||
|
if net.ParseIP(option.Server) != nil {
|
||||||
|
// server is an IP address
|
||||||
|
if option.PortRange != "" {
|
||||||
|
server = &mierupb.ServerEndpoint{
|
||||||
|
IpAddress: proto.String(option.Server),
|
||||||
|
PortBindings: []*mierupb.PortBinding{
|
||||||
|
{
|
||||||
|
PortRange: proto.String(option.PortRange),
|
||||||
|
Protocol: transportProtocol,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
server = &mierupb.ServerEndpoint{
|
||||||
|
IpAddress: proto.String(option.Server),
|
||||||
|
PortBindings: []*mierupb.PortBinding{
|
||||||
|
{
|
||||||
|
Port: proto.Int32(int32(option.Port)),
|
||||||
|
Protocol: transportProtocol,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// server is a domain name
|
||||||
|
if option.PortRange != "" {
|
||||||
|
server = &mierupb.ServerEndpoint{
|
||||||
|
DomainName: proto.String(option.Server),
|
||||||
|
PortBindings: []*mierupb.PortBinding{
|
||||||
|
{
|
||||||
|
PortRange: proto.String(option.PortRange),
|
||||||
|
Protocol: transportProtocol,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
server = &mierupb.ServerEndpoint{
|
||||||
|
DomainName: proto.String(option.Server),
|
||||||
|
PortBindings: []*mierupb.PortBinding{
|
||||||
|
{
|
||||||
|
Port: proto.Int32(int32(option.Port)),
|
||||||
|
Protocol: transportProtocol,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
config := &mieruclient.ClientConfig{
|
||||||
|
Profile: &mierupb.ClientProfile{
|
||||||
|
ProfileName: proto.String(option.Name),
|
||||||
|
User: &mierupb.User{
|
||||||
|
Name: proto.String(option.UserName),
|
||||||
|
Password: proto.String(option.Password),
|
||||||
|
},
|
||||||
|
Servers: []*mierupb.ServerEndpoint{server},
|
||||||
|
},
|
||||||
|
DNSConfig: &mierucommon.ClientDNSConfig{
|
||||||
|
BypassDialerDNS: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if multiplexing, ok := mierupb.MultiplexingLevel_value[option.Multiplexing]; ok {
|
||||||
|
config.Profile.Multiplexing = &mierupb.MultiplexingConfig{
|
||||||
|
Level: mierupb.MultiplexingLevel(multiplexing).Enum(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if handshakeMode, ok := mierupb.HandshakeMode_value[option.HandshakeMode]; ok {
|
||||||
|
config.Profile.HandshakeMode = (*mierupb.HandshakeMode)(&handshakeMode)
|
||||||
|
}
|
||||||
|
if option.TrafficPattern != "" {
|
||||||
|
trafficPattern, _ := mierutp.Decode(option.TrafficPattern)
|
||||||
|
config.Profile.TrafficPattern = trafficPattern
|
||||||
|
}
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateMieruOption(option MieruOption) error {
|
||||||
|
if option.Name == "" {
|
||||||
|
return fmt.Errorf("name is empty")
|
||||||
|
}
|
||||||
|
if option.Server == "" {
|
||||||
|
return fmt.Errorf("server is empty")
|
||||||
|
}
|
||||||
|
if option.Port == 0 && option.PortRange == "" {
|
||||||
|
return fmt.Errorf("either port or port-range must be set")
|
||||||
|
}
|
||||||
|
if option.Port != 0 && option.PortRange != "" {
|
||||||
|
return fmt.Errorf("port and port-range cannot be set at the same time")
|
||||||
|
}
|
||||||
|
if option.Port != 0 && (option.Port < 1 || option.Port > 65535) {
|
||||||
|
return fmt.Errorf("port must be between 1 and 65535")
|
||||||
|
}
|
||||||
|
if option.PortRange != "" {
|
||||||
|
begin, end, err := beginAndEndPortFromPortRange(option.PortRange)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid port-range format")
|
||||||
|
}
|
||||||
|
if begin < 1 || begin > 65535 {
|
||||||
|
return fmt.Errorf("begin port must be between 1 and 65535")
|
||||||
|
}
|
||||||
|
if end < 1 || end > 65535 {
|
||||||
|
return fmt.Errorf("end port must be between 1 and 65535")
|
||||||
|
}
|
||||||
|
if begin > end {
|
||||||
|
return fmt.Errorf("begin port must be less than or equal to end port")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Transport != "TCP" && option.Transport != "UDP" {
|
||||||
|
return fmt.Errorf("transport must be TCP or UDP")
|
||||||
|
}
|
||||||
|
if option.UserName == "" {
|
||||||
|
return fmt.Errorf("username is empty")
|
||||||
|
}
|
||||||
|
if option.Password == "" {
|
||||||
|
return fmt.Errorf("password is empty")
|
||||||
|
}
|
||||||
|
if option.Multiplexing != "" {
|
||||||
|
if _, ok := mierupb.MultiplexingLevel_value[option.Multiplexing]; !ok {
|
||||||
|
return fmt.Errorf("invalid multiplexing level: %s", option.Multiplexing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option.HandshakeMode != "" {
|
||||||
|
if _, ok := mierupb.HandshakeMode_value[option.HandshakeMode]; !ok {
|
||||||
|
return fmt.Errorf("invalid handshake mode: %s", option.HandshakeMode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option.TrafficPattern != "" {
|
||||||
|
trafficPattern, err := mierutp.Decode(option.TrafficPattern)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to decode traffic pattern %q: %w", option.TrafficPattern, err)
|
||||||
|
}
|
||||||
|
if err := mierutp.Validate(trafficPattern); err != nil {
|
||||||
|
return fmt.Errorf("invalid traffic pattern %q: %w", option.TrafficPattern, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func beginAndEndPortFromPortRange(portRange string) (int, int, error) {
|
||||||
|
var begin, end int
|
||||||
|
_, err := fmt.Sscanf(portRange, "%d-%d", &begin, &end)
|
||||||
|
return begin, end, err
|
||||||
|
}
|
||||||
93
adapter/outbound/mieru_test.go
Normal file
93
adapter/outbound/mieru_test.go
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestNewMieru(t *testing.T) {
|
||||||
|
testCases := []struct {
|
||||||
|
option MieruOption
|
||||||
|
wantBaseAddr string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
option: MieruOption{
|
||||||
|
Name: "test",
|
||||||
|
Server: "1.2.3.4",
|
||||||
|
Port: 10000,
|
||||||
|
Transport: "TCP",
|
||||||
|
UserName: "test",
|
||||||
|
Password: "test",
|
||||||
|
},
|
||||||
|
wantBaseAddr: "1.2.3.4:10000",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
option: MieruOption{
|
||||||
|
Name: "test",
|
||||||
|
Server: "2001:db8::1",
|
||||||
|
PortRange: "10001-10002",
|
||||||
|
Transport: "TCP",
|
||||||
|
UserName: "test",
|
||||||
|
Password: "test",
|
||||||
|
},
|
||||||
|
wantBaseAddr: "[2001:db8::1]:10001",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
option: MieruOption{
|
||||||
|
Name: "test",
|
||||||
|
Server: "example.com",
|
||||||
|
Port: 10003,
|
||||||
|
Transport: "UDP",
|
||||||
|
UserName: "test",
|
||||||
|
Password: "test",
|
||||||
|
TrafficPattern: "GgQIARAK",
|
||||||
|
},
|
||||||
|
wantBaseAddr: "example.com:10003",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
mieru, err := NewMieru(testCase.option)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
if mieru.addr != testCase.wantBaseAddr {
|
||||||
|
t.Errorf("got addr %q, want %q", mieru.addr, testCase.wantBaseAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBeginAndEndPortFromPortRange(t *testing.T) {
|
||||||
|
testCases := []struct {
|
||||||
|
input string
|
||||||
|
begin int
|
||||||
|
end int
|
||||||
|
hasErr bool
|
||||||
|
}{
|
||||||
|
{"1-10", 1, 10, false},
|
||||||
|
{"1000-2000", 1000, 2000, false},
|
||||||
|
{"65535-65535", 65535, 65535, false},
|
||||||
|
{"1", 0, 0, true},
|
||||||
|
{"1-", 0, 0, true},
|
||||||
|
{"-10", 0, 0, true},
|
||||||
|
{"a-b", 0, 0, true},
|
||||||
|
{"1-b", 0, 0, true},
|
||||||
|
{"a-10", 0, 0, true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
begin, end, err := beginAndEndPortFromPortRange(testCase.input)
|
||||||
|
if testCase.hasErr {
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("beginAndEndPortFromPortRange(%s) should return an error", testCase.input)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("beginAndEndPortFromPortRange(%s) should not return an error, but got %v", testCase.input, err)
|
||||||
|
}
|
||||||
|
if begin != testCase.begin {
|
||||||
|
t.Errorf("beginAndEndPortFromPortRange(%s) begin port mismatch, got %d, want %d", testCase.input, begin, testCase.begin)
|
||||||
|
}
|
||||||
|
if end != testCase.end {
|
||||||
|
t.Errorf("beginAndEndPortFromPortRange(%s) end port mismatch, got %d, want %d", testCase.input, end, testCase.end)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
47
adapter/outbound/reality.go
Normal file
47
adapter/outbound/reality.go
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdh"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
|
)
|
||||||
|
|
||||||
|
type RealityOptions struct {
|
||||||
|
PublicKey string `proxy:"public-key"`
|
||||||
|
ShortID string `proxy:"short-id,omitempty"`
|
||||||
|
|
||||||
|
SupportX25519MLKEM768 bool `proxy:"support-x25519mlkem768,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o RealityOptions) Parse() (*tlsC.RealityConfig, error) {
|
||||||
|
if o.PublicKey != "" {
|
||||||
|
config := new(tlsC.RealityConfig)
|
||||||
|
config.SupportX25519MLKEM768 = o.SupportX25519MLKEM768
|
||||||
|
|
||||||
|
const x25519ScalarSize = 32
|
||||||
|
publicKey, err := base64.RawURLEncoding.DecodeString(o.PublicKey)
|
||||||
|
if err != nil || len(publicKey) != x25519ScalarSize {
|
||||||
|
return nil, errors.New("invalid REALITY public key")
|
||||||
|
}
|
||||||
|
config.PublicKey, err = ecdh.X25519().NewPublicKey(publicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("fail to create REALITY public key: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
n := hex.DecodedLen(len(o.ShortID))
|
||||||
|
if n > tlsC.RealityMaxShortIDLen {
|
||||||
|
return nil, errors.New("invalid REALITY short id")
|
||||||
|
}
|
||||||
|
n, err = hex.Decode(config.ShortID[:], []byte(o.ShortID))
|
||||||
|
if err != nil || n > tlsC.RealityMaxShortIDLen {
|
||||||
|
return nil, errors.New("invalid REALITY short ID")
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
@@ -4,59 +4,136 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Reject struct {
|
type Reject struct {
|
||||||
*Base
|
*Base
|
||||||
|
drop bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type RejectOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Reject) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
return NewConn(&nopConn{}, r), nil
|
if r.drop {
|
||||||
|
return NewConn(dropConn{}, r), nil
|
||||||
|
}
|
||||||
|
return NewConn(nopConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Reject) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
if err := r.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
return newPacketConn(&nopPacketConn{}, r), nil
|
return newPacketConn(&nopPacketConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func (r *Reject) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
metadata.DstIP = netip.IPv4Unspecified()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRejectWithOption(option RejectOption) *Reject {
|
||||||
return &Reject{
|
return &Reject{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "REJECT",
|
name: option.Name,
|
||||||
tp: C.Reject,
|
tp: C.Reject,
|
||||||
udp: true,
|
udp: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NewReject() *Reject {
|
||||||
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "REJECT",
|
||||||
|
tp: C.Reject,
|
||||||
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRejectDrop() *Reject {
|
||||||
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "REJECT-DROP",
|
||||||
|
tp: C.RejectDrop,
|
||||||
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
|
},
|
||||||
|
drop: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPass() *Reject {
|
||||||
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "PASS",
|
||||||
|
tp: C.Pass,
|
||||||
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type nopConn struct{}
|
type nopConn struct{}
|
||||||
|
|
||||||
func (rw *nopConn) Read(b []byte) (int, error) {
|
func (rw nopConn) Read(b []byte) (int, error) { return 0, io.EOF }
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw *nopConn) Write(b []byte) (int, error) {
|
func (rw nopConn) ReadBuffer(buffer *buf.Buffer) error { return io.EOF }
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rw *nopConn) Close() error { return nil }
|
func (rw nopConn) Write(b []byte) (int, error) { return 0, io.EOF }
|
||||||
func (rw *nopConn) LocalAddr() net.Addr { return nil }
|
func (rw nopConn) WriteBuffer(buffer *buf.Buffer) error { return io.EOF }
|
||||||
func (rw *nopConn) RemoteAddr() net.Addr { return nil }
|
func (rw nopConn) Close() error { return nil }
|
||||||
func (rw *nopConn) SetDeadline(time.Time) error { return nil }
|
func (rw nopConn) LocalAddr() net.Addr { return nil }
|
||||||
func (rw *nopConn) SetReadDeadline(time.Time) error { return nil }
|
func (rw nopConn) RemoteAddr() net.Addr { return nil }
|
||||||
func (rw *nopConn) SetWriteDeadline(time.Time) error { return nil }
|
func (rw nopConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (rw nopConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (rw nopConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
var udpAddrIPv4Unspecified = &net.UDPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
|
|
||||||
type nopPacketConn struct{}
|
type nopPacketConn struct{}
|
||||||
|
|
||||||
func (npc *nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) { return len(b), nil }
|
func (npc nopPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
func (npc *nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { return 0, nil, io.EOF }
|
return len(b), nil
|
||||||
func (npc *nopPacketConn) Close() error { return nil }
|
}
|
||||||
func (npc *nopPacketConn) LocalAddr() net.Addr { return &net.UDPAddr{IP: net.IPv4zero, Port: 0} }
|
func (npc nopPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
func (npc *nopPacketConn) SetDeadline(time.Time) error { return nil }
|
return 0, nil, io.EOF
|
||||||
func (npc *nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
}
|
||||||
func (npc *nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
func (npc nopPacketConn) WaitReadFrom() ([]byte, func(), net.Addr, error) {
|
||||||
|
return nil, nil, nil, io.EOF
|
||||||
|
}
|
||||||
|
func (npc nopPacketConn) Close() error { return nil }
|
||||||
|
func (npc nopPacketConn) LocalAddr() net.Addr { return udpAddrIPv4Unspecified }
|
||||||
|
func (npc nopPacketConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (npc nopPacketConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (npc nopPacketConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|
||||||
|
type dropConn struct{}
|
||||||
|
|
||||||
|
func (rw dropConn) Read(b []byte) (int, error) { return 0, io.EOF }
|
||||||
|
func (rw dropConn) ReadBuffer(buffer *buf.Buffer) error {
|
||||||
|
time.Sleep(C.DefaultDropTime)
|
||||||
|
return io.EOF
|
||||||
|
}
|
||||||
|
func (rw dropConn) Write(b []byte) (int, error) { return 0, io.EOF }
|
||||||
|
func (rw dropConn) WriteBuffer(buffer *buf.Buffer) error { return io.EOF }
|
||||||
|
func (rw dropConn) Close() error { return nil }
|
||||||
|
func (rw dropConn) LocalAddr() net.Addr { return nil }
|
||||||
|
func (rw dropConn) RemoteAddr() net.Addr { return nil }
|
||||||
|
func (rw dropConn) SetDeadline(time.Time) error { return nil }
|
||||||
|
func (rw dropConn) SetReadDeadline(time.Time) error { return nil }
|
||||||
|
func (rw dropConn) SetWriteDeadline(time.Time) error { return nil }
|
||||||
|
|||||||
@@ -2,41 +2,55 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
"github.com/metacubex/mihomo/ntp"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
gost "github.com/metacubex/mihomo/transport/gost-plugin"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
"github.com/metacubex/mihomo/transport/kcptun"
|
||||||
|
"github.com/metacubex/mihomo/transport/restls"
|
||||||
|
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
||||||
|
shadowtls "github.com/metacubex/mihomo/transport/sing-shadowtls"
|
||||||
|
v2rayObfs "github.com/metacubex/mihomo/transport/v2ray-plugin"
|
||||||
|
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
shadowsocks "github.com/metacubex/sing-shadowsocks2"
|
||||||
|
"github.com/metacubex/sing/common/bufio"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
"github.com/metacubex/sing/common/uot"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocks struct {
|
type ShadowSocks struct {
|
||||||
*Base
|
*Base
|
||||||
cipher core.Cipher
|
method shadowsocks.Method
|
||||||
|
|
||||||
|
option *ShadowSocksOption
|
||||||
// obfs
|
// obfs
|
||||||
obfsMode string
|
obfsMode string
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
v2rayOption *v2rayObfs.Option
|
v2rayOption *v2rayObfs.Option
|
||||||
|
gostOption *gost.Option
|
||||||
|
shadowTLSOption *shadowtls.ShadowTLSOption
|
||||||
|
restlsConfig *restls.Config
|
||||||
|
kcptunClient *kcptun.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
type ShadowSocksOption struct {
|
type ShadowSocksOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Plugin string `proxy:"plugin,omitempty"`
|
Plugin string `proxy:"plugin,omitempty"`
|
||||||
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
PluginOpts map[string]any `proxy:"plugin-opts,omitempty"`
|
||||||
|
UDPOverTCP bool `proxy:"udp-over-tcp,omitempty"`
|
||||||
|
UDPOverTCPVersion int `proxy:"udp-over-tcp-version,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@@ -45,17 +59,84 @@ type simpleObfsOption struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type v2rayObfsOption struct {
|
type v2rayObfsOption struct {
|
||||||
|
Mode string `obfs:"mode"`
|
||||||
|
Host string `obfs:"host,omitempty"`
|
||||||
|
Path string `obfs:"path,omitempty"`
|
||||||
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
|
ECHOpts ECHOptions `obfs:"ech-opts,omitempty"`
|
||||||
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
Certificate string `obfs:"certificate,omitempty"`
|
||||||
|
PrivateKey string `obfs:"private-key,omitempty"`
|
||||||
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
|
V2rayHttpUpgrade bool `obfs:"v2ray-http-upgrade,omitempty"`
|
||||||
|
V2rayHttpUpgradeFastOpen bool `obfs:"v2ray-http-upgrade-fast-open,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type gostObfsOption struct {
|
||||||
Mode string `obfs:"mode"`
|
Mode string `obfs:"mode"`
|
||||||
Host string `obfs:"host,omitempty"`
|
Host string `obfs:"host,omitempty"`
|
||||||
Path string `obfs:"path,omitempty"`
|
Path string `obfs:"path,omitempty"`
|
||||||
TLS bool `obfs:"tls,omitempty"`
|
TLS bool `obfs:"tls,omitempty"`
|
||||||
|
ECHOpts ECHOptions `obfs:"ech-opts,omitempty"`
|
||||||
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
Certificate string `obfs:"certificate,omitempty"`
|
||||||
|
PrivateKey string `obfs:"private-key,omitempty"`
|
||||||
Headers map[string]string `obfs:"headers,omitempty"`
|
Headers map[string]string `obfs:"headers,omitempty"`
|
||||||
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
Mux bool `obfs:"mux,omitempty"`
|
Mux bool `obfs:"mux,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
type shadowTLSOption struct {
|
||||||
func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
Password string `obfs:"password,omitempty"`
|
||||||
|
Host string `obfs:"host"`
|
||||||
|
Fingerprint string `obfs:"fingerprint,omitempty"`
|
||||||
|
Certificate string `obfs:"certificate,omitempty"`
|
||||||
|
PrivateKey string `obfs:"private-key,omitempty"`
|
||||||
|
SkipCertVerify bool `obfs:"skip-cert-verify,omitempty"`
|
||||||
|
Version int `obfs:"version,omitempty"`
|
||||||
|
ALPN []string `obfs:"alpn,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type restlsOption struct {
|
||||||
|
Password string `obfs:"password"`
|
||||||
|
Host string `obfs:"host"`
|
||||||
|
VersionHint string `obfs:"version-hint"`
|
||||||
|
RestlsScript string `obfs:"restls-script,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type kcpTunOption struct {
|
||||||
|
Key string `obfs:"key,omitempty"`
|
||||||
|
Crypt string `obfs:"crypt,omitempty"`
|
||||||
|
Mode string `obfs:"mode,omitempty"`
|
||||||
|
Conn int `obfs:"conn,omitempty"`
|
||||||
|
AutoExpire int `obfs:"autoexpire,omitempty"`
|
||||||
|
ScavengeTTL int `obfs:"scavengettl,omitempty"`
|
||||||
|
MTU int `obfs:"mtu,omitempty"`
|
||||||
|
RateLimit int `obfs:"ratelimit,omitempty"`
|
||||||
|
SndWnd int `obfs:"sndwnd,omitempty"`
|
||||||
|
RcvWnd int `obfs:"rcvwnd,omitempty"`
|
||||||
|
DataShard int `obfs:"datashard,omitempty"`
|
||||||
|
ParityShard int `obfs:"parityshard,omitempty"`
|
||||||
|
DSCP int `obfs:"dscp,omitempty"`
|
||||||
|
NoComp bool `obfs:"nocomp,omitempty"`
|
||||||
|
AckNodelay bool `obfs:"acknodelay,omitempty"`
|
||||||
|
NoDelay int `obfs:"nodelay,omitempty"`
|
||||||
|
Interval int `obfs:"interval,omitempty"`
|
||||||
|
Resend int `obfs:"resend,omitempty"`
|
||||||
|
NoCongestion int `obfs:"nc,omitempty"`
|
||||||
|
SockBuf int `obfs:"sockbuf,omitempty"`
|
||||||
|
SmuxVer int `obfs:"smuxver,omitempty"`
|
||||||
|
SmuxBuf int `obfs:"smuxbuf,omitempty"`
|
||||||
|
FrameSize int `obfs:"framesize,omitempty"`
|
||||||
|
StreamBuf int `obfs:"streambuf,omitempty"`
|
||||||
|
KeepAlive int `obfs:"keepalive,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||||
|
useEarly := false
|
||||||
switch ss.obfsMode {
|
switch ss.obfsMode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, ss.obfsOption.Host)
|
||||||
@@ -63,59 +144,162 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
_, port, _ := net.SplitHostPort(ss.addr)
|
_, port, _ := net.SplitHostPort(ss.addr)
|
||||||
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
c = obfs.NewHTTPObfs(c, ss.obfsOption.Host, port)
|
||||||
case "websocket":
|
case "websocket":
|
||||||
var err error
|
if ss.v2rayOption != nil {
|
||||||
c, err = v2rayObfs.NewV2rayObfs(c, ss.v2rayOption)
|
c, err = v2rayObfs.NewV2rayObfs(ctx, c, ss.v2rayOption)
|
||||||
|
} else if ss.gostOption != nil {
|
||||||
|
c, err = gost.NewGostWebsocket(ctx, c, ss.gostOption)
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("plugin options is required")
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
|
case shadowtls.Mode:
|
||||||
|
c, err = shadowtls.NewShadowTLS(ctx, c, ss.shadowTLSOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
useEarly = true
|
||||||
|
case restls.Mode:
|
||||||
|
c, err = restls.NewRestls(ctx, c, ss.restlsConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s (restls) connect error: %w", ss.addr, err)
|
||||||
|
}
|
||||||
|
useEarly = true
|
||||||
|
}
|
||||||
|
useEarly = useEarly || N.NeedHandshake(c)
|
||||||
|
if !useEarly {
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
|
uotDestination := uot.RequestDestination(uint8(ss.option.UDPOverTCPVersion))
|
||||||
|
if useEarly {
|
||||||
|
return ss.method.DialEarlyConn(c, uotDestination), nil
|
||||||
|
} else {
|
||||||
|
return ss.method.DialConn(c, uotDestination)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if useEarly {
|
||||||
|
return ss.method.DialEarlyConn(c, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort)), nil
|
||||||
|
} else {
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
||||||
}
|
}
|
||||||
c = ss.cipher.StreamConn(c)
|
|
||||||
_, err := c.Write(serializesSocksAddr(metadata))
|
|
||||||
return c, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
var c net.Conn
|
||||||
|
if ss.kcptunClient != nil {
|
||||||
|
c, err = ss.kcptunClient.OpenStream(ctx, func(ctx context.Context) (net.PacketConn, net.Addr, error) {
|
||||||
|
if err = ss.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
addr, err := resolveUDPAddr(ctx, "udp", ss.addr, ss.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := ss.dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return pc, addr, nil
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
c, err = ss.dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, ss), err
|
return NewConn(c, ss), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ss *ShadowSocks) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
if ss.option.UDPOverTCP {
|
||||||
|
tcpConn, err := ss.DialContext(ctx, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ss.ListenPacketOnStreamConn(ctx, tcpConn, metadata)
|
||||||
|
}
|
||||||
|
if err := ss.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
addr, err := resolveUDPAddr(ctx, "udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ss.addr)
|
pc, err := ss.dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
pc = ss.method.DialPacketConn(bufio.NewBindPacketConn(pc, addr))
|
||||||
|
return newPacketConn(pc, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
pc = ss.cipher.PacketConn(pc)
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ss), nil
|
func (ss *ShadowSocks) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := ss.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = ss.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if ss.option.UDPOverTCP {
|
||||||
|
if err = ss.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||||
|
if ss.option.UDPOverTCPVersion == uot.LegacyVersion {
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(uot.NewConn(c, uot.Request{Destination: destination})), ss), nil
|
||||||
|
} else {
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination})), ss), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, C.ErrNotSupport
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) SupportUOT() bool {
|
||||||
|
return ss.option.UDPOverTCP
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *ShadowSocks) Close() error {
|
||||||
|
if ss.kcptunClient != nil {
|
||||||
|
return ss.kcptunClient.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
cipher := option.Cipher
|
method, err := shadowsocks.CreateMethod(option.Cipher, shadowsocks.MethodOptions{
|
||||||
password := option.Password
|
Password: option.Password,
|
||||||
ciph, err := core.PickCipher(cipher, nil, password)
|
TimeFunc: ntp.Now,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s cipher: %s initialize error: %w", addr, option.Cipher, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var v2rayOption *v2rayObfs.Option
|
var v2rayOption *v2rayObfs.Option
|
||||||
|
var gostOption *gost.Option
|
||||||
var obfsOption *simpleObfsOption
|
var obfsOption *simpleObfsOption
|
||||||
|
var shadowTLSOpt *shadowtls.ShadowTLSOption
|
||||||
|
var restlsConfig *restls.Config
|
||||||
|
var kcptunClient *kcptun.Client
|
||||||
obfsMode := ""
|
obfsMode := ""
|
||||||
|
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "obfs", WeaklyTypedInput: true})
|
||||||
@@ -141,6 +325,38 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
}
|
}
|
||||||
obfsMode = opts.Mode
|
obfsMode = opts.Mode
|
||||||
v2rayOption = &v2rayObfs.Option{
|
v2rayOption = &v2rayObfs.Option{
|
||||||
|
Host: opts.Host,
|
||||||
|
Path: opts.Path,
|
||||||
|
Headers: opts.Headers,
|
||||||
|
Mux: opts.Mux,
|
||||||
|
V2rayHttpUpgrade: opts.V2rayHttpUpgrade,
|
||||||
|
V2rayHttpUpgradeFastOpen: opts.V2rayHttpUpgradeFastOpen,
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.TLS {
|
||||||
|
v2rayOption.TLS = true
|
||||||
|
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
|
v2rayOption.Fingerprint = opts.Fingerprint
|
||||||
|
v2rayOption.Certificate = opts.Certificate
|
||||||
|
v2rayOption.PrivateKey = opts.PrivateKey
|
||||||
|
|
||||||
|
echConfig, err := opts.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize v2ray-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
v2rayOption.ECHConfig = echConfig
|
||||||
|
}
|
||||||
|
} else if option.Plugin == "gost-plugin" {
|
||||||
|
opts := gostObfsOption{Host: "bing.com", Mux: true}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, &opts); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize gost-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Mode != "websocket" {
|
||||||
|
return nil, fmt.Errorf("ss %s obfs mode error: %s", addr, opts.Mode)
|
||||||
|
}
|
||||||
|
obfsMode = opts.Mode
|
||||||
|
gostOption = &gost.Option{
|
||||||
Host: opts.Host,
|
Host: opts.Host,
|
||||||
Path: opts.Path,
|
Path: opts.Path,
|
||||||
Headers: opts.Headers,
|
Headers: opts.Headers,
|
||||||
@@ -148,57 +364,123 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if opts.TLS {
|
if opts.TLS {
|
||||||
v2rayOption.TLS = true
|
gostOption.TLS = true
|
||||||
v2rayOption.SkipCertVerify = opts.SkipCertVerify
|
gostOption.SkipCertVerify = opts.SkipCertVerify
|
||||||
|
gostOption.Fingerprint = opts.Fingerprint
|
||||||
|
gostOption.Certificate = opts.Certificate
|
||||||
|
gostOption.PrivateKey = opts.PrivateKey
|
||||||
|
|
||||||
|
echConfig, err := opts.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize gost-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
gostOption.ECHConfig = echConfig
|
||||||
}
|
}
|
||||||
|
} else if option.Plugin == shadowtls.Mode {
|
||||||
|
obfsMode = shadowtls.Mode
|
||||||
|
opt := &shadowTLSOption{
|
||||||
|
Version: 2,
|
||||||
|
}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, opt); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize shadow-tls-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
shadowTLSOpt = &shadowtls.ShadowTLSOption{
|
||||||
|
Password: opt.Password,
|
||||||
|
Host: opt.Host,
|
||||||
|
Fingerprint: opt.Fingerprint,
|
||||||
|
Certificate: opt.Certificate,
|
||||||
|
PrivateKey: opt.PrivateKey,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
SkipCertVerify: opt.SkipCertVerify,
|
||||||
|
Version: opt.Version,
|
||||||
|
}
|
||||||
|
|
||||||
|
if opt.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
|
shadowTLSOpt.ALPN = opt.ALPN
|
||||||
|
} else {
|
||||||
|
shadowTLSOpt.ALPN = shadowtls.DefaultALPN
|
||||||
|
}
|
||||||
|
} else if option.Plugin == restls.Mode {
|
||||||
|
obfsMode = restls.Mode
|
||||||
|
restlsOpt := &restlsOption{}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, restlsOpt); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
restlsConfig, err = restls.NewRestlsConfig(restlsOpt.Host, restlsOpt.Password, restlsOpt.VersionHint, restlsOpt.RestlsScript, option.ClientFingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize restls-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if option.Plugin == kcptun.Mode {
|
||||||
|
obfsMode = kcptun.Mode
|
||||||
|
kcptunOpt := &kcpTunOption{}
|
||||||
|
if err := decoder.Decode(option.PluginOpts, kcptunOpt); err != nil {
|
||||||
|
return nil, fmt.Errorf("ss %s initialize kcptun-plugin error: %w", addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
kcptunClient = kcptun.NewClient(kcptun.Config{
|
||||||
|
Key: kcptunOpt.Key,
|
||||||
|
Crypt: kcptunOpt.Crypt,
|
||||||
|
Mode: kcptunOpt.Mode,
|
||||||
|
Conn: kcptunOpt.Conn,
|
||||||
|
AutoExpire: kcptunOpt.AutoExpire,
|
||||||
|
ScavengeTTL: kcptunOpt.ScavengeTTL,
|
||||||
|
MTU: kcptunOpt.MTU,
|
||||||
|
RateLimit: kcptunOpt.RateLimit,
|
||||||
|
SndWnd: kcptunOpt.SndWnd,
|
||||||
|
RcvWnd: kcptunOpt.RcvWnd,
|
||||||
|
DataShard: kcptunOpt.DataShard,
|
||||||
|
ParityShard: kcptunOpt.ParityShard,
|
||||||
|
DSCP: kcptunOpt.DSCP,
|
||||||
|
NoComp: kcptunOpt.NoComp,
|
||||||
|
AckNodelay: kcptunOpt.AckNodelay,
|
||||||
|
NoDelay: kcptunOpt.NoDelay,
|
||||||
|
Interval: kcptunOpt.Interval,
|
||||||
|
Resend: kcptunOpt.Resend,
|
||||||
|
NoCongestion: kcptunOpt.NoCongestion,
|
||||||
|
SockBuf: kcptunOpt.SockBuf,
|
||||||
|
SmuxVer: kcptunOpt.SmuxVer,
|
||||||
|
SmuxBuf: kcptunOpt.SmuxBuf,
|
||||||
|
FrameSize: kcptunOpt.FrameSize,
|
||||||
|
StreamBuf: kcptunOpt.StreamBuf,
|
||||||
|
KeepAlive: kcptunOpt.KeepAlive,
|
||||||
|
})
|
||||||
|
option.UDPOverTCP = true // must open uot
|
||||||
|
}
|
||||||
|
switch option.UDPOverTCPVersion {
|
||||||
|
case uot.Version, uot.LegacyVersion:
|
||||||
|
case 0:
|
||||||
|
option.UDPOverTCPVersion = uot.LegacyVersion
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("ss %s unknown udp over tcp protocol version: %d", addr, option.UDPOverTCPVersion)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocks{
|
outbound := &ShadowSocks{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
pdName: option.ProviderName,
|
||||||
iface: option.Interface,
|
udp: option.UDP,
|
||||||
rmark: option.RoutingMark,
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
cipher: ciph,
|
method: method,
|
||||||
|
|
||||||
obfsMode: obfsMode,
|
option: &option,
|
||||||
v2rayOption: v2rayOption,
|
obfsMode: obfsMode,
|
||||||
obfsOption: obfsOption,
|
v2rayOption: v2rayOption,
|
||||||
}, nil
|
gostOption: gostOption,
|
||||||
}
|
obfsOption: obfsOption,
|
||||||
|
shadowTLSOption: shadowTLSOpt,
|
||||||
type ssPacketConn struct {
|
restlsConfig: restlsConfig,
|
||||||
net.PacketConn
|
kcptunClient: kcptunClient,
|
||||||
rAddr net.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (spc *ssPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
|
||||||
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
return spc.PacketConn.WriteTo(packet[3:], spc.rAddr)
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
}
|
return outbound, nil
|
||||||
|
|
||||||
func (spc *ssPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
n, _, e := spc.PacketConn.ReadFrom(b)
|
|
||||||
if e != nil {
|
|
||||||
return 0, nil, e
|
|
||||||
}
|
|
||||||
|
|
||||||
addr := socks5.SplitAddr(b[:n])
|
|
||||||
if addr == nil {
|
|
||||||
return 0, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
udpAddr := addr.UDPAddr()
|
|
||||||
if udpAddr == nil {
|
|
||||||
return 0, nil, errors.New("parse addr error")
|
|
||||||
}
|
|
||||||
|
|
||||||
copy(b, b[len(addr):])
|
|
||||||
return n - len(addr), udpAddr, e
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,22 +2,24 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/obfs"
|
"github.com/metacubex/mihomo/transport/shadowsocks/core"
|
||||||
"github.com/Dreamacro/clash/transport/ssr/protocol"
|
"github.com/metacubex/mihomo/transport/shadowsocks/shadowaead"
|
||||||
|
"github.com/metacubex/mihomo/transport/shadowsocks/shadowstream"
|
||||||
"github.com/Dreamacro/go-shadowsocks2/core"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
"github.com/Dreamacro/go-shadowsocks2/shadowaead"
|
"github.com/metacubex/mihomo/transport/ssr/obfs"
|
||||||
"github.com/Dreamacro/go-shadowsocks2/shadowstream"
|
"github.com/metacubex/mihomo/transport/ssr/protocol"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ShadowSocksR struct {
|
type ShadowSocksR struct {
|
||||||
*Base
|
*Base
|
||||||
|
option *ShadowSocksROption
|
||||||
cipher core.Cipher
|
cipher core.Cipher
|
||||||
obfs obfs.Obfs
|
obfs obfs.Obfs
|
||||||
protocol protocol.Protocol
|
protocol protocol.Protocol
|
||||||
@@ -37,13 +39,16 @@ type ShadowSocksROption struct {
|
|||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ssr *ShadowSocksR) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
c = ssr.obfs.StreamConn(c)
|
c = ssr.obfs.StreamConn(c)
|
||||||
c = ssr.cipher.StreamConn(c)
|
c = ssr.cipher.StreamConn(c)
|
||||||
var (
|
var (
|
||||||
iv []byte
|
iv []byte
|
||||||
err error
|
|
||||||
)
|
)
|
||||||
switch conn := c.(type) {
|
switch conn := c.(type) {
|
||||||
case *shadowstream.Conn:
|
case *shadowstream.Conn:
|
||||||
@@ -60,40 +65,50 @@ func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ssr *ShadowSocksR) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
c, err := ssr.dialer.DialContext(ctx, "tcp", ssr.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ssr.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ssr.StreamConn(c, metadata)
|
c, err = ssr.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, ssr), err
|
return NewConn(c, ssr), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ssr.Base.DialOptions(opts...)...)
|
if err := ssr.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
addr, err := resolveUDPAddr(ctx, "udp", ssr.addr, ssr.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ssr.addr)
|
pc, err := ssr.dialer.ListenPacket(ctx, "udp", "", addr.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pc.Close()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
pc = ssr.cipher.PacketConn(pc)
|
epc := ssr.cipher.PacketConn(N.NewEnhancePacketConn(pc))
|
||||||
pc = ssr.protocol.PacketConn(pc)
|
epc = ssr.protocol.PacketConn(epc)
|
||||||
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
return newPacketConn(&ssrPacketConn{EnhancePacketConn: epc, rAddr: addr}, ssr), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (ssr *ShadowSocksR) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := ssr.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = ssr.option.DialerProxy
|
||||||
|
return info
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
// SSR protocol compatibility
|
// SSR protocol compatibility
|
||||||
// https://github.com/Dreamacro/clash/pull/2056
|
// https://github.com/metacubex/mihomo/pull/2056
|
||||||
if option.Cipher == "none" {
|
if option.Cipher == "none" {
|
||||||
option.Cipher = "dummy"
|
option.Cipher = "dummy"
|
||||||
}
|
}
|
||||||
@@ -103,7 +118,7 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
password := option.Password
|
password := option.Password
|
||||||
coreCiph, err := core.PickCipher(cipher, nil, password)
|
coreCiph, err := core.PickCipher(cipher, nil, password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ssr %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ssr %s cipher: %s initialize error: %w", addr, cipher, err)
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
ivSize int
|
ivSize int
|
||||||
@@ -142,17 +157,84 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
return nil, fmt.Errorf("ssr %s initialize protocol error: %w", addr, err)
|
return nil, fmt.Errorf("ssr %s initialize protocol error: %w", addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &ShadowSocksR{
|
outbound := &ShadowSocksR{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
pdName: option.ProviderName,
|
||||||
iface: option.Interface,
|
udp: option.UDP,
|
||||||
rmark: option.RoutingMark,
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
protocol: protocol,
|
protocol: protocol,
|
||||||
}, nil
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type ssrPacketConn struct {
|
||||||
|
N.EnhancePacketConn
|
||||||
|
rAddr net.Addr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssrPacketConn) WriteTo(b []byte, addr net.Addr) (n int, err error) {
|
||||||
|
packet, err := socks5.EncodeUDPPacket(socks5.ParseAddrToSocksAddr(addr), b)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return spc.EnhancePacketConn.WriteTo(packet[3:], spc.rAddr)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssrPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
|
n, _, e := spc.EnhancePacketConn.ReadFrom(b)
|
||||||
|
if e != nil {
|
||||||
|
return 0, nil, e
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := socks5.SplitAddr(b[:n])
|
||||||
|
if addr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
return 0, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(b, b[len(addr):])
|
||||||
|
return n - len(addr), udpAddr, e
|
||||||
|
}
|
||||||
|
|
||||||
|
func (spc *ssrPacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
|
||||||
|
data, put, _, err = spc.EnhancePacketConn.WaitReadFrom()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
_addr := socks5.SplitAddr(data)
|
||||||
|
if _addr == nil {
|
||||||
|
if put != nil {
|
||||||
|
put()
|
||||||
|
}
|
||||||
|
return nil, nil, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
|
||||||
|
udpAddr := _addr.UDPAddr()
|
||||||
|
if udpAddr == nil {
|
||||||
|
if put != nil {
|
||||||
|
put()
|
||||||
|
}
|
||||||
|
return nil, nil, nil, errors.New("parse addr error")
|
||||||
|
}
|
||||||
|
addr = udpAddr
|
||||||
|
|
||||||
|
data = data[len(_addr):]
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
121
adapter/outbound/singmux.go
Normal file
121
adapter/outbound/singmux.go
Normal file
@@ -0,0 +1,121 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
|
mux "github.com/metacubex/sing-mux"
|
||||||
|
E "github.com/metacubex/sing/common/exceptions"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SingMux struct {
|
||||||
|
ProxyAdapter
|
||||||
|
client *mux.Client
|
||||||
|
onlyTcp bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type SingMuxOption struct {
|
||||||
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
|
MaxConnections int `proxy:"max-connections,omitempty"`
|
||||||
|
MinStreams int `proxy:"min-streams,omitempty"`
|
||||||
|
MaxStreams int `proxy:"max-streams,omitempty"`
|
||||||
|
Padding bool `proxy:"padding,omitempty"`
|
||||||
|
Statistic bool `proxy:"statistic,omitempty"`
|
||||||
|
OnlyTcp bool `proxy:"only-tcp,omitempty"`
|
||||||
|
BrutalOpts BrutalOption `proxy:"brutal-opts,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type BrutalOption struct {
|
||||||
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
|
Up string `proxy:"up,omitempty"`
|
||||||
|
Down string `proxy:"down,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := s.client.DialContext(ctx, "tcp", M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(c, s), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if s.onlyTcp {
|
||||||
|
return s.ProxyAdapter.ListenPacketContext(ctx, metadata)
|
||||||
|
}
|
||||||
|
if err = s.ProxyAdapter.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pc, err := s.client.ListenPacket(ctx, M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pc == nil {
|
||||||
|
return nil, E.New("packetConn is nil")
|
||||||
|
}
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(pc), s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) SupportUDP() bool {
|
||||||
|
if s.onlyTcp {
|
||||||
|
return s.ProxyAdapter.SupportUDP()
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) SupportUOT() bool {
|
||||||
|
if s.onlyTcp {
|
||||||
|
return s.ProxyAdapter.SupportUOT()
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SingMux) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := s.ProxyAdapter.ProxyInfo()
|
||||||
|
info.SMUX = true
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (s *SingMux) Close() error {
|
||||||
|
if s.client != nil {
|
||||||
|
_ = s.client.Close()
|
||||||
|
}
|
||||||
|
return s.ProxyAdapter.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSingMux(option SingMuxOption, proxy ProxyAdapter) (ProxyAdapter, error) {
|
||||||
|
// TODO
|
||||||
|
// "TCP Brutal is only supported on Linux-based systems"
|
||||||
|
|
||||||
|
singDialer := proxydialer.NewSingDialer(proxydialer.New(proxy, option.Statistic))
|
||||||
|
client, err := mux.NewClient(mux.Options{
|
||||||
|
Dialer: singDialer,
|
||||||
|
Logger: log.SingLogger,
|
||||||
|
Protocol: option.Protocol,
|
||||||
|
MaxConnections: option.MaxConnections,
|
||||||
|
MinStreams: option.MinStreams,
|
||||||
|
MaxStreams: option.MaxStreams,
|
||||||
|
Padding: option.Padding,
|
||||||
|
Brutal: mux.BrutalOptions{
|
||||||
|
Enabled: option.BrutalOpts.Enabled,
|
||||||
|
SendBPS: StringToBps(option.BrutalOpts.Up),
|
||||||
|
ReceiveBPS: StringToBps(option.BrutalOpts.Down),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
outbound := &SingMux{
|
||||||
|
ProxyAdapter: proxy,
|
||||||
|
client: client,
|
||||||
|
onlyTcp: option.OnlyTcp,
|
||||||
|
}
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
@@ -6,15 +6,16 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/metacubex/mihomo/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/snell"
|
"github.com/metacubex/mihomo/transport/snell"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Snell struct {
|
type Snell struct {
|
||||||
*Base
|
*Base
|
||||||
|
option *SnellOption
|
||||||
psk []byte
|
psk []byte
|
||||||
pool *snell.Pool
|
pool *snell.Pool
|
||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
@@ -39,7 +40,7 @@ type streamOption struct {
|
|||||||
obfsOption *simpleObfsOption
|
obfsOption *simpleObfsOption
|
||||||
}
|
}
|
||||||
|
|
||||||
func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
func snellStreamConn(c net.Conn, option streamOption) *snell.Snell {
|
||||||
switch option.obfsOption.Mode {
|
switch option.obfsOption.Mode {
|
||||||
case "tls":
|
case "tls":
|
||||||
c = obfs.NewTLSObfs(c, option.obfsOption.Host)
|
c = obfs.NewTLSObfs(c, option.obfsOption.Host)
|
||||||
@@ -50,60 +51,68 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
|||||||
return snell.StreamConn(c, option.psk, option.version)
|
return snell.StreamConn(c, option.psk, option.version)
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (s *Snell) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = snellStreamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
if metadata.NetWork == C.UDP {
|
err := s.writeHeaderContext(ctx, c, metadata)
|
||||||
err := snell.WriteUDPHeader(c, s.version)
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
|
||||||
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Snell) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (err error) {
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
|
err = snell.WriteUDPHeader(c, s.version)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = snell.WriteHeader(c, metadata.String(), uint(metadata.DstPort), s.version)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
if s.version == snell.Version2 && len(opts) == 0 {
|
if s.version == snell.Version2 {
|
||||||
c, err := s.pool.Get()
|
c, err := s.pool.Get()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
if err = s.writeHeaderContext(ctx, c, metadata); err != nil {
|
||||||
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); err != nil {
|
_ = c.Close()
|
||||||
c.Close()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
c, err := s.dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = s.StreamConn(c, metadata)
|
c, err = s.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, s), err
|
return NewConn(c, s), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", s.addr, s.Base.DialOptions(opts...)...)
|
var err error
|
||||||
|
if err = s.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c, err := s.dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
|
||||||
|
|
||||||
return s.ListenPacketOnStreamConn(c, metadata)
|
c, err = s.StreamConnContext(ctx, c, metadata)
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
|
||||||
func (s *Snell) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
|
||||||
pc := snell.PacketConn(c)
|
pc := snell.PacketConn(c)
|
||||||
return newPacketConn(pc, s), nil
|
return newPacketConn(pc, s), nil
|
||||||
}
|
}
|
||||||
@@ -113,6 +122,13 @@ func (s *Snell) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (s *Snell) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := s.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = s.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
psk := []byte(option.Psk)
|
psk := []byte(option.Psk)
|
||||||
@@ -146,27 +162,32 @@ func NewSnell(option SnellOption) (*Snell, error) {
|
|||||||
|
|
||||||
s := &Snell{
|
s := &Snell{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Snell,
|
tp: C.Snell,
|
||||||
udp: option.UDP,
|
pdName: option.ProviderName,
|
||||||
iface: option.Interface,
|
udp: option.UDP,
|
||||||
rmark: option.RoutingMark,
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
version: option.Version,
|
version: option.Version,
|
||||||
}
|
}
|
||||||
|
s.dialer = option.NewDialer(s.DialOptions())
|
||||||
|
|
||||||
if option.Version == snell.Version2 {
|
if option.Version == snell.Version2 {
|
||||||
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
s.pool = snell.NewPool(func(ctx context.Context) (*snell.Snell, error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", addr, s.Base.DialOptions()...)
|
c, err := s.dialer.DialContext(ctx, "tcp", addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
return snellStreamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
||||||
return streamConn(c, streamOption{psk, option.Version, addr, obfsOption}), nil
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return s, nil
|
return s, nil
|
||||||
|
|||||||
@@ -2,20 +2,24 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
|
|
||||||
|
"github.com/metacubex/tls"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Socks5 struct {
|
type Socks5 struct {
|
||||||
*Base
|
*Base
|
||||||
|
option *Socks5Option
|
||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tls bool
|
tls bool
|
||||||
@@ -33,13 +37,16 @@ type Socks5Option struct {
|
|||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConnContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err := cc.Handshake()
|
err := cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
@@ -53,23 +60,24 @@ func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error)
|
|||||||
Password: ss.pass,
|
Password: ss.pass,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
if _, err := ss.clientHandshakeContext(ctx, c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
c, err := ss.dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = ss.StreamConn(c, metadata)
|
c, err = ss.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -78,8 +86,11 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
if err = ss.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c, err := ss.dialer.DialContext(ctx, "tcp", ss.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
return
|
return
|
||||||
@@ -87,13 +98,16 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
|
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err = cc.Handshake()
|
ctx, cancel := context.WithTimeout(context.Background(), C.DefaultTLSTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err = cc.HandshakeContext(ctx)
|
||||||
c = cc
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
var user *socks5.User
|
var user *socks5.User
|
||||||
if ss.user != "" {
|
if ss.user != "" {
|
||||||
user = &socks5.User{
|
user = &socks5.User{
|
||||||
@@ -102,13 +116,28 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
udpAssocateAddr := socks5.AddrFromStdAddrPort(netip.AddrPortFrom(netip.IPv4Unspecified(), 0))
|
||||||
|
bindAddr, err := ss.clientHandshakeContext(ctx, c, udpAssocateAddr, socks5.CmdUDPAssociate, user)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err = fmt.Errorf("client hanshake error: %w", err)
|
err = fmt.Errorf("client hanshake error: %w", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
// Support unspecified UDP bind address.
|
||||||
|
bindUDPAddr := bindAddr.UDPAddr()
|
||||||
|
if bindUDPAddr == nil {
|
||||||
|
err = errors.New("invalid UDP bind address")
|
||||||
|
return
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr(ctx, "udp", ss.Addr(), C.IPv4Prefer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := ss.dialer.ListenPacket(ctx, "udp", "", bindUDPAddr.AddrPort())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -121,47 +150,64 @@ func (ss *Socks5) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
pc.Close()
|
pc.Close()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
// Support unspecified UDP bind address.
|
|
||||||
bindUDPAddr := bindAddr.UDPAddr()
|
|
||||||
if bindUDPAddr == nil {
|
|
||||||
err = errors.New("invalid UDP bind address")
|
|
||||||
return
|
|
||||||
} else if bindUDPAddr.IP.IsUnspecified() {
|
|
||||||
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
bindUDPAddr.IP = serverAddr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (ss *Socks5) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := ss.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = ss.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ss *Socks5) clientHandshakeContext(ctx context.Context, c net.Conn, addr socks5.Addr, command socks5.Command, user *socks5.User) (_ socks5.Addr, err error) {
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
return socks5.ClientHandshake(c, addr, command, user)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = &tls.Config{
|
var err error
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
tlsConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
ServerName: option.Server,
|
TLSConfig: &tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: option.Server,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Socks5{
|
outbound := &Socks5{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Socks5,
|
tp: C.Socks5,
|
||||||
udp: option.UDP,
|
pdName: option.ProviderName,
|
||||||
iface: option.Interface,
|
udp: option.UDP,
|
||||||
rmark: option.RoutingMark,
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
|
option: &option,
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tls: option.TLS,
|
tls: option.TLS,
|
||||||
skipCertVerify: option.SkipCertVerify,
|
skipCertVerify: option.SkipCertVerify,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
}
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
return outbound, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type socksPacketConn struct {
|
type socksPacketConn struct {
|
||||||
|
|||||||
200
adapter/outbound/ssh.go
Normal file
200
adapter/outbound/ssh.go
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
|
||||||
|
"github.com/metacubex/randv2"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Ssh struct {
|
||||||
|
*Base
|
||||||
|
|
||||||
|
option *SshOption
|
||||||
|
|
||||||
|
config *ssh.ClientConfig
|
||||||
|
client *ssh.Client
|
||||||
|
cMutex sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
type SshOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
PrivateKeyPassphrase string `proxy:"private-key-passphrase,omitempty"`
|
||||||
|
HostKey []string `proxy:"host-key,omitempty"`
|
||||||
|
HostKeyAlgorithms []string `proxy:"host-key-algorithms,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Ssh) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
client, err := s.connect(ctx, s.addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c, err := client.DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Ssh) connect(ctx context.Context, addr string) (client *ssh.Client, err error) {
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client != nil {
|
||||||
|
return s.client, nil
|
||||||
|
}
|
||||||
|
c, err := s.dialer.DialContext(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
|
||||||
|
clientConn, chans, reqs, err := ssh.NewClientConn(c, addr, s.config)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
client = ssh.NewClient(clientConn, chans, reqs)
|
||||||
|
|
||||||
|
s.client = client
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
_ = client.Wait() // wait shutdown
|
||||||
|
_ = client.Close()
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client == client {
|
||||||
|
s.client = nil
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (s *Ssh) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := s.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = s.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (s *Ssh) Close() error {
|
||||||
|
s.cMutex.Lock()
|
||||||
|
defer s.cMutex.Unlock()
|
||||||
|
if s.client != nil {
|
||||||
|
return s.client.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSsh(option SshOption) (*Ssh, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
|
config := ssh.ClientConfig{
|
||||||
|
User: option.UserName,
|
||||||
|
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||||
|
HostKeyAlgorithms: option.HostKeyAlgorithms,
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.PrivateKey != "" {
|
||||||
|
var b []byte
|
||||||
|
var err error
|
||||||
|
if strings.Contains(option.PrivateKey, "PRIVATE KEY") {
|
||||||
|
b = []byte(option.PrivateKey)
|
||||||
|
} else {
|
||||||
|
path := C.Path.Resolve(option.PrivateKey)
|
||||||
|
if !C.Path.IsSafePath(path) {
|
||||||
|
return nil, C.Path.ErrNotSafePath(path)
|
||||||
|
}
|
||||||
|
b, err = os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var pKey ssh.Signer
|
||||||
|
if option.PrivateKeyPassphrase != "" {
|
||||||
|
pKey, err = ssh.ParsePrivateKeyWithPassphrase(b, []byte(option.PrivateKeyPassphrase))
|
||||||
|
} else {
|
||||||
|
pKey, err = ssh.ParsePrivateKey(b)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
config.Auth = append(config.Auth, ssh.PublicKeys(pKey))
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.Password != "" {
|
||||||
|
config.Auth = append(config.Auth, ssh.Password(option.Password))
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.HostKey) != 0 {
|
||||||
|
keys := make([]ssh.PublicKey, len(option.HostKey))
|
||||||
|
for i, hostKey := range option.HostKey {
|
||||||
|
key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(hostKey))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse host key :%s", key)
|
||||||
|
}
|
||||||
|
keys[i] = key
|
||||||
|
}
|
||||||
|
config.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||||
|
serverKey := key.Marshal()
|
||||||
|
for _, hostKey := range keys {
|
||||||
|
if bytes.Equal(serverKey, hostKey.Marshal()) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("host key mismatch, server send :%s %s", key.Type(), base64.StdEncoding.EncodeToString(serverKey))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
version := "SSH-2.0-OpenSSH_"
|
||||||
|
if randv2.IntN(2) == 0 {
|
||||||
|
version += "7." + strconv.Itoa(randv2.IntN(10))
|
||||||
|
} else {
|
||||||
|
version += "8." + strconv.Itoa(randv2.IntN(9))
|
||||||
|
}
|
||||||
|
config.ClientVersion = version
|
||||||
|
|
||||||
|
outbound := &Ssh{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Ssh,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: false,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
config: &config,
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
405
adapter/outbound/sudoku.go
Normal file
405
adapter/outbound/sudoku.go
Normal file
@@ -0,0 +1,405 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/transport/sudoku"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Sudoku struct {
|
||||||
|
*Base
|
||||||
|
option *SudokuOption
|
||||||
|
baseConf sudoku.ProtocolConfig
|
||||||
|
|
||||||
|
httpMaskMu sync.Mutex
|
||||||
|
httpMaskClient *sudoku.HTTPMaskTunnelClient
|
||||||
|
|
||||||
|
muxMu sync.Mutex
|
||||||
|
muxClient *sudoku.MultiplexClient
|
||||||
|
}
|
||||||
|
|
||||||
|
type SudokuOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Key string `proxy:"key"`
|
||||||
|
AEADMethod string `proxy:"aead-method,omitempty"`
|
||||||
|
PaddingMin *int `proxy:"padding-min,omitempty"`
|
||||||
|
PaddingMax *int `proxy:"padding-max,omitempty"`
|
||||||
|
TableType string `proxy:"table-type,omitempty"` // "prefer_ascii" or "prefer_entropy"
|
||||||
|
EnablePureDownlink *bool `proxy:"enable-pure-downlink,omitempty"`
|
||||||
|
HTTPMask bool `proxy:"http-mask,omitempty"`
|
||||||
|
HTTPMaskMode string `proxy:"http-mask-mode,omitempty"` // "legacy" (default), "stream", "poll", "auto"
|
||||||
|
HTTPMaskTLS bool `proxy:"http-mask-tls,omitempty"` // only for http-mask-mode stream/poll/auto
|
||||||
|
HTTPMaskHost string `proxy:"http-mask-host,omitempty"` // optional Host/SNI override (domain or domain:port)
|
||||||
|
PathRoot string `proxy:"path-root,omitempty"` // optional first-level path prefix for HTTP tunnel endpoints
|
||||||
|
HTTPMaskMultiplex string `proxy:"http-mask-multiplex,omitempty"` // "off" (default), "auto" (reuse h1/h2), "on" (single tunnel, multi-target)
|
||||||
|
CustomTable string `proxy:"custom-table,omitempty"` // optional custom byte layout, e.g. xpxvvpvv
|
||||||
|
CustomTables []string `proxy:"custom-tables,omitempty"` // optional table rotation patterns, overrides custom-table when non-empty
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (s *Sudoku) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
cfg, err := s.buildConfig(metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
|
||||||
|
if muxMode == "on" && !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
|
||||||
|
stream, muxErr := s.dialMultiplex(ctx, cfg.TargetAddress)
|
||||||
|
if muxErr == nil {
|
||||||
|
return NewConn(stream, s), nil
|
||||||
|
}
|
||||||
|
return nil, muxErr
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := s.dialAndHandshake(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer func() { safeConnClose(c, err) }()
|
||||||
|
|
||||||
|
addrBuf, err := sudoku.EncodeAddress(cfg.TargetAddress)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("encode target address failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err = c.Write(addrBuf); err != nil {
|
||||||
|
return nil, fmt.Errorf("send target address failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(c, s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (s *Sudoku) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
|
if err := s.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg, err := s.buildConfig(metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := s.dialAndHandshake(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = sudoku.WritePreface(c); err != nil {
|
||||||
|
_ = c.Close()
|
||||||
|
return nil, fmt.Errorf("send uot preface failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(sudoku.NewUoTPacketConn(c)), s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (s *Sudoku) SupportUOT() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (s *Sudoku) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := s.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = s.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) buildConfig(metadata *C.Metadata) (*sudoku.ProtocolConfig, error) {
|
||||||
|
if metadata == nil || metadata.DstPort == 0 || !metadata.Valid() {
|
||||||
|
return nil, fmt.Errorf("invalid metadata for sudoku outbound")
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := s.baseConf
|
||||||
|
cfg.TargetAddress = metadata.RemoteAddress()
|
||||||
|
|
||||||
|
if err := cfg.ValidateClient(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSudoku(option SudokuOption) (*Sudoku, error) {
|
||||||
|
if option.Server == "" {
|
||||||
|
return nil, fmt.Errorf("server is required")
|
||||||
|
}
|
||||||
|
if option.Port <= 0 || option.Port > 65535 {
|
||||||
|
return nil, fmt.Errorf("invalid port: %d", option.Port)
|
||||||
|
}
|
||||||
|
if option.Key == "" {
|
||||||
|
return nil, fmt.Errorf("key is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
tableType := strings.ToLower(option.TableType)
|
||||||
|
if tableType == "" {
|
||||||
|
tableType = "prefer_ascii"
|
||||||
|
}
|
||||||
|
if tableType != "prefer_ascii" && tableType != "prefer_entropy" {
|
||||||
|
return nil, fmt.Errorf("table-type must be prefer_ascii or prefer_entropy")
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultConf := sudoku.DefaultConfig()
|
||||||
|
paddingMin := defaultConf.PaddingMin
|
||||||
|
paddingMax := defaultConf.PaddingMax
|
||||||
|
if option.PaddingMin != nil {
|
||||||
|
paddingMin = *option.PaddingMin
|
||||||
|
}
|
||||||
|
if option.PaddingMax != nil {
|
||||||
|
paddingMax = *option.PaddingMax
|
||||||
|
}
|
||||||
|
if option.PaddingMin == nil && option.PaddingMax != nil && paddingMax < paddingMin {
|
||||||
|
paddingMin = paddingMax
|
||||||
|
}
|
||||||
|
if option.PaddingMax == nil && option.PaddingMin != nil && paddingMax < paddingMin {
|
||||||
|
paddingMax = paddingMin
|
||||||
|
}
|
||||||
|
enablePureDownlink := defaultConf.EnablePureDownlink
|
||||||
|
if option.EnablePureDownlink != nil {
|
||||||
|
enablePureDownlink = *option.EnablePureDownlink
|
||||||
|
}
|
||||||
|
|
||||||
|
baseConf := sudoku.ProtocolConfig{
|
||||||
|
ServerAddress: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
Key: option.Key,
|
||||||
|
AEADMethod: defaultConf.AEADMethod,
|
||||||
|
PaddingMin: paddingMin,
|
||||||
|
PaddingMax: paddingMax,
|
||||||
|
EnablePureDownlink: enablePureDownlink,
|
||||||
|
HandshakeTimeoutSeconds: defaultConf.HandshakeTimeoutSeconds,
|
||||||
|
DisableHTTPMask: !option.HTTPMask,
|
||||||
|
HTTPMaskMode: defaultConf.HTTPMaskMode,
|
||||||
|
HTTPMaskTLSEnabled: option.HTTPMaskTLS,
|
||||||
|
HTTPMaskHost: option.HTTPMaskHost,
|
||||||
|
HTTPMaskPathRoot: strings.TrimSpace(option.PathRoot),
|
||||||
|
HTTPMaskMultiplex: defaultConf.HTTPMaskMultiplex,
|
||||||
|
}
|
||||||
|
if option.HTTPMaskMode != "" {
|
||||||
|
baseConf.HTTPMaskMode = option.HTTPMaskMode
|
||||||
|
}
|
||||||
|
if option.HTTPMaskMultiplex != "" {
|
||||||
|
baseConf.HTTPMaskMultiplex = option.HTTPMaskMultiplex
|
||||||
|
}
|
||||||
|
tables, err := sudoku.NewTablesWithCustomPatterns(sudoku.ClientAEADSeed(option.Key), tableType, option.CustomTable, option.CustomTables)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("build table(s) failed: %w", err)
|
||||||
|
}
|
||||||
|
if len(tables) == 1 {
|
||||||
|
baseConf.Table = tables[0]
|
||||||
|
} else {
|
||||||
|
baseConf.Tables = tables
|
||||||
|
}
|
||||||
|
if option.AEADMethod != "" {
|
||||||
|
baseConf.AEADMethod = option.AEADMethod
|
||||||
|
}
|
||||||
|
|
||||||
|
outbound := &Sudoku{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: baseConf.ServerAddress,
|
||||||
|
tp: C.Sudoku,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
baseConf: baseConf,
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) Close() error {
|
||||||
|
s.resetMuxClient()
|
||||||
|
s.resetHTTPMaskClient()
|
||||||
|
return s.Base.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizeHTTPMaskMultiplex(mode string) string {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(mode)) {
|
||||||
|
case "", "off":
|
||||||
|
return "off"
|
||||||
|
case "auto":
|
||||||
|
return "auto"
|
||||||
|
case "on":
|
||||||
|
return "on"
|
||||||
|
default:
|
||||||
|
return "off"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func httpTunnelModeEnabled(mode string) bool {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(mode)) {
|
||||||
|
case "stream", "poll", "auto":
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) dialAndHandshake(ctx context.Context, cfg *sudoku.ProtocolConfig) (_ net.Conn, err error) {
|
||||||
|
if cfg == nil {
|
||||||
|
return nil, fmt.Errorf("config is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
handshakeCfg := *cfg
|
||||||
|
if !handshakeCfg.DisableHTTPMask && httpTunnelModeEnabled(handshakeCfg.HTTPMaskMode) {
|
||||||
|
handshakeCfg.DisableHTTPMask = true
|
||||||
|
}
|
||||||
|
|
||||||
|
upgrade := func(raw net.Conn) (net.Conn, error) {
|
||||||
|
return sudoku.ClientHandshake(raw, &handshakeCfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
c net.Conn
|
||||||
|
handshakeDone bool
|
||||||
|
)
|
||||||
|
if !cfg.DisableHTTPMask && httpTunnelModeEnabled(cfg.HTTPMaskMode) {
|
||||||
|
muxMode := normalizeHTTPMaskMultiplex(cfg.HTTPMaskMultiplex)
|
||||||
|
switch muxMode {
|
||||||
|
case "auto", "on":
|
||||||
|
client, errX := s.getOrCreateHTTPMaskClient(cfg)
|
||||||
|
if errX != nil {
|
||||||
|
return nil, errX
|
||||||
|
}
|
||||||
|
c, err = client.Dial(ctx, upgrade)
|
||||||
|
default:
|
||||||
|
c, err = sudoku.DialHTTPMaskTunnel(ctx, cfg.ServerAddress, cfg, s.dialer.DialContext, upgrade)
|
||||||
|
}
|
||||||
|
if err == nil && c != nil {
|
||||||
|
handshakeDone = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c == nil && err == nil {
|
||||||
|
c, err = s.dialer.DialContext(ctx, "tcp", s.addr)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", s.addr, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() { safeConnClose(c, err) }()
|
||||||
|
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !handshakeDone {
|
||||||
|
c, err = sudoku.ClientHandshake(c, &handshakeCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) dialMultiplex(ctx context.Context, targetAddress string) (net.Conn, error) {
|
||||||
|
for attempt := 0; attempt < 2; attempt++ {
|
||||||
|
client, err := s.getOrCreateMuxClient(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
stream, err := client.Dial(ctx, targetAddress)
|
||||||
|
if err != nil {
|
||||||
|
s.resetMuxClient()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("multiplex open stream failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) getOrCreateMuxClient(ctx context.Context) (*sudoku.MultiplexClient, error) {
|
||||||
|
if s == nil {
|
||||||
|
return nil, fmt.Errorf("nil adapter")
|
||||||
|
}
|
||||||
|
|
||||||
|
s.muxMu.Lock()
|
||||||
|
if s.muxClient != nil && !s.muxClient.IsClosed() {
|
||||||
|
client := s.muxClient
|
||||||
|
s.muxMu.Unlock()
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
s.muxMu.Unlock()
|
||||||
|
|
||||||
|
s.muxMu.Lock()
|
||||||
|
defer s.muxMu.Unlock()
|
||||||
|
|
||||||
|
if s.muxClient != nil && !s.muxClient.IsClosed() {
|
||||||
|
return s.muxClient, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
baseCfg := s.baseConf
|
||||||
|
baseConn, err := s.dialAndHandshake(ctx, &baseCfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := sudoku.StartMultiplexClient(baseConn)
|
||||||
|
if err != nil {
|
||||||
|
_ = baseConn.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
s.muxClient = client
|
||||||
|
return client, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) resetMuxClient() {
|
||||||
|
s.muxMu.Lock()
|
||||||
|
defer s.muxMu.Unlock()
|
||||||
|
if s.muxClient != nil {
|
||||||
|
_ = s.muxClient.Close()
|
||||||
|
s.muxClient = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) getOrCreateHTTPMaskClient(cfg *sudoku.ProtocolConfig) (*sudoku.HTTPMaskTunnelClient, error) {
|
||||||
|
if s == nil {
|
||||||
|
return nil, fmt.Errorf("nil adapter")
|
||||||
|
}
|
||||||
|
if cfg == nil {
|
||||||
|
return nil, fmt.Errorf("config is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
s.httpMaskMu.Lock()
|
||||||
|
defer s.httpMaskMu.Unlock()
|
||||||
|
|
||||||
|
if s.httpMaskClient != nil {
|
||||||
|
return s.httpMaskClient, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err := sudoku.NewHTTPMaskTunnelClient(cfg.ServerAddress, cfg, s.dialer.DialContext)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
s.httpMaskClient = c
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sudoku) resetHTTPMaskClient() {
|
||||||
|
s.httpMaskMu.Lock()
|
||||||
|
defer s.httpMaskMu.Unlock()
|
||||||
|
if s.httpMaskClient != nil {
|
||||||
|
s.httpMaskClient.CloseIdleConnections()
|
||||||
|
s.httpMaskClient = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,56 +2,85 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/metacubex/mihomo/component/ech"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
|
"github.com/metacubex/mihomo/transport/shadowsocks/core"
|
||||||
|
"github.com/metacubex/mihomo/transport/trojan"
|
||||||
|
"github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
"github.com/metacubex/http"
|
||||||
|
"github.com/metacubex/tls"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Trojan struct {
|
type Trojan struct {
|
||||||
*Base
|
*Base
|
||||||
instance *trojan.Trojan
|
option *TrojanOption
|
||||||
option *TrojanOption
|
hexPassword [trojan.KeyLength]byte
|
||||||
|
|
||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
gunTransport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
|
echConfig *ech.Config
|
||||||
|
|
||||||
|
ssCipher core.Cipher
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
Password string `proxy:"password"`
|
Password string `proxy:"password"`
|
||||||
ALPN []string `proxy:"alpn,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
SNI string `proxy:"sni,omitempty"`
|
SNI string `proxy:"sni,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
SSOpts TrojanSSOption `proxy:"ss-opts,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
// TrojanSSOption from https://github.com/p4gefau1t/trojan-go/blob/v0.10.6/tunnel/shadowsocks/config.go#L5
|
||||||
if t.option.Network == "ws" {
|
type TrojanSSOption struct {
|
||||||
|
Enabled bool `proxy:"enabled,omitempty"`
|
||||||
|
Method string `proxy:"method,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Trojan) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||||
|
switch t.option.Network {
|
||||||
|
case "ws":
|
||||||
host, port, _ := net.SplitHostPort(t.addr)
|
host, port, _ := net.SplitHostPort(t.addr)
|
||||||
wsOpts := &trojan.WebsocketOption{
|
|
||||||
Host: host,
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Port: port,
|
Host: host,
|
||||||
Path: t.option.WSOpts.Path,
|
Port: port,
|
||||||
|
Path: t.option.WSOpts.Path,
|
||||||
|
MaxEarlyData: t.option.WSOpts.MaxEarlyData,
|
||||||
|
EarlyDataHeaderName: t.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
V2rayHttpUpgrade: t.option.WSOpts.V2rayHttpUpgrade,
|
||||||
|
V2rayHttpUpgradeFastOpen: t.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
||||||
|
ClientFingerprint: t.option.ClientFingerprint,
|
||||||
|
ECHConfig: t.echConfig,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.option.SNI != "" {
|
if t.option.SNI != "" {
|
||||||
@@ -59,77 +88,108 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(t.option.WSOpts.Headers) != 0 {
|
if len(t.option.WSOpts.Headers) != 0 {
|
||||||
header := http.Header{}
|
|
||||||
for key, value := range t.option.WSOpts.Headers {
|
for key, value := range t.option.WSOpts.Headers {
|
||||||
header.Add(key, value)
|
wsOpts.Headers.Add(key, value)
|
||||||
}
|
}
|
||||||
wsOpts.Headers = header
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamWebsocketConn(c, wsOpts)
|
alpn := trojan.DefaultWebsocketALPN
|
||||||
|
if t.option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
|
alpn = t.option.ALPN
|
||||||
|
}
|
||||||
|
|
||||||
|
wsOpts.TLS = true
|
||||||
|
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
NextProtos: alpn,
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
InsecureSkipVerify: t.option.SkipCertVerify,
|
||||||
|
ServerName: t.option.SNI,
|
||||||
|
},
|
||||||
|
Fingerprint: t.option.Fingerprint,
|
||||||
|
Certificate: t.option.Certificate,
|
||||||
|
PrivateKey: t.option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
|
case "grpc":
|
||||||
|
break // already handle in gun transport
|
||||||
|
default:
|
||||||
|
// default tcp network
|
||||||
|
// handle TLS
|
||||||
|
alpn := trojan.DefaultALPN
|
||||||
|
if t.option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
|
alpn = t.option.ALPN
|
||||||
|
}
|
||||||
|
c, err = vmess.StreamTLSConn(ctx, c, &vmess.TLSConfig{
|
||||||
|
Host: t.option.SNI,
|
||||||
|
SkipCertVerify: t.option.SkipCertVerify,
|
||||||
|
FingerPrint: t.option.Fingerprint,
|
||||||
|
Certificate: t.option.Certificate,
|
||||||
|
PrivateKey: t.option.PrivateKey,
|
||||||
|
ClientFingerprint: t.option.ClientFingerprint,
|
||||||
|
NextProtos: alpn,
|
||||||
|
ECH: t.echConfig,
|
||||||
|
Reality: t.realityConfig,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.instance.StreamConn(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
var err error
|
|
||||||
if t.transport != nil {
|
|
||||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
|
||||||
} else {
|
|
||||||
c, err = t.plainStream(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = t.instance.PresetXTLSConn(c)
|
return t.streamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
}
|
||||||
return nil, err
|
|
||||||
|
func (t *Trojan) streamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||||
|
if t.ssCipher != nil {
|
||||||
|
c = t.ssCipher.StreamConn(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
if metadata.NetWork == C.UDP {
|
if ctx.Done() != nil {
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
done := N.SetupContextForConn(ctx, c)
|
||||||
return c, err
|
defer done(&err)
|
||||||
}
|
}
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
command := trojan.CommandTCP
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
|
command = trojan.CommandUDP
|
||||||
|
}
|
||||||
|
err = trojan.WriteHeader(c, t.hexPassword, command, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
func (t *Trojan) writeHeaderContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (err error) {
|
||||||
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
if ctx.Done() != nil {
|
||||||
// gun transport
|
done := N.SetupContextForConn(ctx, c)
|
||||||
if t.transport != nil && len(opts) == 0 {
|
defer done(&err)
|
||||||
c, err := gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = t.instance.PresetXTLSConn(c)
|
|
||||||
if err != nil {
|
|
||||||
c.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
|
||||||
c.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(c, t), nil
|
|
||||||
}
|
}
|
||||||
|
command := trojan.CommandTCP
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
|
command = trojan.CommandUDP
|
||||||
|
}
|
||||||
|
err = trojan.WriteHeader(c, t.hexPassword, command, serializesSocksAddr(metadata))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
var c net.Conn
|
||||||
|
// gun transport
|
||||||
|
if t.gunTransport != nil {
|
||||||
|
c, err = gun.StreamGunWithTransport(t.gunTransport, t.gunConfig)
|
||||||
|
} else {
|
||||||
|
c, err = t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
c, err = t.StreamConnContext(ctx, c, metadata)
|
||||||
|
|
||||||
c, err = t.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -138,35 +198,31 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (t *Trojan) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
var c net.Conn
|
if err = t.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
// grpc transport
|
|
||||||
if t.transport != nil && len(opts) == 0 {
|
|
||||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
} else {
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
c, err = t.plainStream(c)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return t.ListenPacketOnStreamConn(c, metadata)
|
var c net.Conn
|
||||||
}
|
// grpc transport
|
||||||
|
if t.gunTransport != nil {
|
||||||
|
c, err = gun.StreamGunWithTransport(t.gunTransport, t.gunConfig)
|
||||||
|
} else {
|
||||||
|
c, err = t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
|
}
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
c, err = t.StreamConnContext(ctx, c, metadata)
|
||||||
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
if err != nil {
|
||||||
pc := t.instance.PacketConn(c)
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc := trojan.NewPacketConn(c)
|
||||||
return newPacketConn(pc, t), err
|
return newPacketConn(pc, t), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,71 +231,98 @@ func (t *Trojan) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := t.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = t.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) Close() error {
|
||||||
|
if t.gunTransport != nil {
|
||||||
|
return t.gunTransport.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
|
||||||
tOption := &trojan.Option{
|
if option.SNI == "" {
|
||||||
Password: option.Password,
|
option.SNI = option.Server
|
||||||
ALPN: option.ALPN,
|
|
||||||
ServerName: option.Server,
|
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
|
||||||
FlowShow: option.FlowShow,
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
|
||||||
option.Flow = option.Flow[:16]
|
|
||||||
switch option.Flow {
|
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
|
||||||
tOption.Flow = option.Flow
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if option.SNI != "" {
|
|
||||||
tOption.ServerName = option.SNI
|
|
||||||
}
|
}
|
||||||
|
|
||||||
t := &Trojan{
|
t := &Trojan{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Trojan,
|
tp: C.Trojan,
|
||||||
udp: option.UDP,
|
pdName: option.ProviderName,
|
||||||
iface: option.Interface,
|
udp: option.UDP,
|
||||||
rmark: option.RoutingMark,
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
instance: trojan.New(tOption),
|
option: &option,
|
||||||
option: &option,
|
hexPassword: trojan.Key(option.Password),
|
||||||
|
}
|
||||||
|
t.dialer = option.NewDialer(t.DialOptions())
|
||||||
|
|
||||||
|
var err error
|
||||||
|
t.realityConfig, err = option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
t.echConfig, err = option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.SSOpts.Enabled {
|
||||||
|
if option.SSOpts.Password == "" {
|
||||||
|
return nil, errors.New("empty password")
|
||||||
|
}
|
||||||
|
if option.SSOpts.Method == "" {
|
||||||
|
option.SSOpts.Method = "AES-128-GCM"
|
||||||
|
}
|
||||||
|
ciph, err := core.PickCipher(option.SSOpts.Method, nil, option.SSOpts.Password)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
t.ssCipher = ciph
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.Network == "grpc" {
|
if option.Network == "grpc" {
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", t.addr, t.Base.DialOptions()...)
|
c, err := t.dialer.DialContext(ctx, "tcp", t.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", t.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &vmess.TLSConfig{
|
||||||
NextProtos: option.ALPN,
|
Host: option.SNI,
|
||||||
MinVersion: tls.VersionTLS12,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
InsecureSkipVerify: tOption.SkipCertVerify,
|
FingerPrint: option.Fingerprint,
|
||||||
ServerName: tOption.ServerName,
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
NextProtos: []string{"h2"},
|
||||||
|
ECH: t.echConfig,
|
||||||
|
Reality: t.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if t.option.Flow != "" {
|
t.gunTransport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
|
||||||
} else {
|
|
||||||
t.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.gunTLSConfig = tlsConfig
|
|
||||||
t.gunConfig = &gun.Config{
|
t.gunConfig = &gun.Config{
|
||||||
ServiceName: option.GrpcOpts.GrpcServiceName,
|
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||||
Host: tOption.ServerName,
|
UserAgent: option.GrpcOpts.GrpcUserAgent,
|
||||||
|
Host: option.SNI,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
144
adapter/outbound/trusttunnel.go
Normal file
144
adapter/outbound/trusttunnel.go
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/transport/trusttunnel"
|
||||||
|
"github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TrustTunnel struct {
|
||||||
|
*Base
|
||||||
|
client *trusttunnel.Client
|
||||||
|
option *TrustTunnelOption
|
||||||
|
}
|
||||||
|
|
||||||
|
type TrustTunnelOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
UserName string `proxy:"username,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
HealthCheck bool `proxy:"health-check,omitempty"`
|
||||||
|
|
||||||
|
Quic bool `proxy:"quic,omitempty"`
|
||||||
|
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||||
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TrustTunnel) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
c, err := t.client.Dial(ctx, metadata.RemoteAddress())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(c, t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TrustTunnel) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if err = t.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pc, err := t.client.ListenPacket(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(pc), t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (t *TrustTunnel) SupportUOT() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (t *TrustTunnel) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := t.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = t.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (t *TrustTunnel) Close() error {
|
||||||
|
return t.client.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTrustTunnel(option TrustTunnelOption) (*TrustTunnel, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
outbound := &TrustTunnel{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.TrustTunnel,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: option.UDP,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
|
||||||
|
tOption := trusttunnel.ClientOptions{
|
||||||
|
Dialer: outbound.dialer,
|
||||||
|
ResolvUDP: func(ctx context.Context, server string) (netip.AddrPort, error) {
|
||||||
|
udpAddr, err := resolveUDPAddr(ctx, "udp", server, option.IPVersion)
|
||||||
|
if err != nil {
|
||||||
|
return netip.AddrPort{}, err
|
||||||
|
}
|
||||||
|
return udpAddr.AddrPort(), nil
|
||||||
|
},
|
||||||
|
Server: addr,
|
||||||
|
Username: option.UserName,
|
||||||
|
Password: option.Password,
|
||||||
|
QUIC: option.Quic,
|
||||||
|
QUICCongestionControl: option.CongestionController,
|
||||||
|
QUICCwnd: option.CWND,
|
||||||
|
HealthCheck: option.HealthCheck,
|
||||||
|
}
|
||||||
|
echConfig, err := option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tlsConfig := &vmess.TLSConfig{
|
||||||
|
Host: option.SNI,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
NextProtos: option.ALPN,
|
||||||
|
FingerPrint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
ECH: echConfig,
|
||||||
|
}
|
||||||
|
if tlsConfig.Host == "" {
|
||||||
|
tlsConfig.Host = option.Server
|
||||||
|
}
|
||||||
|
tOption.TLSConfig = tlsConfig
|
||||||
|
|
||||||
|
client, err := trusttunnel.NewClient(context.TODO(), tOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
outbound.client = client
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
317
adapter/outbound/tuic.go
Normal file
317
adapter/outbound/tuic.go
Normal file
@@ -0,0 +1,317 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"net"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
|
"github.com/metacubex/mihomo/component/ech"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/transport/tuic"
|
||||||
|
|
||||||
|
"github.com/gofrs/uuid/v5"
|
||||||
|
"github.com/metacubex/quic-go"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
"github.com/metacubex/sing/common/uot"
|
||||||
|
"github.com/metacubex/tls"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Tuic struct {
|
||||||
|
*Base
|
||||||
|
option *TuicOption
|
||||||
|
client *tuic.PoolClient
|
||||||
|
|
||||||
|
tlsConfig *tls.Config
|
||||||
|
echConfig *ech.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
type TuicOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Token string `proxy:"token,omitempty"`
|
||||||
|
UUID string `proxy:"uuid,omitempty"`
|
||||||
|
Password string `proxy:"password,omitempty"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
HeartbeatInterval int `proxy:"heartbeat-interval,omitempty"`
|
||||||
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
|
ReduceRtt bool `proxy:"reduce-rtt,omitempty"`
|
||||||
|
RequestTimeout int `proxy:"request-timeout,omitempty"`
|
||||||
|
UdpRelayMode string `proxy:"udp-relay-mode,omitempty"`
|
||||||
|
CongestionController string `proxy:"congestion-controller,omitempty"`
|
||||||
|
DisableSni bool `proxy:"disable-sni,omitempty"`
|
||||||
|
MaxUdpRelayPacketSize int `proxy:"max-udp-relay-packet-size,omitempty"`
|
||||||
|
|
||||||
|
FastOpen bool `proxy:"fast-open,omitempty"`
|
||||||
|
MaxOpenStreams int `proxy:"max-open-streams,omitempty"`
|
||||||
|
CWND int `proxy:"cwnd,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
ReceiveWindowConn int `proxy:"recv-window-conn,omitempty"`
|
||||||
|
ReceiveWindow int `proxy:"recv-window,omitempty"`
|
||||||
|
DisableMTUDiscovery bool `proxy:"disable-mtu-discovery,omitempty"`
|
||||||
|
MaxDatagramFrameSize int `proxy:"max-datagram-frame-size,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
|
|
||||||
|
UDPOverStream bool `proxy:"udp-over-stream,omitempty"`
|
||||||
|
UDPOverStreamVersion int `proxy:"udp-over-stream-version,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialContext implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
|
conn, err := t.client.DialContext(ctx, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return NewConn(conn, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if err = t.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.option.UDPOverStream {
|
||||||
|
uotDestination := uot.RequestDestination(uint8(t.option.UDPOverStreamVersion))
|
||||||
|
uotMetadata := *metadata
|
||||||
|
uotMetadata.Host = uotDestination.Fqdn
|
||||||
|
uotMetadata.DstPort = uotDestination.Port
|
||||||
|
c, err := t.DialContext(ctx, &uotMetadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// tuic uos use stream-oriented udp with a special address, so we need a net.UDPAddr
|
||||||
|
|
||||||
|
destination := M.SocksaddrFromNet(metadata.UDPAddr())
|
||||||
|
if t.option.UDPOverStreamVersion == uot.LegacyVersion {
|
||||||
|
return newPacketConn(uot.NewConn(c, uot.Request{Destination: destination}), t), nil
|
||||||
|
} else {
|
||||||
|
return newPacketConn(uot.NewLazyConn(c, uot.Request{Destination: destination}), t), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pc, err := t.client.ListenPacket(ctx, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(pc, t), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *Tuic) dial(ctx context.Context) (transport *quic.Transport, addr net.Addr, err error) {
|
||||||
|
udpAddr, err := resolveUDPAddr(ctx, "udp", t.addr, t.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
err = t.echConfig.ClientHandle(ctx, t.tlsConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
addr = udpAddr
|
||||||
|
var pc net.PacketConn
|
||||||
|
pc, err = t.dialer.ListenPacket(ctx, "udp", "", udpAddr.AddrPort())
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
transport = &quic.Transport{Conn: pc}
|
||||||
|
transport.SetCreatedConn(true) // auto close conn
|
||||||
|
transport.SetSingleUse(true) // auto close transport
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (t *Tuic) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := t.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = t.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTuic(option TuicOption) (*Tuic, error) {
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
serverName := option.Server
|
||||||
|
if option.SNI != "" {
|
||||||
|
serverName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig, err := ca.GetTLSConfig(ca.Option{
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
ServerName: serverName,
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
},
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.ALPN != nil { // structure's Decode will ensure value not nil when input has value even it was set an empty array
|
||||||
|
tlsConfig.NextProtos = option.ALPN
|
||||||
|
} else {
|
||||||
|
tlsConfig.NextProtos = []string{"h3"}
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.RequestTimeout == 0 {
|
||||||
|
option.RequestTimeout = 8000
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.HeartbeatInterval <= 0 {
|
||||||
|
option.HeartbeatInterval = 10000
|
||||||
|
}
|
||||||
|
|
||||||
|
udpRelayMode := tuic.QUIC
|
||||||
|
if option.UdpRelayMode != "quic" {
|
||||||
|
udpRelayMode = tuic.NATIVE
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxUdpRelayPacketSize == 0 {
|
||||||
|
option.MaxUdpRelayPacketSize = 1252
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxOpenStreams == 0 {
|
||||||
|
option.MaxOpenStreams = 100
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.CWND == 0 {
|
||||||
|
option.CWND = 32
|
||||||
|
}
|
||||||
|
|
||||||
|
packetOverHead := tuic.PacketOverHeadV4
|
||||||
|
if len(option.Token) == 0 {
|
||||||
|
packetOverHead = tuic.PacketOverHeadV5
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxDatagramFrameSize == 0 {
|
||||||
|
option.MaxDatagramFrameSize = option.MaxUdpRelayPacketSize + packetOverHead
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.MaxDatagramFrameSize > 1400 {
|
||||||
|
option.MaxDatagramFrameSize = 1400
|
||||||
|
}
|
||||||
|
option.MaxUdpRelayPacketSize = option.MaxDatagramFrameSize - packetOverHead
|
||||||
|
|
||||||
|
// ensure server's incoming stream can handle correctly, increase to 1.1x
|
||||||
|
quicMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
|
quicMaxOpenStreams = quicMaxOpenStreams + int64(math.Ceil(float64(quicMaxOpenStreams)/10.0))
|
||||||
|
quicConfig := &quic.Config{
|
||||||
|
InitialStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
MaxStreamReceiveWindow: uint64(option.ReceiveWindowConn),
|
||||||
|
InitialConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
MaxConnectionReceiveWindow: uint64(option.ReceiveWindow),
|
||||||
|
MaxIncomingStreams: quicMaxOpenStreams,
|
||||||
|
MaxIncomingUniStreams: quicMaxOpenStreams,
|
||||||
|
KeepAlivePeriod: time.Duration(option.HeartbeatInterval) * time.Millisecond,
|
||||||
|
DisablePathMTUDiscovery: option.DisableMTUDiscovery,
|
||||||
|
MaxDatagramFrameSize: int64(option.MaxDatagramFrameSize),
|
||||||
|
EnableDatagrams: true,
|
||||||
|
}
|
||||||
|
if option.ReceiveWindowConn == 0 {
|
||||||
|
quicConfig.InitialStreamReceiveWindow = tuic.DefaultStreamReceiveWindow / 10
|
||||||
|
quicConfig.MaxStreamReceiveWindow = tuic.DefaultStreamReceiveWindow
|
||||||
|
}
|
||||||
|
if option.ReceiveWindow == 0 {
|
||||||
|
quicConfig.InitialConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow / 10
|
||||||
|
quicConfig.MaxConnectionReceiveWindow = tuic.DefaultConnectionReceiveWindow
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Ip) > 0 {
|
||||||
|
addr = net.JoinHostPort(option.Ip, strconv.Itoa(option.Port))
|
||||||
|
}
|
||||||
|
if option.DisableSni {
|
||||||
|
tlsConfig.ServerName = ""
|
||||||
|
tlsConfig.InsecureSkipVerify = true // tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsClientConfig := tlsConfig
|
||||||
|
echConfig, err := option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch option.UDPOverStreamVersion {
|
||||||
|
case uot.Version, uot.LegacyVersion:
|
||||||
|
case 0:
|
||||||
|
option.UDPOverStreamVersion = uot.LegacyVersion
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("tuic %s unknown udp over stream protocol version: %d", addr, option.UDPOverStreamVersion)
|
||||||
|
}
|
||||||
|
|
||||||
|
t := &Tuic{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Tuic,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: true,
|
||||||
|
tfo: option.FastOpen,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
option: &option,
|
||||||
|
tlsConfig: tlsClientConfig,
|
||||||
|
echConfig: echConfig,
|
||||||
|
}
|
||||||
|
t.dialer = option.NewDialer(t.DialOptions())
|
||||||
|
|
||||||
|
clientMaxOpenStreams := int64(option.MaxOpenStreams)
|
||||||
|
|
||||||
|
// to avoid tuic's "too many open streams", decrease to 0.9x
|
||||||
|
if clientMaxOpenStreams == 100 {
|
||||||
|
clientMaxOpenStreams = clientMaxOpenStreams - int64(math.Ceil(float64(clientMaxOpenStreams)/10.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
if clientMaxOpenStreams < 1 {
|
||||||
|
clientMaxOpenStreams = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Token) > 0 {
|
||||||
|
tkn := tuic.GenTKN(option.Token)
|
||||||
|
clientOption := &tuic.ClientOptionV4{
|
||||||
|
TlsConfig: tlsClientConfig,
|
||||||
|
QuicConfig: quicConfig,
|
||||||
|
Token: tkn,
|
||||||
|
UdpRelayMode: udpRelayMode,
|
||||||
|
CongestionController: option.CongestionController,
|
||||||
|
ReduceRtt: option.ReduceRtt,
|
||||||
|
RequestTimeout: time.Duration(option.RequestTimeout) * time.Millisecond,
|
||||||
|
MaxUdpRelayPacketSize: option.MaxUdpRelayPacketSize,
|
||||||
|
FastOpen: option.FastOpen,
|
||||||
|
MaxOpenStreams: clientMaxOpenStreams,
|
||||||
|
CWND: option.CWND,
|
||||||
|
}
|
||||||
|
|
||||||
|
t.client = tuic.NewPoolClientV4(clientOption, t.dial)
|
||||||
|
} else {
|
||||||
|
maxUdpRelayPacketSize := option.MaxUdpRelayPacketSize
|
||||||
|
if maxUdpRelayPacketSize > tuic.MaxFragSizeV5 {
|
||||||
|
maxUdpRelayPacketSize = tuic.MaxFragSizeV5
|
||||||
|
}
|
||||||
|
clientOption := &tuic.ClientOptionV5{
|
||||||
|
TlsConfig: tlsClientConfig,
|
||||||
|
QuicConfig: quicConfig,
|
||||||
|
Uuid: uuid.FromStringOrNil(option.UUID),
|
||||||
|
Password: option.Password,
|
||||||
|
UdpRelayMode: udpRelayMode,
|
||||||
|
CongestionController: option.CongestionController,
|
||||||
|
ReduceRtt: option.ReduceRtt,
|
||||||
|
MaxUdpRelayPacketSize: maxUdpRelayPacketSize,
|
||||||
|
MaxOpenStreams: clientMaxOpenStreams,
|
||||||
|
CWND: option.CWND,
|
||||||
|
}
|
||||||
|
|
||||||
|
t.client = tuic.NewPoolClientV5(clientOption, t.dial)
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
@@ -2,80 +2,115 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/tls"
|
"context"
|
||||||
xtls "github.com/xtls/go"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/metacubex/mihomo/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
globalClientSessionCache tls.ClientSessionCache
|
|
||||||
globalClientXSessionCache xtls.ClientSessionCache
|
|
||||||
once sync.Once
|
|
||||||
)
|
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
|
||||||
_ = tcp.SetKeepAlive(true)
|
|
||||||
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getClientSessionCache() tls.ClientSessionCache {
|
|
||||||
once.Do(func() {
|
|
||||||
globalClientSessionCache = tls.NewLRUClientSessionCache(128)
|
|
||||||
})
|
|
||||||
return globalClientSessionCache
|
|
||||||
}
|
|
||||||
|
|
||||||
func getClientXSessionCache() xtls.ClientSessionCache {
|
|
||||||
once.Do(func() {
|
|
||||||
globalClientXSessionCache = xtls.NewLRUClientSessionCache(128)
|
|
||||||
})
|
|
||||||
return globalClientXSessionCache
|
|
||||||
}
|
|
||||||
|
|
||||||
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
func serializesSocksAddr(metadata *C.Metadata) []byte {
|
||||||
var buf [][]byte
|
var buf [][]byte
|
||||||
aType := uint8(metadata.AddrType)
|
addrType := metadata.AddrType()
|
||||||
p, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
p := uint(metadata.DstPort)
|
||||||
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
port := []byte{uint8(p >> 8), uint8(p & 0xff)}
|
||||||
switch metadata.AddrType {
|
switch addrType {
|
||||||
case socks5.AtypDomainName:
|
case C.AtypDomainName:
|
||||||
lenM := uint8(len(metadata.Host))
|
lenM := uint8(len(metadata.Host))
|
||||||
host := []byte(metadata.Host)
|
host := []byte(metadata.Host)
|
||||||
buf = [][]byte{{aType, lenM}, host, port}
|
buf = [][]byte{{socks5.AtypDomainName, lenM}, host, port}
|
||||||
case socks5.AtypIPv4:
|
case C.AtypIPv4:
|
||||||
host := metadata.DstIP.AsSlice()
|
host := metadata.DstIP.AsSlice()
|
||||||
buf = [][]byte{{aType}, host, port}
|
buf = [][]byte{{socks5.AtypIPv4}, host, port}
|
||||||
case socks5.AtypIPv6:
|
case C.AtypIPv6:
|
||||||
host := metadata.DstIP.AsSlice()
|
host := metadata.DstIP.AsSlice()
|
||||||
buf = [][]byte{{aType}, host, port}
|
buf = [][]byte{{socks5.AtypIPv6}, host, port}
|
||||||
}
|
}
|
||||||
return bytes.Join(buf, nil)
|
return bytes.Join(buf, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
func resolveUDPAddr(ctx context.Context, network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
||||||
host, port, err := net.SplitHostPort(address)
|
host, port, err := net.SplitHostPort(address)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
ip, err := resolver.ResolveProxyServerHost(host)
|
var ip netip.Addr
|
||||||
|
switch prefer {
|
||||||
|
case C.IPv4Only:
|
||||||
|
ip, err = resolver.ResolveIPv4WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
case C.IPv6Only:
|
||||||
|
ip, err = resolver.ResolveIPv6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
case C.IPv6Prefer:
|
||||||
|
ip, err = resolver.ResolveIPPrefer6WithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
default:
|
||||||
|
ip, err = resolver.ResolveIPWithResolver(ctx, host, resolver.ProxyServerHostResolver)
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
|
||||||
|
ip, port = resolver.LookupIP4P(ip, port)
|
||||||
|
|
||||||
|
var uint16Port uint16
|
||||||
|
if port, err := strconv.ParseUint(port, 10, 16); err == nil {
|
||||||
|
uint16Port = uint16(port)
|
||||||
|
} else {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// our resolver always unmap before return, so unneeded unmap at here
|
||||||
|
// which is different with net.ResolveUDPAddr maybe return 4in6 address
|
||||||
|
// 4in6 addresses can cause some strange effects on sing-based code
|
||||||
|
return net.UDPAddrFromAddrPort(netip.AddrPortFrom(ip, uint16Port)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
if err != nil {
|
if err != nil && c != nil {
|
||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||||
|
|
||||||
|
func StringToBps(s string) uint64 {
|
||||||
|
if s == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// when have not unit, use Mbps
|
||||||
|
if v, err := strconv.Atoi(s); err == nil {
|
||||||
|
return StringToBps(fmt.Sprintf("%d Mbps", v))
|
||||||
|
}
|
||||||
|
|
||||||
|
m := rateStringRegexp.FindStringSubmatch(s)
|
||||||
|
if m == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var n uint64 = 1
|
||||||
|
switch m[2] {
|
||||||
|
case "T":
|
||||||
|
n *= 1000
|
||||||
|
fallthrough
|
||||||
|
case "G":
|
||||||
|
n *= 1000
|
||||||
|
fallthrough
|
||||||
|
case "M":
|
||||||
|
n *= 1000
|
||||||
|
fallthrough
|
||||||
|
case "K":
|
||||||
|
n *= 1000
|
||||||
|
}
|
||||||
|
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||||
|
n *= v
|
||||||
|
if m[3] == "b" {
|
||||||
|
// Bits, need to convert to bytes
|
||||||
|
n /= 8
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,29 +2,27 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/common/convert"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/metacubex/mihomo/component/ech"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
|
"github.com/metacubex/mihomo/transport/vless"
|
||||||
|
"github.com/metacubex/mihomo/transport/vless/encryption"
|
||||||
|
"github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
"github.com/metacubex/http"
|
||||||
)
|
vmessSing "github.com/metacubex/sing-vmess"
|
||||||
|
"github.com/metacubex/sing-vmess/packetaddr"
|
||||||
const (
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
// max packet length
|
"github.com/metacubex/tls"
|
||||||
maxLength = 1024 << 3
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Vless struct {
|
type Vless struct {
|
||||||
@@ -32,71 +30,100 @@ type Vless struct {
|
|||||||
client *vless.Client
|
client *vless.Client
|
||||||
option *VlessOption
|
option *VlessOption
|
||||||
|
|
||||||
|
encryption *encryption.ClientInstance
|
||||||
|
|
||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
gunTransport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
|
echConfig *ech.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
Encryption string `proxy:"encryption,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||||
var err error
|
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &vmess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
||||||
|
V2rayHttpUpgradeFastOpen: v.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
ECHConfig: v.echConfig,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
header := http.Header{}
|
|
||||||
for key, value := range v.option.WSOpts.Headers {
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
header.Add(key, value)
|
wsOpts.Headers.Add(key, value)
|
||||||
}
|
}
|
||||||
wsOpts.Headers = header
|
|
||||||
}
|
}
|
||||||
|
if v.option.TLS {
|
||||||
|
wsOpts.TLS = true
|
||||||
|
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
|
TLSConfig: &tls.Config{
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
ServerName: host,
|
||||||
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
|
NextProtos: []string{"http/1.1"},
|
||||||
|
},
|
||||||
|
Fingerprint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
wsOpts.TLS = true
|
if v.option.ServerName != "" {
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
MinVersion: tls.VersionTLS12,
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
ServerName: host,
|
wsOpts.TLSConfig.ServerName = host
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
}
|
||||||
NextProtos: []string{"http/1.1"},
|
} else {
|
||||||
|
if host := wsOpts.Headers.Get("Host"); host == "" {
|
||||||
|
wsOpts.Headers.Set("Host", convert.RandHost())
|
||||||
|
convert.SetUserAgent(wsOpts.Headers)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if v.option.ServerName != "" {
|
c, err = vmess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
|
||||||
wsOpts.TLSConfig.ServerName = host
|
|
||||||
}
|
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
c, err = v.streamTLSConn(ctx, c, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -111,7 +138,7 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
|
|
||||||
c = vmess.StreamHTTPConn(c, httpOpts)
|
c = vmess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
c, err = v.streamTLSOrXTLSConn(c, true)
|
c, err = v.streamTLSConn(ctx, c, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -121,49 +148,71 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
Path: v.option.HTTP2Opts.Path,
|
Path: v.option.HTTP2Opts.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamH2Conn(c, h2Opts)
|
c, err = vmess.StreamH2Conn(ctx, c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
if v.isXTLSEnabled() {
|
break // already handle in gun transport
|
||||||
c, err = gun.StreamGunWithXTLSConn(c, v.gunTLSConfig, v.gunConfig)
|
|
||||||
} else {
|
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
|
||||||
}
|
|
||||||
default:
|
default:
|
||||||
// default tcp network
|
// default tcp network
|
||||||
// handle TLS And XTLS
|
// handle TLS
|
||||||
c, err = v.streamTLSOrXTLSConn(c, false)
|
c, err = v.streamTLSConn(ctx, c, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
return v.streamConnContext(ctx, c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
func (v *Vless) streamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
if v.isXTLSEnabled() {
|
defer done(&err)
|
||||||
xtlsOpts := vless.XTLSConfig{
|
}
|
||||||
Host: host,
|
if v.encryption != nil {
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
c, err = v.encryption.Handshake(c)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if isH2 {
|
if metadata.NetWork == C.UDP {
|
||||||
xtlsOpts.NextProtos = []string{"h2"}
|
if v.option.PacketAddr {
|
||||||
|
metadata = &C.Metadata{
|
||||||
|
NetWork: C.UDP,
|
||||||
|
Host: packetaddr.SeqPacketMagicAddress,
|
||||||
|
DstPort: 443,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
metadata = &C.Metadata{ // a clear metadata only contains ip
|
||||||
|
NetWork: C.UDP,
|
||||||
|
DstIP: metadata.DstIP,
|
||||||
|
DstPort: metadata.DstPort,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, v.option.XUDP))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.StreamConn(c, parseVlessAddr(metadata, false))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
conn = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
func (v *Vless) streamTLSConn(ctx context.Context, conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||||
xtlsOpts.Host = v.option.ServerName
|
if v.option.TLS {
|
||||||
}
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
|
||||||
|
|
||||||
} else if v.option.TLS {
|
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := vmess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
ECH: v.echConfig,
|
||||||
|
Reality: v.realityConfig,
|
||||||
|
NextProtos: v.option.ALPN,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@@ -174,87 +223,85 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
return vmess.StreamTLSConn(ctx, conn, &tlsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
return conn, nil
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) isXTLSEnabled() bool {
|
|
||||||
return v.client.Addons != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.gunTransport != nil {
|
||||||
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||||
if err != nil {
|
} else {
|
||||||
return nil, err
|
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(c, v), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
defer func(c net.Conn) {
|
||||||
defer safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
if err = v.ResolveUDP(ctx, metadata); err != nil {
|
||||||
if !metadata.Resolved() {
|
return nil, err
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.gunTransport != nil {
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
|
||||||
} else {
|
} else {
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("new vless client error: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vless) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
if err = v.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.XUDP {
|
||||||
|
var globalID [8]byte
|
||||||
|
if metadata.SourceValid() {
|
||||||
|
globalID = utils.GlobalID(metadata.SourceAddress())
|
||||||
|
}
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(
|
||||||
|
vmessSing.NewXUDPConn(c,
|
||||||
|
globalID,
|
||||||
|
M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
|
), v), nil
|
||||||
|
} else if v.option.PacketAddr {
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(
|
||||||
|
packetaddr.NewConn(v.client.PacketConn(c, metadata.UDPAddr()),
|
||||||
|
M.SocksaddrFromNet(metadata.UDPAddr())),
|
||||||
|
), v), nil
|
||||||
|
}
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(v.client.PacketConn(c, metadata.UDPAddr())), v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUOT implements C.ProxyAdapter
|
// SupportUOT implements C.ProxyAdapter
|
||||||
@@ -262,10 +309,25 @@ func (v *Vless) SupportUOT() bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (v *Vless) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := v.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = v.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (v *Vless) Close() error {
|
||||||
|
if v.gunTransport != nil {
|
||||||
|
return v.gunTransport.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseVlessAddr(metadata *C.Metadata, xudp bool) *vless.DstAddr {
|
||||||
var addrType byte
|
var addrType byte
|
||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType {
|
switch metadata.AddrType() {
|
||||||
case C.AtypIPv4:
|
case C.AtypIPv4:
|
||||||
addrType = vless.AtypIPv4
|
addrType = vless.AtypIPv4
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
@@ -281,137 +343,78 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
copy(addr[1:], metadata.Host)
|
copy(addr[1:], metadata.Host)
|
||||||
}
|
}
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
|
||||||
return &vless.DstAddr{
|
return &vless.DstAddr{
|
||||||
UDP: metadata.NetWork == C.UDP,
|
UDP: metadata.NetWork == C.UDP,
|
||||||
AddrType: addrType,
|
AddrType: addrType,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Port: uint(port),
|
Port: metadata.DstPort,
|
||||||
|
Mux: metadata.NetWork == C.UDP && xudp,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type vlessPacketConn struct {
|
|
||||||
net.Conn
|
|
||||||
rAddr net.Addr
|
|
||||||
remain int
|
|
||||||
mux sync.Mutex
|
|
||||||
cache [2]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
|
||||||
binary.BigEndian.PutUint16(c.cache[:], uint16(len(payload)))
|
|
||||||
|
|
||||||
if _, err := c.Conn.Write(c.cache[:]); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.Conn.Write(payload)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
|
||||||
total := len(b)
|
|
||||||
if total == 0 {
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if total <= maxLength {
|
|
||||||
return c.writePacket(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
offset := 0
|
|
||||||
|
|
||||||
for offset < total {
|
|
||||||
cursor := offset + maxLength
|
|
||||||
if cursor > total {
|
|
||||||
cursor = total
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.writePacket(b[offset:cursor])
|
|
||||||
if err != nil {
|
|
||||||
return offset + n, err
|
|
||||||
}
|
|
||||||
|
|
||||||
offset = cursor
|
|
||||||
if offset == total {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return total, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|
||||||
c.mux.Lock()
|
|
||||||
defer c.mux.Unlock()
|
|
||||||
|
|
||||||
if c.remain > 0 {
|
|
||||||
length := len(b)
|
|
||||||
if c.remain < length {
|
|
||||||
length = c.remain
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := c.Conn.Read(b[:length])
|
|
||||||
if err != nil {
|
|
||||||
return 0, c.rAddr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c.remain -= n
|
|
||||||
return n, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := c.Conn.Read(b[:2]); err != nil {
|
|
||||||
return 0, c.rAddr, err
|
|
||||||
}
|
|
||||||
|
|
||||||
total := int(binary.BigEndian.Uint16(b[:2]))
|
|
||||||
if total == 0 {
|
|
||||||
return 0, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
length := len(b)
|
|
||||||
if length > total {
|
|
||||||
length = total
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := io.ReadFull(c.Conn, b[:length]); err != nil {
|
|
||||||
return 0, c.rAddr, errors.New("read packet error")
|
|
||||||
}
|
|
||||||
|
|
||||||
c.remain = total - length
|
|
||||||
|
|
||||||
return length, c.rAddr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewVless(option VlessOption) (*Vless, error) {
|
func NewVless(option VlessOption) (*Vless, error) {
|
||||||
var addons *vless.Addons
|
var addons *vless.Addons
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if len(option.Flow) >= 16 {
|
||||||
option.Flow = option.Flow[:16]
|
option.Flow = option.Flow[:16]
|
||||||
switch option.Flow {
|
if option.Flow != vless.XRV {
|
||||||
case vless.XRO, vless.XRD, vless.XRS:
|
|
||||||
addons = &vless.Addons{
|
|
||||||
Flow: option.Flow,
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
return nil, fmt.Errorf("unsupported xtls flow type: %s", option.Flow)
|
||||||
}
|
}
|
||||||
|
addons = &vless.Addons{
|
||||||
|
Flow: option.Flow,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
client, err := vless.NewClient(uuidMap(option.UUID), addons, option.FlowShow)
|
switch option.PacketEncoding {
|
||||||
|
case "packetaddr", "packet":
|
||||||
|
option.PacketAddr = true
|
||||||
|
option.XUDP = false
|
||||||
|
default: // https://github.com/XTLS/Xray-core/pull/1567#issuecomment-1407305458
|
||||||
|
if !option.PacketAddr {
|
||||||
|
option.XUDP = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if option.XUDP {
|
||||||
|
option.PacketAddr = false
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := vless.NewClient(option.UUID, addons)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
v := &Vless{
|
v := &Vless{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vless,
|
tp: C.Vless,
|
||||||
udp: option.UDP,
|
pdName: option.ProviderName,
|
||||||
iface: option.Interface,
|
udp: option.UDP,
|
||||||
|
xudp: option.XUDP,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
v.dialer = option.NewDialer(v.DialOptions())
|
||||||
|
|
||||||
|
v.encryption, err = encryption.NewClient(option.Encryption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
v.realityConfig, err = v.option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
v.echConfig, err = v.option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2":
|
case "h2":
|
||||||
@@ -419,37 +422,44 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
||||||
}
|
}
|
||||||
case "grpc":
|
case "grpc":
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
c, err := v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
UserAgent: option.GrpcOpts.GrpcUserAgent,
|
||||||
|
Host: option.ServerName,
|
||||||
}
|
}
|
||||||
tlsConfig := &tls.Config{
|
if option.ServerName == "" {
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
gunConfig.Host = v.addr
|
||||||
ServerName: v.option.ServerName,
|
}
|
||||||
|
var tlsConfig *vmess.TLSConfig
|
||||||
|
if option.TLS {
|
||||||
|
tlsConfig = &vmess.TLSConfig{
|
||||||
|
Host: option.ServerName,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
FingerPrint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
NextProtos: []string{"h2"},
|
||||||
|
ECH: v.echConfig,
|
||||||
|
Reality: v.realityConfig,
|
||||||
|
}
|
||||||
|
if option.ServerName == "" {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsConfig.Host = host
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName == "" {
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
|
||||||
tlsConfig.ServerName = host
|
|
||||||
gunConfig.Host = host
|
|
||||||
}
|
|
||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
if v.isXTLSEnabled() {
|
|
||||||
v.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
v.gunTransport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
} else {
|
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
|
|||||||
@@ -2,55 +2,74 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/component/ca"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/metacubex/mihomo/component/ech"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
tlsC "github.com/metacubex/mihomo/component/tls"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/ntp"
|
||||||
|
"github.com/metacubex/mihomo/transport/gun"
|
||||||
|
mihomoVMess "github.com/metacubex/mihomo/transport/vmess"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
"github.com/metacubex/http"
|
||||||
|
vmess "github.com/metacubex/sing-vmess"
|
||||||
|
"github.com/metacubex/sing-vmess/packetaddr"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
"github.com/metacubex/tls"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var ErrUDPRemoteAddrMismatch = errors.New("udp packet dropped due to mismatched remote address")
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
*Base
|
*Base
|
||||||
client *vmess.Client
|
client *vmess.Client
|
||||||
option *VmessOption
|
option *VmessOption
|
||||||
|
|
||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
gunTransport *gun.TransportWrap
|
||||||
|
|
||||||
|
realityConfig *tlsC.RealityConfig
|
||||||
|
echConfig *ech.Config
|
||||||
}
|
}
|
||||||
|
|
||||||
type VmessOption struct {
|
type VmessOption struct {
|
||||||
BasicOption
|
BasicOption
|
||||||
Name string `proxy:"name"`
|
Name string `proxy:"name"`
|
||||||
Server string `proxy:"server"`
|
Server string `proxy:"server"`
|
||||||
Port int `proxy:"port"`
|
Port int `proxy:"port"`
|
||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
AlterID int `proxy:"alterId"`
|
AlterID int `proxy:"alterId"`
|
||||||
Cipher string `proxy:"cipher"`
|
Cipher string `proxy:"cipher"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
TLS bool `proxy:"tls,omitempty"`
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
ALPN []string `proxy:"alpn,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
Certificate string `proxy:"certificate,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
PrivateKey string `proxy:"private-key,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
|
ECHOpts ECHOptions `proxy:"ech-opts,omitempty"`
|
||||||
// TODO: compatible with VMESS WS older version configurations
|
RealityOpts RealityOptions `proxy:"reality-opts,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
|
XUDP bool `proxy:"xudp,omitempty"`
|
||||||
|
PacketEncoding string `proxy:"packet-encoding,omitempty"`
|
||||||
|
GlobalPadding bool `proxy:"global-padding,omitempty"`
|
||||||
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
|
ClientFingerprint string `proxy:"client-fingerprint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@@ -66,205 +85,281 @@ type HTTP2Options struct {
|
|||||||
|
|
||||||
type GrpcOptions struct {
|
type GrpcOptions struct {
|
||||||
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
|
GrpcServiceName string `proxy:"grpc-service-name,omitempty"`
|
||||||
|
GrpcUserAgent string `proxy:"grpc-user-agent,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type WSOptions struct {
|
type WSOptions struct {
|
||||||
Path string `proxy:"path,omitempty"`
|
Path string `proxy:"path,omitempty"`
|
||||||
Headers map[string]string `proxy:"headers,omitempty"`
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
MaxEarlyData int `proxy:"max-early-data,omitempty"`
|
||||||
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
EarlyDataHeaderName string `proxy:"early-data-header-name,omitempty"`
|
||||||
|
V2rayHttpUpgrade bool `proxy:"v2ray-http-upgrade,omitempty"`
|
||||||
|
V2rayHttpUpgradeFastOpen bool `proxy:"v2ray-http-upgrade-fast-open,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
func (v *Vmess) StreamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ net.Conn, err error) {
|
||||||
func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
var err error
|
|
||||||
switch v.option.Network {
|
switch v.option.Network {
|
||||||
case "ws":
|
case "ws":
|
||||||
if v.option.WSOpts.Path == "" {
|
|
||||||
v.option.WSOpts.Path = v.option.WSPath
|
|
||||||
}
|
|
||||||
if len(v.option.WSOpts.Headers) == 0 {
|
|
||||||
v.option.WSOpts.Headers = v.option.WSHeaders
|
|
||||||
}
|
|
||||||
|
|
||||||
host, port, _ := net.SplitHostPort(v.addr)
|
host, port, _ := net.SplitHostPort(v.addr)
|
||||||
wsOpts := &vmess.WebsocketConfig{
|
wsOpts := &mihomoVMess.WebsocketConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Port: port,
|
Port: port,
|
||||||
Path: v.option.WSOpts.Path,
|
Path: v.option.WSOpts.Path,
|
||||||
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
MaxEarlyData: v.option.WSOpts.MaxEarlyData,
|
||||||
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
EarlyDataHeaderName: v.option.WSOpts.EarlyDataHeaderName,
|
||||||
|
V2rayHttpUpgrade: v.option.WSOpts.V2rayHttpUpgrade,
|
||||||
|
V2rayHttpUpgradeFastOpen: v.option.WSOpts.V2rayHttpUpgradeFastOpen,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
ECHConfig: v.echConfig,
|
||||||
|
Headers: http.Header{},
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(v.option.WSOpts.Headers) != 0 {
|
if len(v.option.WSOpts.Headers) != 0 {
|
||||||
header := http.Header{}
|
|
||||||
for key, value := range v.option.WSOpts.Headers {
|
for key, value := range v.option.WSOpts.Headers {
|
||||||
header.Add(key, value)
|
wsOpts.Headers.Add(key, value)
|
||||||
}
|
}
|
||||||
wsOpts.Headers = header
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
wsOpts.TLS = true
|
wsOpts.TLS = true
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
wsOpts.TLSConfig, err = ca.GetTLSConfig(ca.Option{
|
||||||
ServerName: host,
|
TLSConfig: &tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
ServerName: host,
|
||||||
NextProtos: []string{"http/1.1"},
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
|
NextProtos: []string{"http/1.1"},
|
||||||
|
},
|
||||||
|
Fingerprint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
wsOpts.TLSConfig.ServerName = host
|
wsOpts.TLSConfig.ServerName = host
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
c, err = mihomoVMess.StreamWebsocketConn(ctx, c, wsOpts)
|
||||||
case "http":
|
case "http":
|
||||||
// readability first, so just copy default TLS logic
|
// readability first, so just copy default TLS logic
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &vmess.TLSConfig{
|
tlsOpts := &mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
ECH: v.echConfig,
|
||||||
|
Reality: v.realityConfig,
|
||||||
|
NextProtos: v.option.ALPN,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||||
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
httpOpts := &vmess.HTTPConfig{
|
httpOpts := &mihomoVMess.HTTPConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
Method: v.option.HTTPOpts.Method,
|
Method: v.option.HTTPOpts.Method,
|
||||||
Path: v.option.HTTPOpts.Path,
|
Path: v.option.HTTPOpts.Path,
|
||||||
Headers: v.option.HTTPOpts.Headers,
|
Headers: v.option.HTTPOpts.Headers,
|
||||||
}
|
}
|
||||||
|
|
||||||
c = vmess.StreamHTTPConn(c, httpOpts)
|
c = mihomoVMess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
NextProtos: []string{"h2"},
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
Reality: v.realityConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, &tlsOpts)
|
c, err = mihomoVMess.StreamTLSConn(ctx, c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
h2Opts := &vmess.H2Config{
|
h2Opts := &mihomoVMess.H2Config{
|
||||||
Hosts: v.option.HTTP2Opts.Host,
|
Hosts: v.option.HTTP2Opts.Host,
|
||||||
Path: v.option.HTTP2Opts.Path,
|
Path: v.option.HTTP2Opts.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamH2Conn(c, h2Opts)
|
c, err = mihomoVMess.StreamH2Conn(ctx, c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
break // already handle in gun transport
|
||||||
default:
|
default:
|
||||||
// handle TLS
|
// handle TLS
|
||||||
if v.option.TLS {
|
if v.option.TLS {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := &vmess.TLSConfig{
|
tlsOpts := &mihomoVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
|
Certificate: v.option.Certificate,
|
||||||
|
PrivateKey: v.option.PrivateKey,
|
||||||
|
ClientFingerprint: v.option.ClientFingerprint,
|
||||||
|
ECH: v.echConfig,
|
||||||
|
Reality: v.realityConfig,
|
||||||
|
NextProtos: v.option.ALPN,
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName != "" {
|
if v.option.ServerName != "" {
|
||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
c, err = mihomoVMess.StreamTLSConn(ctx, c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
return v.streamConnContext(ctx, c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
func (v *Vmess) streamConnContext(ctx context.Context, c net.Conn, metadata *C.Metadata) (conn net.Conn, err error) {
|
||||||
|
useEarly := N.NeedHandshake(c)
|
||||||
|
if !useEarly {
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
done := N.SetupContextForConn(ctx, c)
|
||||||
|
defer done(&err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
|
if v.option.XUDP {
|
||||||
|
var globalID [8]byte
|
||||||
|
if metadata.SourceValid() {
|
||||||
|
globalID = utils.GlobalID(metadata.SourceAddress())
|
||||||
|
}
|
||||||
|
if useEarly {
|
||||||
|
conn = v.client.DialEarlyXUDPPacketConn(c,
|
||||||
|
globalID,
|
||||||
|
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialXUDPPacketConn(c,
|
||||||
|
globalID,
|
||||||
|
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
}
|
||||||
|
} else if v.option.PacketAddr {
|
||||||
|
if useEarly {
|
||||||
|
conn = v.client.DialEarlyPacketConn(c,
|
||||||
|
M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialPacketConn(c,
|
||||||
|
M.ParseSocksaddrHostPort(packetaddr.SeqPacketMagicAddress, 443))
|
||||||
|
}
|
||||||
|
conn = packetaddr.NewBindConn(conn)
|
||||||
|
} else {
|
||||||
|
if useEarly {
|
||||||
|
conn = v.client.DialEarlyPacketConn(c,
|
||||||
|
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialPacketConn(c,
|
||||||
|
M.SocksaddrFromNet(metadata.UDPAddr()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if useEarly {
|
||||||
|
conn = v.client.DialEarlyConn(c,
|
||||||
|
M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
||||||
|
} else {
|
||||||
|
conn, err = v.client.DialConn(c,
|
||||||
|
M.ParseSocksaddrHostPort(metadata.String(), metadata.DstPort))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
conn = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.gunTransport != nil {
|
||||||
c, err := gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||||
if err != nil {
|
} else {
|
||||||
return nil, err
|
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(c, v), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
defer func(c net.Conn) {
|
||||||
defer safeConnClose(c, err)
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
return NewConn(c, v), err
|
return NewConn(c, v), err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
if err = v.ResolveUDP(ctx, metadata); err != nil {
|
||||||
if !metadata.Resolved() {
|
return nil, err
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.gunTransport != nil {
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.gunTransport, v.gunConfig)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
|
||||||
} else {
|
} else {
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
c, err = v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
|
}
|
||||||
|
defer func(c net.Conn) {
|
||||||
|
safeConnClose(c, err)
|
||||||
|
}(c)
|
||||||
|
|
||||||
|
c, err = v.StreamConnContext(ctx, c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("new vmess client error: %v", err)
|
||||||
}
|
}
|
||||||
|
return v.ListenPacketOnStreamConn(ctx, c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
return v.ListenPacketOnStreamConn(c, metadata)
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := v.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = v.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) Close() error {
|
||||||
|
if v.gunTransport != nil {
|
||||||
|
return v.gunTransport.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
func (v *Vmess) ListenPacketOnStreamConn(ctx context.Context, c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if err = v.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if pc, ok := c.(net.PacketConn); ok {
|
||||||
|
return newPacketConn(N.NewThreadSafePacketConn(pc), v), nil
|
||||||
|
}
|
||||||
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,37 +370,57 @@ func (v *Vmess) SupportUOT() bool {
|
|||||||
|
|
||||||
func NewVmess(option VmessOption) (*Vmess, error) {
|
func NewVmess(option VmessOption) (*Vmess, error) {
|
||||||
security := strings.ToLower(option.Cipher)
|
security := strings.ToLower(option.Cipher)
|
||||||
client, err := vmess.NewClient(vmess.Config{
|
var options []vmess.ClientOption
|
||||||
UUID: uuidMap(option.UUID),
|
if option.GlobalPadding {
|
||||||
AlterID: uint16(option.AlterID),
|
options = append(options, vmess.ClientWithGlobalPadding())
|
||||||
Security: security,
|
}
|
||||||
HostName: option.Server,
|
if option.AuthenticatedLength {
|
||||||
Port: strconv.Itoa(option.Port),
|
options = append(options, vmess.ClientWithAuthenticatedLength())
|
||||||
IsAead: option.AlterID == 0,
|
}
|
||||||
})
|
options = append(options, vmess.ClientWithTimeFunc(ntp.Now))
|
||||||
|
client, err := vmess.NewClient(option.UUID, security, option.AlterID, options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.PacketEncoding {
|
||||||
case "h2", "grpc":
|
case "packetaddr", "packet":
|
||||||
if !option.TLS {
|
option.PacketAddr = true
|
||||||
return nil, fmt.Errorf("TLS must be true with h2/grpc network")
|
case "xudp":
|
||||||
}
|
option.XUDP = true
|
||||||
|
}
|
||||||
|
if option.XUDP {
|
||||||
|
option.PacketAddr = false
|
||||||
}
|
}
|
||||||
|
|
||||||
v := &Vmess{
|
v := &Vmess{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
tp: C.Vmess,
|
tp: C.Vmess,
|
||||||
udp: option.UDP,
|
pdName: option.ProviderName,
|
||||||
iface: option.Interface,
|
udp: option.UDP,
|
||||||
rmark: option.RoutingMark,
|
xudp: option.XUDP,
|
||||||
|
tfo: option.TFO,
|
||||||
|
mpTcp: option.MPTCP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
}
|
}
|
||||||
|
v.dialer = option.NewDialer(v.DialOptions())
|
||||||
|
|
||||||
|
v.realityConfig, err = v.option.RealityOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
v.echConfig, err = v.option.ECHOpts.Parse()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
switch option.Network {
|
switch option.Network {
|
||||||
case "h2":
|
case "h2":
|
||||||
@@ -313,72 +428,65 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
option.HTTP2Opts.Host = append(option.HTTP2Opts.Host, "www.example.com")
|
||||||
}
|
}
|
||||||
case "grpc":
|
case "grpc":
|
||||||
dialFn := func(network, addr string) (net.Conn, error) {
|
dialFn := func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
c, err := dialer.DialContext(context.Background(), "tcp", v.addr, v.Base.DialOptions()...)
|
c, err := v.dialer.DialContext(ctx, "tcp", v.addr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
gunConfig := &gun.Config{
|
gunConfig := &gun.Config{
|
||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
UserAgent: option.GrpcOpts.GrpcUserAgent,
|
||||||
|
Host: option.ServerName,
|
||||||
}
|
}
|
||||||
tlsConfig := &tls.Config{
|
if option.ServerName == "" {
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
gunConfig.Host = v.addr
|
||||||
ServerName: v.option.ServerName,
|
}
|
||||||
|
var tlsConfig *mihomoVMess.TLSConfig
|
||||||
|
if option.TLS {
|
||||||
|
tlsConfig = &mihomoVMess.TLSConfig{
|
||||||
|
Host: option.ServerName,
|
||||||
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
|
FingerPrint: option.Fingerprint,
|
||||||
|
Certificate: option.Certificate,
|
||||||
|
PrivateKey: option.PrivateKey,
|
||||||
|
ClientFingerprint: option.ClientFingerprint,
|
||||||
|
NextProtos: []string{"h2"},
|
||||||
|
ECH: v.echConfig,
|
||||||
|
Reality: v.realityConfig,
|
||||||
|
}
|
||||||
|
if option.ServerName == "" {
|
||||||
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
tlsConfig.Host = host
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if v.option.ServerName == "" {
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
|
||||||
tlsConfig.ServerName = host
|
|
||||||
gunConfig.Host = host
|
|
||||||
}
|
|
||||||
|
|
||||||
v.gunTLSConfig = tlsConfig
|
|
||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
|
||||||
|
v.gunTransport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
|
||||||
var addrType byte
|
|
||||||
var addr []byte
|
|
||||||
switch metadata.AddrType {
|
|
||||||
case C.AtypIPv4:
|
|
||||||
addrType = byte(vmess.AtypIPv4)
|
|
||||||
addr = make([]byte, net.IPv4len)
|
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
|
||||||
case C.AtypIPv6:
|
|
||||||
addrType = byte(vmess.AtypIPv6)
|
|
||||||
addr = make([]byte, net.IPv6len)
|
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
|
||||||
case C.AtypDomainName:
|
|
||||||
addrType = byte(vmess.AtypDomainName)
|
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
|
||||||
addr[0] = byte(len(metadata.Host))
|
|
||||||
copy(addr[1:], []byte(metadata.Host))
|
|
||||||
}
|
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
|
||||||
return &vmess.DstAddr{
|
|
||||||
UDP: metadata.NetWork == C.UDP,
|
|
||||||
AddrType: addrType,
|
|
||||||
Addr: addr,
|
|
||||||
Port: uint(port),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type vmessPacketConn struct {
|
type vmessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
|
access sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WriteTo implments C.PacketConn.WriteTo
|
||||||
|
// Since VMess doesn't support full cone NAT by design, we verify if addr matches uc.rAddr, and drop the packet if not.
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
allowedAddr := uc.rAddr
|
||||||
|
destAddr := addr
|
||||||
|
if allowedAddr.String() != destAddr.String() {
|
||||||
|
return 0, ErrUDPRemoteAddrMismatch
|
||||||
|
}
|
||||||
|
uc.access.Lock()
|
||||||
|
defer uc.access.Unlock()
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
622
adapter/outbound/wireguard.go
Normal file
622
adapter/outbound/wireguard.go
Normal file
@@ -0,0 +1,622 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
|
"github.com/metacubex/mihomo/component/dialer"
|
||||||
|
"github.com/metacubex/mihomo/component/proxydialer"
|
||||||
|
"github.com/metacubex/mihomo/component/resolver"
|
||||||
|
"github.com/metacubex/mihomo/component/slowdown"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/dns"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
|
amnezia "github.com/metacubex/amneziawg-go/device"
|
||||||
|
wireguard "github.com/metacubex/sing-wireguard"
|
||||||
|
"github.com/metacubex/wireguard-go/device"
|
||||||
|
|
||||||
|
"github.com/metacubex/sing/common/debug"
|
||||||
|
E "github.com/metacubex/sing/common/exceptions"
|
||||||
|
M "github.com/metacubex/sing/common/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
type wireguardGoDevice interface {
|
||||||
|
Close()
|
||||||
|
IpcSet(uapiConf string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type WireGuard struct {
|
||||||
|
*Base
|
||||||
|
bind *wireguard.ClientBind
|
||||||
|
device wireguardGoDevice
|
||||||
|
tunDevice wireguard.Device
|
||||||
|
resolver resolver.Resolver
|
||||||
|
|
||||||
|
initOk atomic.Bool
|
||||||
|
initMutex sync.Mutex
|
||||||
|
initErr error
|
||||||
|
option WireGuardOption
|
||||||
|
connectAddr M.Socksaddr
|
||||||
|
localPrefixes []netip.Prefix
|
||||||
|
|
||||||
|
serverAddrMap map[M.Socksaddr]netip.AddrPort
|
||||||
|
serverAddrTime atomic.TypedValue[time.Time]
|
||||||
|
serverAddrMutex sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
type WireGuardOption struct {
|
||||||
|
BasicOption
|
||||||
|
WireGuardPeerOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Ip string `proxy:"ip,omitempty"`
|
||||||
|
Ipv6 string `proxy:"ipv6,omitempty"`
|
||||||
|
PrivateKey string `proxy:"private-key"`
|
||||||
|
Workers int `proxy:"workers,omitempty"`
|
||||||
|
MTU int `proxy:"mtu,omitempty"`
|
||||||
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
|
PersistentKeepalive int `proxy:"persistent-keepalive,omitempty"`
|
||||||
|
|
||||||
|
AmneziaWGOption *AmneziaWGOption `proxy:"amnezia-wg-option,omitempty"`
|
||||||
|
|
||||||
|
Peers []WireGuardPeerOption `proxy:"peers,omitempty"`
|
||||||
|
|
||||||
|
RemoteDnsResolve bool `proxy:"remote-dns-resolve,omitempty"`
|
||||||
|
Dns []string `proxy:"dns,omitempty"`
|
||||||
|
|
||||||
|
RefreshServerIPInterval int `proxy:"refresh-server-ip-interval,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type WireGuardPeerOption struct {
|
||||||
|
Server string `proxy:"server,omitempty"`
|
||||||
|
Port int `proxy:"port,omitempty"`
|
||||||
|
PublicKey string `proxy:"public-key,omitempty"`
|
||||||
|
PreSharedKey string `proxy:"pre-shared-key,omitempty"`
|
||||||
|
Reserved []uint8 `proxy:"reserved,omitempty"`
|
||||||
|
AllowedIPs []string `proxy:"allowed-ips,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AmneziaWGOption struct {
|
||||||
|
JC int `proxy:"jc,omitempty"`
|
||||||
|
JMin int `proxy:"jmin,omitempty"`
|
||||||
|
JMax int `proxy:"jmax,omitempty"`
|
||||||
|
S1 int `proxy:"s1,omitempty"`
|
||||||
|
S2 int `proxy:"s2,omitempty"`
|
||||||
|
S3 int `proxy:"s3,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
S4 int `proxy:"s4,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
H1 string `proxy:"h1,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
|
H2 string `proxy:"h2,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
|
H3 string `proxy:"h3,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
|
H4 string `proxy:"h4,omitempty"` // In AmneziaWG v1.x, it was uint32, but our WeaklyTypedInput can handle this situation
|
||||||
|
I1 string `proxy:"i1,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I2 string `proxy:"i2,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I3 string `proxy:"i3,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I4 string `proxy:"i4,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
I5 string `proxy:"i5,omitempty"` // AmneziaWG v1.5 and v2
|
||||||
|
J1 string `proxy:"j1,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
|
J2 string `proxy:"j2,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
|
J3 string `proxy:"j3,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
|
Itime int64 `proxy:"itime,omitempty"` // AmneziaWG v1.5 only (removed in v2)
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgSingErrorHandler struct {
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ E.Handler = (*wgSingErrorHandler)(nil)
|
||||||
|
|
||||||
|
func (w wgSingErrorHandler) NewError(ctx context.Context, err error) {
|
||||||
|
if E.IsClosedOrCanceled(err) {
|
||||||
|
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) connection closed: %s", w.name, err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", w.name, err))
|
||||||
|
}
|
||||||
|
|
||||||
|
type wgNetDialer struct {
|
||||||
|
tunDevice wireguard.Device
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ dialer.NetDialer = (*wgNetDialer)(nil)
|
||||||
|
|
||||||
|
func (d wgNetDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||||
|
return d.tunDevice.DialContext(ctx, network, M.ParseSocksaddr(address).Unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (option WireGuardPeerOption) Addr() M.Socksaddr {
|
||||||
|
return M.ParseSocksaddrHostPort(option.Server, uint16(option.Port))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (option WireGuardOption) Prefixes() ([]netip.Prefix, error) {
|
||||||
|
localPrefixes := make([]netip.Prefix, 0, 2)
|
||||||
|
if len(option.Ip) > 0 {
|
||||||
|
if !strings.Contains(option.Ip, "/") {
|
||||||
|
option.Ip = option.Ip + "/32"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ip); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, E.Cause(err, "ip address parse error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(option.Ipv6) > 0 {
|
||||||
|
if !strings.Contains(option.Ipv6, "/") {
|
||||||
|
option.Ipv6 = option.Ipv6 + "/128"
|
||||||
|
}
|
||||||
|
if prefix, err := netip.ParsePrefix(option.Ipv6); err == nil {
|
||||||
|
localPrefixes = append(localPrefixes, prefix)
|
||||||
|
} else {
|
||||||
|
return nil, E.Cause(err, "ipv6 address parse error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(localPrefixes) == 0 {
|
||||||
|
return nil, E.New("missing local address")
|
||||||
|
}
|
||||||
|
return localPrefixes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWireGuard(option WireGuardOption) (*WireGuard, error) {
|
||||||
|
outbound := &WireGuard{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: net.JoinHostPort(option.Server, strconv.Itoa(option.Port)),
|
||||||
|
tp: C.WireGuard,
|
||||||
|
pdName: option.ProviderName,
|
||||||
|
udp: option.UDP,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: option.IPVersion,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
outbound.dialer = option.NewDialer(outbound.DialOptions())
|
||||||
|
singDialer := proxydialer.NewSingDialer(proxydialer.NewSlowDownDialer(outbound.dialer, slowdown.New()))
|
||||||
|
|
||||||
|
var reserved [3]uint8
|
||||||
|
if len(option.Reserved) > 0 {
|
||||||
|
if len(option.Reserved) != 3 {
|
||||||
|
return nil, E.New("invalid reserved value, required 3 bytes, got ", len(option.Reserved))
|
||||||
|
}
|
||||||
|
copy(reserved[:], option.Reserved)
|
||||||
|
}
|
||||||
|
var isConnect bool
|
||||||
|
if len(option.Peers) < 2 {
|
||||||
|
isConnect = true
|
||||||
|
if len(option.Peers) == 1 {
|
||||||
|
outbound.connectAddr = option.Peers[0].Addr()
|
||||||
|
} else {
|
||||||
|
outbound.connectAddr = option.Addr()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outbound.bind = wireguard.NewClientBind(context.Background(), wgSingErrorHandler{outbound.Name()}, singDialer, isConnect, outbound.connectAddr.AddrPort(), reserved)
|
||||||
|
|
||||||
|
var err error
|
||||||
|
outbound.localPrefixes, err = option.Prefixes()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PrivateKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode private key")
|
||||||
|
}
|
||||||
|
option.PrivateKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Peers) > 0 {
|
||||||
|
for i := range option.Peers {
|
||||||
|
peer := &option.Peers[i] // we need modify option here
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(peer.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode public key for peer ", i)
|
||||||
|
}
|
||||||
|
peer.PublicKey = hex.EncodeToString(bytes)
|
||||||
|
|
||||||
|
if peer.PreSharedKey != "" {
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(peer.PreSharedKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode pre shared key for peer ", i)
|
||||||
|
}
|
||||||
|
peer.PreSharedKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(peer.AllowedIPs) == 0 {
|
||||||
|
return nil, E.New("missing allowed_ips for peer ", i)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(peer.Reserved) > 0 {
|
||||||
|
if len(peer.Reserved) != 3 {
|
||||||
|
return nil, E.New("invalid reserved value for peer ", i, ", required 3 bytes, got ", len(peer.Reserved))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
{
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PublicKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode peer public key")
|
||||||
|
}
|
||||||
|
option.PublicKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
if option.PreSharedKey != "" {
|
||||||
|
bytes, err := base64.StdEncoding.DecodeString(option.PreSharedKey)
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "decode pre shared key")
|
||||||
|
}
|
||||||
|
option.PreSharedKey = hex.EncodeToString(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outbound.option = option
|
||||||
|
|
||||||
|
mtu := option.MTU
|
||||||
|
if mtu == 0 {
|
||||||
|
mtu = 1408
|
||||||
|
}
|
||||||
|
if len(outbound.localPrefixes) == 0 {
|
||||||
|
return nil, E.New("missing local address")
|
||||||
|
}
|
||||||
|
outbound.tunDevice, err = wireguard.NewStackDevice(outbound.localPrefixes, uint32(mtu))
|
||||||
|
if err != nil {
|
||||||
|
return nil, E.Cause(err, "create WireGuard device")
|
||||||
|
}
|
||||||
|
logger := &device.Logger{
|
||||||
|
Verbosef: func(format string, args ...interface{}) {
|
||||||
|
log.SingLogger.Debug(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
|
},
|
||||||
|
Errorf: func(format string, args ...interface{}) {
|
||||||
|
log.SingLogger.Error(fmt.Sprintf("[WG](%s) %s", option.Name, fmt.Sprintf(format, args...)))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if option.AmneziaWGOption != nil {
|
||||||
|
outbound.bind.SetParseReserved(false) // AmneziaWG don't need parse reserved
|
||||||
|
outbound.device = amnezia.NewDevice(outbound.tunDevice, outbound.bind, logger, option.Workers)
|
||||||
|
} else {
|
||||||
|
outbound.device = device.NewDevice(outbound.tunDevice, outbound.bind, logger, option.Workers)
|
||||||
|
}
|
||||||
|
|
||||||
|
var has6 bool
|
||||||
|
for _, address := range outbound.localPrefixes {
|
||||||
|
if !address.Addr().Unmap().Is4() {
|
||||||
|
has6 = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if option.RemoteDnsResolve && len(option.Dns) > 0 {
|
||||||
|
nss, err := dns.ParseNameServer(option.Dns)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range nss {
|
||||||
|
nss[i].ProxyAdapter = outbound
|
||||||
|
}
|
||||||
|
outbound.resolver = dns.NewResolver(dns.Config{
|
||||||
|
Main: nss,
|
||||||
|
IPv6: has6,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return outbound, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) resolve(ctx context.Context, address M.Socksaddr) (netip.AddrPort, error) {
|
||||||
|
if address.Addr.IsValid() {
|
||||||
|
return address.AddrPort(), nil
|
||||||
|
}
|
||||||
|
udpAddr, err := resolveUDPAddr(ctx, "udp", address.String(), w.prefer)
|
||||||
|
if err != nil {
|
||||||
|
return netip.AddrPort{}, err
|
||||||
|
}
|
||||||
|
// net.ResolveUDPAddr maybe return 4in6 address, so unmap at here
|
||||||
|
addrPort := udpAddr.AddrPort()
|
||||||
|
return netip.AddrPortFrom(addrPort.Addr().Unmap(), addrPort.Port()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) init(ctx context.Context) error {
|
||||||
|
err := w.init0(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
w.updateServerAddr(ctx)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) init0(ctx context.Context) error {
|
||||||
|
if w.initOk.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
w.initMutex.Lock()
|
||||||
|
defer w.initMutex.Unlock()
|
||||||
|
// double check like sync.Once
|
||||||
|
if w.initOk.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if w.initErr != nil {
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
w.bind.ResetReservedForEndpoint()
|
||||||
|
w.serverAddrMap = make(map[M.Socksaddr]netip.AddrPort)
|
||||||
|
ipcConf, err := w.genIpcConf(ctx, false)
|
||||||
|
if err != nil {
|
||||||
|
// !!! do not set initErr here !!!
|
||||||
|
// let us can retry domain resolve in next time
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if debug.Enabled {
|
||||||
|
log.SingLogger.Trace(fmt.Sprintf("[WG](%s) created wireguard ipc conf: \n %s", w.option.Name, ipcConf))
|
||||||
|
}
|
||||||
|
err = w.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
w.initErr = E.Cause(err, "setup wireguard")
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
w.serverAddrTime.Store(time.Now())
|
||||||
|
|
||||||
|
err = w.tunDevice.Start()
|
||||||
|
if err != nil {
|
||||||
|
w.initErr = err
|
||||||
|
return w.initErr
|
||||||
|
}
|
||||||
|
|
||||||
|
w.initOk.Store(true)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) updateServerAddr(ctx context.Context) {
|
||||||
|
if w.option.RefreshServerIPInterval != 0 && time.Since(w.serverAddrTime.Load()) > time.Second*time.Duration(w.option.RefreshServerIPInterval) {
|
||||||
|
if w.serverAddrMutex.TryLock() {
|
||||||
|
defer w.serverAddrMutex.Unlock()
|
||||||
|
ipcConf, err := w.genIpcConf(ctx, true)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[WG](%s)UpdateServerAddr failed to generate wireguard ipc conf: %s", w.option.Name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = w.device.IpcSet(ipcConf)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[WG](%s)UpdateServerAddr failed to update wireguard ipc conf: %s", w.option.Name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.serverAddrTime.Store(time.Now())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) genIpcConf(ctx context.Context, updateOnly bool) (string, error) {
|
||||||
|
ipcConf := ""
|
||||||
|
if !updateOnly {
|
||||||
|
ipcConf += "private_key=" + w.option.PrivateKey + "\n"
|
||||||
|
if w.option.AmneziaWGOption != nil {
|
||||||
|
if w.option.AmneziaWGOption.JC != 0 {
|
||||||
|
ipcConf += "jc=" + strconv.Itoa(w.option.AmneziaWGOption.JC) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.JMin != 0 {
|
||||||
|
ipcConf += "jmin=" + strconv.Itoa(w.option.AmneziaWGOption.JMin) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.JMax != 0 {
|
||||||
|
ipcConf += "jmax=" + strconv.Itoa(w.option.AmneziaWGOption.JMax) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.S1 != 0 {
|
||||||
|
ipcConf += "s1=" + strconv.Itoa(w.option.AmneziaWGOption.S1) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.S2 != 0 {
|
||||||
|
ipcConf += "s2=" + strconv.Itoa(w.option.AmneziaWGOption.S2) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.S3 != 0 {
|
||||||
|
ipcConf += "s3=" + strconv.Itoa(w.option.AmneziaWGOption.S3) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.S4 != 0 {
|
||||||
|
ipcConf += "s4=" + strconv.Itoa(w.option.AmneziaWGOption.S4) + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H1 != "" {
|
||||||
|
ipcConf += "h1=" + w.option.AmneziaWGOption.H1 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H2 != "" {
|
||||||
|
ipcConf += "h2=" + w.option.AmneziaWGOption.H2 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H3 != "" {
|
||||||
|
ipcConf += "h3=" + w.option.AmneziaWGOption.H3 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.H4 != "" {
|
||||||
|
ipcConf += "h4=" + w.option.AmneziaWGOption.H4 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I1 != "" {
|
||||||
|
ipcConf += "i1=" + w.option.AmneziaWGOption.I1 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I2 != "" {
|
||||||
|
ipcConf += "i2=" + w.option.AmneziaWGOption.I2 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I3 != "" {
|
||||||
|
ipcConf += "i3=" + w.option.AmneziaWGOption.I3 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I4 != "" {
|
||||||
|
ipcConf += "i4=" + w.option.AmneziaWGOption.I4 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.I5 != "" {
|
||||||
|
ipcConf += "i5=" + w.option.AmneziaWGOption.I5 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.J1 != "" {
|
||||||
|
ipcConf += "j1=" + w.option.AmneziaWGOption.J1 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.J2 != "" {
|
||||||
|
ipcConf += "j2=" + w.option.AmneziaWGOption.J2 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.J3 != "" {
|
||||||
|
ipcConf += "j3=" + w.option.AmneziaWGOption.J3 + "\n"
|
||||||
|
}
|
||||||
|
if w.option.AmneziaWGOption.Itime != 0 {
|
||||||
|
ipcConf += "itime=" + strconv.FormatInt(int64(w.option.AmneziaWGOption.Itime), 10) + "\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(w.option.Peers) > 0 {
|
||||||
|
for i, peer := range w.option.Peers {
|
||||||
|
peerAddr := peer.Addr()
|
||||||
|
destination, err := w.resolve(ctx, peerAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", E.Cause(err, "resolve endpoint domain for peer ", i)
|
||||||
|
}
|
||||||
|
if w.serverAddrMap[peerAddr] != destination {
|
||||||
|
w.serverAddrMap[peerAddr] = destination
|
||||||
|
} else if updateOnly {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(w.option.Peers) == 1 { // must call SetConnectAddr if isConnect == true
|
||||||
|
w.bind.SetConnectAddr(destination)
|
||||||
|
}
|
||||||
|
ipcConf += "public_key=" + peer.PublicKey + "\n"
|
||||||
|
if updateOnly {
|
||||||
|
ipcConf += "update_only=true\n"
|
||||||
|
}
|
||||||
|
ipcConf += "endpoint=" + destination.String() + "\n"
|
||||||
|
if len(peer.Reserved) > 0 {
|
||||||
|
var reserved [3]uint8
|
||||||
|
copy(reserved[:], w.option.Reserved)
|
||||||
|
w.bind.SetReservedForEndpoint(destination, reserved)
|
||||||
|
}
|
||||||
|
if updateOnly {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if peer.PreSharedKey != "" {
|
||||||
|
ipcConf += "preshared_key=" + peer.PreSharedKey + "\n"
|
||||||
|
}
|
||||||
|
for _, allowedIP := range peer.AllowedIPs {
|
||||||
|
ipcConf += "allowed_ip=" + allowedIP + "\n"
|
||||||
|
}
|
||||||
|
if w.option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("persistent_keepalive_interval=%d\n", w.option.PersistentKeepalive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
destination, err := w.resolve(ctx, w.connectAddr)
|
||||||
|
if err != nil {
|
||||||
|
return "", E.Cause(err, "resolve endpoint domain")
|
||||||
|
}
|
||||||
|
if w.serverAddrMap[w.connectAddr] != destination {
|
||||||
|
w.serverAddrMap[w.connectAddr] = destination
|
||||||
|
} else if updateOnly {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
w.bind.SetConnectAddr(destination) // must call SetConnectAddr if isConnect == true
|
||||||
|
ipcConf += "public_key=" + w.option.PublicKey + "\n"
|
||||||
|
if updateOnly {
|
||||||
|
ipcConf += "update_only=true\n"
|
||||||
|
}
|
||||||
|
ipcConf += "endpoint=" + destination.String() + "\n"
|
||||||
|
if updateOnly {
|
||||||
|
return ipcConf, nil
|
||||||
|
}
|
||||||
|
if w.option.PreSharedKey != "" {
|
||||||
|
ipcConf += "preshared_key=" + w.option.PreSharedKey + "\n"
|
||||||
|
}
|
||||||
|
var has4, has6 bool
|
||||||
|
for _, address := range w.localPrefixes {
|
||||||
|
if address.Addr().Is4() {
|
||||||
|
has4 = true
|
||||||
|
} else {
|
||||||
|
has6 = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if has4 {
|
||||||
|
ipcConf += "allowed_ip=0.0.0.0/0\n"
|
||||||
|
}
|
||||||
|
if has6 {
|
||||||
|
ipcConf += "allowed_ip=::/0\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
if w.option.PersistentKeepalive != 0 {
|
||||||
|
ipcConf += fmt.Sprintf("persistent_keepalive_interval=%d\n", w.option.PersistentKeepalive)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ipcConf, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close implements C.ProxyAdapter
|
||||||
|
func (w *WireGuard) Close() error {
|
||||||
|
if w.device != nil {
|
||||||
|
w.device.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) DialContext(ctx context.Context, metadata *C.Metadata) (_ C.Conn, err error) {
|
||||||
|
var conn net.Conn
|
||||||
|
if err = w.init(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !metadata.Resolved() || w.resolver != nil {
|
||||||
|
r := resolver.DefaultResolver
|
||||||
|
if w.resolver != nil {
|
||||||
|
r = w.resolver
|
||||||
|
}
|
||||||
|
options := w.DialOptions()
|
||||||
|
options = append(options, dialer.WithResolver(r))
|
||||||
|
options = append(options, dialer.WithNetDialer(wgNetDialer{tunDevice: w.tunDevice}))
|
||||||
|
conn, err = dialer.NewDialer(options...).DialContext(ctx, "tcp", metadata.RemoteAddress())
|
||||||
|
} else {
|
||||||
|
conn, err = w.tunDevice.DialContext(ctx, "tcp", M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if conn == nil {
|
||||||
|
return nil, E.New("conn is nil")
|
||||||
|
}
|
||||||
|
return NewConn(conn, w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
var pc net.PacketConn
|
||||||
|
if err = w.init(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = w.ResolveUDP(ctx, metadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pc, err = w.tunDevice.ListenPacket(ctx, M.SocksaddrFrom(metadata.DstIP, metadata.DstPort).Unwrap())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if pc == nil {
|
||||||
|
return nil, E.New("packetConn is nil")
|
||||||
|
}
|
||||||
|
return newPacketConn(pc, w), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *WireGuard) ResolveUDP(ctx context.Context, metadata *C.Metadata) error {
|
||||||
|
if (!metadata.Resolved() || w.resolver != nil) && metadata.Host != "" {
|
||||||
|
r := resolver.DefaultResolver
|
||||||
|
if w.resolver != nil {
|
||||||
|
r = w.resolver
|
||||||
|
}
|
||||||
|
ip, err := resolver.ResolveIPWithResolver(ctx, metadata.Host, r)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("can't resolve ip: %w", err)
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxyInfo implements C.ProxyAdapter
|
||||||
|
func (w *WireGuard) ProxyInfo() C.ProxyInfo {
|
||||||
|
info := w.Base.ProxyInfo()
|
||||||
|
info.DialerProxy = w.option.DialerProxy
|
||||||
|
return info
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (w *WireGuard) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -3,21 +3,24 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/Dreamacro/clash/log"
|
"errors"
|
||||||
"go.uber.org/atomic"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
failedTimes *atomic.Int32
|
testUrl string
|
||||||
failedTime *atomic.Int64
|
selected string
|
||||||
|
expectedStatus string
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@@ -26,61 +29,39 @@ func (f *Fallback) Now() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
proxy := f.findAliveProxy(true)
|
proxy := f.findAliveProxy(true)
|
||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
f.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
} else {
|
} else {
|
||||||
f.onDialFailed()
|
f.onDialFailed(proxy.Type(), err, f.healthCheck)
|
||||||
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
f.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
f.onDialFailed(proxy.Type(), err, f.healthCheck)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
proxy := f.findAliveProxy(true)
|
proxy := f.findAliveProxy(true)
|
||||||
pc, err := proxy.ListenPacketContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
pc, err := proxy.ListenPacketContext(ctx, metadata)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(f)
|
pc.AppendToChains(f)
|
||||||
f.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
f.onDialFailed()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) onDialFailed() {
|
|
||||||
if f.failedTime.Load() == -1 {
|
|
||||||
log.Warnln("%s first failed", f.Name())
|
|
||||||
now := time.Now().UnixMilli()
|
|
||||||
f.failedTime.Store(now)
|
|
||||||
f.failedTimes.Store(1)
|
|
||||||
} else {
|
|
||||||
if f.failedTime.Load()-time.Now().UnixMilli() > 5*time.Second.Milliseconds() {
|
|
||||||
f.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
failedCount := f.failedTimes.Inc()
|
|
||||||
log.Warnln("%s failed count: %d", f.Name(), failedCount)
|
|
||||||
if failedCount >= 5 {
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", f.Name())
|
|
||||||
for _, proxyProvider := range f.providers {
|
|
||||||
go proxyProvider.HealthCheck()
|
|
||||||
}
|
|
||||||
|
|
||||||
f.failedTimes.Store(-1)
|
|
||||||
f.failedTime.Store(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (f *Fallback) SupportUDP() bool {
|
func (f *Fallback) SupportUDP() bool {
|
||||||
if f.disableUDP {
|
if f.disableUDP {
|
||||||
@@ -91,6 +72,11 @@ func (f *Fallback) SupportUDP() bool {
|
|||||||
return proxy.SupportUDP()
|
return proxy.SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (f *Fallback) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return f.findAliveProxy(false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
@@ -98,43 +84,96 @@ func (f *Fallback) MarshalJSON() ([]byte, error) {
|
|||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": f.Type().String(),
|
"type": f.Type().String(),
|
||||||
"now": f.Now(),
|
"now": f.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
|
"testUrl": f.testUrl,
|
||||||
|
"expectedStatus": f.expectedStatus,
|
||||||
|
"fixed": f.selected,
|
||||||
|
"hidden": f.Hidden,
|
||||||
|
"icon": f.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (f *Fallback) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxy := f.findAliveProxy(true)
|
proxy := f.findAliveProxy(touch)
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||||
proxies := f.GetProxies(touch)
|
proxies := f.GetProxies(touch)
|
||||||
for _, proxy := range proxies {
|
for _, proxy := range proxies {
|
||||||
if proxy.Alive() {
|
if len(f.selected) == 0 {
|
||||||
return proxy
|
if proxy.AliveForTestUrl(f.testUrl) {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if proxy.Name() == f.selected {
|
||||||
|
if proxy.AliveForTestUrl(f.testUrl) {
|
||||||
|
return proxy
|
||||||
|
} else {
|
||||||
|
f.selected = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func (f *Fallback) Set(name string) error {
|
||||||
|
var p C.Proxy
|
||||||
|
for _, proxy := range f.GetProxies(false) {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
p = proxy
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if p == nil {
|
||||||
|
return errors.New("proxy not exist")
|
||||||
|
}
|
||||||
|
|
||||||
|
f.selected = name
|
||||||
|
if !p.AliveForTestUrl(f.testUrl) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||||
|
defer cancel()
|
||||||
|
expectedStatus, _ := utils.NewUnsignedRanges[uint16](f.expectedStatus)
|
||||||
|
_, _ = p.URLTest(ctx, f.testUrl, expectedStatus)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) ForceSet(name string) {
|
||||||
|
f.selected = name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Providers() []P.ProxyProvider {
|
||||||
|
return f.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *Fallback) Proxies() []C.Proxy {
|
||||||
|
return f.GetProxies(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFallback(option *GroupCommonOption, providers []P.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.Fallback,
|
||||||
Type: C.Fallback,
|
Filter: option.Filter,
|
||||||
Interface: option.Interface,
|
ExcludeFilter: option.ExcludeFilter,
|
||||||
RoutingMark: option.RoutingMark,
|
ExcludeType: option.ExcludeType,
|
||||||
},
|
TestTimeout: option.TestTimeout,
|
||||||
option.Filter,
|
MaxFailedTimes: option.MaxFailedTimes,
|
||||||
providers,
|
Providers: providers,
|
||||||
}),
|
}),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
failedTimes: atomic.NewInt32(-1),
|
testUrl: option.URL,
|
||||||
failedTime: atomic.NewInt64(-1),
|
expectedStatus: option.ExpectedStatus,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,98 +1,307 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"context"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"errors"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"fmt"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
"strings"
|
||||||
"github.com/Dreamacro/clash/tunnel"
|
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
"github.com/metacubex/mihomo/tunnel"
|
||||||
|
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"golang.org/x/exp/slices"
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupBase struct {
|
type GroupBase struct {
|
||||||
*outbound.Base
|
*outbound.Base
|
||||||
filter *regexp2.Regexp
|
filterRegs []*regexp2.Regexp
|
||||||
providers []provider.ProxyProvider
|
excludeFilterRegs []*regexp2.Regexp
|
||||||
versions sync.Map // map[string]uint
|
excludeTypeArray []string
|
||||||
proxies sync.Map // map[string][]C.Proxy
|
providers []P.ProxyProvider
|
||||||
|
failedTestMux sync.Mutex
|
||||||
|
failedTimes int
|
||||||
|
failedTime time.Time
|
||||||
|
failedTesting atomic.Bool
|
||||||
|
TestTimeout int
|
||||||
|
maxFailedTimes int
|
||||||
|
|
||||||
|
// for GetProxies
|
||||||
|
getProxiesMutex sync.Mutex
|
||||||
|
providerVersions []uint32
|
||||||
|
providerProxies []C.Proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupBaseOption struct {
|
type GroupBaseOption struct {
|
||||||
outbound.BaseOption
|
Name string
|
||||||
filter string
|
Type C.AdapterType
|
||||||
providers []provider.ProxyProvider
|
Filter string
|
||||||
|
ExcludeFilter string
|
||||||
|
ExcludeType string
|
||||||
|
TestTimeout int
|
||||||
|
MaxFailedTimes int
|
||||||
|
Providers []P.ProxyProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
var filter *regexp2.Regexp = nil
|
var excludeTypeArray []string
|
||||||
if opt.filter != "" {
|
if opt.ExcludeType != "" {
|
||||||
filter = regexp2.MustCompile(opt.filter, 0)
|
excludeTypeArray = strings.Split(opt.ExcludeType, "|")
|
||||||
}
|
}
|
||||||
return &GroupBase{
|
|
||||||
Base: outbound.NewBase(opt.BaseOption),
|
var excludeFilterRegs []*regexp2.Regexp
|
||||||
filter: filter,
|
if opt.ExcludeFilter != "" {
|
||||||
providers: opt.providers,
|
for _, excludeFilter := range strings.Split(opt.ExcludeFilter, "`") {
|
||||||
|
excludeFilterReg := regexp2.MustCompile(excludeFilter, regexp2.None)
|
||||||
|
excludeFilterRegs = append(excludeFilterRegs, excludeFilterReg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
|
if opt.Filter != "" {
|
||||||
|
for _, filter := range strings.Split(opt.Filter, "`") {
|
||||||
|
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gb := &GroupBase{
|
||||||
|
Base: outbound.NewBase(outbound.BaseOption{Name: opt.Name, Type: opt.Type}),
|
||||||
|
filterRegs: filterRegs,
|
||||||
|
excludeFilterRegs: excludeFilterRegs,
|
||||||
|
excludeTypeArray: excludeTypeArray,
|
||||||
|
providers: opt.Providers,
|
||||||
|
failedTesting: atomic.NewBool(false),
|
||||||
|
TestTimeout: opt.TestTimeout,
|
||||||
|
maxFailedTimes: opt.MaxFailedTimes,
|
||||||
|
}
|
||||||
|
|
||||||
|
if gb.TestTimeout == 0 {
|
||||||
|
gb.TestTimeout = 5000
|
||||||
|
}
|
||||||
|
if gb.maxFailedTimes == 0 {
|
||||||
|
gb.maxFailedTimes = 5
|
||||||
|
}
|
||||||
|
|
||||||
|
return gb
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) Touch() {
|
||||||
|
for _, pd := range gb.providers {
|
||||||
|
pd.Touch()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||||
if gb.filter == nil {
|
providerVersions := make([]uint32, len(gb.providers))
|
||||||
var proxies []C.Proxy
|
for i, pd := range gb.providers {
|
||||||
for _, pd := range gb.providers {
|
if touch { // touch first
|
||||||
if touch {
|
pd.Touch()
|
||||||
proxies = append(proxies, pd.ProxiesWithTouch()...)
|
|
||||||
} else {
|
|
||||||
proxies = append(proxies, pd.Proxies()...)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if len(proxies) == 0 {
|
providerVersions[i] = pd.Version()
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
|
||||||
}
|
|
||||||
return proxies
|
|
||||||
}
|
}
|
||||||
//TODO("Touch Version 没变的")
|
|
||||||
for _, pd := range gb.providers {
|
|
||||||
if pd.VehicleType() == types.Compatible {
|
|
||||||
if touch {
|
|
||||||
gb.proxies.Store(pd.Name(), pd.ProxiesWithTouch())
|
|
||||||
} else {
|
|
||||||
gb.proxies.Store(pd.Name(), pd.Proxies())
|
|
||||||
}
|
|
||||||
|
|
||||||
gb.versions.Store(pd.Name(), pd.Version())
|
// thread safe
|
||||||
continue
|
gb.getProxiesMutex.Lock()
|
||||||
|
defer gb.getProxiesMutex.Unlock()
|
||||||
|
|
||||||
|
// return the cached proxies if version not changed
|
||||||
|
if slices.Equal(providerVersions, gb.providerVersions) {
|
||||||
|
return gb.providerProxies
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxies []C.Proxy
|
||||||
|
if len(gb.filterRegs) == 0 {
|
||||||
|
for _, pd := range gb.providers {
|
||||||
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
if version, ok := gb.versions.Load(pd.Name()); !ok || version != pd.Version() {
|
for _, pd := range gb.providers {
|
||||||
var (
|
if pd.VehicleType() == P.Compatible { // compatible provider unneeded filter
|
||||||
proxies []C.Proxy
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
newProxies []C.Proxy
|
continue
|
||||||
)
|
|
||||||
|
|
||||||
if touch {
|
|
||||||
proxies = pd.ProxiesWithTouch()
|
|
||||||
} else {
|
|
||||||
proxies = pd.Proxies()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, p := range proxies {
|
var newProxies []C.Proxy
|
||||||
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
proxiesSet := map[string]struct{}{}
|
||||||
newProxies = append(newProxies, p)
|
for _, filterReg := range gb.filterRegs {
|
||||||
|
for _, p := range pd.Proxies() {
|
||||||
|
name := p.Name()
|
||||||
|
if mat, _ := filterReg.MatchString(name); mat {
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
proxies = append(proxies, newProxies...)
|
||||||
gb.proxies.Store(pd.Name(), newProxies)
|
|
||||||
gb.versions.Store(pd.Name(), pd.Version())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var proxies []C.Proxy
|
|
||||||
gb.proxies.Range(func(key, value any) bool {
|
// Multiple filers means that proxies are sorted in the order in which the filers appear.
|
||||||
proxies = append(proxies, value.([]C.Proxy)...)
|
// Although the filter has been performed once in the previous process,
|
||||||
return true
|
// when there are multiple providers, the array needs to be reordered as a whole.
|
||||||
})
|
if len(gb.providers) > 1 && len(gb.filterRegs) > 1 {
|
||||||
if len(proxies) == 0 {
|
var newProxies []C.Proxy
|
||||||
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
proxiesSet := map[string]struct{}{}
|
||||||
|
for _, filterReg := range gb.filterRegs {
|
||||||
|
for _, p := range proxies {
|
||||||
|
name := p.Name()
|
||||||
|
if mat, _ := filterReg.MatchString(name); mat {
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range proxies { // add not matched proxies at the end
|
||||||
|
name := p.Name()
|
||||||
|
if _, ok := proxiesSet[name]; !ok {
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proxies = newProxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(gb.excludeFilterRegs) > 0 {
|
||||||
|
var newProxies []C.Proxy
|
||||||
|
LOOP1:
|
||||||
|
for _, p := range proxies {
|
||||||
|
name := p.Name()
|
||||||
|
for _, excludeFilterReg := range gb.excludeFilterRegs {
|
||||||
|
if mat, _ := excludeFilterReg.MatchString(name); mat {
|
||||||
|
continue LOOP1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
proxies = newProxies
|
||||||
|
}
|
||||||
|
|
||||||
|
if gb.excludeTypeArray != nil {
|
||||||
|
var newProxies []C.Proxy
|
||||||
|
LOOP2:
|
||||||
|
for _, p := range proxies {
|
||||||
|
mType := p.Type().String()
|
||||||
|
for _, excludeType := range gb.excludeTypeArray {
|
||||||
|
if strings.EqualFold(mType, excludeType) {
|
||||||
|
continue LOOP2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
proxies = newProxies
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return []C.Proxy{tunnel.Proxies()["COMPATIBLE"]}
|
||||||
|
}
|
||||||
|
|
||||||
|
// only cache when proxies not empty
|
||||||
|
gb.providerVersions = providerVersions
|
||||||
|
gb.providerProxies = proxies
|
||||||
|
|
||||||
return proxies
|
return proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (map[string]uint16, error) {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var lock sync.Mutex
|
||||||
|
mp := map[string]uint16{}
|
||||||
|
proxies := gb.GetProxies(false)
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
proxy := proxy
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
delay, err := proxy.URLTest(ctx, url, expectedStatus)
|
||||||
|
if err == nil {
|
||||||
|
lock.Lock()
|
||||||
|
mp[proxy.Name()] = delay
|
||||||
|
lock.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Done()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
if len(mp) == 0 {
|
||||||
|
return mp, fmt.Errorf("get delay: all proxies timeout")
|
||||||
|
} else {
|
||||||
|
return mp, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) onDialFailed(adapterType C.AdapterType, err error, fn func()) {
|
||||||
|
if adapterType == C.Direct || adapterType == C.Compatible || adapterType == C.Reject || adapterType == C.Pass || adapterType == C.RejectDrop {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, C.ErrNotSupport) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
if strings.Contains(err.Error(), "connection refused") {
|
||||||
|
fn()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.failedTestMux.Lock()
|
||||||
|
defer gb.failedTestMux.Unlock()
|
||||||
|
|
||||||
|
gb.failedTimes++
|
||||||
|
if gb.failedTimes == 1 {
|
||||||
|
log.Debugln("ProxyGroup: %s first failed", gb.Name())
|
||||||
|
gb.failedTime = time.Now()
|
||||||
|
} else {
|
||||||
|
if time.Since(gb.failedTime) > time.Duration(gb.TestTimeout)*time.Millisecond {
|
||||||
|
gb.failedTimes = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
|
if gb.failedTimes >= gb.maxFailedTimes {
|
||||||
|
log.Warnln("because %s failed multiple times, activate health check", gb.Name())
|
||||||
|
fn()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) healthCheck() {
|
||||||
|
if gb.failedTesting.Load() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.failedTesting.Store(true)
|
||||||
|
wg := sync.WaitGroup{}
|
||||||
|
for _, proxyProvider := range gb.providers {
|
||||||
|
wg.Add(1)
|
||||||
|
proxyProvider := proxyProvider
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
proxyProvider.HealthCheck()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
gb.failedTesting.Store(false)
|
||||||
|
gb.failedTimes = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) onDialSuccess() {
|
||||||
|
if !gb.failedTesting.Load() {
|
||||||
|
gb.failedTimes = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,36 +6,45 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/metacubex/mihomo/common/lru"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
|
||||||
"golang.org/x/net/publicsuffix"
|
"golang.org/x/net/publicsuffix"
|
||||||
)
|
)
|
||||||
|
|
||||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy
|
||||||
|
|
||||||
type LoadBalance struct {
|
type LoadBalance struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
|
testUrl string
|
||||||
|
expectedStatus string
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
}
|
}
|
||||||
|
|
||||||
var errStrategy = errors.New("unsupported strategy")
|
var errStrategy = errors.New("unsupported strategy")
|
||||||
|
|
||||||
func parseStrategy(config map[string]any) string {
|
func parseStrategy(config map[string]any) string {
|
||||||
if elm, ok := config["strategy"]; ok {
|
if strategy, ok := config["strategy"].(string); ok {
|
||||||
if strategy, ok := elm.(string); ok {
|
return strategy
|
||||||
return strategy
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return "consistent-hashing"
|
return "consistent-hashing"
|
||||||
}
|
}
|
||||||
|
|
||||||
func getKey(metadata *C.Metadata) string {
|
func getKey(metadata *C.Metadata) string {
|
||||||
|
if metadata == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
if metadata.Host != "" {
|
if metadata.Host != "" {
|
||||||
// ip host
|
// ip host
|
||||||
if ip := net.ParseIP(metadata.Host); ip != nil {
|
if ip := net.ParseIP(metadata.Host); ip != nil {
|
||||||
@@ -54,6 +63,16 @@ func getKey(metadata *C.Metadata) string {
|
|||||||
return metadata.DstIP.String()
|
return metadata.DstIP.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func getKeyWithSrcAndDst(metadata *C.Metadata) string {
|
||||||
|
dst := getKey(metadata)
|
||||||
|
src := ""
|
||||||
|
if metadata != nil {
|
||||||
|
src = metadata.SrcIP.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("%s%s", src, dst)
|
||||||
|
}
|
||||||
|
|
||||||
func jumpHash(key uint64, buckets int32) int32 {
|
func jumpHash(key uint64, buckets int32) int32 {
|
||||||
var b, j int64
|
var b, j int64
|
||||||
|
|
||||||
@@ -67,29 +86,39 @@ func jumpHash(key uint64, buckets int32) int32 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
defer func() {
|
proxy := lb.Unwrap(metadata, true)
|
||||||
if err == nil {
|
c, err = proxy.DialContext(ctx, metadata)
|
||||||
c.AppendToChains(lb)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata)
|
if err == nil {
|
||||||
|
c.AppendToChains(lb)
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err, lb.healthCheck)
|
||||||
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
lb.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed(proxy.Type(), err, lb.healthCheck)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
c, err = proxy.DialContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (pc C.PacketConn, err error) {
|
func (lb *LoadBalance) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (pc C.PacketConn, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(lb)
|
pc.AppendToChains(lb)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
proxy := lb.Unwrap(metadata)
|
proxy := lb.Unwrap(metadata, true)
|
||||||
return proxy.ListenPacketContext(ctx, metadata, lb.Base.DialOptions(opts...)...)
|
return proxy.ListenPacketContext(ctx, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
@@ -97,14 +126,32 @@ func (lb *LoadBalance) SupportUDP() bool {
|
|||||||
return !lb.disableUDP
|
return !lb.disableUDP
|
||||||
}
|
}
|
||||||
|
|
||||||
func strategyRoundRobin() strategyFn {
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (lb *LoadBalance) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return lb.Unwrap(metadata, false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyRoundRobin(url string) strategyFn {
|
||||||
idx := 0
|
idx := 0
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
idxMutex := sync.Mutex{}
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
|
idxMutex.Lock()
|
||||||
|
defer idxMutex.Unlock()
|
||||||
|
|
||||||
|
i := 0
|
||||||
length := len(proxies)
|
length := len(proxies)
|
||||||
for i := 0; i < length; i++ {
|
|
||||||
idx = (idx + 1) % length
|
if touch {
|
||||||
proxy := proxies[idx]
|
defer func() {
|
||||||
if proxy.Alive() {
|
idx = (idx + i) % length
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
for ; i < length; i++ {
|
||||||
|
id := (idx + i) % length
|
||||||
|
proxy := proxies[id]
|
||||||
|
if proxy.AliveForTestUrl(url) {
|
||||||
|
i++
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,63 +160,125 @@ func strategyRoundRobin() strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func strategyConsistentHashing() strategyFn {
|
func strategyConsistentHashing(url string) strategyFn {
|
||||||
maxRetry := 5
|
maxRetry := 5
|
||||||
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
key := uint64(murmur3.Sum32([]byte(getKey(metadata))))
|
key := utils.MapHash(getKey(metadata))
|
||||||
buckets := int32(len(proxies))
|
buckets := int32(len(proxies))
|
||||||
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
for i := 0; i < maxRetry; i, key = i+1, key+1 {
|
||||||
idx := jumpHash(key, buckets)
|
idx := jumpHash(key, buckets)
|
||||||
proxy := proxies[idx]
|
proxy := proxies[idx]
|
||||||
if proxy.Alive() {
|
if proxy.AliveForTestUrl(url) {
|
||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.AliveForTestUrl(url) {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyStickySessions(url string) strategyFn {
|
||||||
|
ttl := time.Minute * 10
|
||||||
|
maxRetry := 5
|
||||||
|
lruCache := lru.New[uint64, int](
|
||||||
|
lru.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
|
lru.WithSize[uint64, int](1000))
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
|
key := utils.MapHash(getKeyWithSrcAndDst(metadata))
|
||||||
|
length := len(proxies)
|
||||||
|
idx, has := lruCache.Get(key)
|
||||||
|
if !has || idx >= length {
|
||||||
|
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||||
|
}
|
||||||
|
|
||||||
|
nowIdx := idx
|
||||||
|
for i := 1; i < maxRetry; i++ {
|
||||||
|
proxy := proxies[nowIdx]
|
||||||
|
if proxy.AliveForTestUrl(url) {
|
||||||
|
if !has || nowIdx != idx {
|
||||||
|
lruCache.Set(key, nowIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxy
|
||||||
|
} else {
|
||||||
|
nowIdx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lruCache.Set(key, 0)
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (lb *LoadBalance) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
proxies := lb.GetProxies(true)
|
proxies := lb.GetProxies(touch)
|
||||||
return lb.strategyFn(proxies, metadata)
|
return lb.strategyFn(proxies, metadata, touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
var all []string
|
||||||
for _, proxy := range lb.GetProxies(false) {
|
for _, proxy := range lb.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": lb.Type().String(),
|
"type": lb.Type().String(),
|
||||||
"all": all,
|
"all": all,
|
||||||
|
"testUrl": lb.testUrl,
|
||||||
|
"expectedStatus": lb.expectedStatus,
|
||||||
|
"hidden": lb.Hidden,
|
||||||
|
"icon": lb.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
func (lb *LoadBalance) Providers() []P.ProxyProvider {
|
||||||
|
return lb.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) Proxies() []C.Proxy {
|
||||||
|
return lb.GetProxies(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (lb *LoadBalance) Now() string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoadBalance(option *GroupCommonOption, providers []P.ProxyProvider, strategy string) (lb *LoadBalance, err error) {
|
||||||
var strategyFn strategyFn
|
var strategyFn strategyFn
|
||||||
switch strategy {
|
switch strategy {
|
||||||
case "consistent-hashing":
|
case "consistent-hashing":
|
||||||
strategyFn = strategyConsistentHashing()
|
strategyFn = strategyConsistentHashing(option.URL)
|
||||||
case "round-robin":
|
case "round-robin":
|
||||||
strategyFn = strategyRoundRobin()
|
strategyFn = strategyRoundRobin(option.URL)
|
||||||
|
case "sticky-sessions":
|
||||||
|
strategyFn = strategyStickySessions(option.URL)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
}
|
}
|
||||||
return &LoadBalance{
|
return &LoadBalance{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.LoadBalance,
|
||||||
Type: C.LoadBalance,
|
Filter: option.Filter,
|
||||||
Interface: option.Interface,
|
ExcludeFilter: option.ExcludeFilter,
|
||||||
RoutingMark: option.RoutingMark,
|
ExcludeType: option.ExcludeType,
|
||||||
},
|
TestTimeout: option.TestTimeout,
|
||||||
option.Filter,
|
MaxFailedTimes: option.MaxFailedTimes,
|
||||||
providers,
|
Providers: providers,
|
||||||
}),
|
}),
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
testUrl: option.URL,
|
||||||
|
expectedStatus: option.ExpectedStatus,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,36 +3,48 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/dlclark/regexp2"
|
||||||
"github.com/Dreamacro/clash/adapter/provider"
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/adapter/provider"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
errFormat = errors.New("format error")
|
errFormat = errors.New("format error")
|
||||||
errType = errors.New("unsupport type")
|
errType = errors.New("unsupported type")
|
||||||
errMissProxy = errors.New("`use` or `proxies` missing")
|
errMissProxy = errors.New("`use` or `proxies` missing")
|
||||||
errMissHealthCheck = errors.New("`url` or `interval` missing")
|
|
||||||
errDuplicateProvider = errors.New("duplicate provider name")
|
errDuplicateProvider = errors.New("duplicate provider name")
|
||||||
)
|
)
|
||||||
|
|
||||||
type GroupCommonOption struct {
|
type GroupCommonOption struct {
|
||||||
outbound.BasicOption
|
Name string `group:"name"`
|
||||||
Name string `group:"name"`
|
Type string `group:"type"`
|
||||||
Type string `group:"type"`
|
Proxies []string `group:"proxies,omitempty"`
|
||||||
Proxies []string `group:"proxies,omitempty"`
|
Use []string `group:"use,omitempty"`
|
||||||
Use []string `group:"use,omitempty"`
|
URL string `group:"url,omitempty"`
|
||||||
URL string `group:"url,omitempty"`
|
Interval int `group:"interval,omitempty"`
|
||||||
Interval int `group:"interval,omitempty"`
|
TestTimeout int `group:"timeout,omitempty"`
|
||||||
Lazy bool `group:"lazy,omitempty"`
|
MaxFailedTimes int `group:"max-failed-times,omitempty"`
|
||||||
DisableUDP bool `group:"disable-udp,omitempty"`
|
Lazy bool `group:"lazy,omitempty"`
|
||||||
Filter string `group:"filter,omitempty"`
|
DisableUDP bool `group:"disable-udp,omitempty"`
|
||||||
|
Filter string `group:"filter,omitempty"`
|
||||||
|
ExcludeFilter string `group:"exclude-filter,omitempty"`
|
||||||
|
ExcludeType string `group:"exclude-type,omitempty"`
|
||||||
|
ExpectedStatus string `group:"expected-status,omitempty"`
|
||||||
|
IncludeAll bool `group:"include-all,omitempty"`
|
||||||
|
IncludeAllProxies bool `group:"include-all-proxies,omitempty"`
|
||||||
|
IncludeAllProviders bool `group:"include-all-providers,omitempty"`
|
||||||
|
Hidden bool `group:"hidden,omitempty"`
|
||||||
|
Icon string `group:"icon,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]types.ProxyProvider) (C.ProxyAdapter, error) {
|
func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, providersMap map[string]P.ProxyProvider, AllProxies []string, AllProviders []string) (C.ProxyAdapter, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "group", WeaklyTypedInput: true})
|
||||||
|
|
||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
@@ -46,58 +58,118 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if _, ok := config["routing-mark"]; ok {
|
||||||
|
log.Errorln("The group [%s] with routing-mark configuration was removed, please set it directly on the proxy instead", groupOption.Name)
|
||||||
|
}
|
||||||
|
if _, ok := config["interface-name"]; ok {
|
||||||
|
log.Errorln("The group [%s] with interface-name configuration was removed, please set it directly on the proxy instead", groupOption.Name)
|
||||||
|
}
|
||||||
|
if _, ok := config["dialer-proxy"]; ok {
|
||||||
|
log.Errorln("The group [%s] with dialer-proxy configuration is not allowed, please set it directly on the proxy instead", groupOption.Name)
|
||||||
|
}
|
||||||
|
|
||||||
groupName := groupOption.Name
|
groupName := groupOption.Name
|
||||||
|
|
||||||
providers := []types.ProxyProvider{}
|
providers := []P.ProxyProvider{}
|
||||||
|
|
||||||
|
if groupOption.IncludeAll {
|
||||||
|
groupOption.IncludeAllProviders = true
|
||||||
|
groupOption.IncludeAllProxies = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if groupOption.IncludeAllProviders {
|
||||||
|
groupOption.Use = AllProviders
|
||||||
|
}
|
||||||
|
if groupOption.IncludeAllProxies {
|
||||||
|
if groupOption.Filter != "" {
|
||||||
|
var filterRegs []*regexp2.Regexp
|
||||||
|
for _, filter := range strings.Split(groupOption.Filter, "`") {
|
||||||
|
filterReg := regexp2.MustCompile(filter, regexp2.None)
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
for _, p := range AllProxies {
|
||||||
|
for _, filterReg := range filterRegs {
|
||||||
|
if mat, _ := filterReg.MatchString(p); mat {
|
||||||
|
groupOption.Proxies = append(groupOption.Proxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
groupOption.Proxies = append(groupOption.Proxies, AllProxies...)
|
||||||
|
}
|
||||||
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
|
groupOption.Proxies = []string{"COMPATIBLE"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
if len(groupOption.Proxies) == 0 && len(groupOption.Use) == 0 {
|
||||||
return nil, errMissProxy
|
return nil, fmt.Errorf("%s: %w", groupName, errMissProxy)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedStatus, err := utils.NewUnsignedRanges[uint16](groupOption.ExpectedStatus)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
status := strings.TrimSpace(groupOption.ExpectedStatus)
|
||||||
|
if status == "" {
|
||||||
|
status = "*"
|
||||||
|
}
|
||||||
|
groupOption.ExpectedStatus = status
|
||||||
|
|
||||||
|
if len(groupOption.Use) != 0 {
|
||||||
|
PDs, err := getProviders(providersMap, groupOption.Use)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// if test URL is empty, use the first health check URL of providers
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
for _, pd := range PDs {
|
||||||
|
if pd.HealthCheckURL() != "" {
|
||||||
|
groupOption.URL = pd.HealthCheckURL()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if groupOption.URL == "" {
|
||||||
|
groupOption.URL = C.DefaultTestURL
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addTestUrlToProviders(PDs, groupOption.URL, expectedStatus, groupOption.Filter, uint(groupOption.Interval))
|
||||||
|
}
|
||||||
|
providers = append(providers, PDs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(groupOption.Proxies) != 0 {
|
if len(groupOption.Proxies) != 0 {
|
||||||
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
ps, err := getProxies(proxyMap, groupOption.Proxies)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, ok := providersMap[groupName]; ok {
|
if _, ok := providersMap[groupName]; ok {
|
||||||
return nil, errDuplicateProvider
|
return nil, fmt.Errorf("%s: %w", groupName, errDuplicateProvider)
|
||||||
}
|
}
|
||||||
|
|
||||||
// select don't need health check
|
if groupOption.URL == "" {
|
||||||
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
groupOption.URL = C.DefaultTestURL
|
||||||
hc := provider.NewHealthCheck(ps, "", 0, true)
|
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
providers = append(providers, pd)
|
|
||||||
providersMap[groupName] = pd
|
|
||||||
} else {
|
|
||||||
if groupOption.URL == "" || groupOption.Interval == 0 {
|
|
||||||
return nil, errMissHealthCheck
|
|
||||||
}
|
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
|
||||||
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
providers = append(providers, pd)
|
|
||||||
providersMap[groupName] = pd
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if len(groupOption.Use) != 0 {
|
// select don't need auto health check
|
||||||
list, err := getProviders(providersMap, groupOption.Use)
|
if groupOption.Type != "select" && groupOption.Type != "relay" {
|
||||||
|
if groupOption.Interval == 0 {
|
||||||
|
groupOption.Interval = 300
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.TestTimeout), uint(groupOption.Interval), groupOption.Lazy, expectedStatus)
|
||||||
|
|
||||||
|
pd, err := provider.NewCompatibleProvider(groupName, ps, hc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s: %w", groupName, err)
|
||||||
}
|
}
|
||||||
providers = append(providers, list...)
|
|
||||||
} else {
|
providers = append([]P.ProxyProvider{pd}, providers...)
|
||||||
groupOption.Filter = ""
|
providersMap[groupName] = pd
|
||||||
}
|
}
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
@@ -113,7 +185,7 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
strategy := parseStrategy(config)
|
strategy := parseStrategy(config)
|
||||||
return NewLoadBalance(groupOption, providers, strategy)
|
return NewLoadBalance(groupOption, providers, strategy)
|
||||||
case "relay":
|
case "relay":
|
||||||
group = NewRelay(groupOption, providers)
|
return nil, fmt.Errorf("%w: The group [%s] with relay type was removed, please using dialer-proxy instead", errType, groupName)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
return nil, fmt.Errorf("%w: %s", errType, groupOption.Type)
|
||||||
}
|
}
|
||||||
@@ -133,18 +205,28 @@ func getProxies(mapping map[string]C.Proxy, list []string) ([]C.Proxy, error) {
|
|||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
|
func getProviders(mapping map[string]P.ProxyProvider, list []string) ([]P.ProxyProvider, error) {
|
||||||
var ps []types.ProxyProvider
|
var ps []P.ProxyProvider
|
||||||
for _, name := range list {
|
for _, name := range list {
|
||||||
p, ok := mapping[name]
|
p, ok := mapping[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("'%s' not found", name)
|
return nil, fmt.Errorf("'%s' not found", name)
|
||||||
}
|
}
|
||||||
|
|
||||||
if p.VehicleType() == types.Compatible {
|
if p.VehicleType() == P.Compatible {
|
||||||
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
return nil, fmt.Errorf("proxy group %s can't contains in `use`", name)
|
||||||
}
|
}
|
||||||
ps = append(ps, p)
|
ps = append(ps, p)
|
||||||
}
|
}
|
||||||
return ps, nil
|
return ps, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func addTestUrlToProviders(providers []P.ProxyProvider, url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
|
if len(providers) == 0 || len(url) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, pd := range providers {
|
||||||
|
pd.RegisterHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,186 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Relay struct {
|
|
||||||
*GroupBase
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
|
||||||
proxies, chainProxies := r.proxies(metadata, true)
|
|
||||||
|
|
||||||
switch len(proxies) {
|
|
||||||
case 0:
|
|
||||||
return outbound.NewDirect().DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
|
||||||
case 1:
|
|
||||||
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
|
||||||
}
|
|
||||||
|
|
||||||
first := proxies[0]
|
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
var currentMeta *C.Metadata
|
|
||||||
for _, proxy := range proxies[1:] {
|
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = first.StreamConn(c, currentMeta)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
conn := outbound.NewConn(c, last)
|
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
|
||||||
conn.AppendToChains(chainProxies[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
conn.AppendToChains(r)
|
|
||||||
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
|
||||||
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
|
||||||
proxies, chainProxies := r.proxies(metadata, true)
|
|
||||||
|
|
||||||
switch len(proxies) {
|
|
||||||
case 0:
|
|
||||||
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
|
||||||
case 1:
|
|
||||||
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
|
||||||
}
|
|
||||||
|
|
||||||
first := proxies[0]
|
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
var currentMeta *C.Metadata
|
|
||||||
for _, proxy := range proxies[1:] {
|
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = first.StreamConn(c, currentMeta)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var pc C.PacketConn
|
|
||||||
pc, err = last.ListenPacketOnStreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := len(chainProxies) - 2; i >= 0; i-- {
|
|
||||||
pc.AppendToChains(chainProxies[i])
|
|
||||||
}
|
|
||||||
|
|
||||||
pc.AppendToChains(r)
|
|
||||||
|
|
||||||
return pc, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
|
||||||
func (r *Relay) SupportUDP() bool {
|
|
||||||
proxies, _ := r.proxies(nil, false)
|
|
||||||
if len(proxies) == 0 { // C.Direct
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
return last.SupportUDP() && last.SupportUOT()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
|
||||||
func (r *Relay) MarshalJSON() ([]byte, error) {
|
|
||||||
all := []string{}
|
|
||||||
for _, proxy := range r.GetProxies(false) {
|
|
||||||
all = append(all, proxy.Name())
|
|
||||||
}
|
|
||||||
return json.Marshal(map[string]any{
|
|
||||||
"type": r.Type().String(),
|
|
||||||
"all": all,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy) {
|
|
||||||
rawProxies := r.GetProxies(touch)
|
|
||||||
|
|
||||||
var proxies []C.Proxy
|
|
||||||
var chainProxies []C.Proxy
|
|
||||||
var targetProxies []C.Proxy
|
|
||||||
|
|
||||||
for n, proxy := range rawProxies {
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
chainProxies = append(chainProxies, proxy)
|
|
||||||
subproxy := proxy.Unwrap(metadata)
|
|
||||||
for subproxy != nil {
|
|
||||||
chainProxies = append(chainProxies, subproxy)
|
|
||||||
proxies[n] = subproxy
|
|
||||||
subproxy = subproxy.Unwrap(metadata)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, proxy := range proxies {
|
|
||||||
if proxy.Type() != C.Direct && proxy.Type() != C.Compatible {
|
|
||||||
targetProxies = append(targetProxies, proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return targetProxies, chainProxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
|
||||||
return &Relay{
|
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
|
||||||
outbound.BaseOption{
|
|
||||||
Name: option.Name,
|
|
||||||
Type: C.Relay,
|
|
||||||
Interface: option.Interface,
|
|
||||||
RoutingMark: option.RoutingMark,
|
|
||||||
},
|
|
||||||
"",
|
|
||||||
providers,
|
|
||||||
}),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,21 +5,22 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
type Selector struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
selected string
|
selected string
|
||||||
|
testUrl string
|
||||||
|
Hidden bool
|
||||||
|
Icon string
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata) (C.Conn, error) {
|
||||||
c, err := s.selectedProxy(true).DialContext(ctx, metadata, s.Base.DialOptions(opts...)...)
|
c, err := s.selectedProxy(true).DialContext(ctx, metadata)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(s)
|
c.AppendToChains(s)
|
||||||
}
|
}
|
||||||
@@ -27,8 +28,8 @@ func (s *Selector) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (s *Selector) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (s *Selector) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := s.selectedProxy(true).ListenPacketContext(ctx, metadata, s.Base.DialOptions(opts...)...)
|
pc, err := s.selectedProxy(true).ListenPacketContext(ctx, metadata)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(s)
|
pc.AppendToChains(s)
|
||||||
}
|
}
|
||||||
@@ -44,17 +45,31 @@ func (s *Selector) SupportUDP() bool {
|
|||||||
return s.selectedProxy(false).SupportUDP()
|
return s.selectedProxy(false).SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (s *Selector) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return s.selectedProxy(false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
for _, proxy := range s.GetProxies(false) {
|
for _, proxy := range s.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
|
// When testurl is the default value
|
||||||
|
// do not append a value to ensure that the web dashboard follows the settings of the dashboard
|
||||||
|
var url string
|
||||||
|
if s.testUrl != C.DefaultTestURL {
|
||||||
|
url = s.testUrl
|
||||||
|
}
|
||||||
|
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": s.Type().String(),
|
"type": s.Type().String(),
|
||||||
"now": s.Now(),
|
"now": s.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
|
"testUrl": url,
|
||||||
|
"hidden": s.Hidden,
|
||||||
|
"icon": s.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,9 +88,13 @@ func (s *Selector) Set(name string) error {
|
|||||||
return errors.New("proxy not exist")
|
return errors.New("proxy not exist")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *Selector) ForceSet(name string) {
|
||||||
|
s.selected = name
|
||||||
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
func (s *Selector) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return s.selectedProxy(true)
|
return s.selectedProxy(touch)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
@@ -89,19 +108,30 @@ func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
|||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
func (s *Selector) Providers() []P.ProxyProvider {
|
||||||
|
return s.providers
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Selector) Proxies() []C.Proxy {
|
||||||
|
return s.GetProxies(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSelector(option *GroupCommonOption, providers []P.ProxyProvider) *Selector {
|
||||||
return &Selector{
|
return &Selector{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.Selector,
|
||||||
Type: C.Selector,
|
Filter: option.Filter,
|
||||||
Interface: option.Interface,
|
ExcludeFilter: option.ExcludeFilter,
|
||||||
RoutingMark: option.RoutingMark,
|
ExcludeType: option.ExcludeType,
|
||||||
},
|
TestTimeout: option.TestTimeout,
|
||||||
option.Filter,
|
MaxFailedTimes: option.MaxFailedTimes,
|
||||||
providers,
|
Providers: providers,
|
||||||
}),
|
}),
|
||||||
selected: "COMPATIBLE",
|
selected: "COMPATIBLE",
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
testUrl: option.URL,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,15 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/Dreamacro/clash/log"
|
"errors"
|
||||||
"go.uber.org/atomic"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/common/callback"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/metacubex/mihomo/common/singledo"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type urlTestOption func(*URLTest)
|
type urlTestOption func(*URLTest)
|
||||||
@@ -24,54 +24,105 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*GroupBase
|
*GroupBase
|
||||||
tolerance uint16
|
selected string
|
||||||
disableUDP bool
|
testUrl string
|
||||||
fastNode C.Proxy
|
expectedStatus string
|
||||||
fastSingle *singledo.Single[C.Proxy]
|
tolerance uint16
|
||||||
failedTimes *atomic.Int32
|
disableUDP bool
|
||||||
failedTime *atomic.Int64
|
Hidden bool
|
||||||
|
Icon string
|
||||||
|
fastNode C.Proxy
|
||||||
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
func (u *URLTest) Now() string {
|
||||||
return u.fast(false).Name()
|
return u.fast(false).Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) Set(name string) error {
|
||||||
|
var p C.Proxy
|
||||||
|
for _, proxy := range u.GetProxies(false) {
|
||||||
|
if proxy.Name() == name {
|
||||||
|
p = proxy
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p == nil {
|
||||||
|
return errors.New("proxy not exist")
|
||||||
|
}
|
||||||
|
u.ForceSet(name)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) ForceSet(name string) {
|
||||||
|
u.selected = name
|
||||||
|
u.fastSingle.Reset()
|
||||||
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (c C.Conn, err error) {
|
func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata) (c C.Conn, err error) {
|
||||||
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
proxy := u.fast(true)
|
||||||
|
c, err = proxy.DialContext(ctx, metadata)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed()
|
u.onDialFailed(proxy.Type(), err, u.healthCheck)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if N.NeedHandshake(c) {
|
||||||
|
c = callback.NewFirstWriteCallBackConn(c, func(err error) {
|
||||||
|
if err == nil {
|
||||||
|
u.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
u.onDialFailed(proxy.Type(), err, u.healthCheck)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata) (C.PacketConn, error) {
|
||||||
pc, err := u.fast(true).ListenPacketContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
proxy := u.fast(true)
|
||||||
|
pc, err := proxy.ListenPacketContext(ctx, metadata)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(u)
|
pc.AppendToChains(u)
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
} else {
|
||||||
u.onDialFailed()
|
u.onDialFailed(proxy.Type(), err, u.healthCheck)
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
func (u *URLTest) Unwrap(metadata *C.Metadata, touch bool) C.Proxy {
|
||||||
return u.fast(true)
|
return u.fast(touch)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *URLTest) healthCheck() {
|
||||||
|
u.fastSingle.Reset()
|
||||||
|
u.GroupBase.healthCheck()
|
||||||
|
u.fastSingle.Reset()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) fast(touch bool) C.Proxy {
|
func (u *URLTest) fast(touch bool) C.Proxy {
|
||||||
elm, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
elm, _, shared := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.GetProxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
|
if u.selected != "" {
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if !proxy.AliveForTestUrl(u.testUrl) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if proxy.Name() == u.selected {
|
||||||
|
u.fastNode = proxy
|
||||||
|
return proxy, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
minDelay := fast.LastDelayForTestUrl(u.testUrl)
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
|
|
||||||
for _, proxy := range proxies[1:] {
|
for _, proxy := range proxies[1:] {
|
||||||
@@ -79,24 +130,26 @@ func (u *URLTest) fast(touch bool) C.Proxy {
|
|||||||
fastNotExist = false
|
fastNotExist = false
|
||||||
}
|
}
|
||||||
|
|
||||||
if !proxy.Alive() {
|
if !proxy.AliveForTestUrl(u.testUrl) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
delay := proxy.LastDelay()
|
delay := proxy.LastDelayForTestUrl(u.testUrl)
|
||||||
if delay < min {
|
if delay < minDelay {
|
||||||
fast = proxy
|
fast = proxy
|
||||||
min = delay
|
minDelay = delay
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
}
|
||||||
// tolerance
|
// tolerance
|
||||||
if u.fastNode == nil || fastNotExist || !u.fastNode.Alive() || u.fastNode.LastDelay() > fast.LastDelay()+u.tolerance {
|
if u.fastNode == nil || fastNotExist || !u.fastNode.AliveForTestUrl(u.testUrl) || u.fastNode.LastDelayForTestUrl(u.testUrl) > fast.LastDelayForTestUrl(u.testUrl)+u.tolerance {
|
||||||
u.fastNode = fast
|
u.fastNode = fast
|
||||||
}
|
}
|
||||||
|
|
||||||
return u.fastNode, nil
|
return u.fastNode, nil
|
||||||
})
|
})
|
||||||
|
if shared && touch { // a shared fastSingle.Do() may cause providers untouched, so we touch them again
|
||||||
|
u.Touch()
|
||||||
|
}
|
||||||
|
|
||||||
return elm
|
return elm
|
||||||
}
|
}
|
||||||
@@ -106,10 +159,14 @@ func (u *URLTest) SupportUDP() bool {
|
|||||||
if u.disableUDP {
|
if u.disableUDP {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
return u.fast(false).SupportUDP()
|
return u.fast(false).SupportUDP()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsL3Protocol implements C.ProxyAdapter
|
||||||
|
func (u *URLTest) IsL3Protocol(metadata *C.Metadata) bool {
|
||||||
|
return u.fast(false).IsL3Protocol(metadata)
|
||||||
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
all := []string{}
|
all := []string{}
|
||||||
@@ -117,36 +174,27 @@ func (u *URLTest) MarshalJSON() ([]byte, error) {
|
|||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
"type": u.Type().String(),
|
"type": u.Type().String(),
|
||||||
"now": u.Now(),
|
"now": u.Now(),
|
||||||
"all": all,
|
"all": all,
|
||||||
|
"testUrl": u.testUrl,
|
||||||
|
"expectedStatus": u.expectedStatus,
|
||||||
|
"fixed": u.selected,
|
||||||
|
"hidden": u.Hidden,
|
||||||
|
"icon": u.Icon,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) onDialFailed() {
|
func (u *URLTest) Providers() []P.ProxyProvider {
|
||||||
if u.failedTime.Load() == -1 {
|
return u.providers
|
||||||
log.Warnln("%s first failed", u.Name())
|
}
|
||||||
now := time.Now().UnixMilli()
|
|
||||||
u.failedTime.Store(now)
|
|
||||||
u.failedTimes.Store(1)
|
|
||||||
} else {
|
|
||||||
if u.failedTime.Load()-time.Now().UnixMilli() > 5*1000 {
|
|
||||||
u.failedTimes.Store(-1)
|
|
||||||
u.failedTime.Store(-1)
|
|
||||||
} else {
|
|
||||||
failedCount := u.failedTimes.Inc()
|
|
||||||
log.Warnln("%s failed count: %d", u.Name(), failedCount)
|
|
||||||
if failedCount >= 5 {
|
|
||||||
log.Warnln("because %s failed multiple times, active health check", u.Name())
|
|
||||||
for _, proxyProvider := range u.providers {
|
|
||||||
go proxyProvider.HealthCheck()
|
|
||||||
}
|
|
||||||
|
|
||||||
u.failedTimes.Store(-1)
|
func (u *URLTest) Proxies() []C.Proxy {
|
||||||
u.failedTime.Store(-1)
|
return u.GetProxies(false)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
func (u *URLTest) URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (map[string]uint16, error) {
|
||||||
|
return u.GroupBase.URLTest(ctx, u.testUrl, expectedStatus)
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseURLTestOption(config map[string]any) []urlTestOption {
|
func parseURLTestOption(config map[string]any) []urlTestOption {
|
||||||
@@ -162,22 +210,24 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
|
|||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
func NewURLTest(option *GroupCommonOption, providers []P.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||||
urlTest := &URLTest{
|
urlTest := &URLTest{
|
||||||
GroupBase: NewGroupBase(GroupBaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
outbound.BaseOption{
|
Name: option.Name,
|
||||||
Name: option.Name,
|
Type: C.URLTest,
|
||||||
Type: C.URLTest,
|
Filter: option.Filter,
|
||||||
Interface: option.Interface,
|
ExcludeFilter: option.ExcludeFilter,
|
||||||
RoutingMark: option.RoutingMark,
|
ExcludeType: option.ExcludeType,
|
||||||
},
|
TestTimeout: option.TestTimeout,
|
||||||
option.Filter,
|
MaxFailedTimes: option.MaxFailedTimes,
|
||||||
providers,
|
Providers: providers,
|
||||||
}),
|
}),
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
failedTimes: atomic.NewInt32(-1),
|
testUrl: option.URL,
|
||||||
failedTime: atomic.NewInt64(-1),
|
expectedStatus: option.ExpectedStatus,
|
||||||
|
Hidden: option.Hidden,
|
||||||
|
Icon: option.Icon,
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
|
|||||||
@@ -1,53 +1,34 @@
|
|||||||
package outboundgroup
|
package outboundgroup
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"context"
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
type ProxyGroup interface {
|
||||||
host, port, err := net.SplitHostPort(rawAddress)
|
C.ProxyAdapter
|
||||||
if err != nil {
|
|
||||||
err = fmt.Errorf("addrToMetadata failed: %w", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ip, err := netip.ParseAddr(host)
|
Providers() []P.ProxyProvider
|
||||||
if err != nil {
|
Proxies() []C.Proxy
|
||||||
addr = &C.Metadata{
|
Now() string
|
||||||
AddrType: C.AtypDomainName,
|
Touch()
|
||||||
Host: host,
|
|
||||||
DstIP: netip.Addr{},
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
err = nil
|
|
||||||
return
|
|
||||||
} else if ip.Is4() {
|
|
||||||
addr = &C.Metadata{
|
|
||||||
AddrType: C.AtypIPv4,
|
|
||||||
Host: "",
|
|
||||||
DstIP: ip,
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
addr = &C.Metadata{
|
URLTest(ctx context.Context, url string, expectedStatus utils.IntRanges[uint16]) (mp map[string]uint16, err error)
|
||||||
AddrType: C.AtypIPv6,
|
|
||||||
Host: "",
|
|
||||||
DstIP: ip,
|
|
||||||
DstPort: port,
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
var _ ProxyGroup = (*Fallback)(nil)
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
var _ ProxyGroup = (*LoadBalance)(nil)
|
||||||
_ = tcp.SetKeepAlive(true)
|
var _ ProxyGroup = (*URLTest)(nil)
|
||||||
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
var _ ProxyGroup = (*Selector)(nil)
|
||||||
}
|
|
||||||
|
type SelectAble interface {
|
||||||
|
Set(string) error
|
||||||
|
ForceSet(name string)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ SelectAble = (*Fallback)(nil)
|
||||||
|
var _ SelectAble = (*URLTest)(nil)
|
||||||
|
var _ SelectAble = (*Selector)(nil)
|
||||||
|
|||||||
@@ -3,84 +3,176 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/metacubex/mihomo/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/metacubex/mihomo/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any, options ...ProxyOption) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true, KeyReplacer: structure.DefaultKeyReplacer})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
return nil, fmt.Errorf("missing type")
|
return nil, fmt.Errorf("missing type")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
opt := applyProxyOptions(options...)
|
||||||
|
basicOption := outbound.BasicOption{
|
||||||
|
DialerForAPI: opt.DialerForAPI,
|
||||||
|
ProviderName: opt.ProviderName,
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
proxy C.ProxyAdapter
|
proxy outbound.ProxyAdapter
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
switch proxyType {
|
switch proxyType {
|
||||||
case "ss":
|
case "ss":
|
||||||
ssOption := &outbound.ShadowSocksOption{}
|
ssOption := &outbound.ShadowSocksOption{BasicOption: basicOption}
|
||||||
err = decoder.Decode(mapping, ssOption)
|
err = decoder.Decode(mapping, ssOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewShadowSocks(*ssOption)
|
proxy, err = outbound.NewShadowSocks(*ssOption)
|
||||||
case "ssr":
|
case "ssr":
|
||||||
ssrOption := &outbound.ShadowSocksROption{}
|
ssrOption := &outbound.ShadowSocksROption{BasicOption: basicOption}
|
||||||
err = decoder.Decode(mapping, ssrOption)
|
err = decoder.Decode(mapping, ssrOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewShadowSocksR(*ssrOption)
|
proxy, err = outbound.NewShadowSocksR(*ssrOption)
|
||||||
case "socks5":
|
case "socks5":
|
||||||
socksOption := &outbound.Socks5Option{}
|
socksOption := &outbound.Socks5Option{BasicOption: basicOption}
|
||||||
err = decoder.Decode(mapping, socksOption)
|
err = decoder.Decode(mapping, socksOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewSocks5(*socksOption)
|
proxy, err = outbound.NewSocks5(*socksOption)
|
||||||
case "http":
|
case "http":
|
||||||
httpOption := &outbound.HttpOption{}
|
httpOption := &outbound.HttpOption{BasicOption: basicOption}
|
||||||
err = decoder.Decode(mapping, httpOption)
|
err = decoder.Decode(mapping, httpOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy = outbound.NewHttp(*httpOption)
|
proxy, err = outbound.NewHttp(*httpOption)
|
||||||
case "vmess":
|
case "vmess":
|
||||||
vmessOption := &outbound.VmessOption{
|
vmessOption := &outbound.VmessOption{BasicOption: basicOption}
|
||||||
HTTPOpts: outbound.HTTPOptions{
|
|
||||||
Method: "GET",
|
|
||||||
Path: []string{"/"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
err = decoder.Decode(mapping, vmessOption)
|
err = decoder.Decode(mapping, vmessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{}
|
vlessOption := &outbound.VlessOption{BasicOption: basicOption}
|
||||||
err = decoder.Decode(mapping, vlessOption)
|
err = decoder.Decode(mapping, vlessOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewVless(*vlessOption)
|
proxy, err = outbound.NewVless(*vlessOption)
|
||||||
case "snell":
|
case "snell":
|
||||||
snellOption := &outbound.SnellOption{}
|
snellOption := &outbound.SnellOption{BasicOption: basicOption}
|
||||||
err = decoder.Decode(mapping, snellOption)
|
err = decoder.Decode(mapping, snellOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewSnell(*snellOption)
|
proxy, err = outbound.NewSnell(*snellOption)
|
||||||
case "trojan":
|
case "trojan":
|
||||||
trojanOption := &outbound.TrojanOption{}
|
trojanOption := &outbound.TrojanOption{BasicOption: basicOption}
|
||||||
err = decoder.Decode(mapping, trojanOption)
|
err = decoder.Decode(mapping, trojanOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
proxy, err = outbound.NewTrojan(*trojanOption)
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
|
case "hysteria":
|
||||||
|
hyOption := &outbound.HysteriaOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, hyOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
|
case "hysteria2":
|
||||||
|
hyOption := &outbound.Hysteria2Option{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, hyOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewHysteria2(*hyOption)
|
||||||
|
case "wireguard":
|
||||||
|
wgOption := &outbound.WireGuardOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, wgOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewWireGuard(*wgOption)
|
||||||
|
case "tuic":
|
||||||
|
tuicOption := &outbound.TuicOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, tuicOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewTuic(*tuicOption)
|
||||||
|
case "direct":
|
||||||
|
directOption := &outbound.DirectOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, directOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewDirectWithOption(*directOption)
|
||||||
|
case "dns":
|
||||||
|
dnsOptions := &outbound.DnsOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, dnsOptions)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewDnsWithOption(*dnsOptions)
|
||||||
|
case "reject":
|
||||||
|
rejectOption := &outbound.RejectOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, rejectOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy = outbound.NewRejectWithOption(*rejectOption)
|
||||||
|
case "ssh":
|
||||||
|
sshOption := &outbound.SshOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, sshOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewSsh(*sshOption)
|
||||||
|
case "mieru":
|
||||||
|
mieruOption := &outbound.MieruOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, mieruOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewMieru(*mieruOption)
|
||||||
|
case "anytls":
|
||||||
|
anytlsOption := &outbound.AnyTLSOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, anytlsOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewAnyTLS(*anytlsOption)
|
||||||
|
case "sudoku":
|
||||||
|
sudokuOption := &outbound.SudokuOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, sudokuOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewSudoku(*sudokuOption)
|
||||||
|
case "masque":
|
||||||
|
masqueOption := &outbound.MasqueOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, masqueOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewMasque(*masqueOption)
|
||||||
|
case "trusttunnel":
|
||||||
|
trustTunnelOption := &outbound.TrustTunnelOption{BasicOption: basicOption}
|
||||||
|
err = decoder.Decode(mapping, trustTunnelOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewTrustTunnel(*trustTunnelOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
@@ -89,5 +181,47 @@ func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if muxMapping, muxExist := mapping["smux"].(map[string]any); muxExist {
|
||||||
|
muxOption := &outbound.SingMuxOption{}
|
||||||
|
err = decoder.Decode(muxMapping, muxOption)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if muxOption.Enabled {
|
||||||
|
proxy, err = outbound.NewSingMux(*muxOption, proxy)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy = outbound.NewAutoCloseProxyAdapter(proxy)
|
||||||
return NewProxy(proxy), nil
|
return NewProxy(proxy), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type proxyOption struct {
|
||||||
|
DialerForAPI C.Dialer
|
||||||
|
ProviderName string
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyProxyOptions(options ...ProxyOption) proxyOption {
|
||||||
|
opt := proxyOption{}
|
||||||
|
for _, o := range options {
|
||||||
|
o(&opt)
|
||||||
|
}
|
||||||
|
return opt
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProxyOption func(opt *proxyOption)
|
||||||
|
|
||||||
|
func WithDialerForAPI(dialer C.Dialer) ProxyOption {
|
||||||
|
return func(opt *proxyOption) {
|
||||||
|
opt.DialerForAPI = dialer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithProviderName(name string) ProxyOption {
|
||||||
|
return func(opt *proxyOption) {
|
||||||
|
opt.ProviderName = name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,185 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/md5"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
"github.com/Dreamacro/clash/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
fileMode os.FileMode = 0o666
|
|
||||||
dirMode os.FileMode = 0o755
|
|
||||||
)
|
|
||||||
|
|
||||||
type parser = func([]byte) (any, error)
|
|
||||||
|
|
||||||
type fetcher struct {
|
|
||||||
name string
|
|
||||||
vehicle types.Vehicle
|
|
||||||
updatedAt *time.Time
|
|
||||||
ticker *time.Ticker
|
|
||||||
done chan struct{}
|
|
||||||
hash [16]byte
|
|
||||||
parser parser
|
|
||||||
onUpdate func(any)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Name() string {
|
|
||||||
return f.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) VehicleType() types.VehicleType {
|
|
||||||
return f.vehicle.Type()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Initial() (any, error) {
|
|
||||||
var (
|
|
||||||
buf []byte
|
|
||||||
err error
|
|
||||||
isLocal bool
|
|
||||||
)
|
|
||||||
if stat, fErr := os.Stat(f.vehicle.Path()); fErr == nil {
|
|
||||||
buf, err = os.ReadFile(f.vehicle.Path())
|
|
||||||
modTime := stat.ModTime()
|
|
||||||
f.updatedAt = &modTime
|
|
||||||
isLocal = true
|
|
||||||
} else {
|
|
||||||
buf, err = f.vehicle.Read()
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
|
||||||
if err != nil {
|
|
||||||
if !isLocal {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse local file error, fallback to remote
|
|
||||||
buf, err = f.vehicle.Read()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err = f.parser(buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
isLocal = false
|
|
||||||
}
|
|
||||||
|
|
||||||
if f.vehicle.Type() != types.File && !isLocal {
|
|
||||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
f.hash = md5.Sum(buf)
|
|
||||||
|
|
||||||
// pull proxies automatically
|
|
||||||
if f.ticker != nil {
|
|
||||||
go f.pullLoop()
|
|
||||||
}
|
|
||||||
|
|
||||||
return proxies, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Update() (any, bool, error) {
|
|
||||||
buf, err := f.vehicle.Read()
|
|
||||||
if err != nil {
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
hash := md5.Sum(buf)
|
|
||||||
if bytes.Equal(f.hash[:], hash[:]) {
|
|
||||||
f.updatedAt = &now
|
|
||||||
os.Chtimes(f.vehicle.Path(), now, now)
|
|
||||||
return nil, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies, err := f.parser(buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if f.vehicle.Type() != types.File {
|
|
||||||
if err := safeWrite(f.vehicle.Path(), buf); err != nil {
|
|
||||||
return nil, false, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
f.updatedAt = &now
|
|
||||||
f.hash = hash
|
|
||||||
|
|
||||||
return proxies, false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) Destroy() error {
|
|
||||||
if f.ticker != nil {
|
|
||||||
f.done <- struct{}{}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *fetcher) pullLoop() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-f.ticker.C:
|
|
||||||
elm, same, err := f.Update()
|
|
||||||
if err != nil {
|
|
||||||
log.Warnln("[Provider] %s pull error: %s", f.Name(), err.Error())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if same {
|
|
||||||
log.Debugln("[Provider] %s's proxies doesn't change", f.Name())
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Infoln("[Provider] %s's proxies update", f.Name())
|
|
||||||
if f.onUpdate != nil {
|
|
||||||
f.onUpdate(elm)
|
|
||||||
}
|
|
||||||
case <-f.done:
|
|
||||||
f.ticker.Stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func safeWrite(path string, buf []byte) error {
|
|
||||||
dir := filepath.Dir(path)
|
|
||||||
|
|
||||||
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
|
||||||
if err := os.MkdirAll(dir, dirMode); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return os.WriteFile(path, buf, fileMode)
|
|
||||||
}
|
|
||||||
|
|
||||||
func newFetcher(name string, interval time.Duration, vehicle types.Vehicle, parser parser, onUpdate func(any)) *fetcher {
|
|
||||||
var ticker *time.Ticker
|
|
||||||
if interval != 0 {
|
|
||||||
ticker = time.NewTicker(interval)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &fetcher{
|
|
||||||
name: name,
|
|
||||||
ticker: ticker,
|
|
||||||
vehicle: vehicle,
|
|
||||||
parser: parser,
|
|
||||||
done: make(chan struct{}, 1),
|
|
||||||
onUpdate: onUpdate,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,16 +2,18 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/metacubex/mihomo/common/atomic"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/singledo"
|
||||||
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"github.com/dlclark/regexp2"
|
||||||
)
|
"golang.org/x/sync/errgroup"
|
||||||
|
|
||||||
const (
|
|
||||||
defaultURLTestTimeout = time.Second * 5
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type HealthCheckOption struct {
|
type HealthCheckOption struct {
|
||||||
@@ -19,76 +21,197 @@ type HealthCheckOption struct {
|
|||||||
Interval uint
|
Interval uint
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type extraOption struct {
|
||||||
|
expectedStatus utils.IntRanges[uint16]
|
||||||
|
filters map[string]struct{}
|
||||||
|
}
|
||||||
|
|
||||||
type HealthCheck struct {
|
type HealthCheck struct {
|
||||||
url string
|
ctx context.Context
|
||||||
proxies []C.Proxy
|
ctxCancel context.CancelFunc
|
||||||
interval uint
|
url string
|
||||||
lazy bool
|
extra map[string]*extraOption
|
||||||
lastTouch *atomic.Int64
|
mu sync.Mutex
|
||||||
done chan struct{}
|
proxies []C.Proxy
|
||||||
|
interval time.Duration
|
||||||
|
lazy bool
|
||||||
|
expectedStatus utils.IntRanges[uint16]
|
||||||
|
lastTouch atomic.TypedValue[time.Time]
|
||||||
|
singleDo *singledo.Single[struct{}]
|
||||||
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(hc.interval)
|
||||||
|
go hc.check()
|
||||||
go func() {
|
|
||||||
t := time.NewTicker(30 * time.Second)
|
|
||||||
<-t.C
|
|
||||||
t.Stop()
|
|
||||||
hc.check()
|
|
||||||
}()
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
now := time.Now().Unix()
|
lastTouch := hc.lastTouch.Load()
|
||||||
if !hc.lazy || now-hc.lastTouch.Load() < int64(hc.interval) {
|
since := time.Since(lastTouch)
|
||||||
|
if !hc.lazy || since < hc.interval {
|
||||||
hc.check()
|
hc.check()
|
||||||
|
} else {
|
||||||
|
log.Debugln("Skip once health check because we are lazy")
|
||||||
}
|
}
|
||||||
case <-hc.done:
|
case <-hc.ctx.Done():
|
||||||
ticker.Stop()
|
ticker.Stop()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
func (hc *HealthCheck) setProxies(proxies []C.Proxy) {
|
||||||
hc.proxies = proxies
|
hc.proxies = proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) registerHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
|
url = strings.TrimSpace(url)
|
||||||
|
if len(url) == 0 || url == hc.url {
|
||||||
|
log.Debugln("ignore invalid health check url: %s", url)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hc.mu.Lock()
|
||||||
|
defer hc.mu.Unlock()
|
||||||
|
|
||||||
|
// if the provider has not set up health checks, then modify it to be the same as the group's interval
|
||||||
|
if hc.interval == 0 {
|
||||||
|
hc.interval = time.Duration(interval) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
if hc.extra == nil {
|
||||||
|
hc.extra = make(map[string]*extraOption)
|
||||||
|
}
|
||||||
|
|
||||||
|
// prioritize the use of previously registered configurations, especially those from provider
|
||||||
|
if _, ok := hc.extra[url]; ok {
|
||||||
|
// provider default health check does not set filter
|
||||||
|
if url != hc.url && len(filter) != 0 {
|
||||||
|
splitAndAddFiltersToExtra(filter, hc.extra[url])
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugln("health check url: %s exists", url)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
option := &extraOption{filters: map[string]struct{}{}, expectedStatus: expectedStatus}
|
||||||
|
splitAndAddFiltersToExtra(filter, option)
|
||||||
|
hc.extra[url] = option
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitAndAddFiltersToExtra(filter string, option *extraOption) {
|
||||||
|
filter = strings.TrimSpace(filter)
|
||||||
|
if len(filter) != 0 {
|
||||||
|
for _, regex := range strings.Split(filter, "`") {
|
||||||
|
regex = strings.TrimSpace(regex)
|
||||||
|
if len(regex) != 0 {
|
||||||
|
option.filters[regex] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) auto() bool {
|
func (hc *HealthCheck) auto() bool {
|
||||||
return hc.interval != 0
|
return hc.interval != 0
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) touch() {
|
func (hc *HealthCheck) touch() {
|
||||||
hc.lastTouch.Store(time.Now().Unix())
|
hc.lastTouch.Store(time.Now())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
if len(hc.proxies) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
|
id := utils.NewUUIDV4().String()
|
||||||
|
log.Debugln("Start New Health Checking {%s}", id)
|
||||||
|
b := new(errgroup.Group)
|
||||||
|
b.SetLimit(10)
|
||||||
|
|
||||||
|
// execute default health check
|
||||||
|
option := &extraOption{filters: nil, expectedStatus: hc.expectedStatus}
|
||||||
|
hc.execute(b, hc.url, id, option)
|
||||||
|
|
||||||
|
// execute extra health check
|
||||||
|
if len(hc.extra) != 0 {
|
||||||
|
for url, option := range hc.extra {
|
||||||
|
hc.execute(b, url, id, option)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ = b.Wait()
|
||||||
|
log.Debugln("Finish A Health Checking {%s}", id)
|
||||||
|
return struct{}{}, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (hc *HealthCheck) execute(b *errgroup.Group, url, uid string, option *extraOption) {
|
||||||
|
url = strings.TrimSpace(url)
|
||||||
|
if len(url) == 0 {
|
||||||
|
log.Debugln("Health Check has been skipped due to testUrl is empty, {%s}", uid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var filterReg *regexp2.Regexp
|
||||||
|
var expectedStatus utils.IntRanges[uint16]
|
||||||
|
if option != nil {
|
||||||
|
expectedStatus = option.expectedStatus
|
||||||
|
if len(option.filters) != 0 {
|
||||||
|
filters := make([]string, 0, len(option.filters))
|
||||||
|
for filter := range option.filters {
|
||||||
|
filters = append(filters, filter)
|
||||||
|
}
|
||||||
|
|
||||||
|
filterReg = regexp2.MustCompile(strings.Join(filters, "|"), regexp2.None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for _, proxy := range hc.proxies {
|
for _, proxy := range hc.proxies {
|
||||||
|
// skip proxies that do not require health check
|
||||||
|
if filterReg != nil {
|
||||||
|
if match, _ := filterReg.MatchString(proxy.Name()); !match {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
p := proxy
|
p := proxy
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
b.Go(func() error {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
ctx, cancel := context.WithTimeout(hc.ctx, hc.timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
log.Debugln("Health Checking, proxy: %s, url: %s, id: {%s}", p.Name(), url, uid)
|
||||||
return false, nil
|
_, _ = p.URLTest(ctx, url, expectedStatus)
|
||||||
|
log.Debugln("Health Checked, proxy: %s, url: %s, alive: %t, delay: %d ms uid: {%s}", p.Name(), url, p.AliveForTestUrl(url), p.LastDelayForTestUrl(url), uid)
|
||||||
|
return nil
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
b.Wait()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
hc.done <- struct{}{}
|
hc.ctxCancel()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *HealthCheck {
|
func NewHealthCheck(proxies []C.Proxy, url string, timeout uint, interval uint, lazy bool, expectedStatus utils.IntRanges[uint16]) *HealthCheck {
|
||||||
|
if url == "" {
|
||||||
|
expectedStatus = nil
|
||||||
|
interval = 0
|
||||||
|
}
|
||||||
|
if timeout == 0 {
|
||||||
|
timeout = 5000
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
|
||||||
return &HealthCheck{
|
return &HealthCheck{
|
||||||
proxies: proxies,
|
ctx: ctx,
|
||||||
url: url,
|
ctxCancel: cancel,
|
||||||
interval: interval,
|
proxies: proxies,
|
||||||
lazy: lazy,
|
url: url,
|
||||||
lastTouch: atomic.NewInt64(0),
|
timeout: time.Duration(timeout) * time.Millisecond,
|
||||||
done: make(chan struct{}, 1),
|
extra: map[string]*extraOption{},
|
||||||
|
interval: time.Duration(interval) * time.Second,
|
||||||
|
lazy: lazy,
|
||||||
|
expectedStatus: expectedStatus,
|
||||||
|
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
88
adapter/provider/override.go
Normal file
88
adapter/provider/override.go
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type overrideSchema struct {
|
||||||
|
TFO *bool `provider:"tfo,omitempty"`
|
||||||
|
MPTcp *bool `provider:"mptcp,omitempty"`
|
||||||
|
UDP *bool `provider:"udp,omitempty"`
|
||||||
|
UDPOverTCP *bool `provider:"udp-over-tcp,omitempty"`
|
||||||
|
Up *string `provider:"up,omitempty"`
|
||||||
|
Down *string `provider:"down,omitempty"`
|
||||||
|
DialerProxy *string `provider:"dialer-proxy,omitempty"`
|
||||||
|
SkipCertVerify *bool `provider:"skip-cert-verify,omitempty"`
|
||||||
|
Interface *string `provider:"interface-name,omitempty"`
|
||||||
|
RoutingMark *int `provider:"routing-mark,omitempty"`
|
||||||
|
IPVersion *string `provider:"ip-version,omitempty"`
|
||||||
|
|
||||||
|
AdditionalPrefix *string `provider:"additional-prefix,omitempty"`
|
||||||
|
AdditionalSuffix *string `provider:"additional-suffix,omitempty"`
|
||||||
|
ProxyName []overrideProxyNameSchema `provider:"proxy-name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type overrideProxyNameSchema struct {
|
||||||
|
// matching expression for regex replacement
|
||||||
|
Pattern *regexp2.Regexp `provider:"pattern"`
|
||||||
|
// the new content after regex matching
|
||||||
|
Target string `provider:"target"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ encoding.TextUnmarshaler = (*regexp2.Regexp)(nil) // ensure *regexp2.Regexp can decode direct by structure package
|
||||||
|
|
||||||
|
func (o *overrideSchema) Apply(mapping map[string]any) error {
|
||||||
|
if o.TFO != nil {
|
||||||
|
mapping["tfo"] = *o.TFO
|
||||||
|
}
|
||||||
|
if o.MPTcp != nil {
|
||||||
|
mapping["mptcp"] = *o.MPTcp
|
||||||
|
}
|
||||||
|
if o.UDP != nil {
|
||||||
|
mapping["udp"] = *o.UDP
|
||||||
|
}
|
||||||
|
if o.UDPOverTCP != nil {
|
||||||
|
mapping["udp-over-tcp"] = *o.UDPOverTCP
|
||||||
|
}
|
||||||
|
if o.Up != nil {
|
||||||
|
mapping["up"] = *o.Up
|
||||||
|
}
|
||||||
|
if o.Down != nil {
|
||||||
|
mapping["down"] = *o.Down
|
||||||
|
}
|
||||||
|
if o.DialerProxy != nil {
|
||||||
|
mapping["dialer-proxy"] = *o.DialerProxy
|
||||||
|
}
|
||||||
|
if o.SkipCertVerify != nil {
|
||||||
|
mapping["skip-cert-verify"] = *o.SkipCertVerify
|
||||||
|
}
|
||||||
|
if o.Interface != nil {
|
||||||
|
mapping["interface-name"] = *o.Interface
|
||||||
|
}
|
||||||
|
if o.RoutingMark != nil {
|
||||||
|
mapping["routing-mark"] = *o.RoutingMark
|
||||||
|
}
|
||||||
|
if o.IPVersion != nil {
|
||||||
|
mapping["ip-version"] = *o.IPVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, expr := range o.ProxyName {
|
||||||
|
name := mapping["name"].(string)
|
||||||
|
newName, err := expr.Pattern.Replace(name, expr.Target, 0, -1)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("proxy name replace error: %w", err)
|
||||||
|
}
|
||||||
|
mapping["name"] = newName
|
||||||
|
}
|
||||||
|
if o.AdditionalPrefix != nil {
|
||||||
|
mapping["name"] = fmt.Sprintf("%s%s", *o.AdditionalPrefix, mapping["name"])
|
||||||
|
}
|
||||||
|
if o.AdditionalSuffix != nil {
|
||||||
|
mapping["name"] = fmt.Sprintf("%s%s", mapping["name"], *o.AdditionalSuffix)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -5,30 +5,45 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/metacubex/mihomo/common/structure"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errVehicleType = errors.New("unsupport vehicle type")
|
var (
|
||||||
|
errVehicleType = errors.New("unsupport vehicle type")
|
||||||
|
)
|
||||||
|
|
||||||
type healthCheckSchema struct {
|
type healthCheckSchema struct {
|
||||||
Enable bool `provider:"enable"`
|
Enable bool `provider:"enable"`
|
||||||
URL string `provider:"url"`
|
URL string `provider:"url"`
|
||||||
Interval int `provider:"interval"`
|
Interval int `provider:"interval"`
|
||||||
Lazy bool `provider:"lazy,omitempty"`
|
TestTimeout int `provider:"timeout,omitempty"`
|
||||||
|
Lazy bool `provider:"lazy,omitempty"`
|
||||||
|
ExpectedStatus string `provider:"expected-status,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path"`
|
Path string `provider:"path,omitempty"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Proxy string `provider:"proxy,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
|
ExcludeFilter string `provider:"exclude-filter,omitempty"`
|
||||||
|
ExcludeType string `provider:"exclude-type,omitempty"`
|
||||||
|
DialerProxy string `provider:"dialer-proxy,omitempty"`
|
||||||
|
SizeLimit int64 `provider:"size-limit,omitempty"`
|
||||||
|
Payload []map[string]any `provider:"payload,omitempty"`
|
||||||
|
|
||||||
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
|
Override overrideSchema `provider:"override,omitempty"`
|
||||||
|
Header map[string][]string `provider:"header,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (P.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{
|
schema := &proxyProviderSchema{
|
||||||
@@ -40,25 +55,49 @@ func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvide
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
expectedStatus, err := utils.NewUnsignedRanges[uint16](schema.HealthCheck.ExpectedStatus)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
var hcInterval uint
|
var hcInterval uint
|
||||||
if schema.HealthCheck.Enable {
|
if schema.HealthCheck.Enable {
|
||||||
|
if schema.HealthCheck.Interval == 0 {
|
||||||
|
schema.HealthCheck.Interval = 300
|
||||||
|
}
|
||||||
hcInterval = uint(schema.HealthCheck.Interval)
|
hcInterval = uint(schema.HealthCheck.Interval)
|
||||||
}
|
}
|
||||||
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, hcInterval, schema.HealthCheck.Lazy)
|
hc := NewHealthCheck([]C.Proxy{}, schema.HealthCheck.URL, uint(schema.HealthCheck.TestTimeout), hcInterval, schema.HealthCheck.Lazy, expectedStatus)
|
||||||
|
|
||||||
path := C.Path.Resolve(schema.Path)
|
parser, err := NewProxiesParser(name, schema.Filter, schema.ExcludeFilter, schema.ExcludeType, schema.DialerProxy, schema.Override)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
var vehicle types.Vehicle
|
var vehicle P.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
case "file":
|
case "file":
|
||||||
vehicle = NewFileVehicle(path)
|
path := C.Path.Resolve(schema.Path)
|
||||||
|
if !C.Path.IsSafePath(path) {
|
||||||
|
return nil, C.Path.ErrNotSafePath(path)
|
||||||
|
}
|
||||||
|
vehicle = resource.NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
vehicle = NewHTTPVehicle(schema.URL, path)
|
path := C.Path.GetPathByHash("proxies", schema.URL)
|
||||||
|
if schema.Path != "" {
|
||||||
|
path = C.Path.Resolve(schema.Path)
|
||||||
|
if !C.Path.IsSafePath(path) {
|
||||||
|
return nil, C.Path.ErrNotSafePath(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vehicle = resource.NewHTTPVehicle(schema.URL, path, schema.Proxy, schema.Header, resource.DefaultHttpTimeout, schema.SizeLimit)
|
||||||
|
case "inline":
|
||||||
|
return NewInlineProvider(name, schema.Payload, parser, hc)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
|
||||||
}
|
}
|
||||||
|
|
||||||
interval := time.Duration(uint(schema.Interval)) * time.Second
|
interval := time.Duration(uint(schema.Interval)) * time.Second
|
||||||
filter := schema.Filter
|
|
||||||
return NewProxySetProvider(name, interval, filter, vehicle, hc)
|
return NewProxySetProvider(name, interval, schema.Payload, parser, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,23 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/dlclark/regexp2"
|
|
||||||
"math"
|
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/metacubex/mihomo/adapter"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
"github.com/metacubex/mihomo/common/convert"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
"github.com/metacubex/mihomo/common/utils"
|
||||||
|
"github.com/metacubex/mihomo/common/yaml"
|
||||||
|
"github.com/metacubex/mihomo/component/profile/cachefile"
|
||||||
|
"github.com/metacubex/mihomo/component/resource"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
P "github.com/metacubex/mihomo/constant/provider"
|
||||||
|
"github.com/metacubex/mihomo/tunnel/statistic"
|
||||||
|
|
||||||
"gopkg.in/yaml.v2"
|
"github.com/dlclark/regexp2"
|
||||||
|
"github.com/metacubex/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -24,117 +31,349 @@ type ProxySchema struct {
|
|||||||
Proxies []map[string]any `yaml:"proxies"`
|
Proxies []map[string]any `yaml:"proxies"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// for auto gc
|
type providerForApi struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
VehicleType string `json:"vehicleType"`
|
||||||
|
Proxies []C.Proxy `json:"proxies"`
|
||||||
|
TestUrl string `json:"testUrl"`
|
||||||
|
ExpectedStatus string `json:"expectedStatus"`
|
||||||
|
UpdatedAt time.Time `json:"updatedAt,omitempty"`
|
||||||
|
SubscriptionInfo *SubscriptionInfo `json:"subscriptionInfo,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type baseProvider struct {
|
||||||
|
mutex sync.RWMutex
|
||||||
|
name string
|
||||||
|
proxies []C.Proxy
|
||||||
|
healthCheck *HealthCheck
|
||||||
|
version uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Name() string {
|
||||||
|
return bp.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Version() uint32 {
|
||||||
|
bp.mutex.RLock()
|
||||||
|
defer bp.mutex.RUnlock()
|
||||||
|
return bp.version
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Initial() error {
|
||||||
|
if bp.healthCheck.auto() {
|
||||||
|
go bp.healthCheck.process()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) HealthCheck() {
|
||||||
|
bp.healthCheck.check()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Type() P.ProviderType {
|
||||||
|
return P.Proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Proxies() []C.Proxy {
|
||||||
|
bp.mutex.RLock()
|
||||||
|
defer bp.mutex.RUnlock()
|
||||||
|
return bp.proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Count() int {
|
||||||
|
bp.mutex.RLock()
|
||||||
|
defer bp.mutex.RUnlock()
|
||||||
|
return len(bp.proxies)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Touch() {
|
||||||
|
bp.healthCheck.touch()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) HealthCheckURL() string {
|
||||||
|
return bp.healthCheck.url
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) RegisterHealthCheckTask(url string, expectedStatus utils.IntRanges[uint16], filter string, interval uint) {
|
||||||
|
bp.healthCheck.registerHealthCheckTask(url, expectedStatus, filter, interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) setProxies(proxies []C.Proxy) {
|
||||||
|
bp.mutex.Lock()
|
||||||
|
defer bp.mutex.Unlock()
|
||||||
|
bp.proxies = proxies
|
||||||
|
bp.version += 1
|
||||||
|
bp.healthCheck.setProxies(proxies)
|
||||||
|
if bp.healthCheck.auto() {
|
||||||
|
go bp.healthCheck.check()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *baseProvider) Close() error {
|
||||||
|
bp.healthCheck.close()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProxySetProvider for auto gc
|
||||||
type ProxySetProvider struct {
|
type ProxySetProvider struct {
|
||||||
*proxySetProvider
|
*proxySetProvider
|
||||||
}
|
}
|
||||||
|
|
||||||
type proxySetProvider struct {
|
type proxySetProvider struct {
|
||||||
*fetcher
|
baseProvider
|
||||||
proxies []C.Proxy
|
*resource.Fetcher[[]C.Proxy]
|
||||||
healthCheck *HealthCheck
|
subscriptionInfo *SubscriptionInfo
|
||||||
version uint
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) Version() uint {
|
|
||||||
return pp.version
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(providerForApi{
|
||||||
"name": pp.Name(),
|
Name: pp.Name(),
|
||||||
"type": pp.Type().String(),
|
Type: pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
VehicleType: pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
Proxies: pp.Proxies(),
|
||||||
//TODO maybe error because year value overflow
|
TestUrl: pp.healthCheck.url,
|
||||||
"updatedAt": pp.updatedAt,
|
ExpectedStatus: pp.healthCheck.expectedStatus.String(),
|
||||||
|
UpdatedAt: pp.UpdatedAt(),
|
||||||
|
SubscriptionInfo: pp.subscriptionInfo,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Name() string {
|
func (pp *proxySetProvider) Name() string {
|
||||||
return pp.name
|
return pp.Fetcher.Name()
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) HealthCheck() {
|
|
||||||
pp.healthCheck.check()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Update() error {
|
func (pp *proxySetProvider) Update() error {
|
||||||
elm, same, err := pp.fetcher.Update()
|
_, _, err := pp.Fetcher.Update()
|
||||||
if err == nil && !same {
|
|
||||||
pp.onUpdate(elm)
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Initial() error {
|
func (pp *proxySetProvider) Initial() error {
|
||||||
elm, err := pp.fetcher.Initial()
|
if err := pp.baseProvider.Initial(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err := pp.Fetcher.Initial()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if subscriptionInfo := cachefile.Cache().GetSubscriptionInfo(pp.Name()); subscriptionInfo != "" {
|
||||||
pp.onUpdate(elm)
|
pp.subscriptionInfo = NewSubscriptionInfo(subscriptionInfo)
|
||||||
if pp.healthCheck.auto() {
|
|
||||||
go pp.healthCheck.process()
|
|
||||||
}
|
}
|
||||||
|
pp.closeAllConnections()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Type() types.ProviderType {
|
func (pp *proxySetProvider) closeAllConnections() {
|
||||||
return types.Proxy
|
statistic.DefaultManager.Range(func(c statistic.Tracker) bool {
|
||||||
|
for _, chain := range c.ProviderChains() {
|
||||||
|
if chain == pp.Name() {
|
||||||
|
_ = c.Close()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Proxies() []C.Proxy {
|
func (pp *proxySetProvider) Close() error {
|
||||||
return pp.proxies
|
_ = pp.baseProvider.Close()
|
||||||
|
return pp.Fetcher.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
func NewProxySetProvider(name string, interval time.Duration, payload []map[string]any, parser resource.Parser[[]C.Proxy], vehicle P.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
||||||
pp.healthCheck.touch()
|
|
||||||
return pp.Proxies()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
|
||||||
pp.proxies = proxies
|
|
||||||
pp.healthCheck.setProxy(proxies)
|
|
||||||
if pp.healthCheck.auto() {
|
|
||||||
go pp.healthCheck.check()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
|
||||||
pd.healthCheck.close()
|
|
||||||
pd.fetcher.Destroy()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck) (*ProxySetProvider, error) {
|
|
||||||
//filterReg, err := regexp.Compile(filter)
|
|
||||||
filterReg, err := regexp2.Compile(filter, 0)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
pd := &proxySetProvider{
|
pd := &proxySetProvider{
|
||||||
proxies: []C.Proxy{},
|
baseProvider: baseProvider{
|
||||||
healthCheck: hc,
|
name: name,
|
||||||
|
proxies: []C.Proxy{},
|
||||||
|
healthCheck: hc,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
onUpdate := func(elm any) {
|
if len(payload) > 0 { // using as fallback proxies
|
||||||
ret := elm.([]C.Proxy)
|
ps := ProxySchema{Proxies: payload}
|
||||||
pd.setProxies(ret)
|
buf, err := yaml.Marshal(ps)
|
||||||
if pd.version == math.MaxUint {
|
if err != nil {
|
||||||
pd.version = 0
|
return nil, err
|
||||||
} else {
|
}
|
||||||
pd.version++
|
proxies, err := parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
pd.proxies = proxies
|
||||||
|
// direct call setProxies on hc to avoid starting a health check process immediately, it should be done by Initial()
|
||||||
|
hc.setProxies(proxies)
|
||||||
|
}
|
||||||
|
|
||||||
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, parser, pd.setProxies)
|
||||||
|
pd.Fetcher = fetcher
|
||||||
|
if httpVehicle, ok := vehicle.(*resource.HTTPVehicle); ok {
|
||||||
|
httpVehicle.SetInRead(func(resp *http.Response) {
|
||||||
|
if subscriptionInfo := resp.Header.Get("subscription-userinfo"); subscriptionInfo != "" {
|
||||||
|
cachefile.Cache().SetSubscriptionInfo(name, subscriptionInfo)
|
||||||
|
pd.subscriptionInfo = NewSubscriptionInfo(subscriptionInfo)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper := &ProxySetProvider{pd}
|
||||||
|
runtime.SetFinalizer(wrapper, (*ProxySetProvider).Close)
|
||||||
|
return wrapper, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pp *ProxySetProvider) Close() error {
|
||||||
|
runtime.SetFinalizer(pp, nil)
|
||||||
|
return pp.proxySetProvider.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// InlineProvider for auto gc
|
||||||
|
type InlineProvider struct {
|
||||||
|
*inlineProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
type inlineProvider struct {
|
||||||
|
baseProvider
|
||||||
|
updateAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ip *inlineProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(providerForApi{
|
||||||
|
Name: ip.Name(),
|
||||||
|
Type: ip.Type().String(),
|
||||||
|
VehicleType: ip.VehicleType().String(),
|
||||||
|
Proxies: ip.Proxies(),
|
||||||
|
TestUrl: ip.healthCheck.url,
|
||||||
|
ExpectedStatus: ip.healthCheck.expectedStatus.String(),
|
||||||
|
UpdatedAt: ip.updateAt,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ip *inlineProvider) VehicleType() P.VehicleType {
|
||||||
|
return P.Inline
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ip *inlineProvider) Update() error {
|
||||||
|
// make api update happy
|
||||||
|
ip.updateAt = time.Now()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInlineProvider(name string, payload []map[string]any, parser resource.Parser[[]C.Proxy], hc *HealthCheck) (*InlineProvider, error) {
|
||||||
|
ps := ProxySchema{Proxies: payload}
|
||||||
|
buf, err := yaml.Marshal(ps)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
proxies, err := parser(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// direct call setProxies on hc to avoid starting a health check process immediately, it should be done by Initial()
|
||||||
|
hc.setProxies(proxies)
|
||||||
|
|
||||||
|
ip := &inlineProvider{
|
||||||
|
baseProvider: baseProvider{
|
||||||
|
name: name,
|
||||||
|
proxies: proxies,
|
||||||
|
healthCheck: hc,
|
||||||
|
},
|
||||||
|
updateAt: time.Now(),
|
||||||
|
}
|
||||||
|
wrapper := &InlineProvider{ip}
|
||||||
|
runtime.SetFinalizer(wrapper, (*InlineProvider).Close)
|
||||||
|
return wrapper, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ip *InlineProvider) Close() error {
|
||||||
|
runtime.SetFinalizer(ip, nil)
|
||||||
|
return ip.baseProvider.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CompatibleProvider for auto gc
|
||||||
|
type CompatibleProvider struct {
|
||||||
|
*compatibleProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
type compatibleProvider struct {
|
||||||
|
baseProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(providerForApi{
|
||||||
|
Name: cp.Name(),
|
||||||
|
Type: cp.Type().String(),
|
||||||
|
VehicleType: cp.VehicleType().String(),
|
||||||
|
Proxies: cp.Proxies(),
|
||||||
|
TestUrl: cp.healthCheck.url,
|
||||||
|
ExpectedStatus: cp.healthCheck.expectedStatus.String(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Update() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) VehicleType() P.VehicleType {
|
||||||
|
return P.Compatible
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return nil, errors.New("provider need one proxy at least")
|
||||||
|
}
|
||||||
|
|
||||||
|
pd := &compatibleProvider{
|
||||||
|
baseProvider: baseProvider{
|
||||||
|
name: name,
|
||||||
|
proxies: proxies,
|
||||||
|
healthCheck: hc,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapper := &CompatibleProvider{pd}
|
||||||
|
runtime.SetFinalizer(wrapper, (*CompatibleProvider).Close)
|
||||||
|
return wrapper, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cp *CompatibleProvider) Close() error {
|
||||||
|
runtime.SetFinalizer(cp, nil)
|
||||||
|
return cp.compatibleProvider.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProxiesParser(pdName string, filter string, excludeFilter string, excludeType string, dialerProxy string, override overrideSchema) (resource.Parser[[]C.Proxy], error) {
|
||||||
|
var excludeTypeArray []string
|
||||||
|
if excludeType != "" {
|
||||||
|
excludeTypeArray = strings.Split(excludeType, "|")
|
||||||
|
}
|
||||||
|
|
||||||
|
var excludeFilterRegs []*regexp2.Regexp
|
||||||
|
if excludeFilter != "" {
|
||||||
|
for _, excludeFilter := range strings.Split(excludeFilter, "`") {
|
||||||
|
excludeFilterReg, err := regexp2.Compile(excludeFilter, regexp2.None)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid excludeFilter regex: %w", err)
|
||||||
|
}
|
||||||
|
excludeFilterRegs = append(excludeFilterRegs, excludeFilterReg)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
proxiesParseAndFilter := func(buf []byte) (any, error) {
|
var filterRegs []*regexp2.Regexp
|
||||||
|
for _, filter := range strings.Split(filter, "`") {
|
||||||
|
filterReg, err := regexp2.Compile(filter, regexp2.None)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
|
}
|
||||||
|
filterRegs = append(filterRegs, filterReg)
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(buf []byte) ([]C.Proxy, error) {
|
||||||
schema := &ProxySchema{}
|
schema := &ProxySchema{}
|
||||||
|
|
||||||
if err := yaml.Unmarshal(buf, schema); err != nil {
|
if err := yaml.Unmarshal(buf, schema); err != nil {
|
||||||
return nil, err
|
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||||
|
if err1 != nil {
|
||||||
|
return nil, fmt.Errorf("%w, %w", err, err1)
|
||||||
|
}
|
||||||
|
schema.Proxies = proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
if schema.Proxies == nil {
|
if schema.Proxies == nil {
|
||||||
@@ -142,17 +381,66 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
for idx, mapping := range schema.Proxies {
|
proxiesSet := map[string]struct{}{}
|
||||||
name, ok := mapping["name"]
|
for _, filterReg := range filterRegs {
|
||||||
mat, _ := filterReg.FindStringMatch(name.(string))
|
LOOP1:
|
||||||
if ok && len(filter) > 0 && mat == nil {
|
for idx, mapping := range schema.Proxies {
|
||||||
continue
|
if len(excludeTypeArray) > 0 {
|
||||||
|
mType, ok := mapping["type"]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pType, ok := mType.(string)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, excludeType := range excludeTypeArray {
|
||||||
|
if strings.EqualFold(pType, excludeType) {
|
||||||
|
continue LOOP1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mName, ok := mapping["name"]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name, ok := mName.(string)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(excludeFilterRegs) > 0 {
|
||||||
|
for _, excludeFilterReg := range excludeFilterRegs {
|
||||||
|
if mat, _ := excludeFilterReg.MatchString(name); mat {
|
||||||
|
continue LOOP1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(filter) > 0 {
|
||||||
|
if mat, _ := filterReg.MatchString(name); !mat {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := proxiesSet[name]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(dialerProxy) > 0 {
|
||||||
|
mapping["dialer-proxy"] = dialerProxy
|
||||||
|
}
|
||||||
|
|
||||||
|
err := override.Apply(mapping)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("proxy %d override error: %w", idx, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxy, err := adapter.ParseProxy(mapping, adapter.WithProviderName(pdName))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
proxiesSet[name] = struct{}{}
|
||||||
|
proxies = append(proxies, proxy)
|
||||||
}
|
}
|
||||||
proxy, err := adapter.ParseProxy(mapping)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
|
||||||
}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(proxies) == 0 {
|
if len(proxies) == 0 {
|
||||||
@@ -163,94 +451,5 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
}
|
}
|
||||||
|
|
||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}, nil
|
||||||
|
|
||||||
fetcher := newFetcher(name, interval, vehicle, proxiesParseAndFilter, onUpdate)
|
|
||||||
pd.fetcher = fetcher
|
|
||||||
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
|
||||||
return wrapper, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// for auto gc
|
|
||||||
type CompatibleProvider struct {
|
|
||||||
*compatibleProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
type compatibleProvider struct {
|
|
||||||
name string
|
|
||||||
healthCheck *HealthCheck
|
|
||||||
proxies []C.Proxy
|
|
||||||
version uint
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Version() uint {
|
|
||||||
return cp.version
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]any{
|
|
||||||
"name": cp.Name(),
|
|
||||||
"type": cp.Type().String(),
|
|
||||||
"vehicleType": cp.VehicleType().String(),
|
|
||||||
"proxies": cp.Proxies(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Name() string {
|
|
||||||
return cp.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) HealthCheck() {
|
|
||||||
cp.healthCheck.check()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Update() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Initial() error {
|
|
||||||
if cp.healthCheck.auto() {
|
|
||||||
go cp.healthCheck.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) VehicleType() types.VehicleType {
|
|
||||||
return types.Compatible
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Type() types.ProviderType {
|
|
||||||
return types.Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) Proxies() []C.Proxy {
|
|
||||||
return cp.proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
|
||||||
cp.healthCheck.touch()
|
|
||||||
return cp.Proxies()
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
|
||||||
pd.healthCheck.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*CompatibleProvider, error) {
|
|
||||||
if len(proxies) == 0 {
|
|
||||||
return nil, errors.New("provider need one proxy at least")
|
|
||||||
}
|
|
||||||
|
|
||||||
pd := &compatibleProvider{
|
|
||||||
name: name,
|
|
||||||
proxies: proxies,
|
|
||||||
healthCheck: hc,
|
|
||||||
}
|
|
||||||
|
|
||||||
wrapper := &CompatibleProvider{pd}
|
|
||||||
runtime.SetFinalizer(wrapper, stopCompatibleProvider)
|
|
||||||
return wrapper, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
58
adapter/provider/subscription_info.go
Normal file
58
adapter/provider/subscription_info.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package provider
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/metacubex/mihomo/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SubscriptionInfo struct {
|
||||||
|
Upload int64
|
||||||
|
Download int64
|
||||||
|
Total int64
|
||||||
|
Expire int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSubscriptionInfo(userinfo string) (si *SubscriptionInfo) {
|
||||||
|
userinfo = strings.ReplaceAll(strings.ToLower(userinfo), " ", "")
|
||||||
|
si = new(SubscriptionInfo)
|
||||||
|
|
||||||
|
for _, field := range strings.Split(userinfo, ";") {
|
||||||
|
name, value, ok := strings.Cut(field, "=")
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
intValue, err := parseValue(value)
|
||||||
|
if err != nil {
|
||||||
|
log.Warnln("[Provider] get subscription-userinfo: %e", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
switch name {
|
||||||
|
case "upload":
|
||||||
|
si.Upload = intValue
|
||||||
|
case "download":
|
||||||
|
si.Download = intValue
|
||||||
|
case "total":
|
||||||
|
si.Total = intValue
|
||||||
|
case "expire":
|
||||||
|
si.Expire = intValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return si
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseValue(value string) (int64, error) {
|
||||||
|
if intValue, err := strconv.ParseInt(value, 10, 64); err == nil {
|
||||||
|
return intValue, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if floatValue, err := strconv.ParseFloat(value, 64); err == nil {
|
||||||
|
return int64(floatValue), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, fmt.Errorf("failed to parse value '%s'", value)
|
||||||
|
}
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"github.com/Dreamacro/clash/listener/inner"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
netHttp "github.com/Dreamacro/clash/common/net"
|
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
|
||||||
)
|
|
||||||
|
|
||||||
type FileVehicle struct {
|
|
||||||
path string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *FileVehicle) Type() types.VehicleType {
|
|
||||||
return types.File
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *FileVehicle) Path() string {
|
|
||||||
return f.path
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *FileVehicle) Read() ([]byte, error) {
|
|
||||||
return os.ReadFile(f.path)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewFileVehicle(path string) *FileVehicle {
|
|
||||||
return &FileVehicle{path: path}
|
|
||||||
}
|
|
||||||
|
|
||||||
type HTTPVehicle struct {
|
|
||||||
url string
|
|
||||||
path string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HTTPVehicle) Type() types.VehicleType {
|
|
||||||
return types.HTTP
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HTTPVehicle) Path() string {
|
|
||||||
return h.path
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *HTTPVehicle) Read() ([]byte, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
uri, err := url.Parse(h.url)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, uri.String(), nil)
|
|
||||||
req.Header.Set("User-Agent", netHttp.UA)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if user := uri.User; user != nil {
|
|
||||||
password, _ := user.Password()
|
|
||||||
req.SetBasicAuth(user.Username(), password)
|
|
||||||
}
|
|
||||||
|
|
||||||
req = req.WithContext(ctx)
|
|
||||||
|
|
||||||
transport := &http.Transport{
|
|
||||||
// from http.DefaultTransport
|
|
||||||
MaxIdleConns: 100,
|
|
||||||
IdleConnTimeout: 90 * time.Second,
|
|
||||||
TLSHandshakeTimeout: 10 * time.Second,
|
|
||||||
ExpectContinueTimeout: 1 * time.Second,
|
|
||||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
|
||||||
conn := inner.HandleTcp(address, uri.Hostname())
|
|
||||||
return conn, nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
buf, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return buf, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
|
|
||||||
return &HTTPVehicle{url, path}
|
|
||||||
}
|
|
||||||
23
android_tz.go
Normal file
23
android_tz.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// Copyright 2014 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
//go:build android && cgo
|
||||||
|
// +build android,cgo
|
||||||
|
|
||||||
|
// kanged from https://github.com/golang/mobile/blob/c713f31d574bb632a93f169b2cc99c9e753fef0e/app/android.go#L89
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
// #include <time.h>
|
||||||
|
import "C"
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
var currentT C.time_t
|
||||||
|
var currentTM C.struct_tm
|
||||||
|
C.time(¤tT)
|
||||||
|
C.localtime_r(¤tT, ¤tTM)
|
||||||
|
tzOffset := int(currentTM.tm_gmtoff)
|
||||||
|
tz := C.GoString(currentTM.tm_zone)
|
||||||
|
time.Local = time.FixedZone(tz, tzOffset)
|
||||||
|
}
|
||||||
241
common/arc/arc.go
Normal file
241
common/arc/arc.go
Normal file
@@ -0,0 +1,241 @@
|
|||||||
|
package arc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
list "github.com/bahlo/generic-list-go"
|
||||||
|
"github.com/samber/lo"
|
||||||
|
)
|
||||||
|
|
||||||
|
//modify from https://github.com/alexanderGugel/arc
|
||||||
|
|
||||||
|
// Option is part of Functional Options Pattern
|
||||||
|
type Option[K comparable, V any] func(*ARC[K, V])
|
||||||
|
|
||||||
|
func WithSize[K comparable, V any](maxSize int) Option[K, V] {
|
||||||
|
return func(a *ARC[K, V]) {
|
||||||
|
a.c = maxSize
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ARC[K comparable, V any] struct {
|
||||||
|
p int
|
||||||
|
c int
|
||||||
|
t1 *list.List[*entry[K, V]]
|
||||||
|
b1 *list.List[*entry[K, V]]
|
||||||
|
t2 *list.List[*entry[K, V]]
|
||||||
|
b2 *list.List[*entry[K, V]]
|
||||||
|
mutex sync.Mutex
|
||||||
|
len int
|
||||||
|
cache map[K]*entry[K, V]
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a new Adaptive Replacement Cache (ARC).
|
||||||
|
func New[K comparable, V any](options ...Option[K, V]) *ARC[K, V] {
|
||||||
|
arc := &ARC[K, V]{}
|
||||||
|
arc.Clear()
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(arc)
|
||||||
|
}
|
||||||
|
return arc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) Clear() {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
a.p = 0
|
||||||
|
a.t1 = list.New[*entry[K, V]]()
|
||||||
|
a.b1 = list.New[*entry[K, V]]()
|
||||||
|
a.t2 = list.New[*entry[K, V]]()
|
||||||
|
a.b2 = list.New[*entry[K, V]]()
|
||||||
|
a.len = 0
|
||||||
|
a.cache = make(map[K]*entry[K, V])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set inserts a new key-value pair into the cache.
|
||||||
|
// This optimizes future access to this entry (side effect).
|
||||||
|
func (a *ARC[K, V]) Set(key K, value V) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
a.set(key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) set(key K, value V) {
|
||||||
|
a.setWithExpire(key, value, time.Unix(0, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetWithExpire stores any representation of a response for a given key and given expires.
|
||||||
|
// The expires time will round to second.
|
||||||
|
func (a *ARC[K, V]) SetWithExpire(key K, value V, expires time.Time) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
a.setWithExpire(key, value, expires)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) setWithExpire(key K, value V, expires time.Time) {
|
||||||
|
ent, ok := a.cache[key]
|
||||||
|
if !ok {
|
||||||
|
a.len++
|
||||||
|
ent := &entry[K, V]{key: key, value: value, ghost: false, expires: expires.Unix()}
|
||||||
|
a.req(ent)
|
||||||
|
a.cache[key] = ent
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ent.ghost {
|
||||||
|
a.len++
|
||||||
|
}
|
||||||
|
|
||||||
|
ent.value = value
|
||||||
|
ent.ghost = false
|
||||||
|
ent.expires = expires.Unix()
|
||||||
|
a.req(ent)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a previously via Set inserted entry.
|
||||||
|
// This optimizes future access to this entry (side effect).
|
||||||
|
func (a *ARC[K, V]) Get(key K) (value V, ok bool) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
ent, ok := a.get(key)
|
||||||
|
if !ok {
|
||||||
|
return lo.Empty[V](), false
|
||||||
|
}
|
||||||
|
return ent.value, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) get(key K) (e *entry[K, V], ok bool) {
|
||||||
|
ent, ok := a.cache[key]
|
||||||
|
if !ok {
|
||||||
|
return ent, false
|
||||||
|
}
|
||||||
|
a.req(ent)
|
||||||
|
return ent, !ent.ghost
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetWithExpire returns any representation of a cached response,
|
||||||
|
// a time.Time Give expected expires,
|
||||||
|
// and a bool set to true if the key was found.
|
||||||
|
// This method will NOT update the expires.
|
||||||
|
func (a *ARC[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
ent, ok := a.get(key)
|
||||||
|
if !ok {
|
||||||
|
return lo.Empty[V](), time.Time{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return ent.value, time.Unix(ent.expires, 0), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Len determines the number of currently cached entries.
|
||||||
|
// This method is side-effect free in the sense that it does not attempt to optimize random cache access.
|
||||||
|
func (a *ARC[K, V]) Len() int {
|
||||||
|
a.mutex.Lock()
|
||||||
|
defer a.mutex.Unlock()
|
||||||
|
|
||||||
|
return a.len
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) req(ent *entry[K, V]) {
|
||||||
|
switch {
|
||||||
|
case ent.ll == a.t1 || ent.ll == a.t2:
|
||||||
|
// Case I
|
||||||
|
ent.setMRU(a.t2)
|
||||||
|
case ent.ll == a.b1:
|
||||||
|
// Case II
|
||||||
|
// Cache Miss in t1 and t2
|
||||||
|
|
||||||
|
// Adaptation
|
||||||
|
var d int
|
||||||
|
if a.b1.Len() >= a.b2.Len() {
|
||||||
|
d = 1
|
||||||
|
} else {
|
||||||
|
d = a.b2.Len() / a.b1.Len()
|
||||||
|
}
|
||||||
|
a.p = min(a.p+d, a.c)
|
||||||
|
|
||||||
|
a.replace(ent)
|
||||||
|
ent.setMRU(a.t2)
|
||||||
|
case ent.ll == a.b2:
|
||||||
|
// Case III
|
||||||
|
// Cache Miss in t1 and t2
|
||||||
|
|
||||||
|
// Adaptation
|
||||||
|
var d int
|
||||||
|
if a.b2.Len() >= a.b1.Len() {
|
||||||
|
d = 1
|
||||||
|
} else {
|
||||||
|
d = a.b1.Len() / a.b2.Len()
|
||||||
|
}
|
||||||
|
a.p = max(a.p-d, 0)
|
||||||
|
|
||||||
|
a.replace(ent)
|
||||||
|
ent.setMRU(a.t2)
|
||||||
|
case ent.ll == nil && a.t1.Len()+a.b1.Len() == a.c:
|
||||||
|
// Case IV A
|
||||||
|
if a.t1.Len() < a.c {
|
||||||
|
a.delLRU(a.b1)
|
||||||
|
a.replace(ent)
|
||||||
|
} else {
|
||||||
|
a.delLRU(a.t1)
|
||||||
|
}
|
||||||
|
ent.setMRU(a.t1)
|
||||||
|
case ent.ll == nil && a.t1.Len()+a.b1.Len() < a.c:
|
||||||
|
// Case IV B
|
||||||
|
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() >= a.c {
|
||||||
|
if a.t1.Len()+a.t2.Len()+a.b1.Len()+a.b2.Len() == 2*a.c {
|
||||||
|
a.delLRU(a.b2)
|
||||||
|
}
|
||||||
|
a.replace(ent)
|
||||||
|
}
|
||||||
|
ent.setMRU(a.t1)
|
||||||
|
case ent.ll == nil:
|
||||||
|
// Case IV, not A nor B
|
||||||
|
ent.setMRU(a.t1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) delLRU(list *list.List[*entry[K, V]]) {
|
||||||
|
lru := list.Back()
|
||||||
|
list.Remove(lru)
|
||||||
|
a.len--
|
||||||
|
delete(a.cache, lru.Value.key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *ARC[K, V]) replace(ent *entry[K, V]) {
|
||||||
|
if a.t1.Len() > 0 && ((a.t1.Len() > a.p) || (ent.ll == a.b2 && a.t1.Len() == a.p)) {
|
||||||
|
lru := a.t1.Back().Value
|
||||||
|
lru.value = lo.Empty[V]()
|
||||||
|
lru.ghost = true
|
||||||
|
a.len--
|
||||||
|
lru.setMRU(a.b1)
|
||||||
|
} else {
|
||||||
|
lru := a.t2.Back().Value
|
||||||
|
lru.value = lo.Empty[V]()
|
||||||
|
lru.ghost = true
|
||||||
|
a.len--
|
||||||
|
lru.setMRU(a.b2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func min(a, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func max(a int, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
return a
|
||||||
|
}
|
||||||
105
common/arc/arc_test.go
Normal file
105
common/arc/arc_test.go
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
package arc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInsertion(t *testing.T) {
|
||||||
|
cache := New[string, string](WithSize[string, string](3))
|
||||||
|
if got, want := cache.Len(), 0; got != want {
|
||||||
|
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
k1 = "Hello"
|
||||||
|
k2 = "Hallo"
|
||||||
|
k3 = "Ciao"
|
||||||
|
k4 = "Salut"
|
||||||
|
|
||||||
|
v1 = "World"
|
||||||
|
v2 = "Worlds"
|
||||||
|
v3 = "Welt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Insert the first value
|
||||||
|
cache.Set(k1, v1)
|
||||||
|
if got, want := cache.Len(), 1; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k1); !ok || got != v1 {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace existing value for a given key
|
||||||
|
cache.Set(k1, v2)
|
||||||
|
if got, want := cache.Len(), 1; got != want {
|
||||||
|
t.Errorf("re-insertion: cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k1); !ok || got != v2 {
|
||||||
|
t.Errorf("re-insertion: cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a second different key
|
||||||
|
cache.Set(k2, v3)
|
||||||
|
if got, want := cache.Len(), 2; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k1); !ok || got != v2 {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k1, got, ok, v2)
|
||||||
|
}
|
||||||
|
if got, ok := cache.Get(k2); !ok || got != v3 {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", k2, got, ok, v3)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fill cache
|
||||||
|
cache.Set(k3, v1)
|
||||||
|
if got, want := cache.Len(), 3; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exceed size, this should not exceed size:
|
||||||
|
cache.Set(k4, v1)
|
||||||
|
if got, want := cache.Len(), 3; got != want {
|
||||||
|
t.Errorf("insertion of key out of size: cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEviction(t *testing.T) {
|
||||||
|
size := 3
|
||||||
|
cache := New[string, string](WithSize[string, string](size))
|
||||||
|
if got, want := cache.Len(), 0; got != want {
|
||||||
|
t.Errorf("empty cache.Len(): got %d want %d", cache.Len(), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
k, v string
|
||||||
|
}{
|
||||||
|
{"k1", "v1"},
|
||||||
|
{"k2", "v2"},
|
||||||
|
{"k3", "v3"},
|
||||||
|
{"k4", "v4"},
|
||||||
|
}
|
||||||
|
for i, tt := range tests[:size] {
|
||||||
|
cache.Set(tt.k, tt.v)
|
||||||
|
if got, want := cache.Len(), i+1; got != want {
|
||||||
|
t.Errorf("insertion of key #%d: cache.Len(): got %d want %d", want, cache.Len(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exceed size and check we don't outgrow it:
|
||||||
|
cache.Set(tests[size].k, tests[size].v)
|
||||||
|
if got := cache.Len(); got != size {
|
||||||
|
t.Errorf("insertion of overflow key #%d: cache.Len(): got %d want %d", 4, cache.Len(), size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check that LRU got evicted:
|
||||||
|
if got, ok := cache.Get(tests[0].k); ok || got != "" {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (<nil>,true)", tests[0].k, got, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests[1:] {
|
||||||
|
if got, ok := cache.Get(tt.k); !ok || got != tt.v {
|
||||||
|
t.Errorf("cache.Get(%v): got (%v,%t) want (%v,true)", tt.k, got, ok, tt.v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
32
common/arc/entry.go
Normal file
32
common/arc/entry.go
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
package arc
|
||||||
|
|
||||||
|
import (
|
||||||
|
list "github.com/bahlo/generic-list-go"
|
||||||
|
)
|
||||||
|
|
||||||
|
type entry[K comparable, V any] struct {
|
||||||
|
key K
|
||||||
|
value V
|
||||||
|
ll *list.List[*entry[K, V]]
|
||||||
|
el *list.Element[*entry[K, V]]
|
||||||
|
ghost bool
|
||||||
|
expires int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *entry[K, V]) setLRU(list *list.List[*entry[K, V]]) {
|
||||||
|
e.detach()
|
||||||
|
e.ll = list
|
||||||
|
e.el = e.ll.PushBack(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *entry[K, V]) setMRU(list *list.List[*entry[K, V]]) {
|
||||||
|
e.detach()
|
||||||
|
e.ll = list
|
||||||
|
e.el = e.ll.PushFront(e)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *entry[K, V]) detach() {
|
||||||
|
if e.ll != nil {
|
||||||
|
e.ll.Remove(e.el)
|
||||||
|
}
|
||||||
|
}
|
||||||
63
common/atomic/enum.go
Normal file
63
common/atomic/enum.go
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
package atomic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Int32Enum[T ~int32] struct {
|
||||||
|
value atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) UnmarshalJSON(b []byte) error {
|
||||||
|
var v T
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) MarshalYAML() (any, error) {
|
||||||
|
return i.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v T
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) String() string {
|
||||||
|
return fmt.Sprint(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) Store(v T) {
|
||||||
|
i.value.Store(int32(v))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) Load() T {
|
||||||
|
return T(i.value.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) Swap(new T) T {
|
||||||
|
return T(i.value.Swap(int32(new)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32Enum[T]) CompareAndSwap(old, new T) bool {
|
||||||
|
return i.value.CompareAndSwap(int32(old), int32(new))
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInt32Enum[T ~int32](v T) *Int32Enum[T] {
|
||||||
|
a := &Int32Enum[T]{}
|
||||||
|
a.Store(v)
|
||||||
|
return a
|
||||||
|
}
|
||||||
289
common/atomic/type.go
Normal file
289
common/atomic/type.go
Normal file
@@ -0,0 +1,289 @@
|
|||||||
|
package atomic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Bool struct {
|
||||||
|
atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBool(val bool) (i Bool) {
|
||||||
|
i.Store(val)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) UnmarshalJSON(b []byte) error {
|
||||||
|
var v bool
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) MarshalYAML() (any, error) {
|
||||||
|
return i.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v bool
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Bool) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatBool(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Pointer[T any] struct {
|
||||||
|
atomic.Pointer[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPointer[T any](v *T) (p Pointer[T]) {
|
||||||
|
if v != nil {
|
||||||
|
p.Store(v)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(p.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) UnmarshalJSON(b []byte) error {
|
||||||
|
var v *T
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) MarshalYAML() (any, error) {
|
||||||
|
return p.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v *T
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pointer[T]) String() string {
|
||||||
|
return fmt.Sprint(p.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
type Int32 struct {
|
||||||
|
atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInt32(val int32) (i Int32) {
|
||||||
|
i.Store(val)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) UnmarshalJSON(b []byte) error {
|
||||||
|
var v int32
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) MarshalYAML() (any, error) {
|
||||||
|
return i.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v int32
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int32) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatInt(int64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Int64 struct {
|
||||||
|
atomic.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInt64(val int64) (i Int64) {
|
||||||
|
i.Store(val)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) UnmarshalJSON(b []byte) error {
|
||||||
|
var v int64
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) MarshalYAML() (any, error) {
|
||||||
|
return i.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v int64
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Int64) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatInt(int64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Uint32 struct {
|
||||||
|
atomic.Uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUint32(val uint32) (i Uint32) {
|
||||||
|
i.Store(val)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) UnmarshalJSON(b []byte) error {
|
||||||
|
var v uint32
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) MarshalYAML() (any, error) {
|
||||||
|
return i.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v uint32
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint32) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatUint(uint64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Uint64 struct {
|
||||||
|
atomic.Uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUint64(val uint64) (i Uint64) {
|
||||||
|
i.Store(val)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) UnmarshalJSON(b []byte) error {
|
||||||
|
var v uint64
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) MarshalYAML() (any, error) {
|
||||||
|
return i.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v uint64
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uint64) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatUint(uint64(v), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Uintptr struct {
|
||||||
|
atomic.Uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUintptr(val uintptr) (i Uintptr) {
|
||||||
|
i.Store(val)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(i.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) UnmarshalJSON(b []byte) error {
|
||||||
|
var v uintptr
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) MarshalYAML() (any, error) {
|
||||||
|
return i.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v uintptr
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
i.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i *Uintptr) String() string {
|
||||||
|
v := i.Load()
|
||||||
|
return strconv.FormatUint(uint64(v), 10)
|
||||||
|
}
|
||||||
83
common/atomic/value.go
Normal file
83
common/atomic/value.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package atomic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TypedValue[T any] struct {
|
||||||
|
value atomic.Pointer[T]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) Load() (v T) {
|
||||||
|
v, _ = t.LoadOk()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) LoadOk() (v T, ok bool) {
|
||||||
|
value := t.value.Load()
|
||||||
|
if value == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return *value, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) Store(value T) {
|
||||||
|
t.value.Store(&value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) Swap(new T) (v T) {
|
||||||
|
old := t.value.Swap(&new)
|
||||||
|
if old == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return *old
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) CompareAndSwap(old, new T) bool {
|
||||||
|
for {
|
||||||
|
currentP := t.value.Load()
|
||||||
|
var currentValue T
|
||||||
|
if currentP != nil {
|
||||||
|
currentValue = *currentP
|
||||||
|
}
|
||||||
|
// Compare old and current via runtime equality check.
|
||||||
|
if any(currentValue) != any(old) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if t.value.CompareAndSwap(currentP, &new) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) MarshalJSON() ([]byte, error) {
|
||||||
|
return json.Marshal(t.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) UnmarshalJSON(b []byte) error {
|
||||||
|
var v T
|
||||||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
t.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) MarshalYAML() (any, error) {
|
||||||
|
return t.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TypedValue[T]) UnmarshalYAML(unmarshal func(any) error) error {
|
||||||
|
var v T
|
||||||
|
if err := unmarshal(&v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
t.Store(v)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTypedValue[T any](t T) (v TypedValue[T]) {
|
||||||
|
v.Store(t)
|
||||||
|
return
|
||||||
|
}
|
||||||
169
common/atomic/value_test.go
Normal file
169
common/atomic/value_test.go
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
package atomic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTypedValue(t *testing.T) {
|
||||||
|
{
|
||||||
|
var v TypedValue[int]
|
||||||
|
got, gotOk := v.LoadOk()
|
||||||
|
if got != 0 || gotOk {
|
||||||
|
t.Fatalf("LoadOk = (%v, %v), want (0, false)", got, gotOk)
|
||||||
|
}
|
||||||
|
v.Store(1)
|
||||||
|
got, gotOk = v.LoadOk()
|
||||||
|
if got != 1 || !gotOk {
|
||||||
|
t.Fatalf("LoadOk = (%v, %v), want (1, true)", got, gotOk)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
var v TypedValue[error]
|
||||||
|
got, gotOk := v.LoadOk()
|
||||||
|
if got != nil || gotOk {
|
||||||
|
t.Fatalf("LoadOk = (%v, %v), want (nil, false)", got, gotOk)
|
||||||
|
}
|
||||||
|
v.Store(io.EOF)
|
||||||
|
got, gotOk = v.LoadOk()
|
||||||
|
if got != io.EOF || !gotOk {
|
||||||
|
t.Fatalf("LoadOk = (%v, %v), want (EOF, true)", got, gotOk)
|
||||||
|
}
|
||||||
|
err := &os.PathError{}
|
||||||
|
v.Store(err)
|
||||||
|
got, gotOk = v.LoadOk()
|
||||||
|
if got != err || !gotOk {
|
||||||
|
t.Fatalf("LoadOk = (%v, %v), want (%v, true)", got, gotOk, err)
|
||||||
|
}
|
||||||
|
v.Store(nil)
|
||||||
|
got, gotOk = v.LoadOk()
|
||||||
|
if got != nil || !gotOk {
|
||||||
|
t.Fatalf("LoadOk = (%v, %v), want (nil, true)", got, gotOk)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
e1, e2, e3 := io.EOF, &os.PathError{}, &os.PathError{}
|
||||||
|
var v TypedValue[error]
|
||||||
|
if v.CompareAndSwap(e1, e2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != nil {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, nil)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, e1) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(e2, e3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(e1, e2) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(e3, e2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, e3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != e2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, e2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
c1, c2, c3 := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||||
|
var v TypedValue[chan struct{}]
|
||||||
|
if v.CompareAndSwap(c1, c2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != nil {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, nil)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, c1) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c2, c3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c1, c2) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c3, c2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, c3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
c1, c2, c3 := &io.LimitedReader{}, &io.SectionReader{}, &io.SectionReader{}
|
||||||
|
var v TypedValue[io.Reader]
|
||||||
|
if v.CompareAndSwap(c1, c2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != nil {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, nil)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, c1) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c2, c3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c1 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c1)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c1, c2) != true {
|
||||||
|
t.Fatalf("CompareAndSwap = false, want true")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(c3, c2) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
if v.CompareAndSwap(nil, c3) != false {
|
||||||
|
t.Fatalf("CompareAndSwap = true, want false")
|
||||||
|
}
|
||||||
|
if value := v.Load(); value != c2 {
|
||||||
|
t.Fatalf("Load = (%v), want (%v)", value, c2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
59
common/buf/sing.go
Normal file
59
common/buf/sing.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package buf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/metacubex/sing/common/buf"
|
||||||
|
)
|
||||||
|
|
||||||
|
const BufferSize = buf.BufferSize
|
||||||
|
|
||||||
|
type Buffer = buf.Buffer
|
||||||
|
|
||||||
|
func New() *Buffer {
|
||||||
|
return buf.New()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPacket() *Buffer {
|
||||||
|
return buf.NewPacket()
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSize(size int) *Buffer {
|
||||||
|
return buf.NewSize(size)
|
||||||
|
}
|
||||||
|
|
||||||
|
func With(data []byte) *Buffer {
|
||||||
|
return buf.With(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func As(data []byte) *Buffer {
|
||||||
|
return buf.As(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReleaseMulti(buffers []*Buffer) {
|
||||||
|
buf.ReleaseMulti(buffers)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Error(_ any, err error) error {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func Must(errs ...error) {
|
||||||
|
for _, err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Must1[T any](result T, err error) T {
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func Must2[T any, T2 any](result T, result2 T2, err error) (T, T2) {
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return result, result2
|
||||||
|
}
|
||||||
106
common/cache/cache.go
vendored
106
common/cache/cache.go
vendored
@@ -1,106 +0,0 @@
|
|||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Cache store element with a expired time
|
|
||||||
type Cache[K comparable, V any] struct {
|
|
||||||
*cache[K, V]
|
|
||||||
}
|
|
||||||
|
|
||||||
type cache[K comparable, V any] struct {
|
|
||||||
mapping sync.Map
|
|
||||||
janitor *janitor[K, V]
|
|
||||||
}
|
|
||||||
|
|
||||||
type element[V any] struct {
|
|
||||||
Expired time.Time
|
|
||||||
Payload V
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put element in Cache with its ttl
|
|
||||||
func (c *cache[K, V]) Put(key K, payload V, ttl time.Duration) {
|
|
||||||
c.mapping.Store(key, &element[V]{
|
|
||||||
Payload: payload,
|
|
||||||
Expired: time.Now().Add(ttl),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get element in Cache, and drop when it expired
|
|
||||||
func (c *cache[K, V]) Get(key K) V {
|
|
||||||
item, exist := c.mapping.Load(key)
|
|
||||||
if !exist {
|
|
||||||
return getZero[V]()
|
|
||||||
}
|
|
||||||
elm := item.(*element[V])
|
|
||||||
// expired
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
return getZero[V]()
|
|
||||||
}
|
|
||||||
return elm.Payload
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetWithExpire element in Cache with Expire Time
|
|
||||||
func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
|
||||||
item, exist := c.mapping.Load(key)
|
|
||||||
if !exist {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
elm := item.(*element[V])
|
|
||||||
// expired
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
return elm.Payload, elm.Expired
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *cache[K, V]) cleanup() {
|
|
||||||
c.mapping.Range(func(k, v any) bool {
|
|
||||||
key := k.(string)
|
|
||||||
elm := v.(*element[V])
|
|
||||||
if time.Since(elm.Expired) > 0 {
|
|
||||||
c.mapping.Delete(key)
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
type janitor[K comparable, V any] struct {
|
|
||||||
interval time.Duration
|
|
||||||
stop chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *janitor[K, V]) process(c *cache[K, V]) {
|
|
||||||
ticker := time.NewTicker(j.interval)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ticker.C:
|
|
||||||
c.cleanup()
|
|
||||||
case <-j.stop:
|
|
||||||
ticker.Stop()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopJanitor[K comparable, V any](c *Cache[K, V]) {
|
|
||||||
c.janitor.stop <- struct{}{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// New return *Cache
|
|
||||||
func New[K comparable, V any](interval time.Duration) *Cache[K, V] {
|
|
||||||
j := &janitor[K, V]{
|
|
||||||
interval: interval,
|
|
||||||
stop: make(chan struct{}),
|
|
||||||
}
|
|
||||||
c := &cache[K, V]{janitor: j}
|
|
||||||
go j.process(c)
|
|
||||||
C := &Cache[K, V]{c}
|
|
||||||
runtime.SetFinalizer(C, stopJanitor[K, V])
|
|
||||||
return C
|
|
||||||
}
|
|
||||||
72
common/cache/cache_test.go
vendored
72
common/cache/cache_test.go
vendored
@@ -1,72 +0,0 @@
|
|||||||
package cache
|
|
||||||
|
|
||||||
import (
|
|
||||||
"runtime"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCache_Basic(t *testing.T) {
|
|
||||||
interval := 200 * time.Millisecond
|
|
||||||
ttl := 20 * time.Millisecond
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
|
|
||||||
d := New[string, string](interval)
|
|
||||||
d.Put("string", "a", ttl)
|
|
||||||
|
|
||||||
i := c.Get("int")
|
|
||||||
assert.Equal(t, i, 1, "should recv 1")
|
|
||||||
|
|
||||||
s := d.Get("string")
|
|
||||||
assert.Equal(t, s, "a", "should recv 'a'")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_TTL(t *testing.T) {
|
|
||||||
interval := 200 * time.Millisecond
|
|
||||||
ttl := 20 * time.Millisecond
|
|
||||||
now := time.Now()
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
c.Put("int2", 2, ttl)
|
|
||||||
|
|
||||||
i := c.Get("int")
|
|
||||||
_, expired := c.GetWithExpire("int2")
|
|
||||||
assert.Equal(t, i, 1, "should recv 1")
|
|
||||||
assert.True(t, now.Before(expired))
|
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
|
||||||
i = c.Get("int")
|
|
||||||
j, _ := c.GetWithExpire("int2")
|
|
||||||
assert.True(t, i == 0, "should recv 0")
|
|
||||||
assert.True(t, j == 0, "should recv 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_AutoCleanup(t *testing.T) {
|
|
||||||
interval := 10 * time.Millisecond
|
|
||||||
ttl := 15 * time.Millisecond
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
|
|
||||||
time.Sleep(ttl * 2)
|
|
||||||
i := c.Get("int")
|
|
||||||
j, _ := c.GetWithExpire("int")
|
|
||||||
assert.True(t, i == 0, "should recv 0")
|
|
||||||
assert.True(t, j == 0, "should recv 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCache_AutoGC(t *testing.T) {
|
|
||||||
sign := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
interval := 10 * time.Millisecond
|
|
||||||
ttl := 15 * time.Millisecond
|
|
||||||
c := New[string, int](interval)
|
|
||||||
c.Put("int", 1, ttl)
|
|
||||||
sign <- struct{}{}
|
|
||||||
}()
|
|
||||||
|
|
||||||
<-sign
|
|
||||||
runtime.GC()
|
|
||||||
}
|
|
||||||
55
common/callback/callback.go
Normal file
55
common/callback/callback.go
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
package callback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/metacubex/mihomo/common/buf"
|
||||||
|
N "github.com/metacubex/mihomo/common/net"
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type firstWriteCallBackConn struct {
|
||||||
|
C.Conn
|
||||||
|
callback func(error)
|
||||||
|
written bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) Write(b []byte) (n int, err error) {
|
||||||
|
defer func() {
|
||||||
|
if !c.written {
|
||||||
|
c.written = true
|
||||||
|
c.callback(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return c.Conn.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) WriteBuffer(buffer *buf.Buffer) (err error) {
|
||||||
|
defer func() {
|
||||||
|
if !c.written {
|
||||||
|
c.written = true
|
||||||
|
c.callback(err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return c.Conn.WriteBuffer(buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) Upstream() any {
|
||||||
|
return c.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) WriterReplaceable() bool {
|
||||||
|
return c.written
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *firstWriteCallBackConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ N.ExtendedConn = (*firstWriteCallBackConn)(nil)
|
||||||
|
|
||||||
|
func NewFirstWriteCallBackConn(c C.Conn, callback func(error)) C.Conn {
|
||||||
|
return &firstWriteCallBackConn{
|
||||||
|
Conn: c,
|
||||||
|
callback: callback,
|
||||||
|
written: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
61
common/callback/close_callback.go
Normal file
61
common/callback/close_callback.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package callback
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
C "github.com/metacubex/mihomo/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
type closeCallbackConn struct {
|
||||||
|
C.Conn
|
||||||
|
closeFunc func()
|
||||||
|
closeOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) Close() error {
|
||||||
|
w.closeOnce.Do(w.closeFunc)
|
||||||
|
return w.Conn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackConn) Upstream() any {
|
||||||
|
return w.Conn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCloseCallbackConn(conn C.Conn, callback func()) C.Conn {
|
||||||
|
return &closeCallbackConn{Conn: conn, closeFunc: callback}
|
||||||
|
}
|
||||||
|
|
||||||
|
type closeCallbackPacketConn struct {
|
||||||
|
C.PacketConn
|
||||||
|
closeFunc func()
|
||||||
|
closeOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) Close() error {
|
||||||
|
w.closeOnce.Do(w.closeFunc)
|
||||||
|
return w.PacketConn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) ReaderReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) WriterReplaceable() bool {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *closeCallbackPacketConn) Upstream() any {
|
||||||
|
return w.PacketConn
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCloseCallbackPacketConn(conn C.PacketConn, callback func()) C.PacketConn {
|
||||||
|
return &closeCallbackPacketConn{PacketConn: conn, closeFunc: callback}
|
||||||
|
}
|
||||||
@@ -21,7 +21,7 @@ func TestSplitArgs(t *testing.T) {
|
|||||||
|
|
||||||
func TestExecCmd(t *testing.T) {
|
func TestExecCmd(t *testing.T) {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
_, err := ExecCmd("dir")
|
_, err := ExecCmd("cmd -c 'dir'")
|
||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
package collections
|
|
||||||
|
|
||||||
import "sync"
|
|
||||||
|
|
||||||
type (
|
|
||||||
stack struct {
|
|
||||||
top *node
|
|
||||||
length int
|
|
||||||
lock *sync.RWMutex
|
|
||||||
}
|
|
||||||
|
|
||||||
node struct {
|
|
||||||
value interface{}
|
|
||||||
prev *node
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewStack Create a new stack
|
|
||||||
func NewStack() *stack {
|
|
||||||
return &stack{nil, 0, &sync.RWMutex{}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Len Return the number of items in the stack
|
|
||||||
func (this *stack) Len() int {
|
|
||||||
return this.length
|
|
||||||
}
|
|
||||||
|
|
||||||
// Peek View the top item on the stack
|
|
||||||
func (this *stack) Peek() interface{} {
|
|
||||||
if this.length == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return this.top.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pop the top item of the stack and return it
|
|
||||||
func (this *stack) Pop() interface{} {
|
|
||||||
this.lock.Lock()
|
|
||||||
defer this.lock.Unlock()
|
|
||||||
if this.length == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
n := this.top
|
|
||||||
this.top = n.prev
|
|
||||||
this.length--
|
|
||||||
return n.value
|
|
||||||
}
|
|
||||||
|
|
||||||
// Push a value onto the top of the stack
|
|
||||||
func (this *stack) Push(value interface{}) {
|
|
||||||
this.lock.Lock()
|
|
||||||
defer this.lock.Unlock()
|
|
||||||
n := &node{value, this.top}
|
|
||||||
this.top = n
|
|
||||||
this.length++
|
|
||||||
}
|
|
||||||
31
common/contextutils/afterfunc_compact.go
Normal file
31
common/contextutils/afterfunc_compact.go
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
package contextutils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
func afterFunc(ctx context.Context, f func()) (stop func() bool) {
|
||||||
|
stopc := make(chan struct{})
|
||||||
|
once := sync.Once{} // either starts running f or stops f from running
|
||||||
|
if ctx.Done() != nil {
|
||||||
|
go func() {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
once.Do(func() {
|
||||||
|
go f()
|
||||||
|
})
|
||||||
|
case <-stopc:
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
return func() bool {
|
||||||
|
stopped := false
|
||||||
|
once.Do(func() {
|
||||||
|
stopped = true
|
||||||
|
close(stopc)
|
||||||
|
})
|
||||||
|
return stopped
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user