Compare commits
750 Commits
Author | SHA1 | Date | |
---|---|---|---|
33abbdfd24 | |||
af97922e94 | |||
db94dc76b4 | |||
99effb051b | |||
42e489e199 | |||
d3b88d1b4f | |||
ec318f1cc5 | |||
6cfae6919f | |||
b23a071050 | |||
732e82e3d0 | |||
fecbc7a091 | |||
4b39362039 | |||
835cab58cf | |||
9317dd610b | |||
8dc56b56ad | |||
4611fbfe0c | |||
b725c91b05 | |||
482062376e | |||
32fc990c68 | |||
dfeb901417 | |||
02933ae568 | |||
4ca2d4146b | |||
5d97a7f9ca | |||
6eab1f158a | |||
65a289e16f | |||
637707e58f | |||
95e602bf3b | |||
4ac192f520 | |||
473d0f74bd | |||
93ea1248e3 | |||
97270dcbe0 | |||
50cc274b2e | |||
3867329ef3 | |||
2899a126fc | |||
5391425123 | |||
1e7af0bbc7 | |||
dd67a8c8ba | |||
28ba9c5efa | |||
bb413ece49 | |||
31f4d20477 | |||
57a15088c2 | |||
be6d55e5c4 | |||
09419d88af | |||
9c4bae6f23 | |||
b74320008a | |||
35b87e79a7 | |||
9be70f67ca | |||
bb86098235 | |||
dec32da262 | |||
a33e511c12 | |||
d71a2ce61e | |||
133bb2319f | |||
7d84a47683 | |||
38e6b81d07 | |||
143c5de51d | |||
3e424dea7b | |||
b0fd50453a | |||
fe3ad3724c | |||
e1c6142851 | |||
6e7002dbd3 | |||
6a4063af0d | |||
6b636c051a | |||
9a035d3c51 | |||
850c52d07c | |||
10f8f5dd7b | |||
4e272ff066 | |||
a73e690172 | |||
947d9d4560 | |||
179bc6ecdf | |||
fbabcfce94 | |||
3a92ad47e7 | |||
92a20a5362 | |||
9565b5194c | |||
23b2f3b971 | |||
f93dd6052e | |||
80df572b18 | |||
0c64d7e56a | |||
a8ce283727 | |||
ab8e9e7d7a | |||
dbce268692 | |||
fef9f95e65 | |||
60e1947ed2 | |||
5b35822945 | |||
0a76876764 | |||
e382496e4c | |||
0c91a4e0f3 | |||
56fae0b1f5 | |||
baee951657 | |||
253dc24e40 | |||
503b1efd8a | |||
50f2ecbcb0 | |||
97e158989f | |||
e732fbb414 | |||
f8a168e64d | |||
e599621a32 | |||
59ab2083aa | |||
2d7c4eda66 | |||
3cc1870aee | |||
8eec86232c | |||
10d2d14938 | |||
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 | |||
c1a99b9be4 | |||
bf55428954 | |||
5e55d6b08f | |||
21098d2627 | |||
8da67ba61c | |||
54a0947bb4 | |||
a562b249a2 | |||
5af17f70b4 | |||
ca5bb91977 | |||
bbac54433e | |||
b6a5ec6490 | |||
aaf700f0b5 | |||
2ce89aca1e | |||
efdf69022a | |||
d4d1d4cc2a | |||
a8c4900891 | |||
930a7af8e7 | |||
77acd4ba8d | |||
691cf1d8d6 | |||
d1decb8e58 | |||
625c4a1079 | |||
341ef19099 | |||
2563b20019 | |||
1b3b5b4dfe | |||
2e6bdc5636 | |||
be298cfa16 | |||
277e71b26a | |||
f7c903a586 | |||
ff4a5bef9b | |||
d8dc44e786 | |||
c968104a19 | |||
f7481ecadf | |||
85c37b473a | |||
23bc231df3 | |||
2146b605f7 | |||
8853e97b40 | |||
7d04904109 | |||
a5acd3aa97 | |||
099aa1e3c2 | |||
63fdb348db | |||
81ee44f6c0 | |||
130a3a261d | |||
94368f43eb | |||
9a55213ddc | |||
5055542d61 | |||
23063ae0b9 | |||
a7f9aa909a | |||
15ecc451f3 | |||
186a4cfdf3 | |||
220ef9e2e2 | |||
7079116aa8 | |||
b9e6de45e6 | |||
d3503ff940 | |||
c3f4e1ba2e | |||
695fb64fa8 | |||
eea9a12560 | |||
0a4570b55c | |||
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 | |||
1af39cb228 | |||
c95735f083 | |||
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 | |||
7431001ed6 | |||
149b4b5b43 | |||
c0eb9aac1c | |||
79469fc8d6 | |||
948700eed6 | |||
3ab82849d4 | |||
0f43a19fdb | |||
cc1c1340a3 | |||
fe25ae83df | |||
c787bbe0e5 | |||
7aff9aac82 | |||
8b09db5f7f | |||
b5623602f5 | |||
16b27b3a1f | |||
8b00be9039 | |||
fa9e27c5e4 | |||
f4d9384603 | |||
c4408612b3 | |||
0742f7db26 | |||
891c2fe899 | |||
b831eb178b | |||
962ceaa89e | |||
d52b00bd34 | |||
aa0d174ccb | |||
b8e9c3d55a | |||
0b4c498c93 | |||
efc7c82cac | |||
63917aa020 | |||
5016f529af | |||
5bd5f1bfda | |||
d4dcbce9cb | |||
df8196a68c | |||
c1631759fc | |||
9e9c3c810f | |||
463101aec1 | |||
2072964701 | |||
aded1b78b5 | |||
ca9c859059 | |||
55811dae32 | |||
7136d145f8 | |||
2fbbf7519f | |||
663bf4fbb0 | |||
f0a22a4a4c | |||
4ab91520bd | |||
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 | |||
bb1eb5979b | |||
032b6a2cc5 | |||
45a02e3439 | |||
9d8cd036ff | |||
2aad9818e8 | |||
4d5c0d2bf4 | |||
861205dbbe | |||
9dbe20f2c5 | |||
8dea62cd63 | |||
2d99f86780 | |||
fac63625fc | |||
b9f270162a | |||
bbbe371ea9 | |||
e2409f9639 | |||
4f634edaa9 | |||
f1dab9e9ce | |||
8217db82ce | |||
f9dd0a6bfc | |||
b9b25be68d | |||
179e5aad58 | |||
fc1eaf9a9d | |||
1756730693 | |||
c7bc67e44c | |||
949c1551f8 | |||
b23a333acf | |||
47568051bf | |||
22c1e05e1c | |||
c161d5e6be | |||
573be855f7 | |||
a38b2bcb6d | |||
2e74986fe4 | |||
30eaa8add6 | |||
b498d2dda2 | |||
96a32f5038 | |||
e11f6f84df | |||
5a1e1050b7 | |||
73aa8c7be7 | |||
183973e823 | |||
2e08a4b4e1 | |||
564a6fdf35 | |||
cca3a1a934 | |||
ffb49ba4c5 | |||
e4fb10faf9 | |||
16a35527b7 | |||
4fd7d0f707 | |||
dee1aeb6c3 | |||
2f95d56a12 | |||
c77993eed3 | |||
ce663a7b96 | |||
9c2ca0feb0 | |||
b8d5321615 | |||
eb6f7e3158 | |||
0947cb4a5a | |||
0368bb4180 | |||
4aeac0e227 | |||
bd3c493c9f | |||
0a99fc4d74 | |||
19fc70b2c4 | |||
81b5543b0d | |||
2e1d9a4f2e | |||
de4341c8cd | |||
8a85c63b08 | |||
b0dd74e74e | |||
4dd9e199b7 | |||
3d6aea4c1e | |||
0cb5270452 | |||
3f6d2e5f91 | |||
3b16fcef92 | |||
f91d106cdf | |||
9e6ba64940 | |||
bee1bddceb | |||
e98dcc4267 | |||
4b79f8de93 | |||
f40c2eb71d | |||
7ca1a03d73 | |||
6c4791480e | |||
42d853a7e6 | |||
5d36d8b139 | |||
5a4441c47f | |||
0ca10798ea | |||
3ea3653d7a | |||
58cd8f9ac1 | |||
ea0d236259 | |||
48a01adb7a | |||
f8d7f29856 | |||
1cf9321aa0 | |||
71a1f5dfbd | |||
25426cba33 | |||
9d364f66e9 | |||
7c23fa2bd4 | |||
0658ecadd3 | |||
efbc334b3b | |||
80764217c2 | |||
45fe6e996b | |||
36a719e2f8 | |||
1b6b0052c2 | |||
c981ef0f28 | |||
1bf291d240 | |||
b179d09efb | |||
4be17653e0 | |||
21446ba5d4 | |||
75ce6b59bf | |||
ce96ac35fb | |||
173e10abe6 | |||
a6eb11ce18 | |||
0c65f6962a | |||
baa9e02af6 | |||
673541e2a8 | |||
14878b37f6 | |||
83e0abaa8c | |||
7166db2ac9 | |||
815a060309 | |||
544e0f137d | |||
07906c0aa5 | |||
b2981f921c | |||
7be3e617ab | |||
9a3bc8ef9e | |||
e083d1c57d | |||
ce4902e5e6 | |||
4b9edc3b66 | |||
91e48b707b | |||
5719b9d22f | |||
b553dd749b | |||
9461bcd44e | |||
6548dc90fa | |||
908ca20afa | |||
88e4b3575e | |||
559b3ff9f3 | |||
127634028d | |||
81c5a65f23 | |||
591ee119c2 | |||
5b03cc56e7 | |||
c4216218c8 | |||
63840b3358 | |||
045dd0589b | |||
705311b70e | |||
55ce40fbd1 | |||
07fda93111 | |||
012e044c54 | |||
b323315583 | |||
4c10d6e212 | |||
ece3bb360a | |||
5a7b9bdf45 | |||
028ecb70c5 | |||
4e0b22f42d | |||
dbd27ef910 | |||
ffff1418f2 | |||
64a5fd02da | |||
611ce5f5f1 | |||
0a0b8074f4 | |||
f66c3b6f86 | |||
a3d49d1ed4 | |||
0d068e7b5f | |||
24583009c4 | |||
a593d68c42 | |||
520657e953 | |||
6c64164bee | |||
9b4ddbed2c | |||
79d984ee8e | |||
7a54d616c4 | |||
f19b67fe9d | |||
91e83ea955 | |||
a375b85fa0 | |||
4cc661920e | |||
b5f6f26de4 | |||
e068563b58 | |||
bf6839e5f3 | |||
e0040b7e5d | |||
3beb71b6e1 | |||
668d29d91f | |||
5386c3903d | |||
6a4d2b3368 | |||
d9d8507c8f | |||
5b7f46bc97 | |||
d1838f663e | |||
2d1c031ce0 | |||
e67f94b87a | |||
2df890c4ee | |||
520256365e | |||
9270d3c475 | |||
c8b1050c15 | |||
39de5d58c8 | |||
a38f30ec3b | |||
2ea92d70f9 | |||
ea2e715da9 | |||
1350330fe0 | |||
317797acc8 | |||
8766764d49 | |||
b8d48e1618 | |||
f972d1fa58 | |||
df78ba8fa6 | |||
0c83575302 | |||
e9151bc43f | |||
68345b6a19 | |||
435bee0ca2 | |||
92d169ca81 | |||
30f1b29257 | |||
c503e44324 | |||
ce509295c0 | |||
f671d6a1fd | |||
e194efcecb | |||
609d69191a | |||
c791044ddf | |||
dc2abe6eeb | |||
1071e3f4a3 | |||
acc249495d | |||
5a2cc9a36f | |||
1cc6cfab9c | |||
0183d752a0 | |||
2f24e49ff6 | |||
016862f7a5 | |||
c3df768f79 | |||
0f2123179a | |||
1034780e8e | |||
f01ac69654 | |||
c85305ead8 | |||
3e89bee524 | |||
68fccfacc0 | |||
cf52fbed65 | |||
a924819fbf | |||
13c82754ff | |||
002163f07b | |||
9c5b184db6 | |||
3ab784dd80 | |||
f1c4d85eb3 | |||
b9fc393f95 | |||
557347d366 | |||
a7f3b85200 | |||
7550067fde | |||
076a0840bf | |||
5ebcc526de | |||
3772ad8ddb | |||
5ad7237fa7 | |||
49e25f502f | |||
06942c67fd | |||
9259c9f3ff | |||
37cf166d14 | |||
27292dac0c | |||
847c91503b | |||
ca8ed0a01b | |||
46dc262e8e | |||
7465eaafa1 | |||
d70cfefde7 | |||
52c37f7140 | |||
180bce2940 | |||
4a446c4e31 | |||
d7f5e8d3de | |||
0a180eeb40 | |||
7ff48ea42d | |||
a0e44f4041 | |||
2f6f9ebc2e | |||
28a1475f66 | |||
c28f42d823 | |||
2bf34c766e | |||
35b19c3d7f | |||
90e6ed4612 | |||
ae5a790510 | |||
3b277aa8ec | |||
176eb3926b | |||
776728fb30 | |||
a732e1a603 | |||
1cdaf782ba | |||
f1157d0a09 | |||
f376409041 | |||
45b3afdd33 | |||
875fdb3a5b | |||
25e115d042 | |||
d633e3d96e | |||
6e9d837a7d | |||
63b9d66365 | |||
be0fadc09e | |||
76dccebbf6 | |||
cd5b735973 | |||
9e4e1482d9 | |||
9974fba56e | |||
4bd5764c4e | |||
deeab8b45f | |||
af30664c51 | |||
6962f0b7e1 | |||
6e5859d1bf | |||
87ca93b979 | |||
11052d8f77 | |||
a5ce62db33 | |||
2f8e575308 | |||
62b70725ef | |||
8595d6c2e9 | |||
03b956b7a3 | |||
e5c99cbee7 | |||
58a47e1835 | |||
daf83eb6f7 | |||
bb68b59c9a | |||
c3cfa3d6cd | |||
b15344ec78 | |||
56c38890f9 | |||
daae846db3 | |||
ee6c1871a9 | |||
00e44cd141 | |||
4ab986cccb | |||
64869d0f17 | |||
7f0368da66 | |||
4f1b227ca2 | |||
16abba385a | |||
75b5f633cd | |||
8ae68552a6 | |||
d35d6c9ac9 | |||
a832cfdb65 | |||
951a5a0eb5 | |||
89609cc4a2 | |||
bfb976bbdc | |||
a15d2535f1 | |||
610c79570a | |||
051c81518c | |||
0209efd423 | |||
ba6fdd2962 | |||
c14dd79e69 | |||
9475799615 | |||
14917c8af1 | |||
3bb32d12e0 | |||
013b839678 | |||
a06382cebc | |||
ebc3f36236 | |||
e2a0437685 | |||
82c8e02d02 | |||
a210ec4197 | |||
0b72395704 | |||
8955107d6b | |||
69aef9cec0 | |||
9e44e21406 | |||
b0fdd8dc47 | |||
e92ef587bb | |||
5657aa50cf | |||
7d17d53a8f | |||
58ef4ddbba | |||
a78b89d16e | |||
833b43a538 | |||
8df3efe932 | |||
645c3154d6 | |||
a847d7b58d | |||
37ea8aff5c | |||
cb4ce8be6a | |||
a85395e777 | |||
819b29956b | |||
eb999b3bf1 | |||
8580ee8898 | |||
58552447ef | |||
23ca356447 | |||
fae65b97ec | |||
99f0231a9b | |||
edf1bb476d | |||
5c53243e81 | |||
b99b4ad15f | |||
6369921364 | |||
c6f923041f | |||
53eb3f15bb | |||
b15a7c8b6f | |||
038f973f90 | |||
bf6bfdd930 | |||
0431969a73 | |||
c7b257b188 | |||
885f69b81d | |||
cb52682790 | |||
c65835d9e4 | |||
92bb026f70 | |||
c22c7efd07 | |||
e4b30dacd4 | |||
353ae30839 | |||
828ff82ff2 | |||
35cf39e415 | |||
340efef2d8 | |||
796eb5c95c | |||
0f2b87497b | |||
06e9243fda | |||
d4cc650633 | |||
14af94205c | |||
078389f4f6 | |||
cad18b7529 | |||
aeddc8eb1d | |||
f7393509a3 | |||
8e641a4e31 | |||
223de1f3fd | |||
1fb2bc07d7 | |||
eb57d246cf | |||
0001a1b844 | |||
b20e202321 | |||
900e852525 | |||
1f3968bd50 | |||
5d510eb5aa | |||
3d246d5150 | |||
3686446919 | |||
a412745314 | |||
d0c23998d2 | |||
038cc1f6b5 | |||
6bd186d3c0 | |||
4c6bb7178b | |||
cec14db4a8 | |||
53287d597b | |||
964bbe1957 | |||
c824ace2d7 | |||
78cef7df59 | |||
62b3ebe49f | |||
ff420ed2ee | |||
d1568325e6 | |||
5a27df899f | |||
ab12b440aa | |||
4b614090f8 | |||
63d07db4bf | |||
cbea46b0c8 | |||
c0e9d69163 | |||
d29d824da8 | |||
862174d21b |
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
76
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,76 +0,0 @@
|
|||||||
name: Bug report
|
|
||||||
description: Create a report to help us improve
|
|
||||||
title: "[Bug] "
|
|
||||||
body:
|
|
||||||
- type: checkboxes
|
|
||||||
id: ensure
|
|
||||||
attributes:
|
|
||||||
label: Verify steps
|
|
||||||
description: "
|
|
||||||
在提交之前,请确认
|
|
||||||
Please verify that you've followed these steps
|
|
||||||
"
|
|
||||||
options:
|
|
||||||
- label: "
|
|
||||||
如果你可以自己 debug 并解决的话,提交 PR 吧
|
|
||||||
Is this something you can **debug and fix**? Send a pull request! Bug fixes and documentation fixes are welcome.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经在 [Issue Tracker](……/) 中找过我要提出的问题
|
|
||||||
I have searched on the [issue tracker](……/) for a related issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经使用 dev 分支版本测试过,问题依旧存在
|
|
||||||
I have tested using the dev branch, and the issue still exists.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
我已经仔细看过 [Documentation](https://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- label: "
|
|
||||||
这是 Clash 核心的问题,并非我所使用的 Clash 衍生版本(如 OpenClash、KoolClash 等)的特定问题
|
|
||||||
This is an issue of the Clash core *per se*, not to the derivatives of Clash, like OpenClash or KoolClash.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: input
|
|
||||||
attributes:
|
|
||||||
label: Clash version
|
|
||||||
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: "Clash config"
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash core 脱敏后配置文件的内容
|
|
||||||
Paste the Clash core configuration below.
|
|
||||||
"
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
render: shell
|
|
||||||
label: Clash log
|
|
||||||
description: "
|
|
||||||
在下方附上 Clash Core 的日志,log level 使用 DEBUG
|
|
||||||
Paste the Clash core log below with the log level set to `DEBUG`.
|
|
||||||
"
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
validations:
|
|
||||||
required: true
|
|
6
.github/ISSUE_TEMPLATE/config.yml
vendored
6
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -1,6 +0,0 @@
|
|||||||
blank_issues_enabled: false
|
|
||||||
|
|
||||||
contact_links:
|
|
||||||
- name: Get help in GitHub Discussions
|
|
||||||
url: https://github.com/Dreamacro/clash/discussions
|
|
||||||
about: Have a question? Not sure if your issue affects everyone reproducibly? The quickest way to get help is on Clash's GitHub Discussions!
|
|
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
36
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -1,36 +0,0 @@
|
|||||||
name: Feature request
|
|
||||||
description: Suggest an idea for this project
|
|
||||||
title: "[Feature] "
|
|
||||||
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://github.com/Dreamacro/clash/wiki/) 并无法自行解决问题
|
|
||||||
I have read the [documentation](https://github.com/Dreamacro/clash/wiki/) and was unable to solve the issue.
|
|
||||||
"
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Description
|
|
||||||
description: 请详细、清晰地表达你要提出的论述,例如这个问题如何影响到你?你想实现什么功能?目前 Clash 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
|
|
||||||
"
|
|
142
.github/workflows/build-windows-amd.yml
vendored
142
.github/workflows/build-windows-amd.yml
vendored
@ -1,142 +0,0 @@
|
|||||||
name: Build-Windows
|
|
||||||
on: [push]
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: windows-latest
|
|
||||||
steps:
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v2
|
|
||||||
with:
|
|
||||||
go-version: 1.18.x
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Go cache paths
|
|
||||||
id: go-cache-paths
|
|
||||||
run: |
|
|
||||||
echo "::set-output name=go-build::$(go env GOCACHE)"
|
|
||||||
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
|
|
||||||
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
${{ steps.go-cache-paths.outputs.go-mod }}
|
|
||||||
${{ steps.go-cache-paths.outputs.go-build }}
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
|
|
||||||
- name: Setup Python
|
|
||||||
uses: actions/setup-python@v3
|
|
||||||
with:
|
|
||||||
python-version: '3.9'
|
|
||||||
architecture: 'x64'
|
|
||||||
|
|
||||||
- name: Get dependencies, run test
|
|
||||||
id: test
|
|
||||||
run: |
|
|
||||||
cmd /c mklink /J D:\python-amd64 $env:pythonLocation
|
|
||||||
|
|
||||||
echo "::set-output name=file_sha::$(git describe --tags --always)"
|
|
||||||
echo "::set-output name=file_date::$(Get-Date -Format 'yyyyMMdd')"
|
|
||||||
|
|
||||||
((Get-Content -path constant/version.go -Raw) -replace 'unknown version',$(Get-Date -Format 'yyyy.MM.dd')) | Set-Content -Path constant/version.go
|
|
||||||
((Get-Content -path constant/version.go -Raw) -replace 'unknown time',$(Get-Date)) | Set-Content -Path constant/version.go
|
|
||||||
|
|
||||||
# go test
|
|
||||||
go test -tags build_actions ./...
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
#if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
run: |
|
|
||||||
$env:CGO_ENABLED=1; go build -tags build_actions -trimpath -ldflags '-w -s -buildid=' -o bin/clash-plus-pro-windows-amd64.exe
|
|
||||||
$env:GOAMD64="v3"; $env:CGO_ENABLED=1; go build -tags build_actions -trimpath -ldflags '-w -s -buildid=' -o bin/clash-plus-pro-windows-amd64-v3.exe
|
|
||||||
|
|
||||||
$version = Get-Date -Format 'yyyy.MM.dd'
|
|
||||||
|
|
||||||
cd bin/
|
|
||||||
Compress-Archive -Path clash-plus-pro-windows-amd64.exe -DestinationPath clash-plus-pro-windows-amd64-$version.zip
|
|
||||||
Compress-Archive -Path clash-plus-pro-windows-amd64-v3.exe -DestinationPath clash-plus-pro-windows-amd64-v3-$version.zip
|
|
||||||
Remove-Item -Force clash-plus-pro-windows-amd64.exe
|
|
||||||
Remove-Item -Force clash-plus-pro-windows-amd64-v3.exe
|
|
||||||
"$version" | Out-File version.txt -NoNewLine
|
|
||||||
|
|
||||||
- name: Upload files to tag
|
|
||||||
if: startsWith(github.ref, 'refs/tags/') == false
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
run: |
|
|
||||||
$version = Get-Date -Format 'yyyy.MM.dd'
|
|
||||||
|
|
||||||
$plus_pro = curl `
|
|
||||||
-H "Accept: application/vnd.github.v3+json" `
|
|
||||||
-H "Authorization: token $env:GITHUB_TOKEN" `
|
|
||||||
https://api.github.com/repos/yaling888/clash/releases/tags/plus_pro | ConvertFrom-Json
|
|
||||||
|
|
||||||
$plus_pro_url = $plus_pro.url
|
|
||||||
$upload_url = $plus_pro.upload_url
|
|
||||||
$plus_pro_upload_url = $upload_url.Substring(0,$upload_url.Length-13)
|
|
||||||
|
|
||||||
curl `
|
|
||||||
-X PATCH `
|
|
||||||
-H "Accept: application/vnd.github.v3+json" `
|
|
||||||
-H "Authorization: token $env:GITHUB_TOKEN" `
|
|
||||||
"$plus_pro_url" `
|
|
||||||
-d "{`"name`":`"Plus Pro $version`",`"draft`":true}" | Out-Null
|
|
||||||
|
|
||||||
foreach ($asset in $plus_pro.assets)
|
|
||||||
{
|
|
||||||
curl `
|
|
||||||
-X DELETE `
|
|
||||||
-H "Accept: application/vnd.github.v3+json" `
|
|
||||||
-H "Authorization: token $env:GITHUB_TOKEN" `
|
|
||||||
"$($asset.url)" | Out-Null
|
|
||||||
}
|
|
||||||
|
|
||||||
curl `
|
|
||||||
-X POST `
|
|
||||||
-H "Content-Type: application/zip" `
|
|
||||||
-T "bin/clash-plus-pro-windows-amd64-$version.zip" `
|
|
||||||
-H "Accept: application/vnd.github.v3+json" `
|
|
||||||
-H "Authorization: token $env:GITHUB_TOKEN" `
|
|
||||||
"$plus_pro_upload_url?name=clash-plus-pro-windows-amd64-$version.zip" | Out-Null
|
|
||||||
|
|
||||||
curl `
|
|
||||||
-X POST `
|
|
||||||
-H "Content-Type: application/zip" `
|
|
||||||
-T "bin/clash-plus-pro-windows-amd64-v3-$version.zip" `
|
|
||||||
-H "Accept: application/vnd.github.v3+json" `
|
|
||||||
-H "Authorization: token $env:GITHUB_TOKEN" `
|
|
||||||
"$plus_pro_upload_url?name=clash-plus-pro-windows-amd64-v3-$version.zip" | Out-Null
|
|
||||||
|
|
||||||
curl `
|
|
||||||
-X POST `
|
|
||||||
-H "Content-Type: text/plain" `
|
|
||||||
-T "bin/version.txt" `
|
|
||||||
-H "Accept: application/vnd.github.v3+json" `
|
|
||||||
-H "Authorization: token $env:GITHUB_TOKEN" `
|
|
||||||
"$plus_pro_upload_url?name=version.txt" | Out-Null
|
|
||||||
|
|
||||||
#- name: Upload files to Artifacts
|
|
||||||
# uses: actions/upload-artifact@v2
|
|
||||||
# with:
|
|
||||||
# name: clash-windows-amd64-${{ steps.test.outputs.file_sha }}-${{ steps.test.outputs.file_date }}
|
|
||||||
# path: |
|
|
||||||
# bin/*
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
||||||
prerelease: false
|
|
||||||
generate_release_notes: false
|
|
||||||
|
|
||||||
#- name: Delete workflow runs
|
|
||||||
# uses: GitRML/delete-workflow-runs@main
|
|
||||||
# with:
|
|
||||||
# retain_days: 1
|
|
||||||
# keep_minimum_runs: 2
|
|
20
.github/workflows/build.yaml
vendored
Normal file
20
.github/workflows/build.yaml
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
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
|
29
.github/workflows/codeql-analysis.yml
vendored
29
.github/workflows/codeql-analysis.yml
vendored
@ -1,29 +0,0 @@
|
|||||||
name: CodeQL
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [ rm ]
|
|
||||||
jobs:
|
|
||||||
analyze:
|
|
||||||
name: Analyze
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
language: ['go']
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- name: Initialize CodeQL
|
|
||||||
uses: github/codeql-action/init@v1
|
|
||||||
with:
|
|
||||||
languages: ${{ matrix.language }}
|
|
||||||
|
|
||||||
- name: Autobuild
|
|
||||||
uses: github/codeql-action/autobuild@v1
|
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
|
||||||
uses: github/codeql-action/analyze@v1
|
|
61
.github/workflows/docker.yaml
vendored
Normal file
61
.github/workflows/docker.yaml
vendored
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
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 }}
|
79
.github/workflows/docker.yml
vendored
79
.github/workflows/docker.yml
vendored
@ -1,79 +0,0 @@
|
|||||||
name: Publish Docker Image
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- rm
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
build:
|
|
||||||
name: Build
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
|
|
||||||
- name: Check out code into the Go module directory
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v1
|
|
||||||
with:
|
|
||||||
platforms: all
|
|
||||||
|
|
||||||
- name: Set up docker buildx
|
|
||||||
id: buildx
|
|
||||||
uses: docker/setup-buildx-action@v1
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
|
|
||||||
- name: Login to DockerHub
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
|
||||||
|
|
||||||
- name: Login to Github Package
|
|
||||||
uses: docker/login-action@v1
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: Dreamacro
|
|
||||||
password: ${{ secrets.PACKAGE_TOKEN }}
|
|
||||||
|
|
||||||
- name: Build dev branch and push
|
|
||||||
if: github.ref == 'refs/heads/dev'
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
|
||||||
push: true
|
|
||||||
tags: 'dreamacro/clash:dev,ghcr.io/dreamacro/clash:dev'
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
||||||
|
|
||||||
- name: Get all docker tags
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
uses: actions/github-script@v6
|
|
||||||
id: tags
|
|
||||||
with:
|
|
||||||
script: |
|
|
||||||
const ref = context.payload.ref.replace(/\/?refs\/tags\//, '')
|
|
||||||
const tags = [
|
|
||||||
'dreamacro/clash:latest',
|
|
||||||
`dreamacro/clash:${ref}`,
|
|
||||||
'ghcr.io/dreamacro/clash:latest',
|
|
||||||
`ghcr.io/dreamacro/clash:${ref}`
|
|
||||||
]
|
|
||||||
return tags.join(',')
|
|
||||||
result-encoding: string
|
|
||||||
|
|
||||||
- name: Build release and push
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
uses: docker/build-push-action@v2
|
|
||||||
with:
|
|
||||||
context: .
|
|
||||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
|
|
||||||
push: true
|
|
||||||
tags: ${{steps.tags.outputs.result}}
|
|
||||||
cache-from: type=gha
|
|
||||||
cache-to: type=gha,mode=max
|
|
23
.github/workflows/linter.yml
vendored
23
.github/workflows/linter.yml
vendored
@ -1,23 +0,0 @@
|
|||||||
name: Linter
|
|
||||||
on: [push, pull_request]
|
|
||||||
jobs:
|
|
||||||
lint:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- 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: golangci-lint
|
|
||||||
uses: golangci/golangci-lint-action@v3
|
|
||||||
with:
|
|
||||||
version: latest
|
|
||||||
args: --build-tags=build_local
|
|
70
.github/workflows/prerelease.yml
vendored
Normal file
70
.github/workflows/prerelease.yml
vendored
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
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@v3
|
||||||
|
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: ${{github.ref_name=='Beta'}}
|
||||||
|
run: |
|
||||||
|
go test ./...
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
if: success()
|
||||||
|
env:
|
||||||
|
NAME: Clash.Meta
|
||||||
|
BINDIR: bin
|
||||||
|
run: make -j$(($(nproc) + 1)) releases
|
||||||
|
|
||||||
|
- name: Delete current release assets
|
||||||
|
uses: andreaswilli/delete-release-assets-action@v2.0.0
|
||||||
|
with:
|
||||||
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
tag: Prerelease-${{ github.ref_name }}
|
||||||
|
deleteOnlyFromDrafts: false
|
||||||
|
|
||||||
|
- name: Tag Repo
|
||||||
|
uses: richardsimko/update-tag@v1
|
||||||
|
with:
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Upload Alpha
|
||||||
|
uses: softprops/action-gh-release@v1
|
||||||
|
if: ${{ success() }}
|
||||||
|
with:
|
||||||
|
tag: ${{ github.ref_name }}
|
||||||
|
tag_name: Prerelease-${{ github.ref_name }}
|
||||||
|
files: bin/*
|
||||||
|
prerelease: true
|
||||||
|
generate_release_notes: true
|
44
.github/workflows/release.yaml
vendored
Normal file
44
.github/workflows/release.yaml
vendored
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
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$(($(nproc) + 1)) 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
|
120
.github/workflows/release.yml
vendored
120
.github/workflows/release.yml
vendored
@ -1,120 +0,0 @@
|
|||||||
name: Release
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- rm
|
|
||||||
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: Go cache paths
|
|
||||||
id: go-cache-paths
|
|
||||||
run: |
|
|
||||||
echo "::set-output name=go-build::$(go env GOCACHE)"
|
|
||||||
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
|
|
||||||
|
|
||||||
- name: Cache go module
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
${{ steps.go-cache-paths.outputs.go-mod }}
|
|
||||||
${{ steps.go-cache-paths.outputs.go-build }}
|
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-go-
|
|
||||||
|
|
||||||
- name: Setup Python
|
|
||||||
uses: actions/setup-python@v2
|
|
||||||
with:
|
|
||||||
python-version: '3.9'
|
|
||||||
|
|
||||||
- name: Get dependencies, run test
|
|
||||||
run: |
|
|
||||||
# fetch python cross compile source files
|
|
||||||
mkdir -p bin/python/
|
|
||||||
cd bin/python/
|
|
||||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-darwin-amd64.tar.xz
|
|
||||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-darwin-arm64.tar.xz
|
|
||||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-windows-amd64.tar.xz
|
|
||||||
curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-windows-386.tar.xz
|
|
||||||
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-amd64.tar.xz
|
|
||||||
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-arm64.tar.xz
|
|
||||||
#curl -LO https://raw.githubusercontent.com/yaling888/snack/main/python-3.9.7-linux-386.tar.xz
|
|
||||||
tar -Jxf python-3.9.7-darwin-amd64.tar.xz
|
|
||||||
tar -Jxf python-3.9.7-darwin-arm64.tar.xz
|
|
||||||
tar -Jxf python-3.9.7-windows-amd64.tar.xz
|
|
||||||
tar -Jxf python-3.9.7-windows-386.tar.xz
|
|
||||||
#tar -Jxf python-3.9.7-linux-amd64.tar.xz
|
|
||||||
#tar -Jxf python-3.9.7-linux-arm64.tar.xz
|
|
||||||
#tar -Jxf python-3.9.7-linux-386.tar.xz
|
|
||||||
rm python-3.9.7-*.tar.xz
|
|
||||||
cd ../../
|
|
||||||
|
|
||||||
# go test
|
|
||||||
go test -tags build_local ./...
|
|
||||||
|
|
||||||
# init xgo
|
|
||||||
docker pull techknowlogick/xgo:latest
|
|
||||||
go install src.techknowlogick.com/xgo@latest
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
#if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
env:
|
|
||||||
NAME: clash
|
|
||||||
BINDIR: bin
|
|
||||||
run: |
|
|
||||||
make -j releases
|
|
||||||
#ls -lahF bin/python/
|
|
||||||
|
|
||||||
- name: Prepare upload
|
|
||||||
if: startsWith(github.ref, 'refs/tags/') == false
|
|
||||||
run: |
|
|
||||||
rm -rf bin/python/
|
|
||||||
echo "FILE_DATE=_$(date +"%Y%m%d%H%M")" >> $GITHUB_ENV
|
|
||||||
echo "FILE_SHA=$(git describe --tags --always 2>/dev/null)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Upload files to Artifacts
|
|
||||||
uses: actions/upload-artifact@v2
|
|
||||||
if: startsWith(github.ref, 'refs/tags/') == false
|
|
||||||
with:
|
|
||||||
name: clash_${{ env.FILE_SHA }}${{ env.FILE_DATE }}
|
|
||||||
path: |
|
|
||||||
bin/*
|
|
||||||
|
|
||||||
- name: Upload Release
|
|
||||||
uses: softprops/action-gh-release@v1
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
with:
|
|
||||||
files: bin/*
|
|
||||||
draft: true
|
|
||||||
prerelease: true
|
|
||||||
generate_release_notes: true
|
|
||||||
|
|
||||||
#- name: Delete workflow runs
|
|
||||||
# uses: GitRML/delete-workflow-runs@main
|
|
||||||
# with:
|
|
||||||
# retain_days: 1
|
|
||||||
# keep_minimum_runs: 2
|
|
||||||
|
|
||||||
- name: Remove old Releases
|
|
||||||
uses: dev-drprasad/delete-older-releases@v0.2.0
|
|
||||||
if: startsWith(github.ref, 'refs/tags/') && !cancelled()
|
|
||||||
with:
|
|
||||||
keep_latest: 1
|
|
||||||
delete_tags: true
|
|
||||||
delete_tag_pattern: plus-pro
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
19
.github/workflows/stale.yml
vendored
19
.github/workflows/stale.yml
vendored
@ -1,19 +0,0 @@
|
|||||||
|
|
||||||
name: Mark stale issues and pull requests
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- rm
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
stale:
|
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/stale@v5
|
|
||||||
with:
|
|
||||||
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days'
|
|
||||||
days-before-stale: 60
|
|
||||||
days-before-close: 5
|
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -23,3 +23,5 @@ vendor
|
|||||||
|
|
||||||
# test suite
|
# test suite
|
||||||
test/config/cache*
|
test/config/cache*
|
||||||
|
/output
|
||||||
|
/.vscode
|
28
Dockerfile
28
Dockerfile
@ -1,18 +1,26 @@
|
|||||||
FROM golang:alpine as builder
|
FROM golang:alpine as builder
|
||||||
|
|
||||||
RUN apk add --no-cache make git && \
|
RUN apk add --no-cache make git && \
|
||||||
wget -O /Country.mmdb https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb
|
mkdir /clash-config && \
|
||||||
WORKDIR /clash-src
|
wget -O /clash-config/Country.mmdb https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb && \
|
||||||
COPY --from=tonistiigi/xx:golang / /
|
wget -O /clash-config/geosite.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat && \
|
||||||
|
wget -O /clash-config/geoip.dat https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||||
|
|
||||||
|
|
||||||
COPY . /clash-src
|
COPY . /clash-src
|
||||||
RUN go mod download && \
|
WORKDIR /clash-src
|
||||||
make docker && \
|
RUN go mod download &&\
|
||||||
mv ./bin/clash-docker /clash
|
make docker &&\
|
||||||
|
mv ./bin/Clash.Meta-docker /clash
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
LABEL org.opencontainers.image.source="https://github.com/Dreamacro/clash"
|
LABEL org.opencontainers.image.source="https://github.com/MetaCubeX/Clash.Meta"
|
||||||
|
|
||||||
RUN apk add --no-cache ca-certificates tzdata
|
RUN apk add --no-cache ca-certificates tzdata
|
||||||
COPY --from=builder /Country.mmdb /root/.config/clash/
|
|
||||||
COPY --from=builder /clash /
|
VOLUME ["/root/.config/clash/"]
|
||||||
ENTRYPOINT ["/clash"]
|
|
||||||
|
COPY --from=builder /clash-config/ /root/.config/clash/
|
||||||
|
COPY --from=builder /clash /clash
|
||||||
|
RUN chmod +x /clash
|
||||||
|
ENTRYPOINT [ "/clash" ]
|
162
Makefile
162
Makefile
@ -1,70 +1,129 @@
|
|||||||
GOCMD=go
|
NAME=Clash.Meta
|
||||||
XGOCMD=xgo -go=go-1.18.x
|
BINDIR=bin
|
||||||
GOBUILD=CGO_ENABLED=1 $(GOCMD) build -trimpath
|
BRANCH=$(shell git branch --show-current)
|
||||||
GOCLEAN=$(GOCMD) clean
|
ifeq ($(BRANCH),Alpha)
|
||||||
NAME=clash
|
VERSION=alpha-$(shell git rev-parse --short HEAD)
|
||||||
BINDIR=$(shell pwd)/bin
|
else ifeq ($(BRANCH),Beta)
|
||||||
VERSION=$(shell git describe --tags --always 2>/dev/null || date +%F)
|
VERSION=beta-$(shell git rev-parse --short HEAD)
|
||||||
|
else ifeq ($(BRANCH),)
|
||||||
|
VERSION=$(shell git describe --tags)
|
||||||
|
else
|
||||||
|
VERSION=$(shell git rev-parse --short HEAD)
|
||||||
|
endif
|
||||||
|
|
||||||
BUILDTIME=$(shell date -u)
|
BUILDTIME=$(shell date -u)
|
||||||
BUILD_PACKAGE=.
|
GOBUILD=CGO_ENABLED=0 go build -trimpath -ldflags '-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
||||||
RELEASE_LDFLAGS='-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
-w -s -buildid='
|
||||||
-w -s -buildid='
|
|
||||||
STATIC_LDFLAGS='-X "github.com/Dreamacro/clash/constant.Version=$(VERSION)" \
|
|
||||||
-X "github.com/Dreamacro/clash/constant.BuildTime=$(BUILDTIME)" \
|
|
||||||
-extldflags "-static" \
|
|
||||||
-w -s -buildid='
|
|
||||||
|
|
||||||
PLATFORM_LIST = \
|
PLATFORM_LIST = \
|
||||||
darwin-amd64 \
|
darwin-amd64 \
|
||||||
darwin-arm64 \
|
darwin-arm64 \
|
||||||
linux-amd64
|
linux-amd64-compatible \
|
||||||
# linux-arm64
|
linux-amd64 \
|
||||||
# linux-386
|
linux-armv5 \
|
||||||
|
linux-armv6 \
|
||||||
|
linux-armv7 \
|
||||||
|
linux-arm64 \
|
||||||
|
linux-mips64 \
|
||||||
|
linux-mips64le \
|
||||||
|
linux-mips-softfloat \
|
||||||
|
linux-mips-hardfloat \
|
||||||
|
linux-mipsle-softfloat \
|
||||||
|
linux-mipsle-hardfloat \
|
||||||
|
android-arm64 \
|
||||||
|
freebsd-386 \
|
||||||
|
freebsd-amd64 \
|
||||||
|
freebsd-arm64
|
||||||
|
|
||||||
WINDOWS_ARCH_LIST = \
|
WINDOWS_ARCH_LIST = \
|
||||||
|
windows-386 \
|
||||||
|
windows-amd64-compatible \
|
||||||
windows-amd64 \
|
windows-amd64 \
|
||||||
windows-386
|
windows-arm64 \
|
||||||
# windows-arm64
|
windows-arm32v7
|
||||||
|
|
||||||
all: linux-amd64 darwin-amd64 windows-amd64 # Most used
|
all:linux-amd64 linux-arm64\
|
||||||
|
darwin-amd64 darwin-arm64\
|
||||||
|
windows-amd64 windows-arm64\
|
||||||
|
|
||||||
local:
|
docker:
|
||||||
$(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
local-v3:
|
|
||||||
GOAMD64=v3 $(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -tags build_local -o $(BINDIR)/$(NAME)-$@
|
|
||||||
|
|
||||||
darwin-amd64:
|
darwin-amd64:
|
||||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=darwin-10.12/amd64 $(BUILD_PACKAGE) && \
|
GOARCH=amd64 GOOS=darwin GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
mv $(BINDIR)/$(NAME)-darwin-10.12-amd64 $(BINDIR)/$(NAME)-darwin-amd64
|
|
||||||
|
darwin-amd64-compatible:
|
||||||
|
GOARCH=amd64 GOOS=darwin GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
darwin-arm64:
|
darwin-arm64:
|
||||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=darwin-11.1/arm64 $(BUILD_PACKAGE) && \
|
GOARCH=arm64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
mv $(BINDIR)/$(NAME)-darwin-11.1-arm64 $(BINDIR)/$(NAME)-darwin-arm64
|
|
||||||
|
|
||||||
linux-386:
|
linux-386:
|
||||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/386 $(BUILD_PACKAGE)
|
GOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-amd64:
|
linux-amd64:
|
||||||
$(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -o $(BINDIR)/$(NAME)-$@
|
GOARCH=amd64 GOOS=linux GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
#GOARCH=amd64 GOOS=linux $(GOBUILD) -ldflags $(RELEASE_LDFLAGS) -o $(BINDIR)/$(NAME)-$@
|
|
||||||
#$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/amd64 $(BUILD_PACKAGE)
|
linux-amd64-compatible:
|
||||||
|
GOARCH=amd64 GOOS=linux GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
linux-arm64:
|
linux-arm64:
|
||||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(STATIC_LDFLAGS) -targets=linux/arm64 $(BUILD_PACKAGE)
|
GOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-armv5:
|
||||||
|
GOARCH=arm GOOS=linux GOARM=5 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-armv6:
|
||||||
|
GOARCH=arm GOOS=linux GOARM=6 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-armv7:
|
||||||
|
GOARCH=arm GOOS=linux GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips-softfloat:
|
||||||
|
GOARCH=mips GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips-hardfloat:
|
||||||
|
GOARCH=mips GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mipsle-softfloat:
|
||||||
|
GOARCH=mipsle GOMIPS=softfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mipsle-hardfloat:
|
||||||
|
GOARCH=mipsle GOMIPS=hardfloat GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips64:
|
||||||
|
GOARCH=mips64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
linux-mips64le:
|
||||||
|
GOARCH=mips64le GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
android-arm64:
|
||||||
|
GOARCH=arm64 GOOS=android $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-386:
|
||||||
|
GOARCH=386 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-amd64:
|
||||||
|
GOARCH=amd64 GOOS=freebsd GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
|
freebsd-arm64:
|
||||||
|
GOARCH=arm64 GOOS=freebsd $(GOBUILD) -o $(BINDIR)/$(NAME)-$@
|
||||||
|
|
||||||
windows-386:
|
windows-386:
|
||||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows-6.0/386 $(BUILD_PACKAGE) && \
|
GOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
mv $(BINDIR)/$(NAME)-windows-6.0-386.exe $(BINDIR)/$(NAME)-windows-386.exe
|
|
||||||
|
|
||||||
windows-amd64:
|
windows-amd64:
|
||||||
$(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows-6.0/amd64 $(BUILD_PACKAGE) && \
|
GOARCH=amd64 GOOS=windows GOAMD64=v3 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
mv $(BINDIR)/$(NAME)-windows-6.0-amd64.exe $(BINDIR)/$(NAME)-windows-amd64.exe
|
|
||||||
|
|
||||||
#windows-arm64:
|
windows-amd64-compatible:
|
||||||
# $(XGOCMD) -dest=$(BINDIR) -out=$(NAME) -trimpath=true -ldflags=$(RELEASE_LDFLAGS) -targets=windows/arm64 $(BUILD_PACKAGE)
|
GOARCH=amd64 GOOS=windows GOAMD64=v2 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
# mv $(NAME)-windows-4.0-arm64.exe $(NAME)-windows-arm64.exe
|
|
||||||
|
windows-arm64:
|
||||||
|
GOARCH=arm64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
|
windows-arm32v7:
|
||||||
|
GOARCH=arm GOOS=windows GOARM=7 $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe
|
||||||
|
|
||||||
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
gz_releases=$(addsuffix .gz, $(PLATFORM_LIST))
|
||||||
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
zip_releases=$(addsuffix .zip, $(WINDOWS_ARCH_LIST))
|
||||||
@ -81,17 +140,18 @@ all-arch: $(PLATFORM_LIST) $(WINDOWS_ARCH_LIST)
|
|||||||
releases: $(gz_releases) $(zip_releases)
|
releases: $(gz_releases) $(zip_releases)
|
||||||
|
|
||||||
vet:
|
vet:
|
||||||
$(GOCMD) test -tags build_local ./...
|
go test ./...
|
||||||
|
|
||||||
lint:
|
lint:
|
||||||
golangci-lint run --build-tags=build_local ./...
|
golangci-lint run ./...
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf $(BINDIR)/
|
rm $(BINDIR)/*
|
||||||
mkdir -p $(BINDIR)
|
|
||||||
|
|
||||||
cleancache:
|
CLANG ?= clang-14
|
||||||
# go build cache may need to cleanup if changing C source code
|
CFLAGS := -O2 -g -Wall -Werror $(CFLAGS)
|
||||||
$(GOCLEAN) -cache
|
|
||||||
rm -rf $(BINDIR)/
|
ebpf: export BPF_CLANG := $(CLANG)
|
||||||
mkdir -p $(BINDIR)
|
ebpf: export BPF_CFLAGS := $(CFLAGS)
|
||||||
|
ebpf:
|
||||||
|
cd component/ebpf/ && go generate ./...
|
519
README.md
519
README.md
@ -1,23 +1,20 @@
|
|||||||
<h1 align="center">
|
<h1 align="center">
|
||||||
<img src="https://github.com/Dreamacro/clash/raw/master/docs/logo.png" alt="Clash" width="200">
|
<img src="Meta.png" alt="Meta Kennel" width="200">
|
||||||
<br>Clash<br>
|
<br>Meta Kernel<br>
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<h4 align="center">A rule-based tunnel in Go.</h4>
|
<h3 align="center">Another Clash Kernel.</h3>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/Dreamacro/clash/actions">
|
<a href="https://goreportcard.com/report/github.com/Clash-Mini/Clash.Meta">
|
||||||
<img src="https://img.shields.io/github/workflow/status/Dreamacro/clash/Go?style=flat-square" alt="Github Actions">
|
<img src="https://goreportcard.com/badge/github.com/Clash-Mini/Clash.Meta?style=flat-square">
|
||||||
</a>
|
|
||||||
<a href="https://goreportcard.com/report/github.com/Dreamacro/clash">
|
|
||||||
<img src="https://goreportcard.com/badge/github.com/Dreamacro/clash?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/Dreamacro/clash?style=flat-square">
|
||||||
<a href="https://github.com/Dreamacro/clash/releases">
|
<a href="https://github.com/Clash-Mini/Clash.Meta/releases">
|
||||||
<img src="https://img.shields.io/github/release/Dreamacro/clash/all.svg?style=flat-square">
|
<img src="https://img.shields.io/github/release/Clash-Mini/Clash.Meta/all.svg?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
<a href="https://github.com/Dreamacro/clash/releases/tag/premium">
|
<a href="https://github.com/Clash-Mini/Clash.Meta">
|
||||||
<img src="https://img.shields.io/badge/release-Premium-00b4f0?style=flat-square">
|
<img src="https://img.shields.io/badge/release-Meta-00b4f0?style=flat-square">
|
||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@ -36,194 +33,85 @@
|
|||||||
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
Documentations are now moved to [GitHub Wiki](https://github.com/Dreamacro/clash/wiki).
|
||||||
|
|
||||||
## Advanced usage for this branch
|
## Advanced usage for this branch
|
||||||
### Build
|
|
||||||
This branch requires cgo and Python3.9, so make sure you set up Python3.9 before building.
|
|
||||||
|
|
||||||
For example, build on macOS:
|
|
||||||
```sh
|
|
||||||
brew update
|
|
||||||
brew install python@3.9
|
|
||||||
|
|
||||||
export PKG_CONFIG_PATH=$(find /usr/local/Cellar -name 'pkgconfig' -type d | grep lib/pkgconfig | tr '\n' ':' | sed s/.$//)
|
|
||||||
|
|
||||||
git clone -b plus-pro https://github.com/yaling888/clash.git
|
|
||||||
cd clash
|
|
||||||
|
|
||||||
# build
|
|
||||||
make local
|
|
||||||
# or make local-v3
|
|
||||||
|
|
||||||
ls bin/
|
|
||||||
|
|
||||||
# run
|
|
||||||
sudo bin/clash-local
|
|
||||||
```
|
|
||||||
|
|
||||||
### General configuration
|
|
||||||
```yaml
|
|
||||||
sniffing: true # Sniff TLS SNI
|
|
||||||
|
|
||||||
force-cert-verify: true # force verify TLS Certificate, prevent machine-in-the-middle attacks
|
|
||||||
```
|
|
||||||
|
|
||||||
### MITM configuration
|
|
||||||
A root CA certificate is required, the
|
|
||||||
MITM proxy server will generate a CA certificate file and a CA private key file in your Clash home directory, you can use your own certificate replace it.
|
|
||||||
|
|
||||||
Need to install and trust the CA certificate on the client device, open this URL [http://mitm.clash/cert.crt](http://mitm.clash/cert.crt) by the web browser to install the CA certificate, the host name 'mitm.clash' was always been hijacked.
|
|
||||||
|
|
||||||
NOTE: this feature cannot work on tls pinning
|
|
||||||
|
|
||||||
WARNING: DO NOT USE THIS FEATURE TO BREAK LOCAL LAWS
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
# Port of MITM proxy server on the local end
|
|
||||||
mitm-port: 7894
|
|
||||||
|
|
||||||
# Man-In-The-Middle attack
|
|
||||||
mitm:
|
|
||||||
hosts: # use for others proxy type. E.g: TUN, socks
|
|
||||||
- +.example.com
|
|
||||||
rules: # rewrite rules
|
|
||||||
- '^https?://www\.example\.com/1 url reject' # The "reject" returns HTTP status code 404 with no content.
|
|
||||||
- '^https?://www\.example\.com/2 url reject-200' # The "reject-200" returns HTTP status code 200 with no content.
|
|
||||||
- '^https?://www\.example\.com/3 url reject-img' # The "reject-img" returns HTTP status code 200 with content of 1px png.
|
|
||||||
- '^https?://www\.example\.com/4 url reject-dict' # The "reject-dict" returns HTTP status code 200 with content of empty json object.
|
|
||||||
- '^https?://www\.example\.com/5 url reject-array' # The "reject-array" returns HTTP status code 200 with content of empty json array.
|
|
||||||
- '^https?://www\.example\.com/(6) url 302 https://www.example.com/new-$1'
|
|
||||||
- '^https?://www\.(example)\.com/7 url 307 https://www.$1.com/new-7'
|
|
||||||
- '^https?://www\.example\.com/8 url request-header (\r\n)User-Agent:.+(\r\n) request-header $1User-Agent: haha-wriohoh$2' # The "request-header" works for all the http headers not just one single header, so you can match two or more headers including CRLF in one regular expression.
|
|
||||||
- '^https?://www\.example\.com/9 url request-body "pos_2":\[.*\],"pos_3" request-body "pos_2":[{"xx": "xx"}],"pos_3"'
|
|
||||||
- '^https?://www\.example\.com/10 url response-header (\r\n)Tracecode:.+(\r\n) response-header $1Tracecode: 88888888888$2'
|
|
||||||
- '^https?://www\.example\.com/11 url response-body "errmsg":"ok" response-body "errmsg":"not-ok"'
|
|
||||||
```
|
|
||||||
|
|
||||||
### DNS configuration
|
### DNS configuration
|
||||||
Support resolve ip with a proxy tunnel or interface.
|
|
||||||
|
|
||||||
Support `geosite` with `fallback-filter`.
|
Support `geosite` with `fallback-filter`.
|
||||||
|
|
||||||
Use `curl -X POST controllerip:port/cache/fakeip/flush` to flush persistence fakeip
|
Restore `Redir remote resolution`.
|
||||||
```yaml
|
|
||||||
dns:
|
Support resolve ip with a `Proxy Tunnel`.
|
||||||
enable: true
|
|
||||||
use-hosts: true
|
```yaml
|
||||||
ipv6: false
|
proxy-groups:
|
||||||
enhanced-mode: fake-ip
|
|
||||||
fake-ip-range: 198.18.0.1/16
|
- name: DNS
|
||||||
listen: 127.0.0.1:6868
|
type: url-test
|
||||||
default-nameserver:
|
use:
|
||||||
- 119.29.29.29
|
- HK
|
||||||
- 114.114.114.114
|
url: http://cp.cloudflare.com
|
||||||
nameserver:
|
interval: 180
|
||||||
- https://doh.pub/dns-query
|
lazy: true
|
||||||
- tls://223.5.5.5:853
|
```
|
||||||
fallback:
|
```yaml
|
||||||
- 'tls://8.8.4.4:853#proxy or interface'
|
dns:
|
||||||
- 'https://1.0.0.1/dns-query#Proxy' # append the proxy adapter name to the end of DNS URL with '#' prefix.
|
enable: true
|
||||||
fallback-filter:
|
use-hosts: true
|
||||||
geoip: false
|
ipv6: false
|
||||||
geosite:
|
enhanced-mode: redir-host
|
||||||
- gfw # `geosite` filter only use fallback server to resolve ip, prevent DNS leaks to untrusted DNS providers.
|
fake-ip-range: 198.18.0.1/16
|
||||||
domain:
|
listen: 127.0.0.1:6868
|
||||||
- +.example.com
|
default-nameserver:
|
||||||
ipcidr:
|
- 119.29.29.29
|
||||||
- 0.0.0.0/32
|
- 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
|
### TUN configuration
|
||||||
Simply add the following to the main configuration:
|
|
||||||
|
|
||||||
#### NOTE:
|
Supports macOS, Linux and Windows.
|
||||||
> auto-route and auto-detect-interface only available on macOS, Windows and Linux, receive IPv4 traffic
|
|
||||||
|
Built-in [Wintun](https://www.wintun.net) driver.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
# Enable the TUN listener
|
||||||
tun:
|
tun:
|
||||||
enable: true
|
enable: true
|
||||||
stack: system # or gvisor
|
stack: gvisor # only gvisor
|
||||||
# device: tun://utun8 # or fd://xxx, it's optional
|
|
||||||
# dns-hijack:
|
|
||||||
# - 8.8.8.8:53
|
|
||||||
# - tcp://8.8.8.8:53
|
|
||||||
# - any:53
|
|
||||||
# - tcp://any:53
|
|
||||||
auto-route: true # auto set global route
|
|
||||||
auto-detect-interface: true # conflict with interface-name
|
|
||||||
```
|
|
||||||
or
|
|
||||||
```yaml
|
|
||||||
interface-name: en0
|
|
||||||
|
|
||||||
tun:
|
|
||||||
enable: true
|
|
||||||
stack: system # or gvisor
|
|
||||||
# dns-hijack:
|
|
||||||
# - 8.8.8.8:53
|
|
||||||
# - tcp://8.8.8.8:53
|
|
||||||
auto-route: true # auto set global route
|
|
||||||
```
|
|
||||||
It's recommended to use fake-ip mode for the DNS server.
|
|
||||||
|
|
||||||
Clash needs elevated permission to create TUN device:
|
|
||||||
```sh
|
|
||||||
$ sudo ./clash
|
|
||||||
```
|
|
||||||
Then manually create the default route and DNS server. If your device already has some TUN device, Clash TUN might not work. In this case, fake-ip-filter may helpful.
|
|
||||||
|
|
||||||
Enjoy! :)
|
|
||||||
|
|
||||||
#### For Windows:
|
|
||||||
```yaml
|
|
||||||
tun:
|
|
||||||
enable: true
|
|
||||||
stack: gvisor # or system
|
|
||||||
dns-hijack:
|
dns-hijack:
|
||||||
- 198.18.0.2:53 # when `fake-ip-range` is 198.18.0.1/16, should hijack 198.18.0.2:53
|
- 0.0.0.0:53 # additional dns server listen on TUN
|
||||||
auto-route: true # auto set global route for Windows
|
auto-route: true # auto set global route
|
||||||
# It is recommended to use `interface-name`
|
|
||||||
auto-detect-interface: true # auto detect interface, conflict with `interface-name`
|
|
||||||
```
|
```
|
||||||
Finally, open the Clash
|
|
||||||
|
|
||||||
### Rules configuration
|
### Rules configuration
|
||||||
- Support rule `GEOSITE`.
|
- Support rule `GEOSITE`.
|
||||||
- Support rule `USER-AGENT`.
|
- Support rule-providers `RULE-SET`.
|
||||||
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
- Support `multiport` condition for rule `SRC-PORT` and `DST-PORT`.
|
||||||
- Support `network` condition for all rules.
|
- Support `network` condition for all rules.
|
||||||
- Support `process` condition for all rules.
|
|
||||||
- Support source IPCIDR condition for all rules, just append to the end.
|
- Support source IPCIDR condition for all rules, just append to the end.
|
||||||
|
- The `GEOSITE` databases via https://github.com/Loyalsoldier/v2ray-rules-dat.
|
||||||
The `GEOIP` databases via [https://github.com/Loyalsoldier/geoip](https://raw.githubusercontent.com/Loyalsoldier/geoip/release/Country.mmdb).
|
|
||||||
|
|
||||||
The `GEOSITE` databases via [https://github.com/Loyalsoldier/v2ray-rules-dat](https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat).
|
|
||||||
```yaml
|
```yaml
|
||||||
mode: rule
|
|
||||||
|
|
||||||
script:
|
|
||||||
shortcuts:
|
|
||||||
quic: 'network == "udp" and dst_port == 443'
|
|
||||||
privacy: '"analytics" in host or "adservice" in host or "firebase" in host or "safebrowsing" in host or "doubleclick" in host'
|
|
||||||
BilibiliUdp: |
|
|
||||||
network == "udp" and match_provider("geosite:bilibili")
|
|
||||||
rules:
|
rules:
|
||||||
# rule SCRIPT shortcuts
|
|
||||||
- SCRIPT,quic,REJECT # Disable QUIC, same as rule "DST-PORT,443,REJECT,udp"
|
|
||||||
- SCRIPT,privacy,REJECT
|
|
||||||
- SCRIPT,BilibiliUdp,REJECT # same as rule "GEOSITE,bilibili,REJECT,udp"
|
|
||||||
|
|
||||||
# network condition for all rules
|
# network(tcp/udp) condition for all rules
|
||||||
- DOMAIN-SUFFIX,example.com,DIRECT,tcp
|
- DOMAIN-SUFFIX,bilibili.com,DIRECT,tcp
|
||||||
- DOMAIN-SUFFIX,example.com,REJECT,udp
|
- DOMAIN-SUFFIX,bilibili.com,REJECT,udp
|
||||||
|
|
||||||
# process condition for all rules (add 'P:' prefix)
|
|
||||||
- DOMAIN-SUFFIX,example.com,REJECT,P:Google Chrome Helper
|
|
||||||
|
|
||||||
# multiport condition for rules SRC-PORT and DST-PORT
|
# multiport condition for rules SRC-PORT and DST-PORT
|
||||||
- DST-PORT,123/136/137-139,DIRECT,udp
|
- DST-PORT,123/136/137-139,DIRECT,udp
|
||||||
|
|
||||||
# USER-AGENT payload cannot include the comma character, '*' meaning any character.
|
|
||||||
- USER-AGENT,*example*,PROXY
|
|
||||||
|
|
||||||
# rule GEOSITE
|
# rule GEOSITE
|
||||||
- GEOSITE,category-ads-all,REJECT
|
- GEOSITE,category-ads-all,REJECT
|
||||||
- GEOSITE,icloud@cn,DIRECT
|
- GEOSITE,icloud@cn,DIRECT
|
||||||
@ -239,178 +127,89 @@ rules:
|
|||||||
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
#- GEOSITE,geolocation-!cn,REJECT,192.168.1.88/32,192.168.1.99/32
|
||||||
|
|
||||||
- GEOIP,telegram,PROXY,no-resolve
|
- GEOIP,telegram,PROXY,no-resolve
|
||||||
- GEOIP,lan,DIRECT,no-resolve
|
- GEOIP,private,DIRECT,no-resolve
|
||||||
- GEOIP,cn,DIRECT
|
- GEOIP,cn,DIRECT
|
||||||
|
|
||||||
- MATCH,PROXY
|
- MATCH,PROXY
|
||||||
```
|
```
|
||||||
|
|
||||||
### Script configuration
|
|
||||||
Script enables users to programmatically select a policy for the packets with more flexibility.
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
mode: script
|
|
||||||
|
|
||||||
script:
|
|
||||||
# path: ./script.star
|
|
||||||
code: |
|
|
||||||
def main(ctx, metadata):
|
|
||||||
if metadata["process_name"] == 'apsd':
|
|
||||||
return "DIRECT"
|
|
||||||
|
|
||||||
if metadata["network"] == 'udp' and metadata["dst_port"] == 443:
|
|
||||||
return "REJECT"
|
|
||||||
|
|
||||||
host = metadata["host"]
|
|
||||||
for kw in ['analytics', 'adservice', 'firebase', 'bugly', 'safebrowsing', 'doubleclick']:
|
|
||||||
if kw in host:
|
|
||||||
return "REJECT"
|
|
||||||
|
|
||||||
now = time.now()
|
|
||||||
if (now.hour < 8 or now.hour > 17) and metadata["src_ip"] == '192.168.1.99':
|
|
||||||
return "REJECT"
|
|
||||||
|
|
||||||
if ctx.rule_providers["geosite:category-ads-all"].match(metadata):
|
|
||||||
return "REJECT"
|
|
||||||
|
|
||||||
if ctx.rule_providers["geosite:youtube"].match(metadata):
|
|
||||||
ctx.log('[Script] domain %s matched youtube' % host)
|
|
||||||
return "Proxy"
|
|
||||||
|
|
||||||
if ctx.rule_providers["geosite:geolocation-cn"].match(metadata):
|
|
||||||
ctx.log('[Script] domain %s matched geolocation-cn' % host)
|
|
||||||
return "DIRECT"
|
|
||||||
|
|
||||||
ip = metadata["dst_ip"]
|
|
||||||
if host != "":
|
|
||||||
ip = ctx.resolve_ip(host)
|
|
||||||
if ip == "":
|
|
||||||
return "Proxy"
|
|
||||||
|
|
||||||
code = ctx.geoip(ip)
|
|
||||||
if code == "LAN" or code == "CN":
|
|
||||||
return "DIRECT"
|
|
||||||
|
|
||||||
return "Proxy" # default policy for requests which are not matched by any other script
|
|
||||||
```
|
|
||||||
the context and metadata
|
|
||||||
```ts
|
|
||||||
interface Metadata {
|
|
||||||
type: string // socks5、http
|
|
||||||
network: string // tcp
|
|
||||||
host: string
|
|
||||||
process_name: string
|
|
||||||
process_path: string
|
|
||||||
src_ip: string
|
|
||||||
src_port: int
|
|
||||||
dst_ip: string
|
|
||||||
dst_port: int
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Context {
|
|
||||||
resolve_ip: (host: string) => string // ip string
|
|
||||||
geoip: (ip: string) => string // country code
|
|
||||||
log: (log: string) => void
|
|
||||||
rule_providers: Record<string, { match: (metadata: Metadata) => boolean }>
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Proxies configuration
|
### Proxies configuration
|
||||||
Support outbound protocol `VLESS`.
|
|
||||||
|
|
||||||
Support `Trojan` with XTLS.
|
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 relay `UDP` traffic.
|
Support `Policy Group Filter`
|
||||||
|
|
||||||
Support filtering proxy providers in proxy groups.
|
|
||||||
|
|
||||||
Support custom http request header, prefix name and V2Ray subscription URL in proxy providers.
|
|
||||||
```yaml
|
```yaml
|
||||||
proxies:
|
|
||||||
# VLESS
|
|
||||||
- name: "vless-tls"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
network: tcp
|
|
||||||
servername: example.com
|
|
||||||
udp: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
- name: "vless-xtls"
|
|
||||||
type: vless
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
uuid: uuid
|
|
||||||
network: tcp
|
|
||||||
servername: example.com
|
|
||||||
flow: xtls-rprx-direct # or xtls-rprx-origin
|
|
||||||
# flow-show: true # print the XTLS direction log
|
|
||||||
# udp: true
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
# Trojan
|
|
||||||
- name: "trojan-xtls"
|
|
||||||
type: trojan
|
|
||||||
server: server
|
|
||||||
port: 443
|
|
||||||
password: yourpsk
|
|
||||||
network: tcp
|
|
||||||
flow: xtls-rprx-direct # or xtls-rprx-origin
|
|
||||||
# flow-show: true # print the XTLS direction log
|
|
||||||
# udp: true
|
|
||||||
# sni: example.com # aka server name
|
|
||||||
# skip-cert-verify: true
|
|
||||||
|
|
||||||
proxy-groups:
|
proxy-groups:
|
||||||
# Relay chains the proxies. proxies shall not contain a relay.
|
|
||||||
# Support relay UDP traffic.
|
|
||||||
# Traffic: clash <-> ss1 <-> trojan <-> vmess <-> ss2 <-> Internet
|
|
||||||
- name: "relay-udp-over-tcp"
|
|
||||||
type: relay
|
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- trojan
|
|
||||||
- vmess
|
|
||||||
- ss2
|
|
||||||
|
|
||||||
- name: "relay-raw-udp"
|
- name: 🚀 HK Group
|
||||||
type: relay
|
type: select
|
||||||
proxies:
|
|
||||||
- ss1
|
|
||||||
- ss2
|
|
||||||
- ss3
|
|
||||||
|
|
||||||
- name: "filtering-proxy-providers"
|
|
||||||
type: url-test
|
|
||||||
url: "http://www.gstatic.com/generate_204"
|
|
||||||
interval: 300
|
|
||||||
tolerance: 200
|
|
||||||
# lazy: true
|
|
||||||
filter: "XXX" # a regular expression
|
|
||||||
use:
|
use:
|
||||||
- provider1
|
- ALL
|
||||||
|
filter: 'HK'
|
||||||
|
|
||||||
|
- name: 🚀 US Group
|
||||||
|
type: select
|
||||||
|
use:
|
||||||
|
- ALL
|
||||||
|
filter: 'US'
|
||||||
|
|
||||||
proxy-providers:
|
proxy-providers:
|
||||||
provider1:
|
ALL:
|
||||||
type: http
|
type: http
|
||||||
url: "url" # support V2Ray subscription URL
|
url: "xxxxx"
|
||||||
interval: 3600
|
interval: 3600
|
||||||
path: ./providers/provider1.yaml
|
path: "xxxxx"
|
||||||
# filter: "xxx"
|
|
||||||
# prefix-name: "XXX-"
|
|
||||||
header: # custom http request header
|
|
||||||
User-Agent:
|
|
||||||
- "Clash/v1.10.6"
|
|
||||||
# Accept:
|
|
||||||
# - 'application/vnd.github.v3.raw'
|
|
||||||
# Authorization:
|
|
||||||
# - ' token xxxxxxxxxxx'
|
|
||||||
health-check:
|
health-check:
|
||||||
enable: false
|
enable: true
|
||||||
interval: 1200
|
interval: 600
|
||||||
# lazy: false # default value is true
|
|
||||||
url: http://www.gstatic.com/generate_204
|
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
|
||||||
@ -424,61 +223,73 @@ iptables:
|
|||||||
enable: true # default is false
|
enable: true # default is false
|
||||||
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
inbound-interface: eth0 # detect the inbound interface, default is 'lo'
|
||||||
```
|
```
|
||||||
Run Clash as a daemon.
|
|
||||||
|
|
||||||
Create the systemd configuration file at /etc/systemd/system/clash.service:
|
|
||||||
```sh
|
### General installation guide for Linux
|
||||||
|
+ Create user given name `clash-meta`
|
||||||
|
|
||||||
|
+ 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]
|
[Unit]
|
||||||
Description=Clash daemon, A rule-based proxy in Go.
|
Description=Clash-Meta Daemon, Another Clash Kernel.
|
||||||
After=network.target
|
After=network.target NetworkManager.service systemd-networkd.service iwd.service
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
CapabilityBoundingSet=cap_net_admin
|
User=clash-meta
|
||||||
|
Group=clash-meta
|
||||||
|
LimitNPROC=500
|
||||||
|
LimitNOFILE=1000000
|
||||||
|
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
||||||
|
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_RAW CAP_NET_BIND_SERVICE
|
||||||
Restart=always
|
Restart=always
|
||||||
ExecStart=/usr/local/bin/clash -d /etc/clash
|
ExecStartPre=/usr/bin/sleep 1s
|
||||||
|
ExecStart=/usr/local/bin/Clash-Meta -d /etc/Clash-Meta
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
```
|
```
|
||||||
Launch clashd on system startup with:
|
Launch clashd on system startup with:
|
||||||
```sh
|
```shell
|
||||||
$ systemctl enable clash
|
$ systemctl enable Clash-Meta
|
||||||
```
|
```
|
||||||
Launch clashd immediately with:
|
Launch clashd immediately with:
|
||||||
```sh
|
|
||||||
$ systemctl start clash
|
```shell
|
||||||
|
$ systemctl start Clash-Meta
|
||||||
```
|
```
|
||||||
|
|
||||||
### Display Process name
|
### Display Process name
|
||||||
To display process name online by click [http://yacd.clash-plus.cf](http://yacd.clash-plus.cf) for local API by Safari or [https://yacd.clash-plus.cf](https://yacd.clash-plus.cf) for local API by Chrome.
|
|
||||||
|
|
||||||
You can download the [Dashboard](https://github.com/yaling888/yacd/archive/gh-pages.zip) into Clash home directory:
|
Clash add field `Process` to `Metadata` and prepare to get process name for Restful API `GET /connections`.
|
||||||
```sh
|
|
||||||
$ cd ~/.config/clash
|
|
||||||
$ curl -LJ https://github.com/yaling888/yacd/archive/gh-pages.zip -o yacd-gh-pages.zip
|
|
||||||
$ unzip yacd-gh-pages.zip
|
|
||||||
$ mv yacd-gh-pages dashboard
|
|
||||||
```
|
|
||||||
|
|
||||||
Add to config file:
|
To display process name in GUI please use [Dashboard For Meta](https://github.com/MetaCubeX/clash-dashboard).
|
||||||
```yaml
|
|
||||||
external-controller: 127.0.0.1:9090
|
|
||||||
external-ui: dashboard
|
|
||||||
```
|
|
||||||
Open [http://127.0.0.1:9090/ui/](http://127.0.0.1:9090/ui/) by web browser.
|
|
||||||
|
|
||||||
## Plus Pro Release
|

|
||||||
[Release](https://github.com/yaling888/clash/releases/tag/plus_pro)
|
|
||||||
|
|
||||||
## Development
|
## 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)
|
|
||||||
|
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)
|
||||||
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
* [riobard/go-shadowsocks2](https://github.com/riobard/go-shadowsocks2)
|
||||||
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
* [v2ray/v2ray-core](https://github.com/v2ray/v2ray-core)
|
||||||
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
* [WireGuard/wireguard-go](https://github.com/WireGuard/wireguard-go)
|
||||||
|
* [yaling888/clash-plus-pro](https://github.com/yaling888/clash)
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -4,19 +4,20 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/queue"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"net/url"
|
"net/url"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/queue"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
|
|
||||||
"go.uber.org/atomic"
|
"go.uber.org/atomic"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var UnifiedDelay = atomic.NewBool(false)
|
||||||
|
|
||||||
type Proxy struct {
|
type Proxy struct {
|
||||||
C.ProxyAdapter
|
C.ProxyAdapter
|
||||||
history *queue.Queue[C.DelayHistory]
|
history *queue.Queue[C.DelayHistory]
|
||||||
@ -38,7 +39,6 @@ func (p *Proxy) Dial(metadata *C.Metadata) (C.Conn, error) {
|
|||||||
// 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, opts ...dialer.Option) (C.Conn, error) {
|
||||||
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
conn, err := p.ProxyAdapter.DialContext(ctx, metadata, opts...)
|
||||||
p.alive.Store(err == nil)
|
|
||||||
return conn, err
|
return conn, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -52,7 +52,6 @@ func (p *Proxy) DialUDP(metadata *C.Metadata) (C.PacketConn, error) {
|
|||||||
// 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, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
pc, err := p.ProxyAdapter.ListenPacketContext(ctx, metadata, opts...)
|
||||||
p.alive.Store(err == nil)
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -111,6 +110,8 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
unifiedDelay := UnifiedDelay.Load()
|
||||||
|
|
||||||
addr, err := urlToMetadata(url)
|
addr, err := urlToMetadata(url)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
@ -143,18 +144,32 @@ func (p *Proxy) URLTest(ctx context.Context, url string) (t uint16, err error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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()
|
_ = resp.Body.Close()
|
||||||
|
|
||||||
|
if unifiedDelay {
|
||||||
|
second := time.Now()
|
||||||
|
resp, err = client.Do(req)
|
||||||
|
if err == nil {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
start = second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
t = uint16(time.Since(start) / time.Millisecond)
|
t = uint16(time.Since(start) / time.Millisecond)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
// 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) *context.ConnContext {
|
||||||
metadata := parseHTTPAddr(request)
|
metadata := parseHTTPAddr(request)
|
||||||
metadata.Type = C.HTTPCONNECT
|
metadata.Type = C.HTTPS
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
||||||
metadata.SrcIP = ip
|
metadata.SrcIP = ip
|
||||||
metadata.SrcPort = port
|
metadata.SrcPort = port
|
||||||
|
@ -1,22 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/context"
|
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// NewMitm receive mitm request and return MitmContext
|
|
||||||
func NewMitm(target socks5.Addr, source net.Addr, userAgent string, conn net.Conn) *context.ConnContext {
|
|
||||||
metadata := parseSocksAddr(target)
|
|
||||||
metadata.NetWork = C.TCP
|
|
||||||
metadata.Type = C.MITM
|
|
||||||
metadata.UserAgent = userAgent
|
|
||||||
if ip, port, err := parseAddr(source.String()); err == nil {
|
|
||||||
metadata.SrcIP = ip
|
|
||||||
metadata.SrcPort = port
|
|
||||||
}
|
|
||||||
return context.NewConnContext(conn, metadata)
|
|
||||||
}
|
|
@ -2,6 +2,7 @@ package inbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/context"
|
"github.com/Dreamacro/clash/context"
|
||||||
@ -13,9 +14,37 @@ func NewSocket(target socks5.Addr, conn net.Conn, source C.Type) *context.ConnCo
|
|||||||
metadata := parseSocksAddr(target)
|
metadata := parseSocksAddr(target)
|
||||||
metadata.NetWork = C.TCP
|
metadata.NetWork = C.TCP
|
||||||
metadata.Type = source
|
metadata.Type = source
|
||||||
if ip, port, err := parseAddr(conn.RemoteAddr().String()); err == nil {
|
remoteAddr := conn.RemoteAddr()
|
||||||
metadata.SrcIP = ip
|
// Filter when net.Addr interface is nil
|
||||||
metadata.SrcPort = port
|
if remoteAddr != nil {
|
||||||
|
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)
|
return context.NewConnContext(conn, metadata)
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
package inbound
|
package inbound
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"github.com/Dreamacro/clash/common/nnip"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/nnip"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
@ -26,7 +26,8 @@ func parseSocksAddr(target socks5.Addr) *C.Metadata {
|
|||||||
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
metadata.DstIP = nnip.IpToAddr(net.IP(target[1 : 1+net.IPv4len]))
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv4len]) << 8) | int(target[1+net.IPv4len+1]))
|
metadata.DstPort = strconv.Itoa((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]))
|
ip6, _ := netip.AddrFromSlice(target[1 : 1+net.IPv6len])
|
||||||
|
metadata.DstIP = ip6.Unmap()
|
||||||
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
metadata.DstPort = strconv.Itoa((int(target[1+net.IPv6len]) << 8) | int(target[1+net.IPv6len+1]))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -4,20 +4,23 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"github.com/gofrs/uuid"
|
||||||
"net"
|
"net"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Base struct {
|
type Base struct {
|
||||||
name string
|
name string
|
||||||
addr string
|
addr string
|
||||||
iface string
|
iface string
|
||||||
tp C.AdapterType
|
tp C.AdapterType
|
||||||
udp bool
|
udp bool
|
||||||
rmark int
|
rmark int
|
||||||
|
id string
|
||||||
|
prefer C.DNSPrefer
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name implements C.ProxyAdapter
|
// Name implements C.ProxyAdapter
|
||||||
@ -25,26 +28,49 @@ func (b *Base) Name() string {
|
|||||||
return b.name
|
return b.name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Id implements C.ProxyAdapter
|
||||||
|
func (b *Base) Id() string {
|
||||||
|
if b.id == "" {
|
||||||
|
id, err := uuid.NewV6()
|
||||||
|
if err != nil {
|
||||||
|
b.id = b.name
|
||||||
|
} else {
|
||||||
|
b.id = id.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
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (b *Base) StreamConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
func (b *Base) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
return c, errors.New("no support")
|
return c, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
func (b *Base) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
func (b *Base) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
return nil, errors.New("no support")
|
||||||
return c, errors.New("no support")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (b *Base) ListenPacketContext(_ context.Context, _ *C.Metadata, _ ...dialer.Option) (C.PacketConn, error) {
|
func (b *Base) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return nil, errors.New("no support")
|
return nil, errors.New("no support")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
func (b *Base) SupportUOT() bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// SupportUDP implements C.ProxyAdapter
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (b *Base) SupportUDP() bool {
|
func (b *Base) SupportUDP() bool {
|
||||||
return b.udp
|
return b.udp
|
||||||
@ -54,6 +80,7 @@ func (b *Base) SupportUDP() bool {
|
|||||||
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(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -63,7 +90,7 @@ func (b *Base) Addr() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (b *Base) Unwrap(_ *C.Metadata) C.Proxy {
|
func (b *Base) Unwrap(metadata *C.Metadata) C.Proxy {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -77,12 +104,25 @@ 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:
|
||||||
|
}
|
||||||
|
|
||||||
return opts
|
return opts
|
||||||
}
|
}
|
||||||
|
|
||||||
type BasicOption struct {
|
type BasicOption struct {
|
||||||
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
Interface string `proxy:"interface-name,omitempty" group:"interface-name,omitempty"`
|
||||||
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
RoutingMark int `proxy:"routing-mark,omitempty" group:"routing-mark,omitempty"`
|
||||||
|
IPVersion string `proxy:"ip-version,omitempty" group:"ip-version,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaseOption struct {
|
type BaseOption struct {
|
||||||
@ -92,22 +132,29 @@ type BaseOption struct {
|
|||||||
UDP bool
|
UDP 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,
|
iface: opt.Interface,
|
||||||
rmark: opt.RoutingMark,
|
rmark: opt.RoutingMark,
|
||||||
|
prefer: opt.Prefer,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
actualRemoteDestination string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *conn) RemoteDestination() string {
|
||||||
|
return c.actualRemoteDestination
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@ -121,12 +168,17 @@ func (c *conn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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()}}
|
return &conn{c, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
type packetConn struct {
|
type packetConn struct {
|
||||||
net.PacketConn
|
net.PacketConn
|
||||||
chain C.Chain
|
chain C.Chain
|
||||||
|
actualRemoteDestination string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *packetConn) RemoteDestination() string {
|
||||||
|
return c.actualRemoteDestination
|
||||||
}
|
}
|
||||||
|
|
||||||
// Chains implements C.Connection
|
// Chains implements C.Connection
|
||||||
@ -139,40 +191,18 @@ func (c *packetConn) AppendToChains(a C.ProxyAdapter) {
|
|||||||
c.chain = append(c.chain, a.Name())
|
c.chain = append(c.chain, a.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
func newPacketConn(pc net.PacketConn, a C.ProxyAdapter) C.PacketConn {
|
||||||
return &packetConn{pc, []string{a.Name()}}
|
return &packetConn{pc, []string{a.Name()}, parseRemoteDestination(a.Addr())}
|
||||||
}
|
}
|
||||||
|
|
||||||
type wrapConn struct {
|
func parseRemoteDestination(addr string) string {
|
||||||
net.PacketConn
|
if dst, _, err := net.SplitHostPort(addr); err == nil {
|
||||||
}
|
return dst
|
||||||
|
} else {
|
||||||
func (*wrapConn) Read([]byte) (int, error) {
|
if addrError, ok := err.(*net.AddrError); ok && strings.Contains(addrError.Err, "missing port") {
|
||||||
return 0, io.EOF
|
return dst
|
||||||
}
|
} else {
|
||||||
|
return ""
|
||||||
func (*wrapConn) Write([]byte) (int, error) {
|
}
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
func (*wrapConn) RemoteAddr() net.Addr {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func WrapConn(packetConn net.PacketConn) net.Conn {
|
|
||||||
return &wrapConn{
|
|
||||||
PacketConn: packetConn,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func IsPacketConn(c net.Conn) bool {
|
|
||||||
if _, ok := c.(net.PacketConn); !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if ua, ok := c.LocalAddr().(*net.UnixAddr); ok {
|
|
||||||
return ua.Net == "unixgram"
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
@ -3,7 +3,6 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
@ -20,26 +19,18 @@ func (d *Direct) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
if !metadata.DstIP.IsValid() && c.RemoteAddr() != nil {
|
|
||||||
if h, _, err := net.SplitHostPort(c.RemoteAddr().String()); err == nil {
|
|
||||||
metadata.DstIP = netip.MustParseAddr(h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(c, d), nil
|
return NewConn(c, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListenPacketContext implements C.ProxyAdapter
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (d *Direct) ListenPacketContext(ctx context.Context, _ *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (d *Direct) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
opts = append(opts, dialer.WithDirect())
|
opts = append(opts, dialer.WithDirect())
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", d.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return NewPacketConn(&directPacketConn{pc}, d), nil
|
return newPacketConn(&directPacketConn{pc}, d), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type directPacketConn struct {
|
type directPacketConn struct {
|
||||||
@ -49,9 +40,21 @@ type directPacketConn struct {
|
|||||||
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,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCompatible() *Direct {
|
||||||
|
return &Direct{
|
||||||
|
Base: &Base{
|
||||||
|
name: "COMPATIBLE",
|
||||||
|
tp: C.Compatible,
|
||||||
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,7 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -22,18 +23,21 @@ type Http struct {
|
|||||||
user string
|
user string
|
||||||
pass string
|
pass string
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
|
option *HttpOption
|
||||||
}
|
}
|
||||||
|
|
||||||
type HttpOption struct {
|
type HttpOption 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"`
|
||||||
UserName string `proxy:"username,omitempty"`
|
UserName string `proxy:"username,omitempty"`
|
||||||
Password string `proxy:"password,omitempty"`
|
Password string `proxy:"password,omitempty"`
|
||||||
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"`
|
||||||
|
Headers map[string]string `proxy:"headers,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
@ -84,15 +88,18 @@ func (h *Http) shakeHand(metadata *C.Metadata, rw io.ReadWriter) error {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//增加headers
|
||||||
|
if len(h.option.Headers) != 0 {
|
||||||
|
for key, value := range h.option.Headers {
|
||||||
|
req.Header.Add(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)))
|
req.Header.Add("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth)))
|
||||||
}
|
}
|
||||||
|
|
||||||
if metadata.Type == C.MITM {
|
|
||||||
req.Header.Set("Origin-Request-Source-Address", metadata.SourceAddress())
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := req.Write(rw); err != nil {
|
if err := req.Write(rw); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -121,29 +128,41 @@ 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{
|
if len(option.Fingerprint) == 0 {
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
ServerName: sni,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(&tls.Config{
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
ServerName: sni,
|
||||||
|
}, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Http{
|
return &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,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
user: option.UserName,
|
user: option.UserName,
|
||||||
pass: option.Password,
|
pass: option.Password,
|
||||||
tlsConfig: tlsConfig,
|
tlsConfig: tlsConfig,
|
||||||
}
|
option: &option,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
309
adapter/outbound/hysteria.go
Normal file
309
adapter/outbound/hysteria.go
Normal file
@ -0,0 +1,309 @@
|
|||||||
|
package outbound
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/core"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/obfs"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/pmtud_fix"
|
||||||
|
"github.com/Dreamacro/clash/transport/hysteria/transport"
|
||||||
|
"github.com/lucas-clemente/quic-go"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
hyCongestion "github.com/Dreamacro/clash/transport/hysteria/congestion"
|
||||||
|
"github.com/lucas-clemente/quic-go/congestion"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
mbpsToBps = 125000
|
||||||
|
minSpeedBPS = 16384
|
||||||
|
|
||||||
|
DefaultStreamReceiveWindow = 15728640 // 15 MB/s
|
||||||
|
DefaultConnectionReceiveWindow = 67108864 // 64 MB/s
|
||||||
|
DefaultMaxIncomingStreams = 1024
|
||||||
|
|
||||||
|
DefaultALPN = "hysteria"
|
||||||
|
DefaultProtocol = "udp"
|
||||||
|
)
|
||||||
|
|
||||||
|
var rateStringRegexp = regexp.MustCompile(`^(\d+)\s*([KMGT]?)([Bb])ps$`)
|
||||||
|
|
||||||
|
type Hysteria struct {
|
||||||
|
*Base
|
||||||
|
|
||||||
|
client *core.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
|
hdc := hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||||
|
},
|
||||||
|
remoteAddr: func(addr string) (net.Addr, error) {
|
||||||
|
return resolveUDPAddrWithPrefer("udp", addr, h.prefer)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
tcpConn, err := h.client.DialTCP(metadata.RemoteAddress(), &hdc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return NewConn(tcpConn, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Hysteria) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
hdc := hyDialerWithContext{
|
||||||
|
ctx: context.Background(),
|
||||||
|
hyDialer: func() (net.PacketConn, error) {
|
||||||
|
return dialer.ListenPacket(ctx, "udp", "", h.Base.DialOptions(opts...)...)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
udpConn, err := h.client.DialUDP(&hdc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(&hyPacketConn{udpConn}, h), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type HysteriaOption struct {
|
||||||
|
BasicOption
|
||||||
|
Name string `proxy:"name"`
|
||||||
|
Server string `proxy:"server"`
|
||||||
|
Port int `proxy:"port"`
|
||||||
|
Protocol string `proxy:"protocol,omitempty"`
|
||||||
|
Up string `proxy:"up"`
|
||||||
|
Down string `proxy:"down"`
|
||||||
|
AuthString string `proxy:"auth_str,omitempty"`
|
||||||
|
Obfs string `proxy:"obfs,omitempty"`
|
||||||
|
SNI string `proxy:"sni,omitempty"`
|
||||||
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
|
ALPN string `proxy:"alpn,omitempty"`
|
||||||
|
CustomCA string `proxy:"ca,omitempty"`
|
||||||
|
CustomCAString string `proxy:"ca_str,omitempty"`
|
||||||
|
ReceiveWindowConn int `proxy:"recv_window_conn,omitempty"`
|
||||||
|
ReceiveWindow int `proxy:"recv_window,omitempty"`
|
||||||
|
DisableMTUDiscovery bool `proxy:"disable_mtu_discovery,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{
|
||||||
|
Dialer: &net.Dialer{
|
||||||
|
Timeout: 8 * time.Second,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
|
||||||
|
serverName := option.Server
|
||||||
|
if option.SNI != "" {
|
||||||
|
serverName = option.SNI
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
ServerName: serverName,
|
||||||
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
}
|
||||||
|
|
||||||
|
var bs []byte
|
||||||
|
var err error
|
||||||
|
if len(option.CustomCA) > 0 {
|
||||||
|
bs, err = os.ReadFile(option.CustomCA)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hysteria %s load ca error: %w", addr, err)
|
||||||
|
}
|
||||||
|
} else if option.CustomCAString != "" {
|
||||||
|
bs = []byte(option.CustomCAString)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(bs) > 0 {
|
||||||
|
block, _ := pem.Decode(bs)
|
||||||
|
if block == nil {
|
||||||
|
return nil, fmt.Errorf("CA cert is not PEM")
|
||||||
|
}
|
||||||
|
|
||||||
|
fpBytes := sha256.Sum256(block.Bytes)
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
option.Fingerprint = hex.EncodeToString(fpBytes[:])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) != 0 {
|
||||||
|
var err error
|
||||||
|
tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(option.ALPN) > 0 {
|
||||||
|
tlsConfig.NextProtos = []string{option.ALPN}
|
||||||
|
} else {
|
||||||
|
tlsConfig.NextProtos = []string{DefaultALPN}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.Protocol == "" {
|
||||||
|
option.Protocol = DefaultProtocol
|
||||||
|
}
|
||||||
|
if option.ReceiveWindowConn == 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)
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
client, err := core.NewClient(
|
||||||
|
addr, option.Protocol, auth, tlsConfig, quicConfig, clientTransport, up, down, func(refBPS uint64) congestion.CongestionControl {
|
||||||
|
return hyCongestion.NewBrutalSender(congestion.ByteCount(refBPS))
|
||||||
|
}, obfuscator,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("hysteria %s create error: %w", addr, err)
|
||||||
|
}
|
||||||
|
return &Hysteria{
|
||||||
|
Base: &Base{
|
||||||
|
name: option.Name,
|
||||||
|
addr: addr,
|
||||||
|
tp: C.Hysteria,
|
||||||
|
udp: true,
|
||||||
|
iface: option.Interface,
|
||||||
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
|
},
|
||||||
|
client: client,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
switch m[2] {
|
||||||
|
case "K":
|
||||||
|
n = 1 << 10
|
||||||
|
case "M":
|
||||||
|
n = 1 << 20
|
||||||
|
case "G":
|
||||||
|
n = 1 << 30
|
||||||
|
case "T":
|
||||||
|
n = 1 << 40
|
||||||
|
default:
|
||||||
|
n = 1
|
||||||
|
}
|
||||||
|
v, _ := strconv.ParseUint(m[1], 10, 64)
|
||||||
|
n = v * n
|
||||||
|
if m[3] == "b" {
|
||||||
|
// Bits, need to convert to bytes
|
||||||
|
n = n >> 3
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
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) 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() (net.PacketConn, error)
|
||||||
|
ctx context.Context
|
||||||
|
remoteAddr func(host string) (net.Addr, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) ListenPacket() (net.PacketConn, error) {
|
||||||
|
return h.hyDialer()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) Context() context.Context {
|
||||||
|
return h.ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *hyDialerWithContext) RemoteAddr(host string) (net.Addr, error) {
|
||||||
|
return h.remoteAddr(host)
|
||||||
|
}
|
@ -1,49 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Mitm struct {
|
|
||||||
*Base
|
|
||||||
serverAddr *net.TCPAddr
|
|
||||||
httpProxyClient *Http
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
|
||||||
func (m *Mitm) DialContext(_ context.Context, metadata *C.Metadata, _ ...dialer.Option) (C.Conn, error) {
|
|
||||||
c, err := net.DialTCP("tcp", nil, m.serverAddr)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = c.SetKeepAlive(true)
|
|
||||||
_ = c.SetKeepAlivePeriod(60 * time.Second)
|
|
||||||
|
|
||||||
metadata.Type = C.MITM
|
|
||||||
|
|
||||||
hc, err := m.httpProxyClient.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
_ = c.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(hc, m), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewMitm(serverAddr string) *Mitm {
|
|
||||||
tcpAddr, _ := net.ResolveTCPAddr("tcp", serverAddr)
|
|
||||||
return &Mitm{
|
|
||||||
Base: &Base{
|
|
||||||
name: "Mitm",
|
|
||||||
tp: C.Mitm,
|
|
||||||
},
|
|
||||||
serverAddr: tcpAddr,
|
|
||||||
httpProxyClient: NewHttp(HttpOption{}),
|
|
||||||
}
|
|
||||||
}
|
|
@ -6,57 +6,42 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/cache"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
rejectCountLimit = 50
|
|
||||||
rejectDelay = time.Second * 35
|
|
||||||
)
|
|
||||||
|
|
||||||
var rejectCounter = cache.NewLRUCache[string, int](cache.WithAge[string, int](15), cache.WithStale[string, int](false), cache.WithSize[string, int](512))
|
|
||||||
|
|
||||||
type Reject struct {
|
type Reject struct {
|
||||||
*Base
|
*Base
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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, opts ...dialer.Option) (C.Conn, error) {
|
||||||
key := metadata.RemoteAddress()
|
|
||||||
|
|
||||||
count, existed := rejectCounter.Get(key)
|
|
||||||
if !existed {
|
|
||||||
count = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
count = count + 1
|
|
||||||
|
|
||||||
rejectCounter.Set(key, count)
|
|
||||||
|
|
||||||
if count > rejectCountLimit {
|
|
||||||
c, _ := net.Pipe()
|
|
||||||
|
|
||||||
_ = c.SetDeadline(time.Now().Add(rejectDelay))
|
|
||||||
|
|
||||||
return NewConn(c, r), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return NewConn(&nopConn{}, 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, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
return NewPacketConn(&nopPacketConn{}, r), nil
|
return newPacketConn(&nopPacketConn{}, r), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewReject() *Reject {
|
func NewReject() *Reject {
|
||||||
return &Reject{
|
return &Reject{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: "REJECT",
|
name: "REJECT",
|
||||||
tp: C.Reject,
|
tp: C.Reject,
|
||||||
udp: true,
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPass() *Reject {
|
||||||
|
return &Reject{
|
||||||
|
Base: &Base{
|
||||||
|
name: "PASS",
|
||||||
|
tp: C.Pass,
|
||||||
|
udp: true,
|
||||||
|
prefer: C.DualStack,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,19 +7,30 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/pool"
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/shadowsocks/core"
|
|
||||||
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
obfs "github.com/Dreamacro/clash/transport/simple-obfs"
|
||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
v2rayObfs "github.com/Dreamacro/clash/transport/v2ray-plugin"
|
||||||
|
"github.com/sagernet/sing-shadowsocks"
|
||||||
|
"github.com/sagernet/sing-shadowsocks/shadowimpl"
|
||||||
|
"github.com/sagernet/sing/common/buf"
|
||||||
|
"github.com/sagernet/sing/common/bufio"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
"github.com/sagernet/sing/common/uot"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
buf.DefaultAllocator = pool.DefaultAllocator
|
||||||
|
}
|
||||||
|
|
||||||
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
|
||||||
@ -36,6 +47,7 @@ type ShadowSocksOption struct {
|
|||||||
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type simpleObfsOption struct {
|
type simpleObfsOption struct {
|
||||||
@ -48,6 +60,7 @@ type v2rayObfsOption struct {
|
|||||||
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"`
|
||||||
|
Fingerprint string `obfs:"fingerprint,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"`
|
||||||
@ -68,24 +81,11 @@ func (ss *ShadowSocks) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, e
|
|||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
c = ss.cipher.StreamConn(c)
|
if metadata.NetWork == C.UDP && ss.option.UDPOverTCP {
|
||||||
_, err := c.Write(serializesSocksAddr(metadata))
|
metadata.Host = uot.UOTMagicAddress
|
||||||
return c, err
|
metadata.DstPort = "443"
|
||||||
}
|
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (ss *ShadowSocks) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
|
||||||
if !IsPacketConn(c) {
|
|
||||||
return c, fmt.Errorf("%s connect error: can not convert net.Conn to net.PacketConn", ss.addr)
|
|
||||||
}
|
}
|
||||||
|
return ss.method.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
addr, err := resolveUDPAddr("udp", ss.addr)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pc := ss.cipher.PacketConn(c.(net.PacketConn))
|
|
||||||
return WrapConn(&ssPacketConn{PacketConn: pc, rAddr: addr}), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -104,25 +104,43 @@ func (ss *ShadowSocks) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
|
|
||||||
// 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, opts ...dialer.Option) (C.PacketConn, error) {
|
||||||
|
if ss.option.UDPOverTCP {
|
||||||
|
tcpConn, err := ss.DialContext(ctx, metadata, opts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return newPacketConn(uot.NewClientConn(tcpConn), ss), nil
|
||||||
|
}
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := ss.StreamPacketConn(WrapConn(pc), metadata)
|
addr, err := resolveUDPAddrWithPrefer("udp", ss.addr, ss.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = pc.Close()
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
pc = ss.method.DialPacketConn(&bufio.BindPacketConn{PacketConn: pc, Addr: addr})
|
||||||
|
return newPacketConn(pc, ss), nil
|
||||||
|
}
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), ss), nil
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if ss.option.UDPOverTCP {
|
||||||
|
return newPacketConn(uot.NewClientConn(c), ss), nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("no support")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (ss *ShadowSocks) SupportUOT() bool {
|
||||||
|
return ss.option.UDPOverTCP
|
||||||
}
|
}
|
||||||
|
|
||||||
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 := shadowimpl.FetchMethod(option.Cipher, option.Password)
|
||||||
password := option.Password
|
|
||||||
ciph, err := core.PickCipher(cipher, nil, password)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
return nil, fmt.Errorf("ss %s initialize error: %w", addr, err)
|
||||||
}
|
}
|
||||||
@ -168,15 +186,17 @@ func NewShadowSocks(option ShadowSocksOption) (*ShadowSocks, error) {
|
|||||||
|
|
||||||
return &ShadowSocks{
|
return &ShadowSocks{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.Shadowsocks,
|
tp: C.Shadowsocks,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
cipher: ciph,
|
method: method,
|
||||||
|
|
||||||
|
option: &option,
|
||||||
obfsMode: obfsMode,
|
obfsMode: obfsMode,
|
||||||
v2rayOption: v2rayOption,
|
v2rayOption: v2rayOption,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -58,22 +58,6 @@ func (ssr *ShadowSocksR) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn,
|
|||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (ssr *ShadowSocksR) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
|
||||||
if !IsPacketConn(c) {
|
|
||||||
return c, fmt.Errorf("%s connect error: can not convert net.Conn to net.PacketConn", ssr.addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
addr, err := resolveUDPAddr("udp", ssr.addr)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pc := ssr.cipher.PacketConn(c.(net.PacketConn))
|
|
||||||
pc = ssr.protocol.PacketConn(pc)
|
|
||||||
return WrapConn(&ssPacketConn{PacketConn: pc, rAddr: addr}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ssr.addr, ssr.Base.DialOptions(opts...)...)
|
||||||
@ -95,13 +79,15 @@ func (ssr *ShadowSocksR) ListenPacketContext(ctx context.Context, metadata *C.Me
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := ssr.StreamPacketConn(WrapConn(pc), metadata)
|
addr, err := resolveUDPAddrWithPrefer("udp", ssr.addr, ssr.prefer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = pc.Close()
|
pc.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), ssr), nil
|
pc = ssr.cipher.PacketConn(pc)
|
||||||
|
pc = ssr.protocol.PacketConn(pc)
|
||||||
|
return newPacketConn(&ssPacketConn{PacketConn: pc, rAddr: addr}, ssr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
||||||
@ -157,12 +143,13 @@ func NewShadowSocksR(option ShadowSocksROption) (*ShadowSocksR, error) {
|
|||||||
|
|
||||||
return &ShadowSocksR{
|
return &ShadowSocksR{
|
||||||
Base: &Base{
|
Base: &Base{
|
||||||
name: option.Name,
|
name: option.Name,
|
||||||
addr: addr,
|
addr: addr,
|
||||||
tp: C.ShadowsocksR,
|
tp: C.ShadowsocksR,
|
||||||
udp: option.UDP,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
cipher: coreCiph,
|
cipher: coreCiph,
|
||||||
obfs: obfs,
|
obfs: obfs,
|
||||||
|
@ -53,23 +53,15 @@ func streamConn(c net.Conn, option streamOption) *snell.Snell {
|
|||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (s *Snell) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
|
err := snell.WriteUDPHeader(c, s.version)
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
err := snell.WriteHeader(c, metadata.String(), uint(port), s.version)
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (s *Snell) StreamPacketConn(c net.Conn, _ *C.Metadata) (net.Conn, error) {
|
|
||||||
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
|
||||||
|
|
||||||
err := snell.WriteUDPHeader(c, s.version)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return WrapConn(snell.PacketConn(c)), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
if s.version == snell.Version2 && len(opts) == 0 {
|
if s.version == snell.Version2 && len(opts) == 0 {
|
||||||
@ -80,7 +72,7 @@ func (s *Snell) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
if err = snell.WriteHeader(c, metadata.String(), uint(port), s.version); 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
|
||||||
@ -105,14 +97,26 @@ func (s *Snell) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
tcpKeepAlive(c)
|
tcpKeepAlive(c)
|
||||||
|
c = streamConn(c, streamOption{s.psk, s.version, s.addr, s.obfsOption})
|
||||||
|
|
||||||
pc, err := s.StreamPacketConn(c, metadata)
|
err = snell.WriteUDPHeader(c, s.version)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_ = c.Close()
|
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(pc.(net.PacketConn), s), nil
|
pc := snell.PacketConn(c)
|
||||||
|
return newPacketConn(pc, s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (s *Snell) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
pc := snell.PacketConn(c)
|
||||||
|
return newPacketConn(pc, s), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (s *Snell) SupportUOT() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSnell(option SnellOption) (*Snell, error) {
|
func NewSnell(option SnellOption) (*Snell, error) {
|
||||||
@ -148,12 +152,13 @@ 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,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
psk: psk,
|
psk: psk,
|
||||||
obfsOption: obfsOption,
|
obfsOption: obfsOption,
|
||||||
|
@ -5,6 +5,7 @@ import (
|
|||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -33,63 +34,17 @@ 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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
// StreamConn implements C.ProxyAdapter
|
||||||
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (ss *Socks5) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
|
||||||
c, _, err = ss.streamConn(c, metadata)
|
|
||||||
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) StreamSocks5PacketConn(c net.Conn, pc net.PacketConn, metadata *C.Metadata) (net.PacketConn, error) {
|
|
||||||
if c == nil {
|
|
||||||
return pc, fmt.Errorf("%s connect error: parameter net.Conn is nil", ss.addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
if pc == nil {
|
|
||||||
return pc, fmt.Errorf("%s connect error: parameter net.PacketConn is nil", ss.addr)
|
|
||||||
}
|
|
||||||
|
|
||||||
cc, bindAddr, err := ss.streamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return pc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
c = cc
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
_, _ = io.Copy(io.Discard, c)
|
|
||||||
_ = c.Close()
|
|
||||||
// A UDP association terminates when the TCP connection that the UDP
|
|
||||||
// ASSOCIATE request arrived on terminates. RFC1928
|
|
||||||
_ = pc.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Support unspecified UDP bind address.
|
|
||||||
bindUDPAddr := bindAddr.UDPAddr()
|
|
||||||
if bindUDPAddr == nil {
|
|
||||||
return pc, errors.New("invalid UDP bind address")
|
|
||||||
} else if bindUDPAddr.IP.IsUnspecified() {
|
|
||||||
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
|
||||||
if err != nil {
|
|
||||||
return pc, err
|
|
||||||
}
|
|
||||||
|
|
||||||
bindUDPAddr.IP = serverAddr.IP
|
|
||||||
}
|
|
||||||
|
|
||||||
return &socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ss *Socks5) streamConn(c net.Conn, metadata *C.Metadata) (_ net.Conn, bindAddr socks5.Addr, err error) {
|
|
||||||
if ss.tls {
|
if ss.tls {
|
||||||
cc := tls.Client(c, ss.tlsConfig)
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
err := cc.Handshake()
|
err := cc.Handshake()
|
||||||
c = cc
|
c = cc
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c, nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -100,14 +55,10 @@ func (ss *Socks5) streamConn(c net.Conn, metadata *C.Metadata) (_ net.Conn, bind
|
|||||||
Password: ss.pass,
|
Password: ss.pass,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if _, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user); err != nil {
|
||||||
if metadata.NetWork == C.UDP {
|
return nil, err
|
||||||
bindAddr, err = socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
|
||||||
} else {
|
|
||||||
bindAddr, err = socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdConnect, user)
|
|
||||||
}
|
}
|
||||||
|
return c, nil
|
||||||
return c, bindAddr, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -132,50 +83,97 @@ func (ss *Socks5) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
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, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", ss.addr, ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", ss.addr, err)
|
err = fmt.Errorf("%s connect error: %w", ss.addr, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if ss.tls {
|
||||||
|
cc := tls.Client(c, ss.tlsConfig)
|
||||||
|
err = cc.Handshake()
|
||||||
|
c = cc
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
var user *socks5.User
|
||||||
|
if ss.user != "" {
|
||||||
|
user = &socks5.User{
|
||||||
|
Username: ss.user,
|
||||||
|
Password: ss.pass,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bindAddr, err := socks5.ClientHandshake(c, serializesSocksAddr(metadata), socks5.CmdUDPAssociate, user)
|
||||||
|
if err != nil {
|
||||||
|
err = fmt.Errorf("client hanshake error: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
pc, err := dialer.ListenPacket(ctx, "udp", "", ss.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
go func() {
|
||||||
|
io.Copy(io.Discard, c)
|
||||||
|
c.Close()
|
||||||
|
// A UDP association terminates when the TCP connection that the UDP
|
||||||
|
// ASSOCIATE request arrived on terminates. RFC1928
|
||||||
|
pc.Close()
|
||||||
|
}()
|
||||||
|
|
||||||
pc, err = ss.StreamSocks5PacketConn(c, pc, metadata)
|
// Support unspecified UDP bind address.
|
||||||
if err != nil {
|
bindUDPAddr := bindAddr.UDPAddr()
|
||||||
|
if bindUDPAddr == nil {
|
||||||
|
err = errors.New("invalid UDP bind address")
|
||||||
return
|
return
|
||||||
|
} else if bindUDPAddr.IP.IsUnspecified() {
|
||||||
|
serverAddr, err := resolveUDPAddr("udp", ss.Addr())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bindUDPAddr.IP = serverAddr.IP
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(pc, ss), nil
|
return newPacketConn(&socksPacketConn{PacketConn: pc, rAddr: bindUDPAddr, tcpConn: c}, ss), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSocks5(option Socks5Option) *Socks5 {
|
func NewSocks5(option Socks5Option) (*Socks5, error) {
|
||||||
var tlsConfig *tls.Config
|
var tlsConfig *tls.Config
|
||||||
if option.TLS {
|
if option.TLS {
|
||||||
tlsConfig = &tls.Config{
|
tlsConfig = &tls.Config{
|
||||||
InsecureSkipVerify: option.SkipCertVerify,
|
InsecureSkipVerify: option.SkipCertVerify,
|
||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Socks5{
|
return &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,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
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,
|
||||||
}
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type socksPacketConn struct {
|
type socksPacketConn struct {
|
||||||
@ -213,6 +211,6 @@ func (uc *socksPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (uc *socksPacketConn) Close() error {
|
func (uc *socksPacketConn) Close() error {
|
||||||
_ = uc.tcpConn.Close()
|
uc.tcpConn.Close()
|
||||||
return uc.PacketConn.Close()
|
return uc.PacketConn.Close()
|
||||||
}
|
}
|
||||||
|
@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@ -13,8 +14,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/trojan"
|
"github.com/Dreamacro/clash/transport/trojan"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Trojan struct {
|
type Trojan struct {
|
||||||
@ -25,7 +24,7 @@ type Trojan struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
transport *gun.TransportWrap
|
||||||
}
|
}
|
||||||
|
|
||||||
type TrojanOption struct {
|
type TrojanOption struct {
|
||||||
@ -37,6 +36,7 @@ type TrojanOption struct {
|
|||||||
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"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
@ -72,7 +72,8 @@ func (t *Trojan) plainStream(c net.Conn) (net.Conn, error) {
|
|||||||
return t.instance.StreamConn(c)
|
return t.instance.StreamConn(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *Trojan) trojanStream(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
// StreamConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err error
|
var err error
|
||||||
if t.transport != nil {
|
if t.transport != nil {
|
||||||
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
c, err = gun.StreamGunWithConn(c, t.gunTLSConfig, t.gunConfig)
|
||||||
@ -84,63 +85,43 @@ func (t *Trojan) trojanStream(c net.Conn, metadata *C.Metadata) (net.Conn, error
|
|||||||
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.PrepareXTLSConn(c)
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if metadata.NetWork == C.UDP {
|
if metadata.NetWork == C.UDP {
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata))
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
return t.trojanStream(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (t *Trojan) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
var err error
|
|
||||||
c, err = t.trojanStream(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return c, err
|
|
||||||
}
|
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
|
||||||
return WrapConn(pc), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
|
||||||
var c net.Conn
|
|
||||||
|
|
||||||
// gun transport
|
// gun transport
|
||||||
if t.transport != nil && len(opts) == 0 {
|
if t.transport != nil && len(opts) == 0 {
|
||||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
c, err := gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
c, err = t.instance.PresetXTLSConn(c)
|
||||||
|
|
||||||
c, err = t.instance.PrepareXTLSConn(c)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
if err = t.instance.WriteHeader(c, trojan.CommandTCP, serializesSocksAddr(metadata)); err != nil {
|
||||||
|
c.Close()
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewConn(c, t), nil
|
return NewConn(c, t), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
c, err := dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
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)
|
||||||
}
|
}
|
||||||
@ -160,44 +141,44 @@ func (t *Trojan) DialContext(ctx context.Context, metadata *C.Metadata, opts ...
|
|||||||
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, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
|
|
||||||
// gun transport
|
// grpc transport
|
||||||
if t.transport != nil && len(opts) == 0 {
|
if t.transport != nil && len(opts) == 0 {
|
||||||
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
c, err = gun.StreamGunWithTransport(t.transport, t.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
} else {
|
||||||
c, err = t.instance.PrepareXTLSConn(c)
|
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
defer safeConnClose(c, err)
|
||||||
if err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata)); err != nil {
|
tcpKeepAlive(c)
|
||||||
return nil, err
|
c, err = t.plainStream(c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pc := t.instance.PacketConn(c)
|
|
||||||
|
|
||||||
return NewPacketConn(pc, t), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", t.addr, t.Base.DialOptions(opts...)...)
|
err = t.instance.WriteHeader(c, trojan.CommandUDP, serializesSocksAddr(metadata))
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", t.addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = t.StreamPacketConn(c, metadata)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return NewPacketConn(c.(net.PacketConn), t), nil
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(pc, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
pc := t.instance.PacketConn(c)
|
||||||
|
return newPacketConn(pc, t), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (t *Trojan) SupportUOT() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
func NewTrojan(option TrojanOption) (*Trojan, error) {
|
||||||
@ -209,6 +190,7 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: option.Server,
|
ServerName: option.Server,
|
||||||
SkipCertVerify: option.SkipCertVerify,
|
SkipCertVerify: option.SkipCertVerify,
|
||||||
FlowShow: option.FlowShow,
|
FlowShow: option.FlowShow,
|
||||||
|
Fingerprint: option.Fingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if option.Network != "ws" && len(option.Flow) >= 16 {
|
if option.Network != "ws" && len(option.Flow) >= 16 {
|
||||||
@ -227,12 +209,13 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
|
|
||||||
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,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
instance: trojan.New(tOption),
|
instance: trojan.New(tOption),
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -255,6 +238,15 @@ func NewTrojan(option TrojanOption) (*Trojan, error) {
|
|||||||
ServerName: tOption.ServerName,
|
ServerName: tOption.ServerName,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(option.Fingerprint) == 0 {
|
||||||
|
tlsConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if tlsConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, option.Fingerprint); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if t.option.Flow != "" {
|
if t.option.Flow != "" {
|
||||||
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
t.transport = gun.NewHTTP2XTLSClient(dialFn, tlsConfig)
|
||||||
} else {
|
} else {
|
||||||
|
@ -2,8 +2,12 @@ package outbound
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
|
xtls "github.com/xtls/go"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
@ -11,6 +15,12 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/socks5"
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
globalClientSessionCache tls.ClientSessionCache
|
||||||
|
globalClientXSessionCache xtls.ClientSessionCache
|
||||||
|
once sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
func tcpKeepAlive(c net.Conn) {
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
if tcp, ok := c.(*net.TCPConn); ok {
|
||||||
_ = tcp.SetKeepAlive(true)
|
_ = tcp.SetKeepAlive(true)
|
||||||
@ -18,6 +28,20 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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)
|
aType := uint8(metadata.AddrType)
|
||||||
@ -51,8 +75,62 @@ func resolveUDPAddr(network, address string) (*net.UDPAddr, error) {
|
|||||||
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func resolveUDPAddrWithPrefer(network, address string, prefer C.DNSPrefer) (*net.UDPAddr, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var ip netip.Addr
|
||||||
|
switch prefer {
|
||||||
|
case C.IPv4Only:
|
||||||
|
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
|
case C.IPv6Only:
|
||||||
|
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
|
case C.IPv6Prefer:
|
||||||
|
var ips []netip.Addr
|
||||||
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
var fallback netip.Addr
|
||||||
|
if err == nil {
|
||||||
|
for _, addr := range ips {
|
||||||
|
if addr.Is6() {
|
||||||
|
ip = addr
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
if !fallback.IsValid() {
|
||||||
|
fallback = addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ip = fallback
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// C.IPv4Prefer, C.DualStack and other
|
||||||
|
var ips []netip.Addr
|
||||||
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
var fallback netip.Addr
|
||||||
|
if err == nil {
|
||||||
|
for _, addr := range ips {
|
||||||
|
if addr.Is4() {
|
||||||
|
ip = addr
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
if !fallback.IsValid() {
|
||||||
|
fallback = addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ip = fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return net.ResolveUDPAddr(network, net.JoinHostPort(ip.String(), port))
|
||||||
|
}
|
||||||
|
|
||||||
func safeConnClose(c net.Conn, err error) {
|
func safeConnClose(c net.Conn, err error) {
|
||||||
if err != nil && c != nil {
|
if err != nil {
|
||||||
_ = c.Close()
|
_ = c.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,8 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@ -18,8 +20,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/vless"
|
"github.com/Dreamacro/clash/transport/vless"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
"github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
|
||||||
"golang.org/x/net/http2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -35,7 +35,7 @@ type Vless struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
transport *gun.TransportWrap
|
||||||
}
|
}
|
||||||
|
|
||||||
type VlessOption struct {
|
type VlessOption struct {
|
||||||
@ -46,6 +46,7 @@ type VlessOption struct {
|
|||||||
UUID string `proxy:"uuid"`
|
UUID string `proxy:"uuid"`
|
||||||
Flow string `proxy:"flow,omitempty"`
|
Flow string `proxy:"flow,omitempty"`
|
||||||
FlowShow bool `proxy:"flow-show,omitempty"`
|
FlowShow bool `proxy:"flow-show,omitempty"`
|
||||||
|
TLS bool `proxy:"tls,omitempty"`
|
||||||
UDP bool `proxy:"udp,omitempty"`
|
UDP bool `proxy:"udp,omitempty"`
|
||||||
Network string `proxy:"network,omitempty"`
|
Network string `proxy:"network,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
@ -55,20 +56,14 @@ type VlessOption struct {
|
|||||||
WSPath string `proxy:"ws-path,omitempty"`
|
WSPath string `proxy:"ws-path,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
||||||
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamConn implements C.ProxyAdapter
|
|
||||||
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
||||||
var err 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 := &vmess.WebsocketConfig{
|
||||||
@ -77,29 +72,40 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
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,
|
||||||
|
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
|
||||||
|
tlsConfig := &tls.Config{
|
||||||
|
MinVersion: tls.VersionTLS12,
|
||||||
|
ServerName: host,
|
||||||
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
|
NextProtos: []string{"http/1.1"},
|
||||||
|
}
|
||||||
|
|
||||||
wsOpts.TLS = true
|
if len(v.option.Fingerprint) == 0 {
|
||||||
wsOpts.TLSConfig = &tls.Config{
|
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
MinVersion: tls.VersionTLS12,
|
} else {
|
||||||
ServerName: host,
|
wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint)
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
}
|
||||||
NextProtos: []string{"http/1.1"},
|
|
||||||
}
|
|
||||||
if v.option.ServerName != "" {
|
|
||||||
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
|
||||||
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
|
||||||
wsOpts.TLSConfig.ServerName = host
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if v.option.ServerName != "" {
|
||||||
|
wsOpts.TLSConfig.ServerName = v.option.ServerName
|
||||||
|
} else if host := wsOpts.Headers.Get("Host"); host != "" {
|
||||||
|
wsOpts.TLSConfig.ServerName = host
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if host := wsOpts.Headers.Get("Host"); host == "" {
|
||||||
|
wsOpts.Headers.Set("Host", convert.RandHost())
|
||||||
|
convert.SetUserAgent(wsOpts.Headers)
|
||||||
|
}
|
||||||
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
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
|
||||||
@ -148,26 +154,6 @@ func (v *Vless) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
return v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
}
|
}
|
||||||
|
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (v *Vless) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return WrapConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error) {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
|
||||||
@ -175,6 +161,7 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
xtlsOpts := vless.XTLSConfig{
|
xtlsOpts := vless.XTLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
|
FingerPrint: v.option.Fingerprint,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -187,10 +174,11 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
return vless.StreamXTLSConn(conn, &xtlsOpts)
|
||||||
|
|
||||||
} else {
|
} 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,
|
||||||
}
|
}
|
||||||
|
|
||||||
if isH2 {
|
if isH2 {
|
||||||
@ -203,6 +191,8 @@ func (v *Vless) streamTLSOrXTLSConn(conn net.Conn, isH2 bool) (net.Conn, error)
|
|||||||
|
|
||||||
return vmess.StreamTLSConn(conn, &tlsOpts)
|
return vmess.StreamTLSConn(conn, &tlsOpts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return conn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *Vless) isXTLSEnabled() bool {
|
func (v *Vless) isXTLSEnabled() bool {
|
||||||
@ -240,18 +230,18 @@ func (v *Vless) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// 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, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
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.transport != nil && len(opts) == 0 {
|
||||||
// vless use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.New("can't resolve ip")
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@ -259,27 +249,32 @@ func (v *Vless) ListenPacketContext(ctx context.Context, metadata *C.Metadata, o
|
|||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
c, err = v.client.StreamConn(c, parseVlessAddr(metadata))
|
||||||
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vless client error: %v", err)
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
return NewPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
c, err = v.StreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamPacketConn(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 NewPacketConn(c.(net.PacketConn), v), nil
|
return v.ListenPacketOnStreamConn(c, metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (v *Vless) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
return newPacketConn(&vlessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (v *Vless) SupportUOT() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
||||||
@ -287,18 +282,18 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
var addr []byte
|
var addr []byte
|
||||||
switch metadata.AddrType {
|
switch metadata.AddrType {
|
||||||
case C.AtypIPv4:
|
case C.AtypIPv4:
|
||||||
addrType = byte(vless.AtypIPv4)
|
addrType = vless.AtypIPv4
|
||||||
addr = make([]byte, net.IPv4len)
|
addr = make([]byte, net.IPv4len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypIPv6:
|
case C.AtypIPv6:
|
||||||
addrType = byte(vless.AtypIPv6)
|
addrType = vless.AtypIPv6
|
||||||
addr = make([]byte, net.IPv6len)
|
addr = make([]byte, net.IPv6len)
|
||||||
copy(addr[:], metadata.DstIP.AsSlice())
|
copy(addr[:], metadata.DstIP.AsSlice())
|
||||||
case C.AtypDomainName:
|
case C.AtypDomainName:
|
||||||
addrType = byte(vless.AtypDomainName)
|
addrType = vless.AtypDomainName
|
||||||
addr = make([]byte, len(metadata.Host)+1)
|
addr = make([]byte, len(metadata.Host)+1)
|
||||||
addr[0] = byte(len(metadata.Host))
|
addr[0] = byte(len(metadata.Host))
|
||||||
copy(addr[1:], []byte(metadata.Host))
|
copy(addr[1:], metadata.Host)
|
||||||
}
|
}
|
||||||
|
|
||||||
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
port, _ := strconv.ParseUint(metadata.DstPort, 10, 16)
|
||||||
@ -313,29 +308,40 @@ func parseVlessAddr(metadata *C.Metadata) *vless.DstAddr {
|
|||||||
type vlessPacketConn struct {
|
type vlessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
cache [2]byte
|
|
||||||
remain int
|
remain int
|
||||||
mux sync.Mutex
|
mux sync.Mutex
|
||||||
|
cache [2]byte
|
||||||
}
|
}
|
||||||
|
|
||||||
func (vc *vlessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
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)
|
total := len(b)
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if total < maxLength {
|
if total <= maxLength {
|
||||||
return vc.writePacket(b)
|
return c.writePacket(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
offset := 0
|
offset := 0
|
||||||
for {
|
|
||||||
|
for offset < total {
|
||||||
cursor := offset + maxLength
|
cursor := offset + maxLength
|
||||||
if cursor > total {
|
if cursor > total {
|
||||||
cursor = total
|
cursor = total
|
||||||
}
|
}
|
||||||
|
|
||||||
n, err := vc.writePacket(b[offset:cursor])
|
n, err := c.writePacket(b[offset:cursor])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return offset + n, err
|
return offset + n, err
|
||||||
}
|
}
|
||||||
@ -349,33 +355,32 @@ func (vc *vlessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
|||||||
return total, nil
|
return total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
func (c *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
||||||
vc.mux.Lock()
|
c.mux.Lock()
|
||||||
defer vc.mux.Unlock()
|
defer c.mux.Unlock()
|
||||||
|
|
||||||
if vc.remain != 0 {
|
if c.remain > 0 {
|
||||||
length := len(b)
|
length := len(b)
|
||||||
if length > vc.remain {
|
if c.remain < length {
|
||||||
length = vc.remain
|
length = c.remain
|
||||||
}
|
}
|
||||||
|
|
||||||
n, err := vc.Conn.Read(b[:length])
|
n, err := c.Conn.Read(b[:length])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, vc.rAddr, err
|
return 0, c.rAddr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
vc.remain -= n
|
c.remain -= n
|
||||||
|
return n, c.rAddr, nil
|
||||||
return n, vc.rAddr, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := vc.Conn.Read(b[:2]); err != nil {
|
if _, err := c.Conn.Read(b[:2]); err != nil {
|
||||||
return 0, vc.rAddr, err
|
return 0, c.rAddr, err
|
||||||
}
|
}
|
||||||
|
|
||||||
total := int(binary.BigEndian.Uint16(b[:2]))
|
total := int(binary.BigEndian.Uint16(b[:2]))
|
||||||
if total == 0 {
|
if total == 0 {
|
||||||
return 0, vc.rAddr, nil
|
return 0, c.rAddr, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
length := len(b)
|
length := len(b)
|
||||||
@ -383,23 +388,13 @@ func (vc *vlessPacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
|
|||||||
length = total
|
length = total
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := io.ReadFull(vc.Conn, b[:length]); err != nil {
|
if _, err := io.ReadFull(c.Conn, b[:length]); err != nil {
|
||||||
return 0, vc.rAddr, errors.New("read packet error")
|
return 0, c.rAddr, errors.New("read packet error")
|
||||||
}
|
}
|
||||||
|
|
||||||
vc.remain = total - length
|
c.remain = total - length
|
||||||
|
|
||||||
return length, vc.rAddr, nil
|
return length, c.rAddr, nil
|
||||||
}
|
|
||||||
|
|
||||||
func (vc *vlessPacketConn) writePacket(payload []byte) (int, error) {
|
|
||||||
binary.BigEndian.PutUint16(vc.cache[:], uint16(len(payload)))
|
|
||||||
|
|
||||||
if _, err := vc.Conn.Write(vc.cache[:]); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return vc.Conn.Write(payload)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewVless(option VlessOption) (*Vless, error) {
|
func NewVless(option VlessOption) (*Vless, error) {
|
||||||
@ -423,11 +418,12 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
|
|
||||||
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,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -452,10 +448,10 @@ func NewVless(option VlessOption) (*Vless, error) {
|
|||||||
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
ServiceName: v.option.GrpcOpts.GrpcServiceName,
|
||||||
Host: v.option.ServerName,
|
Host: v.option.ServerName,
|
||||||
}
|
}
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := tlsC.GetGlobalFingerprintTLCConfig(&tls.Config{
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
ServerName: v.option.ServerName,
|
ServerName: v.option.ServerName,
|
||||||
}
|
})
|
||||||
|
|
||||||
if v.option.ServerName == "" {
|
if v.option.ServerName == "" {
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
|
@ -3,20 +3,23 @@ package outbound
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
tlsC "github.com/Dreamacro/clash/component/tls"
|
||||||
|
vmess "github.com/sagernet/sing-vmess"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/transport/gun"
|
"github.com/Dreamacro/clash/transport/gun"
|
||||||
"github.com/Dreamacro/clash/transport/vmess"
|
clashVMess "github.com/Dreamacro/clash/transport/vmess"
|
||||||
|
"github.com/sagernet/sing-vmess/packetaddr"
|
||||||
"golang.org/x/net/http2"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Vmess struct {
|
type Vmess struct {
|
||||||
@ -27,30 +30,29 @@ type Vmess struct {
|
|||||||
// for gun mux
|
// for gun mux
|
||||||
gunTLSConfig *tls.Config
|
gunTLSConfig *tls.Config
|
||||||
gunConfig *gun.Config
|
gunConfig *gun.Config
|
||||||
transport *http2.Transport
|
transport *gun.TransportWrap
|
||||||
}
|
}
|
||||||
|
|
||||||
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"`
|
SkipCertVerify bool `proxy:"skip-cert-verify,omitempty"`
|
||||||
ServerName string `proxy:"servername,omitempty"`
|
Fingerprint string `proxy:"fingerprint,omitempty"`
|
||||||
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
ServerName string `proxy:"servername,omitempty"`
|
||||||
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
HTTPOpts HTTPOptions `proxy:"http-opts,omitempty"`
|
||||||
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
HTTP2Opts HTTP2Options `proxy:"h2-opts,omitempty"`
|
||||||
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
GrpcOpts GrpcOptions `proxy:"grpc-opts,omitempty"`
|
||||||
|
WSOpts WSOptions `proxy:"ws-opts,omitempty"`
|
||||||
// TODO: compatible with VMESS WS older version configurations
|
PacketAddr bool `proxy:"packet-addr,omitempty"`
|
||||||
WSHeaders map[string]string `proxy:"ws-headers,omitempty"`
|
AuthenticatedLength bool `proxy:"authenticated-length,omitempty"`
|
||||||
WSPath string `proxy:"ws-path,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPOptions struct {
|
type HTTPOptions struct {
|
||||||
@ -80,52 +82,52 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
var err 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 := &clashVMess.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,
|
||||||
|
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{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: host,
|
ServerName: host,
|
||||||
InsecureSkipVerify: v.option.SkipCertVerify,
|
InsecureSkipVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"http/1.1"},
|
NextProtos: []string{"http/1.1"},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(v.option.Fingerprint) == 0 {
|
||||||
|
wsOpts.TLSConfig = tlsC.GetGlobalFingerprintTLCConfig(tlsConfig)
|
||||||
|
} else {
|
||||||
|
var err error
|
||||||
|
if wsOpts.TLSConfig, err = tlsC.GetSpecifiedFingerprintTLSConfig(tlsConfig, v.option.Fingerprint); 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
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
wsOpts.Headers.Set("Host", convert.RandHost())
|
|
||||||
convert.SetUserAgent(wsOpts.Headers)
|
|
||||||
}
|
}
|
||||||
c, err = vmess.StreamWebsocketConn(c, wsOpts)
|
c, err = clashVMess.StreamWebsocketConn(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 := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
}
|
}
|
||||||
@ -134,27 +136,24 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
http.Header(v.option.HTTPOpts.Headers).Set("Host", convert.RandHost())
|
|
||||||
convert.SetUserAgent(v.option.HTTPOpts.Headers)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
httpOpts := &vmess.HTTPConfig{
|
httpOpts := &clashVMess.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 = clashVMess.StreamHTTPConn(c, httpOpts)
|
||||||
case "h2":
|
case "h2":
|
||||||
host, _, _ := net.SplitHostPort(v.addr)
|
host, _, _ := net.SplitHostPort(v.addr)
|
||||||
tlsOpts := vmess.TLSConfig{
|
tlsOpts := clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
NextProtos: []string{"h2"},
|
NextProtos: []string{"h2"},
|
||||||
@ -164,24 +163,24 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, &tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, &tlsOpts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
h2Opts := &vmess.H2Config{
|
h2Opts := &clashVMess.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 = clashVMess.StreamH2Conn(c, h2Opts)
|
||||||
case "grpc":
|
case "grpc":
|
||||||
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
c, err = gun.StreamGunWithConn(c, v.gunTLSConfig, v.gunConfig)
|
||||||
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 := &clashVMess.TLSConfig{
|
||||||
Host: host,
|
Host: host,
|
||||||
SkipCertVerify: v.option.SkipCertVerify,
|
SkipCertVerify: v.option.SkipCertVerify,
|
||||||
}
|
}
|
||||||
@ -190,35 +189,18 @@ func (v *Vmess) StreamConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|||||||
tlsOpts.Host = v.option.ServerName
|
tlsOpts.Host = v.option.ServerName
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = vmess.StreamTLSConn(c, tlsOpts)
|
c, err = clashVMess.StreamTLSConn(c, tlsOpts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if metadata.NetWork == C.UDP {
|
||||||
return v.client.StreamConn(c, parseVmessAddr(metadata))
|
return v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
}
|
} else {
|
||||||
|
return v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
// StreamPacketConn implements C.ProxyAdapter
|
|
||||||
func (v *Vmess) StreamPacketConn(c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return c, fmt.Errorf("can't resolve ip: %w", err)
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var err error
|
|
||||||
c, err = v.StreamConn(c, metadata)
|
|
||||||
if err != nil {
|
|
||||||
return c, fmt.Errorf("new vmess client error: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return WrapConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -231,7 +213,7 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
c, err = v.client.DialConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -252,58 +234,75 @@ func (v *Vmess) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
|
|
||||||
// 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, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
|
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
||||||
|
if !metadata.Resolved() {
|
||||||
|
ip, err := resolver.ResolveIP(metadata.Host)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.New("can't resolve ip")
|
||||||
|
}
|
||||||
|
metadata.DstIP = ip
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
metadata.Host = packetaddr.SeqPacketMagicAddress
|
||||||
|
metadata.DstPort = "443"
|
||||||
|
}
|
||||||
|
|
||||||
var c net.Conn
|
var c net.Conn
|
||||||
// gun transport
|
// gun transport
|
||||||
if v.transport != nil && len(opts) == 0 {
|
if v.transport != nil && len(opts) == 0 {
|
||||||
// vmess use stream-oriented udp with a special address, so we needs a net.UDPAddr
|
|
||||||
if !metadata.Resolved() {
|
|
||||||
ip, err := resolver.ResolveIP(metadata.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
|
||||||
}
|
|
||||||
metadata.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
c, err = gun.StreamGunWithTransport(v.transport, v.gunConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer safeConnClose(c, err)
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
c, err = v.client.StreamConn(c, parseVmessAddr(metadata))
|
c, err = v.client.DialPacketConn(c, M.ParseSocksaddr(metadata.RemoteAddress()))
|
||||||
|
} else {
|
||||||
|
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("new vmess client error: %v", err)
|
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
||||||
}
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
defer safeConnClose(c, err)
|
||||||
|
|
||||||
return NewPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
c, err = v.StreamConn(c, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err = dialer.DialContext(ctx, "tcp", v.addr, v.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %s", v.addr, err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
defer safeConnClose(c, err)
|
|
||||||
|
|
||||||
c, err = v.StreamPacketConn(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 NewPacketConn(c.(net.PacketConn), v), nil
|
if v.option.PacketAddr {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindClient(c)}, v), nil
|
||||||
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
|
}
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPacketOnStreamConn implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) ListenPacketOnStreamConn(c net.Conn, metadata *C.Metadata) (_ C.PacketConn, err error) {
|
||||||
|
if v.option.PacketAddr {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: packetaddr.NewBindClient(c)}, v), nil
|
||||||
|
} else if pc, ok := c.(net.PacketConn); ok {
|
||||||
|
return newPacketConn(&threadSafePacketConn{PacketConn: pc}, v), nil
|
||||||
|
}
|
||||||
|
return newPacketConn(&vmessPacketConn{Conn: c, rAddr: metadata.UDPAddr()}, v), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SupportUOT implements C.ProxyAdapter
|
||||||
|
func (v *Vmess) SupportUOT() bool {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
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: option.UUID,
|
if option.AuthenticatedLength {
|
||||||
AlterID: uint16(option.AlterID),
|
options = append(options, vmess.ClientWithAuthenticatedLength())
|
||||||
Security: security,
|
}
|
||||||
HostName: option.Server,
|
client, err := vmess.NewClient(option.UUID, security, option.AlterID, options...)
|
||||||
Port: strconv.Itoa(option.Port),
|
|
||||||
IsAead: option.AlterID == 0,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -317,12 +316,13 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
|
|
||||||
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,
|
udp: option.UDP,
|
||||||
iface: option.Interface,
|
iface: option.Interface,
|
||||||
rmark: option.RoutingMark,
|
rmark: option.RoutingMark,
|
||||||
|
prefer: C.NewDNSPrefer(option.IPVersion),
|
||||||
},
|
},
|
||||||
client: client,
|
client: client,
|
||||||
option: &option,
|
option: &option,
|
||||||
@ -362,44 +362,29 @@ func NewVmess(option VmessOption) (*Vmess, error) {
|
|||||||
v.gunConfig = gunConfig
|
v.gunConfig = gunConfig
|
||||||
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
v.transport = gun.NewHTTP2Client(dialFn, tlsConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return v, nil
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseVmessAddr(metadata *C.Metadata) *vmess.DstAddr {
|
type threadSafePacketConn struct {
|
||||||
var addrType byte
|
net.PacketConn
|
||||||
var addr []byte
|
access sync.Mutex
|
||||||
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)
|
func (c *threadSafePacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
return &vmess.DstAddr{
|
c.access.Lock()
|
||||||
UDP: metadata.NetWork == C.UDP,
|
defer c.access.Unlock()
|
||||||
AddrType: addrType,
|
return c.PacketConn.WriteTo(b, addr)
|
||||||
Addr: addr,
|
|
||||||
Port: uint(port),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type vmessPacketConn struct {
|
type vmessPacketConn struct {
|
||||||
net.Conn
|
net.Conn
|
||||||
rAddr net.Addr
|
rAddr net.Addr
|
||||||
|
access sync.Mutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func (uc *vmessPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) {
|
func (uc *vmessPacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
|
||||||
|
uc.access.Lock()
|
||||||
|
defer uc.access.Unlock()
|
||||||
return uc.Conn.Write(b)
|
return uc.Conn.Write(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,24 +0,0 @@
|
|||||||
package outboundgroup
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
defaultGetProxiesDuration = time.Second * 5
|
|
||||||
)
|
|
||||||
|
|
||||||
func getProvidersProxies(providers []provider.ProxyProvider, touch bool) []C.Proxy {
|
|
||||||
proxies := []C.Proxy{}
|
|
||||||
for _, provider := range providers {
|
|
||||||
if touch {
|
|
||||||
proxies = append(proxies, provider.ProxiesWithTouch()...)
|
|
||||||
} else {
|
|
||||||
proxies = append(proxies, provider.Proxies()...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return proxies
|
|
||||||
}
|
|
@ -3,19 +3,19 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Fallback struct {
|
type Fallback struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single[[]C.Proxy]
|
testUrl string
|
||||||
providers []provider.ProxyProvider
|
selected string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) Now() string {
|
func (f *Fallback) Now() string {
|
||||||
@ -29,7 +29,11 @@ func (f *Fallback) DialContext(ctx context.Context, metadata *C.Metadata, opts .
|
|||||||
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
c, err := proxy.DialContext(ctx, metadata, f.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(f)
|
c.AppendToChains(f)
|
||||||
|
f.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
f.onDialFailed()
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -40,6 +44,7 @@ func (f *Fallback) ListenPacketContext(ctx context.Context, metadata *C.Metadata
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(f)
|
pc.AppendToChains(f)
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,8 +60,8 @@ func (f *Fallback) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
func (f *Fallback) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range f.proxies(false) {
|
for _, proxy := range f.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -72,35 +77,63 @@ func (f *Fallback) Unwrap(metadata *C.Metadata) C.Proxy {
|
|||||||
return proxy
|
return proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Fallback) proxies(touch bool) []C.Proxy {
|
|
||||||
elm, _, _ := f.single.Do(func() ([]C.Proxy, error) {
|
|
||||||
return getProvidersProxies(f.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
func (f *Fallback) findAliveProxy(touch bool) C.Proxy {
|
||||||
proxies := f.proxies(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.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if proxy.Name() == f.selected {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
} else {
|
||||||
|
f.selected = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies[0]
|
return proxies[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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.Alive() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(5000))
|
||||||
|
defer cancel()
|
||||||
|
_, _ = p.URLTest(ctx, f.testUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
func NewFallback(option *GroupCommonOption, providers []provider.ProxyProvider) *Fallback {
|
||||||
return &Fallback{
|
return &Fallback{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.Fallback,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.Fallback,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
|
||||||
providers: providers,
|
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
|
testUrl: option.URL,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
196
adapter/outboundgroup/groupbase.go
Normal file
196
adapter/outboundgroup/groupbase.go
Normal file
@ -0,0 +1,196 @@
|
|||||||
|
package outboundgroup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"github.com/Dreamacro/clash/tunnel"
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type GroupBase struct {
|
||||||
|
*outbound.Base
|
||||||
|
filter *regexp2.Regexp
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
failedTestMux sync.Mutex
|
||||||
|
failedTimes int
|
||||||
|
failedTime time.Time
|
||||||
|
failedTesting *atomic.Bool
|
||||||
|
proxies [][]C.Proxy
|
||||||
|
versions []atomic.Uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
type GroupBaseOption struct {
|
||||||
|
outbound.BaseOption
|
||||||
|
filter string
|
||||||
|
providers []provider.ProxyProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGroupBase(opt GroupBaseOption) *GroupBase {
|
||||||
|
var filter *regexp2.Regexp = nil
|
||||||
|
if opt.filter != "" {
|
||||||
|
filter = regexp2.MustCompile(opt.filter, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
gb := &GroupBase{
|
||||||
|
Base: outbound.NewBase(opt.BaseOption),
|
||||||
|
filter: filter,
|
||||||
|
providers: opt.providers,
|
||||||
|
failedTesting: atomic.NewBool(false),
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.proxies = make([][]C.Proxy, len(opt.providers))
|
||||||
|
gb.versions = make([]atomic.Uint32, len(opt.providers))
|
||||||
|
|
||||||
|
return gb
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) GetProxies(touch bool) []C.Proxy {
|
||||||
|
if gb.filter == nil {
|
||||||
|
var proxies []C.Proxy
|
||||||
|
for _, pd := range gb.providers {
|
||||||
|
if touch {
|
||||||
|
pd.Touch()
|
||||||
|
}
|
||||||
|
proxies = append(proxies, pd.Proxies()...)
|
||||||
|
}
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
|
}
|
||||||
|
return proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
for i, pd := range gb.providers {
|
||||||
|
if touch {
|
||||||
|
pd.Touch()
|
||||||
|
}
|
||||||
|
|
||||||
|
if pd.VehicleType() == types.Compatible {
|
||||||
|
gb.versions[i].Store(pd.Version())
|
||||||
|
gb.proxies[i] = pd.Proxies()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
version := gb.versions[i].Load()
|
||||||
|
if version != pd.Version() && gb.versions[i].CAS(version, pd.Version()) {
|
||||||
|
var (
|
||||||
|
proxies []C.Proxy
|
||||||
|
newProxies []C.Proxy
|
||||||
|
)
|
||||||
|
|
||||||
|
proxies = pd.Proxies()
|
||||||
|
for _, p := range proxies {
|
||||||
|
if mat, _ := gb.filter.FindStringMatch(p.Name()); mat != nil {
|
||||||
|
newProxies = append(newProxies, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
gb.proxies[i] = newProxies
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var proxies []C.Proxy
|
||||||
|
for _, p := range gb.proxies {
|
||||||
|
proxies = append(proxies, p...)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(proxies) == 0 {
|
||||||
|
return append(proxies, tunnel.Proxies()["COMPATIBLE"])
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) URLTest(ctx context.Context, url string) (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)
|
||||||
|
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() {
|
||||||
|
if gb.failedTesting.Load() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
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) > gb.failedTimeoutInterval() {
|
||||||
|
gb.failedTimes = 0
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debugln("ProxyGroup: %s failed count: %d", gb.Name(), gb.failedTimes)
|
||||||
|
if gb.failedTimes >= gb.maxFailedTimes() {
|
||||||
|
gb.failedTesting.Store(true)
|
||||||
|
log.Warnln("because %s failed multiple times, active health check", gb.Name())
|
||||||
|
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) failedIntervalTime() int64 {
|
||||||
|
return 5 * time.Second.Milliseconds()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) onDialSuccess() {
|
||||||
|
if !gb.failedTesting.Load() {
|
||||||
|
gb.failedTimes = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) maxFailedTimes() int {
|
||||||
|
return 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func (gb *GroupBase) failedTimeoutInterval() time.Duration {
|
||||||
|
return 5 * time.Second
|
||||||
|
}
|
@ -5,11 +5,12 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/common/cache"
|
||||||
"net"
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/murmur3"
|
"github.com/Dreamacro/clash/common/murmur3"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
@ -20,25 +21,25 @@ import (
|
|||||||
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
type strategyFn = func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy
|
||||||
|
|
||||||
type LoadBalance struct {
|
type LoadBalance struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single[[]C.Proxy]
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
strategyFn strategyFn
|
strategyFn strategyFn
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
@ -57,6 +58,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
|
||||||
|
|
||||||
@ -74,6 +85,9 @@ func (lb *LoadBalance) DialContext(ctx context.Context, metadata *C.Metadata, op
|
|||||||
defer func() {
|
defer func() {
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(lb)
|
c.AppendToChains(lb)
|
||||||
|
lb.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
lb.onDialFailed()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
@ -129,28 +143,62 @@ func strategyConsistentHashing() strategyFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// when availability is poor, traverse the entire list to get the available nodes
|
||||||
|
for _, proxy := range proxies {
|
||||||
|
if proxy.Alive() {
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxies[0]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func strategyStickySessions() strategyFn {
|
||||||
|
ttl := time.Minute * 10
|
||||||
|
maxRetry := 5
|
||||||
|
lruCache := cache.NewLRUCache[uint64, int](
|
||||||
|
cache.WithAge[uint64, int](int64(ttl.Seconds())),
|
||||||
|
cache.WithSize[uint64, int](1000))
|
||||||
|
return func(proxies []C.Proxy, metadata *C.Metadata) C.Proxy {
|
||||||
|
key := uint64(murmur3.Sum32([]byte(getKeyWithSrcAndDst(metadata))))
|
||||||
|
length := len(proxies)
|
||||||
|
idx, has := lruCache.Get(key)
|
||||||
|
if !has {
|
||||||
|
idx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||||
|
}
|
||||||
|
|
||||||
|
nowIdx := idx
|
||||||
|
for i := 1; i < maxRetry; i++ {
|
||||||
|
proxy := proxies[nowIdx]
|
||||||
|
if proxy.Alive() {
|
||||||
|
if nowIdx != idx {
|
||||||
|
lruCache.Delete(key)
|
||||||
|
lruCache.Set(key, nowIdx)
|
||||||
|
}
|
||||||
|
|
||||||
|
return proxy
|
||||||
|
} else {
|
||||||
|
nowIdx = int(jumpHash(key+uint64(time.Now().UnixNano()), int32(length)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lruCache.Delete(key)
|
||||||
|
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) C.Proxy {
|
||||||
proxies := lb.proxies(true)
|
proxies := lb.GetProxies(true)
|
||||||
return lb.strategyFn(proxies, metadata)
|
return lb.strategyFn(proxies, metadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lb *LoadBalance) proxies(touch bool) []C.Proxy {
|
|
||||||
elm, _, _ := lb.single.Do(func() ([]C.Proxy, error) {
|
|
||||||
return getProvidersProxies(lb.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
func (lb *LoadBalance) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
var all []string
|
||||||
for _, proxy := range lb.proxies(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{
|
||||||
@ -166,18 +214,22 @@ func NewLoadBalance(option *GroupCommonOption, providers []provider.ProxyProvide
|
|||||||
strategyFn = strategyConsistentHashing()
|
strategyFn = strategyConsistentHashing()
|
||||||
case "round-robin":
|
case "round-robin":
|
||||||
strategyFn = strategyRoundRobin()
|
strategyFn = strategyRoundRobin()
|
||||||
|
case "sticky-sessions":
|
||||||
|
strategyFn = strategyStickySessions()
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
return nil, fmt.Errorf("%w: %s", errStrategy, strategy)
|
||||||
}
|
}
|
||||||
return &LoadBalance{
|
return &LoadBalance{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.LoadBalance,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.LoadBalance,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
|
||||||
providers: providers,
|
|
||||||
strategyFn: strategyFn,
|
strategyFn: strategyFn,
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}, nil
|
}, nil
|
||||||
|
@ -3,7 +3,6 @@ package outboundgroup
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/adapter/provider"
|
"github.com/Dreamacro/clash/adapter/provider"
|
||||||
@ -39,23 +38,10 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
groupOption := &GroupCommonOption{
|
groupOption := &GroupCommonOption{
|
||||||
Lazy: true,
|
Lazy: true,
|
||||||
}
|
}
|
||||||
|
if err := decoder.Decode(config, groupOption); err != nil {
|
||||||
var (
|
|
||||||
filterRegx *regexp.Regexp
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
|
|
||||||
if err = decoder.Decode(config, groupOption); err != nil {
|
|
||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
|
|
||||||
if groupOption.Filter != "" {
|
|
||||||
filterRegx, err = regexp.Compile(groupOption.Filter)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if groupOption.Type == "" || groupOption.Name == "" {
|
if groupOption.Type == "" || groupOption.Name == "" {
|
||||||
return nil, errFormat
|
return nil, errFormat
|
||||||
}
|
}
|
||||||
@ -89,8 +75,12 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
providers = append(providers, pd)
|
providers = append(providers, pd)
|
||||||
providersMap[groupName] = pd
|
providersMap[groupName] = pd
|
||||||
} else {
|
} else {
|
||||||
if groupOption.URL == "" || groupOption.Interval == 0 {
|
if groupOption.URL == "" {
|
||||||
return nil, errMissHealthCheck
|
groupOption.URL = "http://www.gstatic.com/generate_204"
|
||||||
|
}
|
||||||
|
|
||||||
|
if groupOption.Interval == 0 {
|
||||||
|
groupOption.Interval = 300
|
||||||
}
|
}
|
||||||
|
|
||||||
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
hc := provider.NewHealthCheck(ps, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
||||||
@ -105,11 +95,13 @@ func ParseProxyGroup(config map[string]any, proxyMap map[string]C.Proxy, provide
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(groupOption.Use) != 0 {
|
if len(groupOption.Use) != 0 {
|
||||||
list, err := getProviders(providersMap, groupOption, filterRegx)
|
list, err := getProviders(providersMap, groupOption.Use)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
providers = append(providers, list...)
|
providers = append(providers, list...)
|
||||||
|
} else {
|
||||||
|
groupOption.Filter = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
var group C.ProxyAdapter
|
var group C.ProxyAdapter
|
||||||
@ -145,13 +137,8 @@ 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, groupOption *GroupCommonOption, filterRegx *regexp.Regexp) ([]types.ProxyProvider, error) {
|
func getProviders(mapping map[string]types.ProxyProvider, list []string) ([]types.ProxyProvider, error) {
|
||||||
var (
|
var ps []types.ProxyProvider
|
||||||
ps []types.ProxyProvider
|
|
||||||
list = groupOption.Use
|
|
||||||
groupName = groupOption.Name
|
|
||||||
)
|
|
||||||
|
|
||||||
for _, name := range list {
|
for _, name := range list {
|
||||||
p, ok := mapping[name]
|
p, ok := mapping[name]
|
||||||
if !ok {
|
if !ok {
|
||||||
@ -161,27 +148,6 @@ func getProviders(mapping map[string]types.ProxyProvider, groupOption *GroupComm
|
|||||||
if p.VehicleType() == types.Compatible {
|
if p.VehicleType() == types.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)
|
||||||
}
|
}
|
||||||
|
|
||||||
if filterRegx != nil {
|
|
||||||
var hc *provider.HealthCheck
|
|
||||||
if groupOption.Type == "select" || groupOption.Type == "relay" {
|
|
||||||
hc = provider.NewHealthCheck([]C.Proxy{}, "", 0, true)
|
|
||||||
} else {
|
|
||||||
if groupOption.URL == "" || groupOption.Interval == 0 {
|
|
||||||
return nil, errMissHealthCheck
|
|
||||||
}
|
|
||||||
hc = provider.NewHealthCheck([]C.Proxy{}, groupOption.URL, uint(groupOption.Interval), groupOption.Lazy)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok = mapping[groupName]; ok {
|
|
||||||
groupName += "->" + p.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
pd := p.(*provider.ProxySetProvider)
|
|
||||||
p = provider.NewProxyFilterProvider(groupName, pd, hc, filterRegx)
|
|
||||||
pd.RegisterProvidersInUse(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
ps = append(ps, p)
|
ps = append(ps, p)
|
||||||
}
|
}
|
||||||
return ps, nil
|
return ps, nil
|
||||||
|
@ -4,32 +4,20 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Relay struct {
|
type Relay struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
single *singledo.Single[[]C.Proxy]
|
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.Conn, error) {
|
||||||
var proxies []C.Proxy
|
proxies, chainProxies := r.proxies(metadata, true)
|
||||||
for _, proxy := range r.proxies(metadata, true) {
|
|
||||||
if proxy.Type() != C.Direct {
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch len(proxies) {
|
switch len(proxies) {
|
||||||
case 0:
|
case 0:
|
||||||
@ -38,165 +26,115 @@ func (r *Relay) DialContext(ctx context.Context, metadata *C.Metadata, opts ...d
|
|||||||
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return proxies[0].DialContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, err := r.streamContext(ctx, proxies, 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 {
|
if err != nil {
|
||||||
return nil, err
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
last := proxies[len(proxies)-1]
|
|
||||||
c, err = last.StreamConn(c, metadata)
|
c, err = last.StreamConn(c, metadata)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return outbound.NewConn(c, r), nil
|
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
|
// ListenPacketContext implements C.ProxyAdapter
|
||||||
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (C.PacketConn, error) {
|
func (r *Relay) ListenPacketContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.PacketConn, err error) {
|
||||||
var proxies []C.Proxy
|
proxies, chainProxies := r.proxies(metadata, true)
|
||||||
for _, proxy := range r.proxies(metadata, true) {
|
|
||||||
if proxy.Type() != C.Direct {
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
length := len(proxies)
|
switch len(proxies) {
|
||||||
|
|
||||||
switch length {
|
|
||||||
case 0:
|
case 0:
|
||||||
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
return outbound.NewDirect().ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
case 1:
|
case 1:
|
||||||
proxy := proxies[0]
|
return proxies[0].ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
||||||
if !proxy.SupportUDP() {
|
|
||||||
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported", proxy.Addr(), proxy.Name())
|
|
||||||
}
|
|
||||||
return proxy.ListenPacketContext(ctx, metadata, r.Base.DialOptions(opts...)...)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
first := proxies[0]
|
||||||
firstIndex = 0
|
last := proxies[len(proxies)-1]
|
||||||
nextIndex = 1
|
|
||||||
lastUDPOverTCPIndex = -1
|
|
||||||
rawUDPRelay = false
|
|
||||||
|
|
||||||
first = proxies[firstIndex]
|
|
||||||
last = proxies[length-1]
|
|
||||||
|
|
||||||
c net.Conn
|
|
||||||
cc net.Conn
|
|
||||||
err error
|
|
||||||
currentMeta *C.Metadata
|
|
||||||
)
|
|
||||||
|
|
||||||
if !last.SupportUDP() {
|
|
||||||
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported in relay chains", last.Addr(), last.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
rawUDPRelay, lastUDPOverTCPIndex = isRawUDPRelay(proxies)
|
|
||||||
|
|
||||||
if first.Type() == C.Socks5 {
|
|
||||||
cc1, err1 := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
|
||||||
if err1 != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
cc = cc1
|
|
||||||
tcpKeepAlive(cc)
|
|
||||||
|
|
||||||
var pc net.PacketConn
|
|
||||||
pc, err = dialer.ListenPacket(ctx, "udp", "", r.Base.DialOptions(opts...)...)
|
|
||||||
c = outbound.WrapConn(pc)
|
|
||||||
} else if rawUDPRelay {
|
|
||||||
var pc net.PacketConn
|
|
||||||
pc, err = dialer.ListenPacket(ctx, "udp", "", r.Base.DialOptions(opts...)...)
|
|
||||||
c = outbound.WrapConn(pc)
|
|
||||||
} else {
|
|
||||||
firstIndex = lastUDPOverTCPIndex
|
|
||||||
nextIndex = firstIndex + 1
|
|
||||||
first = proxies[firstIndex]
|
|
||||||
c, err = r.streamContext(ctx, proxies[:nextIndex], r.Base.DialOptions(opts...)...)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), r.Base.DialOptions(opts...)...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
}
|
}
|
||||||
|
tcpKeepAlive(c)
|
||||||
|
|
||||||
if nextIndex < length {
|
var currentMeta *C.Metadata
|
||||||
for i, proxy := range proxies[nextIndex:] { // raw udp in loop
|
for _, proxy := range proxies[1:] {
|
||||||
currentMeta, err = addrToMetadata(proxy.Addr())
|
currentMeta, err = addrToMetadata(proxy.Addr())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
|
||||||
currentMeta.NetWork = C.UDP
|
|
||||||
|
|
||||||
if !isRawUDP(first) && !first.SupportUDP() {
|
|
||||||
return nil, fmt.Errorf("%s connect error: proxy [%s] UDP is not supported in relay chains", first.Addr(), first.Name())
|
|
||||||
}
|
|
||||||
|
|
||||||
if needResolveIP(first, currentMeta) {
|
|
||||||
var ip netip.Addr
|
|
||||||
ip, err = resolver.ResolveProxyServerHost(currentMeta.Host)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("can't resolve ip: %w", err)
|
|
||||||
}
|
|
||||||
currentMeta.DstIP = ip
|
|
||||||
}
|
|
||||||
|
|
||||||
if cc != nil { // socks5
|
|
||||||
c, err = streamSocks5PacketConn(first, cc, c, currentMeta)
|
|
||||||
cc = nil
|
|
||||||
} else {
|
|
||||||
c, err = first.StreamPacketConn(c, currentMeta)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if proxy.Type() == C.Socks5 {
|
|
||||||
endIndex := nextIndex + i + 1
|
|
||||||
cc, err = r.streamContext(ctx, proxies[:endIndex], r.Base.DialOptions(opts...)...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
first = proxy
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c, err = first.StreamConn(c, currentMeta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
first = proxy
|
||||||
}
|
}
|
||||||
|
|
||||||
if cc != nil {
|
c, err = last.StreamConn(c, metadata)
|
||||||
c, err = streamSocks5PacketConn(last, cc, c, metadata)
|
|
||||||
} else {
|
|
||||||
c, err = last.StreamPacketConn(c, metadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
return nil, fmt.Errorf("%s connect error: %w", last.Addr(), err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return outbound.NewPacketConn(c.(net.PacketConn), r), nil
|
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
|
// SupportUDP implements C.ProxyAdapter
|
||||||
func (r *Relay) SupportUDP() bool {
|
func (r *Relay) SupportUDP() bool {
|
||||||
proxies := r.rawProxies(true)
|
proxies, _ := r.proxies(nil, false)
|
||||||
|
if len(proxies) == 0 { // C.Direct
|
||||||
l := len(proxies)
|
|
||||||
|
|
||||||
if l == 0 {
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
last := proxies[len(proxies)-1]
|
||||||
last := proxies[l-1]
|
return last.SupportUDP() && last.SupportUOT()
|
||||||
|
|
||||||
return isRawUDP(last) || last.SupportUDP()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (r *Relay) MarshalJSON() ([]byte, error) {
|
func (r *Relay) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range r.rawProxies(false) {
|
for _, proxy := range r.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -205,114 +143,49 @@ func (r *Relay) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Relay) rawProxies(touch bool) []C.Proxy {
|
func (r *Relay) proxies(metadata *C.Metadata, touch bool) ([]C.Proxy, []C.Proxy) {
|
||||||
elm, _, _ := r.single.Do(func() ([]C.Proxy, error) {
|
rawProxies := r.GetProxies(touch)
|
||||||
return getProvidersProxies(r.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
var proxies []C.Proxy
|
||||||
}
|
var chainProxies []C.Proxy
|
||||||
|
var targetProxies []C.Proxy
|
||||||
|
|
||||||
func (r *Relay) proxies(metadata *C.Metadata, touch bool) []C.Proxy {
|
for n, proxy := range rawProxies {
|
||||||
proxies := r.rawProxies(touch)
|
proxies = append(proxies, proxy)
|
||||||
|
chainProxies = append(chainProxies, proxy)
|
||||||
for n, proxy := range proxies {
|
|
||||||
subproxy := proxy.Unwrap(metadata)
|
subproxy := proxy.Unwrap(metadata)
|
||||||
for subproxy != nil {
|
for subproxy != nil {
|
||||||
|
chainProxies = append(chainProxies, subproxy)
|
||||||
proxies[n] = subproxy
|
proxies[n] = subproxy
|
||||||
subproxy = subproxy.Unwrap(metadata)
|
subproxy = subproxy.Unwrap(metadata)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return proxies
|
for _, proxy := range proxies {
|
||||||
}
|
if proxy.Type() != C.Direct && proxy.Type() != C.Compatible {
|
||||||
|
targetProxies = append(targetProxies, proxy)
|
||||||
func (r *Relay) streamContext(ctx context.Context, proxies []C.Proxy, opts ...dialer.Option) (net.Conn, error) {
|
|
||||||
first := proxies[0]
|
|
||||||
|
|
||||||
c, err := dialer.DialContext(ctx, "tcp", first.Addr(), opts...)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s connect error: %w", first.Addr(), err)
|
|
||||||
}
|
|
||||||
tcpKeepAlive(c)
|
|
||||||
|
|
||||||
if len(proxies) > 1 {
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return c, nil
|
return targetProxies, chainProxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func streamSocks5PacketConn(proxy C.Proxy, cc, c net.Conn, metadata *C.Metadata) (net.Conn, error) {
|
func (r *Relay) Addr() string {
|
||||||
pc, err := proxy.(*adapter.Proxy).ProxyAdapter.(*outbound.Socks5).StreamSocks5PacketConn(cc, c.(net.PacketConn), metadata)
|
proxies, _ := r.proxies(nil, true)
|
||||||
return outbound.WrapConn(pc), err
|
return proxies[len(proxies)-1].Addr()
|
||||||
}
|
|
||||||
|
|
||||||
func isRawUDPRelay(proxies []C.Proxy) (bool, int) {
|
|
||||||
var (
|
|
||||||
lastIndex = len(proxies) - 1
|
|
||||||
last = proxies[lastIndex]
|
|
||||||
isLastRawUDP = isRawUDP(last)
|
|
||||||
isUDPOverTCP = false
|
|
||||||
lastUDPOverTCPIndex = -1
|
|
||||||
)
|
|
||||||
|
|
||||||
for i := lastIndex; i >= 0; i-- {
|
|
||||||
p := proxies[i]
|
|
||||||
|
|
||||||
isUDPOverTCP = isUDPOverTCP || !isRawUDP(p)
|
|
||||||
|
|
||||||
if isLastRawUDP && isUDPOverTCP && lastUDPOverTCPIndex == -1 {
|
|
||||||
lastUDPOverTCPIndex = i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !isLastRawUDP {
|
|
||||||
lastUDPOverTCPIndex = lastIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
return !isUDPOverTCP, lastUDPOverTCPIndex
|
|
||||||
}
|
|
||||||
|
|
||||||
func isRawUDP(proxy C.ProxyAdapter) bool {
|
|
||||||
if proxy.Type() == C.Shadowsocks || proxy.Type() == C.ShadowsocksR || proxy.Type() == C.Socks5 {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func needResolveIP(proxy C.ProxyAdapter, metadata *C.Metadata) bool {
|
|
||||||
if metadata.Resolved() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if proxy.Type() != C.Vmess && proxy.Type() != C.Vless {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
func NewRelay(option *GroupCommonOption, providers []provider.ProxyProvider) *Relay {
|
||||||
return &Relay{
|
return &Relay{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.Relay,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.Relay,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
"",
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
|
||||||
providers: providers,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,18 +6,15 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter/outbound"
|
"github.com/Dreamacro/clash/adapter/outbound"
|
||||||
"github.com/Dreamacro/clash/common/singledo"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/constant/provider"
|
"github.com/Dreamacro/clash/constant/provider"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Selector struct {
|
type Selector struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
single *singledo.Single[C.Proxy]
|
|
||||||
selected string
|
selected string
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// DialContext implements C.ProxyAdapter
|
// DialContext implements C.ProxyAdapter
|
||||||
@ -49,8 +46,8 @@ func (s *Selector) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (s *Selector) MarshalJSON() ([]byte, error) {
|
func (s *Selector) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range getProvidersProxies(s.providers, false) {
|
for _, proxy := range s.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,10 +63,9 @@ func (s *Selector) Now() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) Set(name string) error {
|
func (s *Selector) Set(name string) error {
|
||||||
for _, proxy := range getProvidersProxies(s.providers, false) {
|
for _, proxy := range s.GetProxies(false) {
|
||||||
if proxy.Name() == name {
|
if proxy.Name() == name {
|
||||||
s.selected = name
|
s.selected = name
|
||||||
s.single.Reset()
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -78,37 +74,34 @@ func (s *Selector) Set(name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (s *Selector) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (s *Selector) Unwrap(*C.Metadata) C.Proxy {
|
||||||
return s.selectedProxy(true)
|
return s.selectedProxy(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
func (s *Selector) selectedProxy(touch bool) C.Proxy {
|
||||||
elm, _, _ := s.single.Do(func() (C.Proxy, error) {
|
proxies := s.GetProxies(touch)
|
||||||
proxies := getProvidersProxies(s.providers, touch)
|
for _, proxy := range proxies {
|
||||||
for _, proxy := range proxies {
|
if proxy.Name() == s.selected {
|
||||||
if proxy.Name() == s.selected {
|
return proxy
|
||||||
return proxy, nil
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return proxies[0], nil
|
return proxies[0]
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
func NewSelector(option *GroupCommonOption, providers []provider.ProxyProvider) *Selector {
|
||||||
selected := providers[0].Proxies()[0].Name()
|
|
||||||
return &Selector{
|
return &Selector{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.Selector,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.Selector,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[C.Proxy](defaultGetProxiesDuration),
|
selected: "COMPATIBLE",
|
||||||
providers: providers,
|
|
||||||
selected: selected,
|
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,13 +21,11 @@ func urlTestWithTolerance(tolerance uint16) urlTestOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type URLTest struct {
|
type URLTest struct {
|
||||||
*outbound.Base
|
*GroupBase
|
||||||
tolerance uint16
|
tolerance uint16
|
||||||
disableUDP bool
|
disableUDP bool
|
||||||
fastNode C.Proxy
|
fastNode C.Proxy
|
||||||
single *singledo.Single[[]C.Proxy]
|
|
||||||
fastSingle *singledo.Single[C.Proxy]
|
fastSingle *singledo.Single[C.Proxy]
|
||||||
providers []provider.ProxyProvider
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) Now() string {
|
func (u *URLTest) Now() string {
|
||||||
@ -39,6 +37,9 @@ func (u *URLTest) DialContext(ctx context.Context, metadata *C.Metadata, opts ..
|
|||||||
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
c, err = u.fast(true).DialContext(ctx, metadata, u.Base.DialOptions(opts...)...)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
c.AppendToChains(u)
|
c.AppendToChains(u)
|
||||||
|
u.onDialSuccess()
|
||||||
|
} else {
|
||||||
|
u.onDialFailed()
|
||||||
}
|
}
|
||||||
return c, err
|
return c, err
|
||||||
}
|
}
|
||||||
@ -49,25 +50,18 @@ func (u *URLTest) ListenPacketContext(ctx context.Context, metadata *C.Metadata,
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
pc.AppendToChains(u)
|
pc.AppendToChains(u)
|
||||||
}
|
}
|
||||||
|
|
||||||
return pc, err
|
return pc, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unwrap implements C.ProxyAdapter
|
// Unwrap implements C.ProxyAdapter
|
||||||
func (u *URLTest) Unwrap(metadata *C.Metadata) C.Proxy {
|
func (u *URLTest) Unwrap(*C.Metadata) C.Proxy {
|
||||||
return u.fast(true)
|
return u.fast(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *URLTest) proxies(touch bool) []C.Proxy {
|
|
||||||
elm, _, _ := u.single.Do(func() ([]C.Proxy, error) {
|
|
||||||
return getProvidersProxies(u.providers, touch), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return elm
|
|
||||||
}
|
|
||||||
|
|
||||||
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, _, _ := u.fastSingle.Do(func() (C.Proxy, error) {
|
||||||
proxies := u.proxies(touch)
|
proxies := u.GetProxies(touch)
|
||||||
fast := proxies[0]
|
fast := proxies[0]
|
||||||
min := fast.LastDelay()
|
min := fast.LastDelay()
|
||||||
fastNotExist := true
|
fastNotExist := true
|
||||||
@ -110,8 +104,8 @@ func (u *URLTest) SupportUDP() bool {
|
|||||||
|
|
||||||
// MarshalJSON implements C.ProxyAdapter
|
// MarshalJSON implements C.ProxyAdapter
|
||||||
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
func (u *URLTest) MarshalJSON() ([]byte, error) {
|
||||||
var all []string
|
all := []string{}
|
||||||
for _, proxy := range u.proxies(false) {
|
for _, proxy := range u.GetProxies(false) {
|
||||||
all = append(all, proxy.Name())
|
all = append(all, proxy.Name())
|
||||||
}
|
}
|
||||||
return json.Marshal(map[string]any{
|
return json.Marshal(map[string]any{
|
||||||
@ -136,15 +130,18 @@ func parseURLTestOption(config map[string]any) []urlTestOption {
|
|||||||
|
|
||||||
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
func NewURLTest(option *GroupCommonOption, providers []provider.ProxyProvider, options ...urlTestOption) *URLTest {
|
||||||
urlTest := &URLTest{
|
urlTest := &URLTest{
|
||||||
Base: outbound.NewBase(outbound.BaseOption{
|
GroupBase: NewGroupBase(GroupBaseOption{
|
||||||
Name: option.Name,
|
outbound.BaseOption{
|
||||||
Type: C.URLTest,
|
Name: option.Name,
|
||||||
Interface: option.Interface,
|
Type: C.URLTest,
|
||||||
RoutingMark: option.RoutingMark,
|
Interface: option.Interface,
|
||||||
|
RoutingMark: option.RoutingMark,
|
||||||
|
},
|
||||||
|
|
||||||
|
option.Filter,
|
||||||
|
providers,
|
||||||
}),
|
}),
|
||||||
single: singledo.NewSingle[[]C.Proxy](defaultGetProxiesDuration),
|
|
||||||
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
fastSingle: singledo.NewSingle[C.Proxy](time.Second * 10),
|
||||||
providers: providers,
|
|
||||||
disableUDP: option.DisableUDP,
|
disableUDP: option.DisableUDP,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -24,7 +24,8 @@ func addrToMetadata(rawAddress string) (addr *C.Metadata, err error) {
|
|||||||
DstIP: netip.Addr{},
|
DstIP: netip.Addr{},
|
||||||
DstPort: port,
|
DstPort: port,
|
||||||
}
|
}
|
||||||
return addr, nil
|
err = nil
|
||||||
|
return
|
||||||
} else if ip.Is4() {
|
} else if ip.Is4() {
|
||||||
addr = &C.Metadata{
|
addr = &C.Metadata{
|
||||||
AddrType: C.AtypIPv4,
|
AddrType: C.AtypIPv4,
|
||||||
@ -50,3 +51,7 @@ func tcpKeepAlive(c net.Conn) {
|
|||||||
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SelectAble interface {
|
||||||
|
Set(string) error
|
||||||
|
}
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
func ParseProxy(mapping map[string]any) (C.Proxy, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "proxy", WeaklyTypedInput: true})
|
||||||
proxyType, existType := mapping["type"].(string)
|
proxyType, existType := mapping["type"].(string)
|
||||||
if !existType {
|
if !existType {
|
||||||
@ -40,20 +40,14 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
proxy, err = outbound.NewSocks5(*socksOption)
|
||||||
socksOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy = outbound.NewSocks5(*socksOption)
|
|
||||||
case "http":
|
case "http":
|
||||||
httpOption := &outbound.HttpOption{}
|
httpOption := &outbound.HttpOption{}
|
||||||
err = decoder.Decode(mapping, httpOption)
|
err = decoder.Decode(mapping, httpOption)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
proxy, err = outbound.NewHttp(*httpOption)
|
||||||
httpOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy = outbound.NewHttp(*httpOption)
|
|
||||||
case "vmess":
|
case "vmess":
|
||||||
vmessOption := &outbound.VmessOption{
|
vmessOption := &outbound.VmessOption{
|
||||||
HTTPOpts: outbound.HTTPOptions{
|
HTTPOpts: outbound.HTTPOptions{
|
||||||
@ -65,9 +59,6 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
vmessOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewVmess(*vmessOption)
|
proxy, err = outbound.NewVmess(*vmessOption)
|
||||||
case "vless":
|
case "vless":
|
||||||
vlessOption := &outbound.VlessOption{}
|
vlessOption := &outbound.VlessOption{}
|
||||||
@ -75,9 +66,6 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
vlessOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewVless(*vlessOption)
|
proxy, err = outbound.NewVless(*vlessOption)
|
||||||
case "snell":
|
case "snell":
|
||||||
snellOption := &outbound.SnellOption{}
|
snellOption := &outbound.SnellOption{}
|
||||||
@ -92,10 +80,14 @@ func ParseProxy(mapping map[string]any, forceCertVerify bool) (C.Proxy, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if forceCertVerify {
|
|
||||||
trojanOption.SkipCertVerify = false
|
|
||||||
}
|
|
||||||
proxy, err = outbound.NewTrojan(*trojanOption)
|
proxy, err = outbound.NewTrojan(*trojanOption)
|
||||||
|
case "hysteria":
|
||||||
|
hyOption := &outbound.HysteriaOption{}
|
||||||
|
err = decoder.Decode(mapping, hyOption)
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
proxy, err = outbound.NewHysteria(*hyOption)
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
return nil, fmt.Errorf("unsupport proxy type: %s", proxyType)
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,7 @@ package provider
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"github.com/Dreamacro/clash/common/singledo"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/batch"
|
"github.com/Dreamacro/clash/common/batch"
|
||||||
@ -26,15 +27,14 @@ type HealthCheck struct {
|
|||||||
lazy bool
|
lazy bool
|
||||||
lastTouch *atomic.Int64
|
lastTouch *atomic.Int64
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
|
singleDo *singledo.Single[struct{}]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) process() {
|
func (hc *HealthCheck) process() {
|
||||||
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
t := time.NewTicker(30 * time.Second)
|
time.Sleep(30 * time.Second)
|
||||||
<-t.C
|
|
||||||
t.Stop()
|
|
||||||
hc.check()
|
hc.check()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
@ -65,22 +65,21 @@ func (hc *HealthCheck) touch() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) check() {
|
func (hc *HealthCheck) check() {
|
||||||
proxies := hc.proxies
|
_, _, _ = hc.singleDo.Do(func() (struct{}, error) {
|
||||||
if len(proxies) == 0 {
|
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
||||||
return
|
for _, proxy := range hc.proxies {
|
||||||
}
|
p := proxy
|
||||||
|
b.Go(p.Name(), func() (bool, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
||||||
|
defer cancel()
|
||||||
|
_, _ = p.URLTest(ctx, hc.url)
|
||||||
|
return false, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
b, _ := batch.New[bool](context.Background(), batch.WithConcurrencyNum[bool](10))
|
b.Wait()
|
||||||
for _, proxy := range proxies {
|
return struct{}{}, nil
|
||||||
p := proxy
|
})
|
||||||
b.Go(p.Name(), func() (bool, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
|
||||||
defer cancel()
|
|
||||||
_, _ = p.URLTest(ctx, hc.url)
|
|
||||||
return false, nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
b.Wait()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) close() {
|
func (hc *HealthCheck) close() {
|
||||||
@ -95,5 +94,6 @@ func NewHealthCheck(proxies []C.Proxy, url string, interval uint, lazy bool) *He
|
|||||||
lazy: lazy,
|
lazy: lazy,
|
||||||
lastTouch: atomic.NewInt64(0),
|
lastTouch: atomic.NewInt64(0),
|
||||||
done: make(chan struct{}, 1),
|
done: make(chan struct{}, 1),
|
||||||
|
singleDo: singledo.NewSingle[struct{}](time.Second),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,6 +3,7 @@ package provider
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/structure"
|
"github.com/Dreamacro/clash/common/structure"
|
||||||
@ -20,18 +21,15 @@ type healthCheckSchema struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxyProviderSchema struct {
|
type proxyProviderSchema struct {
|
||||||
Type string `provider:"type"`
|
Type string `provider:"type"`
|
||||||
Path string `provider:"path"`
|
Path string `provider:"path"`
|
||||||
URL string `provider:"url,omitempty"`
|
URL string `provider:"url,omitempty"`
|
||||||
Interval int `provider:"interval,omitempty"`
|
Interval int `provider:"interval,omitempty"`
|
||||||
Filter string `provider:"filter,omitempty"`
|
Filter string `provider:"filter,omitempty"`
|
||||||
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
|
||||||
ForceCertVerify bool `provider:"force-cert-verify,omitempty"`
|
|
||||||
PrefixName string `provider:"prefix-name,omitempty"`
|
|
||||||
Header map[string][]string `provider:"header,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ParseProxyProvider(name string, mapping map[string]any, forceCertVerify bool) (types.ProxyProvider, error) {
|
func ParseProxyProvider(name string, mapping map[string]any) (types.ProxyProvider, error) {
|
||||||
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
|
||||||
|
|
||||||
schema := &proxyProviderSchema{
|
schema := &proxyProviderSchema{
|
||||||
@ -39,11 +37,6 @@ func ParseProxyProvider(name string, mapping map[string]any, forceCertVerify boo
|
|||||||
Lazy: true,
|
Lazy: true,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if forceCertVerify {
|
|
||||||
schema.ForceCertVerify = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := decoder.Decode(mapping, schema); err != nil {
|
if err := decoder.Decode(mapping, schema); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -59,14 +52,14 @@ func ParseProxyProvider(name string, mapping map[string]any, forceCertVerify boo
|
|||||||
var vehicle types.Vehicle
|
var vehicle types.Vehicle
|
||||||
switch schema.Type {
|
switch schema.Type {
|
||||||
case "file":
|
case "file":
|
||||||
vehicle = NewFileVehicle(path)
|
vehicle = resource.NewFileVehicle(path)
|
||||||
case "http":
|
case "http":
|
||||||
vehicle = NewHTTPVehicle(schema.URL, path, schema.Header)
|
vehicle = resource.NewHTTPVehicle(schema.URL, path)
|
||||||
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
|
filter := schema.Filter
|
||||||
return NewProxySetProvider(name, interval, filter, vehicle, hc, schema.ForceCertVerify, schema.PrefixName)
|
return NewProxySetProvider(name, interval, filter, vehicle, hc)
|
||||||
}
|
}
|
||||||
|
@ -4,12 +4,13 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"github.com/Dreamacro/clash/common/convert"
|
||||||
|
"github.com/Dreamacro/clash/component/resource"
|
||||||
|
"github.com/dlclark/regexp2"
|
||||||
"runtime"
|
"runtime"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/adapter"
|
"github.com/Dreamacro/clash/adapter"
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
types "github.com/Dreamacro/clash/constant/provider"
|
types "github.com/Dreamacro/clash/constant/provider"
|
||||||
|
|
||||||
@ -30,10 +31,10 @@ type ProxySetProvider struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type proxySetProvider struct {
|
type proxySetProvider struct {
|
||||||
*fetcher[[]C.Proxy]
|
*resource.Fetcher[[]C.Proxy]
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
providersInUse []types.ProxyProvider
|
version uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -42,12 +43,16 @@ func (pp *proxySetProvider) MarshalJSON() ([]byte, error) {
|
|||||||
"type": pp.Type().String(),
|
"type": pp.Type().String(),
|
||||||
"vehicleType": pp.VehicleType().String(),
|
"vehicleType": pp.VehicleType().String(),
|
||||||
"proxies": pp.Proxies(),
|
"proxies": pp.Proxies(),
|
||||||
"updatedAt": pp.updatedAt,
|
"updatedAt": pp.UpdatedAt,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pp *proxySetProvider) Version() uint32 {
|
||||||
|
return pp.version
|
||||||
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Name() string {
|
func (pp *proxySetProvider) Name() string {
|
||||||
return pp.name
|
return pp.Fetcher.Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) HealthCheck() {
|
func (pp *proxySetProvider) HealthCheck() {
|
||||||
@ -55,20 +60,19 @@ func (pp *proxySetProvider) HealthCheck() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Update() error {
|
func (pp *proxySetProvider) Update() error {
|
||||||
elm, same, err := pp.fetcher.Update()
|
elm, same, err := pp.Fetcher.Update()
|
||||||
if err == nil && !same {
|
if err == nil && !same {
|
||||||
pp.onUpdate(elm)
|
pp.OnUpdate(elm)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) Initial() error {
|
func (pp *proxySetProvider) Initial() error {
|
||||||
elm, err := pp.fetcher.Initial()
|
elm, err := pp.Fetcher.Initial()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
pp.OnUpdate(elm)
|
||||||
pp.onUpdate(elm)
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -80,31 +84,25 @@ func (pp *proxySetProvider) Proxies() []C.Proxy {
|
|||||||
return pp.proxies
|
return pp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) ProxiesWithTouch() []C.Proxy {
|
func (pp *proxySetProvider) Touch() {
|
||||||
pp.healthCheck.touch()
|
pp.healthCheck.touch()
|
||||||
return pp.Proxies()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
func (pp *proxySetProvider) setProxies(proxies []C.Proxy) {
|
||||||
pp.proxies = proxies
|
pp.proxies = proxies
|
||||||
pp.healthCheck.setProxy(proxies)
|
pp.healthCheck.setProxy(proxies)
|
||||||
|
if pp.healthCheck.auto() {
|
||||||
for _, use := range pp.providersInUse {
|
defer func() { go pp.healthCheck.check() }()
|
||||||
_ = use.Update()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (pp *proxySetProvider) RegisterProvidersInUse(providers ...types.ProxyProvider) {
|
|
||||||
pp.providersInUse = append(pp.providersInUse, providers...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopProxyProvider(pd *ProxySetProvider) {
|
func stopProxyProvider(pd *ProxySetProvider) {
|
||||||
pd.healthCheck.close()
|
pd.healthCheck.close()
|
||||||
_ = pd.fetcher.Destroy()
|
_ = pd.Fetcher.Destroy()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewProxySetProvider(name string, interval time.Duration, filter string, vehicle types.Vehicle, hc *HealthCheck, forceCertVerify bool, prefixName string) (*ProxySetProvider, error) {
|
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 {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
return nil, fmt.Errorf("invalid filter regex: %w", err)
|
||||||
}
|
}
|
||||||
@ -118,8 +116,8 @@ func NewProxySetProvider(name string, interval time.Duration, filter string, veh
|
|||||||
healthCheck: hc,
|
healthCheck: hc,
|
||||||
}
|
}
|
||||||
|
|
||||||
fetcher := newFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg, forceCertVerify, prefixName), proxiesOnUpdate(pd))
|
fetcher := resource.NewFetcher[[]C.Proxy](name, interval, vehicle, proxiesParseAndFilter(filter, filterReg), proxiesOnUpdate(pd))
|
||||||
pd.fetcher = fetcher
|
pd.Fetcher = fetcher
|
||||||
|
|
||||||
wrapper := &ProxySetProvider{pd}
|
wrapper := &ProxySetProvider{pd}
|
||||||
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
runtime.SetFinalizer(wrapper, stopProxyProvider)
|
||||||
@ -135,6 +133,7 @@ type compatibleProvider struct {
|
|||||||
name string
|
name string
|
||||||
healthCheck *HealthCheck
|
healthCheck *HealthCheck
|
||||||
proxies []C.Proxy
|
proxies []C.Proxy
|
||||||
|
version uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
||||||
@ -146,6 +145,10 @@ func (cp *compatibleProvider) MarshalJSON() ([]byte, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (cp *compatibleProvider) Version() uint32 {
|
||||||
|
return cp.version
|
||||||
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) Name() string {
|
func (cp *compatibleProvider) Name() string {
|
||||||
return cp.name
|
return cp.name
|
||||||
}
|
}
|
||||||
@ -174,9 +177,8 @@ func (cp *compatibleProvider) Proxies() []C.Proxy {
|
|||||||
return cp.proxies
|
return cp.proxies
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cp *compatibleProvider) ProxiesWithTouch() []C.Proxy {
|
func (cp *compatibleProvider) Touch() {
|
||||||
cp.healthCheck.touch()
|
cp.healthCheck.touch()
|
||||||
return cp.Proxies()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopCompatibleProvider(pd *CompatibleProvider) {
|
func stopCompatibleProvider(pd *CompatibleProvider) {
|
||||||
@ -203,112 +205,21 @@ func NewCompatibleProvider(name string, proxies []C.Proxy, hc *HealthCheck) (*Co
|
|||||||
return wrapper, nil
|
return wrapper, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ProxyFilterProvider for filter provider
|
|
||||||
type ProxyFilterProvider struct {
|
|
||||||
*proxyFilterProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
type proxyFilterProvider struct {
|
|
||||||
name string
|
|
||||||
psd *ProxySetProvider
|
|
||||||
proxies []C.Proxy
|
|
||||||
filter *regexp.Regexp
|
|
||||||
healthCheck *HealthCheck
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) MarshalJSON() ([]byte, error) {
|
|
||||||
return json.Marshal(map[string]any{
|
|
||||||
"name": pf.Name(),
|
|
||||||
"type": pf.Type().String(),
|
|
||||||
"vehicleType": pf.VehicleType().String(),
|
|
||||||
"proxies": pf.Proxies(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Name() string {
|
|
||||||
return pf.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) HealthCheck() {
|
|
||||||
pf.healthCheck.check()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Update() error {
|
|
||||||
var proxies []C.Proxy
|
|
||||||
if pf.filter != nil {
|
|
||||||
for _, proxy := range pf.psd.Proxies() {
|
|
||||||
if !pf.filter.MatchString(proxy.Name()) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
proxies = append(proxies, proxy)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
proxies = pf.psd.Proxies()
|
|
||||||
}
|
|
||||||
|
|
||||||
pf.proxies = proxies
|
|
||||||
pf.healthCheck.setProxy(proxies)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Initial() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) VehicleType() types.VehicleType {
|
|
||||||
return pf.psd.VehicleType()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Type() types.ProviderType {
|
|
||||||
return types.Proxy
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) Proxies() []C.Proxy {
|
|
||||||
return pf.proxies
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pf *proxyFilterProvider) ProxiesWithTouch() []C.Proxy {
|
|
||||||
pf.healthCheck.touch()
|
|
||||||
return pf.Proxies()
|
|
||||||
}
|
|
||||||
|
|
||||||
func stopProxyFilterProvider(pf *ProxyFilterProvider) {
|
|
||||||
pf.healthCheck.close()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewProxyFilterProvider(name string, psd *ProxySetProvider, hc *HealthCheck, filterRegx *regexp.Regexp) *ProxyFilterProvider {
|
|
||||||
pd := &proxyFilterProvider{
|
|
||||||
psd: psd,
|
|
||||||
name: name,
|
|
||||||
healthCheck: hc,
|
|
||||||
filter: filterRegx,
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = pd.Update()
|
|
||||||
|
|
||||||
if hc.auto() {
|
|
||||||
go hc.process()
|
|
||||||
}
|
|
||||||
|
|
||||||
wrapper := &ProxyFilterProvider{pd}
|
|
||||||
runtime.SetFinalizer(wrapper, stopProxyFilterProvider)
|
|
||||||
return wrapper
|
|
||||||
}
|
|
||||||
|
|
||||||
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
func proxiesOnUpdate(pd *proxySetProvider) func([]C.Proxy) {
|
||||||
return func(elm []C.Proxy) {
|
return func(elm []C.Proxy) {
|
||||||
pd.setProxies(elm)
|
pd.setProxies(elm)
|
||||||
|
pd.version += 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func proxiesParseAndFilter(filter string, filterReg *regexp.Regexp, forceCertVerify bool, prefixName string) parser[[]C.Proxy] {
|
func proxiesParseAndFilter(filter string, filterReg *regexp2.Regexp) resource.Parser[[]C.Proxy] {
|
||||||
return func(buf []byte) ([]C.Proxy, error) {
|
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 {
|
||||||
proxies, err1 := convert.ConvertsV2Ray(buf)
|
proxies, err1 := convert.ConvertsV2Ray(buf)
|
||||||
if err1 != nil {
|
if err1 != nil {
|
||||||
return nil, fmt.Errorf("%w, %s", err, err1.Error())
|
return nil, fmt.Errorf("%s, %w", err.Error(), err1)
|
||||||
}
|
}
|
||||||
schema.Proxies = proxies
|
schema.Proxies = proxies
|
||||||
}
|
}
|
||||||
@ -319,15 +230,12 @@ func proxiesParseAndFilter(filter string, filterReg *regexp.Regexp, forceCertVer
|
|||||||
|
|
||||||
proxies := []C.Proxy{}
|
proxies := []C.Proxy{}
|
||||||
for idx, mapping := range schema.Proxies {
|
for idx, mapping := range schema.Proxies {
|
||||||
if name, ok := mapping["name"]; ok && len(filter) > 0 && !filterReg.MatchString(name.(string)) {
|
name, ok := mapping["name"]
|
||||||
|
mat, _ := filterReg.FindStringMatch(name.(string))
|
||||||
|
if ok && len(filter) > 0 && mat == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
proxy, err := adapter.ParseProxy(mapping)
|
||||||
if prefixName != "" {
|
|
||||||
mapping["name"] = prefixName + mapping["name"].(string)
|
|
||||||
}
|
|
||||||
|
|
||||||
proxy, err := adapter.ParseProxy(mapping, forceCertVerify)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
return nil, fmt.Errorf("proxy %d error: %w", idx, err)
|
||||||
}
|
}
|
||||||
|
@ -1,114 +0,0 @@
|
|||||||
package provider
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/common/convert"
|
|
||||||
"github.com/Dreamacro/clash/component/dialer"
|
|
||||||
C "github.com/Dreamacro/clash/constant"
|
|
||||||
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
|
|
||||||
header http.Header
|
|
||||||
}
|
|
||||||
|
|
||||||
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)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if h.header != nil {
|
|
||||||
req.Header = h.header
|
|
||||||
}
|
|
||||||
|
|
||||||
if user := uri.User; user != nil {
|
|
||||||
password, _ := user.Password()
|
|
||||||
req.SetBasicAuth(user.Username(), password)
|
|
||||||
}
|
|
||||||
|
|
||||||
convert.SetUserAgent(req.Header)
|
|
||||||
|
|
||||||
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) (conn net.Conn, err error) {
|
|
||||||
conn, err = dialer.DialContext(ctx, network, address) // with direct
|
|
||||||
if err != nil {
|
|
||||||
// fallback to tun if tun enabled
|
|
||||||
conn, err = (&net.Dialer{Timeout: C.DefaultTCPTimeout}).Dial(network, address)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
client := http.Client{Transport: transport}
|
|
||||||
resp, err := client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
_ = resp.Body.Close()
|
|
||||||
}()
|
|
||||||
|
|
||||||
buf, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return buf, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHTTPVehicle(url string, path string, header http.Header) *HTTPVehicle {
|
|
||||||
return &HTTPVehicle{url, path, header}
|
|
||||||
}
|
|
28
check_amd64.sh
Normal file
28
check_amd64.sh
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
flags=$(grep '^flags\b' </proc/cpuinfo | head -n 1)
|
||||||
|
flags=" ${flags#*:} "
|
||||||
|
|
||||||
|
has_flags () {
|
||||||
|
for flag; do
|
||||||
|
case "$flags" in
|
||||||
|
*" $flag "*) :;;
|
||||||
|
*) return 1;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
}
|
||||||
|
|
||||||
|
determine_level () {
|
||||||
|
level=0
|
||||||
|
has_flags lm cmov cx8 fpu fxsr mmx syscall sse2 || return 0
|
||||||
|
level=1
|
||||||
|
has_flags cx16 lahf_lm popcnt sse4_1 sse4_2 ssse3 || return 0
|
||||||
|
level=2
|
||||||
|
has_flags avx avx2 bmi1 bmi2 f16c fma abm movbe xsave || return 0
|
||||||
|
level=3
|
||||||
|
has_flags avx512f avx512bw avx512cd avx512dq avx512vl || return 0
|
||||||
|
level=4
|
||||||
|
}
|
||||||
|
|
||||||
|
determine_level
|
||||||
|
echo "Your CPU supports amd64-v$level"
|
||||||
|
return $level
|
2
common/cache/cache.go
vendored
2
common/cache/cache.go
vendored
@ -61,7 +61,7 @@ func (c *cache[K, V]) GetWithExpire(key K) (payload V, expired time.Time) {
|
|||||||
|
|
||||||
func (c *cache[K, V]) cleanup() {
|
func (c *cache[K, V]) cleanup() {
|
||||||
c.mapping.Range(func(k, v any) bool {
|
c.mapping.Range(func(k, v any) bool {
|
||||||
key := k
|
key := k.(string)
|
||||||
elm := v.(*element[V])
|
elm := v.(*element[V])
|
||||||
if time.Since(elm.Expired) > 0 {
|
if time.Since(elm.Expired) > 0 {
|
||||||
c.mapping.Delete(key)
|
c.mapping.Delete(key)
|
||||||
|
@ -1,303 +0,0 @@
|
|||||||
package cert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/sha1"
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"crypto/x509/pkix"
|
|
||||||
"encoding/pem"
|
|
||||||
"math/big"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var currentSerialNumber = time.Now().Unix()
|
|
||||||
|
|
||||||
type Config struct {
|
|
||||||
ca *x509.Certificate
|
|
||||||
caPrivateKey *rsa.PrivateKey
|
|
||||||
|
|
||||||
roots *x509.CertPool
|
|
||||||
|
|
||||||
privateKey *rsa.PrivateKey
|
|
||||||
|
|
||||||
validity time.Duration
|
|
||||||
keyID []byte
|
|
||||||
organization string
|
|
||||||
|
|
||||||
certsStorage CertsStorage
|
|
||||||
}
|
|
||||||
|
|
||||||
type CertsStorage interface {
|
|
||||||
Get(key string) (*tls.Certificate, bool)
|
|
||||||
|
|
||||||
Set(key string, cert *tls.Certificate)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAuthority(name, organization string, validity time.Duration) (*x509.Certificate, *rsa.PrivateKey, error) {
|
|
||||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
pub := privateKey.Public()
|
|
||||||
|
|
||||||
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
h := sha1.New()
|
|
||||||
_, err = h.Write(pkixPub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
keyID := h.Sum(nil)
|
|
||||||
|
|
||||||
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
|
||||||
|
|
||||||
tmpl := &x509.Certificate{
|
|
||||||
SerialNumber: big.NewInt(serial),
|
|
||||||
Subject: pkix.Name{
|
|
||||||
CommonName: name,
|
|
||||||
Organization: []string{organization},
|
|
||||||
},
|
|
||||||
SubjectKeyId: keyID,
|
|
||||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
NotBefore: time.Now().Add(-validity),
|
|
||||||
NotAfter: time.Now().Add(validity),
|
|
||||||
DNSNames: []string{name},
|
|
||||||
IsCA: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
raw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, privateKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
x509c, err := x509.ParseCertificate(raw)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return x509c, privateKey, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConfig(ca *x509.Certificate, caPrivateKey *rsa.PrivateKey) (*Config, error) {
|
|
||||||
roots := x509.NewCertPool()
|
|
||||||
roots.AddCert(ca)
|
|
||||||
|
|
||||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
pub := privateKey.Public()
|
|
||||||
|
|
||||||
pkixPub, err := x509.MarshalPKIXPublicKey(pub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
h := sha1.New()
|
|
||||||
_, err = h.Write(pkixPub)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
keyID := h.Sum(nil)
|
|
||||||
|
|
||||||
return &Config{
|
|
||||||
ca: ca,
|
|
||||||
caPrivateKey: caPrivateKey,
|
|
||||||
privateKey: privateKey,
|
|
||||||
keyID: keyID,
|
|
||||||
validity: time.Hour,
|
|
||||||
organization: "Clash",
|
|
||||||
certsStorage: NewDomainTrieCertsStorage(),
|
|
||||||
roots: roots,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) GetCA() *x509.Certificate {
|
|
||||||
return c.ca
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) SetOrganization(organization string) {
|
|
||||||
c.organization = organization
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) SetValidity(validity time.Duration) {
|
|
||||||
c.validity = validity
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) NewTLSConfigForHost(hostname string) *tls.Config {
|
|
||||||
tlsConfig := &tls.Config{
|
|
||||||
GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
|
||||||
host := clientHello.ServerName
|
|
||||||
if host == "" {
|
|
||||||
host = hostname
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.GetOrCreateCert(host)
|
|
||||||
},
|
|
||||||
NextProtos: []string{"http/1.1"},
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsConfig.InsecureSkipVerify = true
|
|
||||||
|
|
||||||
return tlsConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) GetOrCreateCert(hostname string, ips ...net.IP) (*tls.Certificate, error) {
|
|
||||||
var leaf *x509.Certificate
|
|
||||||
tlsCertificate, ok := c.certsStorage.Get(hostname)
|
|
||||||
if ok {
|
|
||||||
leaf = tlsCertificate.Leaf
|
|
||||||
if _, err := leaf.Verify(x509.VerifyOptions{
|
|
||||||
DNSName: hostname,
|
|
||||||
Roots: c.roots,
|
|
||||||
}); err == nil {
|
|
||||||
return tlsCertificate, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
key = hostname
|
|
||||||
topHost = hostname
|
|
||||||
wildcardHost = "*." + hostname
|
|
||||||
dnsNames []string
|
|
||||||
)
|
|
||||||
|
|
||||||
if ip := net.ParseIP(hostname); ip != nil {
|
|
||||||
ips = append(ips, ip)
|
|
||||||
} else {
|
|
||||||
parts := strings.Split(hostname, ".")
|
|
||||||
l := len(parts)
|
|
||||||
|
|
||||||
if leaf != nil {
|
|
||||||
dnsNames = append(dnsNames, leaf.DNSNames...)
|
|
||||||
}
|
|
||||||
|
|
||||||
if l > 2 {
|
|
||||||
topIndex := l - 2
|
|
||||||
topHost = strings.Join(parts[topIndex:], ".")
|
|
||||||
|
|
||||||
for i := topIndex; i > 0; i-- {
|
|
||||||
wildcardHost = "*." + strings.Join(parts[i:], ".")
|
|
||||||
|
|
||||||
if i == topIndex && (len(dnsNames) == 0 || dnsNames[0] != topHost) {
|
|
||||||
dnsNames = append(dnsNames, topHost, wildcardHost)
|
|
||||||
} else if !hasDnsNames(dnsNames, wildcardHost) {
|
|
||||||
dnsNames = append(dnsNames, wildcardHost)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
dnsNames = append(dnsNames, topHost, wildcardHost)
|
|
||||||
}
|
|
||||||
|
|
||||||
key = "+." + topHost
|
|
||||||
}
|
|
||||||
|
|
||||||
serial := atomic.AddInt64(¤tSerialNumber, 1)
|
|
||||||
|
|
||||||
tmpl := &x509.Certificate{
|
|
||||||
SerialNumber: big.NewInt(serial),
|
|
||||||
Subject: pkix.Name{
|
|
||||||
CommonName: topHost,
|
|
||||||
Organization: []string{c.organization},
|
|
||||||
},
|
|
||||||
SubjectKeyId: c.keyID,
|
|
||||||
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
NotBefore: time.Now().Add(-c.validity),
|
|
||||||
NotAfter: time.Now().Add(c.validity),
|
|
||||||
DNSNames: dnsNames,
|
|
||||||
IPAddresses: ips,
|
|
||||||
}
|
|
||||||
|
|
||||||
raw, err := x509.CreateCertificate(rand.Reader, tmpl, c.ca, c.privateKey.Public(), c.caPrivateKey)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
x509c, err := x509.ParseCertificate(raw)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
tlsCertificate = &tls.Certificate{
|
|
||||||
Certificate: [][]byte{raw, c.ca.Raw},
|
|
||||||
PrivateKey: c.privateKey,
|
|
||||||
Leaf: x509c,
|
|
||||||
}
|
|
||||||
|
|
||||||
c.certsStorage.Set(key, tlsCertificate)
|
|
||||||
return tlsCertificate, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GenerateAndSave generate CA private key and CA certificate and dump them to file
|
|
||||||
func GenerateAndSave(caPath string, caKeyPath string) error {
|
|
||||||
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
tmpl := &x509.Certificate{
|
|
||||||
SerialNumber: big.NewInt(time.Now().Unix()),
|
|
||||||
Subject: pkix.Name{
|
|
||||||
Country: []string{"US"},
|
|
||||||
CommonName: "Clash Root CA",
|
|
||||||
Organization: []string{"Clash Trust Services"},
|
|
||||||
},
|
|
||||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
|
|
||||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
|
||||||
NotBefore: time.Now().Add(-(time.Hour * 24 * 60)),
|
|
||||||
NotAfter: time.Now().Add(time.Hour * 24 * 365 * 25),
|
|
||||||
BasicConstraintsValid: true,
|
|
||||||
IsCA: true,
|
|
||||||
}
|
|
||||||
|
|
||||||
caRaw, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, privateKey.Public(), privateKey)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
caOut, err := os.OpenFile(caPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer func(caOut *os.File) {
|
|
||||||
_ = caOut.Close()
|
|
||||||
}(caOut)
|
|
||||||
|
|
||||||
if err = pem.Encode(caOut, &pem.Block{Type: "CERTIFICATE", Bytes: caRaw}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
caKeyOut, err := os.OpenFile(caKeyPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer func(caKeyOut *os.File) {
|
|
||||||
_ = caKeyOut.Close()
|
|
||||||
}(caKeyOut)
|
|
||||||
|
|
||||||
if err = pem.Encode(caKeyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func hasDnsNames(dnsNames []string, hostname string) bool {
|
|
||||||
for _, name := range dnsNames {
|
|
||||||
if name == hostname {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
@ -1,104 +0,0 @@
|
|||||||
package cert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
"crypto/x509"
|
|
||||||
"net"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestCert(t *testing.T) {
|
|
||||||
ca, privateKey, err := NewAuthority("Clash ca", "Clash", 24*time.Hour)
|
|
||||||
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.NotNil(t, ca)
|
|
||||||
assert.NotNil(t, privateKey)
|
|
||||||
|
|
||||||
c, err := NewConfig(ca, privateKey)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
|
|
||||||
c.SetValidity(20 * time.Hour)
|
|
||||||
c.SetOrganization("Test Organization")
|
|
||||||
|
|
||||||
conf := c.NewTLSConfigForHost("example.org")
|
|
||||||
assert.Equal(t, []string{"http/1.1"}, conf.NextProtos)
|
|
||||||
assert.True(t, conf.InsecureSkipVerify)
|
|
||||||
|
|
||||||
// Test generating a certificate
|
|
||||||
clientHello := &tls.ClientHelloInfo{
|
|
||||||
ServerName: "example.org",
|
|
||||||
}
|
|
||||||
tlsCert, err := conf.GetCertificate(clientHello)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.NotNil(t, tlsCert)
|
|
||||||
|
|
||||||
// Assert certificate details
|
|
||||||
x509c := tlsCert.Leaf
|
|
||||||
assert.Equal(t, "example.org", x509c.Subject.CommonName)
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("abc.example.org"))
|
|
||||||
assert.Equal(t, []string{"Test Organization"}, x509c.Subject.Organization)
|
|
||||||
assert.NotNil(t, x509c.SubjectKeyId)
|
|
||||||
assert.True(t, x509c.BasicConstraintsValid)
|
|
||||||
assert.True(t, x509c.KeyUsage&x509.KeyUsageKeyEncipherment == x509.KeyUsageKeyEncipherment)
|
|
||||||
assert.True(t, x509c.KeyUsage&x509.KeyUsageDigitalSignature == x509.KeyUsageDigitalSignature)
|
|
||||||
assert.Equal(t, []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, x509c.ExtKeyUsage)
|
|
||||||
assert.Equal(t, []string{"example.org", "*.example.org"}, x509c.DNSNames)
|
|
||||||
assert.True(t, x509c.NotBefore.Before(time.Now().Add(-2*time.Hour)))
|
|
||||||
assert.True(t, x509c.NotAfter.After(time.Now().Add(2*time.Hour)))
|
|
||||||
|
|
||||||
// Check that certificate is cached
|
|
||||||
tlsCert2, err := c.GetOrCreateCert("abc.example.org")
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.True(t, tlsCert == tlsCert2)
|
|
||||||
|
|
||||||
// Check that certificate is new
|
|
||||||
_, _ = c.GetOrCreateCert("a.b.c.d.e.f.g.h.i.j.example.org")
|
|
||||||
tlsCert3, err := c.GetOrCreateCert("m.k.l.example.org")
|
|
||||||
x509c = tlsCert3.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.False(t, tlsCert == tlsCert3)
|
|
||||||
assert.Equal(t, []string{"example.org", "*.example.org", "*.j.example.org", "*.i.j.example.org", "*.h.i.j.example.org", "*.g.h.i.j.example.org", "*.f.g.h.i.j.example.org", "*.e.f.g.h.i.j.example.org", "*.d.e.f.g.h.i.j.example.org", "*.c.d.e.f.g.h.i.j.example.org", "*.b.c.d.e.f.g.h.i.j.example.org", "*.l.example.org", "*.k.l.example.org"}, x509c.DNSNames)
|
|
||||||
|
|
||||||
// Check that certificate is cached
|
|
||||||
tlsCert4, err := c.GetOrCreateCert("xyz.example.org")
|
|
||||||
x509c = tlsCert4.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.True(t, tlsCert3 == tlsCert4)
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("jkf.example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("n.j.example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("c.i.j.example.org"))
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("m.l.example.org"))
|
|
||||||
assert.Error(t, x509c.VerifyHostname("m.l.jkf.example.org"))
|
|
||||||
|
|
||||||
// Check the certificate for an IP
|
|
||||||
tlsCertForIP, err := c.GetOrCreateCert("192.168.0.1")
|
|
||||||
x509c = tlsCertForIP.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, 1, len(x509c.IPAddresses))
|
|
||||||
assert.True(t, net.ParseIP("192.168.0.1").Equal(x509c.IPAddresses[0]))
|
|
||||||
|
|
||||||
// Check that certificate is cached
|
|
||||||
tlsCertForIP2, err := c.GetOrCreateCert("192.168.0.1")
|
|
||||||
x509c = tlsCertForIP2.Leaf
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.True(t, tlsCertForIP == tlsCertForIP2)
|
|
||||||
assert.Nil(t, x509c.VerifyHostname("192.168.0.1"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGenerateAndSave(t *testing.T) {
|
|
||||||
caPath := "ca.crt"
|
|
||||||
caKeyPath := "ca.key"
|
|
||||||
|
|
||||||
err := GenerateAndSave(caPath, caKeyPath)
|
|
||||||
|
|
||||||
assert.Nil(t, err)
|
|
||||||
|
|
||||||
_ = os.Remove(caPath)
|
|
||||||
_ = os.Remove(caKeyPath)
|
|
||||||
}
|
|
@ -1,32 +0,0 @@
|
|||||||
package cert
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/tls"
|
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/trie"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DomainTrieCertsStorage cache wildcard certificates
|
|
||||||
type DomainTrieCertsStorage struct {
|
|
||||||
certsCache *trie.DomainTrie[*tls.Certificate]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get gets the certificate from the storage
|
|
||||||
func (c *DomainTrieCertsStorage) Get(key string) (*tls.Certificate, bool) {
|
|
||||||
ca := c.certsCache.Search(key)
|
|
||||||
if ca == nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return ca.Data, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set saves the certificate to the storage
|
|
||||||
func (c *DomainTrieCertsStorage) Set(key string, cert *tls.Certificate) {
|
|
||||||
_ = c.certsCache.Insert(key, cert)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDomainTrieCertsStorage() *DomainTrieCertsStorage {
|
|
||||||
return &DomainTrieCertsStorage{
|
|
||||||
certsCache: trie.New[*tls.Certificate](),
|
|
||||||
}
|
|
||||||
}
|
|
@ -14,8 +14,9 @@ func ExecCmd(cmdStr string) (string, error) {
|
|||||||
cmd = exec.Command(args[0])
|
cmd = exec.Command(args[0])
|
||||||
} else {
|
} else {
|
||||||
cmd = exec.Command(args[0], args[1:]...)
|
cmd = exec.Command(args[0], args[1:]...)
|
||||||
}
|
|
||||||
|
|
||||||
|
}
|
||||||
|
prepareBackgroundCommand(cmd)
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("%v, %s", err, string(out))
|
return "", fmt.Errorf("%v, %s", err, string(out))
|
||||||
|
11
common/cmd/cmd_other.go
Normal file
11
common/cmd/cmd_other.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
)
|
||||||
|
|
||||||
|
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
||||||
|
|
||||||
|
}
|
12
common/cmd/cmd_windows.go
Normal file
12
common/cmd/cmd_windows.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package cmd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os/exec"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func prepareBackgroundCommand(cmd *exec.Cmd) {
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
|
||||||
|
}
|
56
common/collections/stack.go
Normal file
56
common/collections/stack.go
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
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++
|
||||||
|
}
|
45
common/convert/base64.go
Normal file
45
common/convert/base64.go
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
package convert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
encRaw = base64.RawStdEncoding
|
||||||
|
enc = base64.StdEncoding
|
||||||
|
)
|
||||||
|
|
||||||
|
// DecodeBase64 try to decode content from the given bytes,
|
||||||
|
// which can be in base64.RawStdEncoding, base64.StdEncoding or just plaintext.
|
||||||
|
func DecodeBase64(buf []byte) []byte {
|
||||||
|
result, err := tryDecodeBase64(buf)
|
||||||
|
if err != nil {
|
||||||
|
return buf
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func tryDecodeBase64(buf []byte) ([]byte, error) {
|
||||||
|
dBuf := make([]byte, encRaw.DecodedLen(len(buf)))
|
||||||
|
n, err := encRaw.Decode(dBuf, buf)
|
||||||
|
if err != nil {
|
||||||
|
n, err = enc.Decode(dBuf, buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dBuf[:n], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func urlSafe(data string) string {
|
||||||
|
return strings.NewReplacer("+", "-", "/", "_").Replace(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeUrlSafe(data string) string {
|
||||||
|
dcBuf, err := base64.RawURLEncoding.DecodeString(data)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return string(dcBuf)
|
||||||
|
}
|
@ -2,41 +2,16 @@ package convert
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
var enc = base64.StdEncoding
|
|
||||||
|
|
||||||
func DecodeBase64(buf []byte) ([]byte, error) {
|
|
||||||
dBuf := make([]byte, enc.DecodedLen(len(buf)))
|
|
||||||
n, err := enc.Decode(dBuf, buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dBuf[:n], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeBase64StringToString decode base64 string to string
|
|
||||||
func DecodeBase64StringToString(s string) (string, error) {
|
|
||||||
dBuf, err := enc.DecodeString(s)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return string(dBuf), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
// ConvertsV2Ray convert V2Ray subscribe proxies data to clash proxies config
|
||||||
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
||||||
data, err := DecodeBase64(buf)
|
data := DecodeBase64(buf)
|
||||||
if err != nil {
|
|
||||||
data = buf
|
|
||||||
}
|
|
||||||
|
|
||||||
arr := strings.Split(string(data), "\n")
|
arr := strings.Split(string(data), "\n")
|
||||||
|
|
||||||
@ -56,6 +31,39 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
|
|
||||||
scheme = strings.ToLower(scheme)
|
scheme = strings.ToLower(scheme)
|
||||||
switch scheme {
|
switch scheme {
|
||||||
|
case "hysteria":
|
||||||
|
urlHysteria, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
query := urlHysteria.Query()
|
||||||
|
name := uniqueName(names, urlHysteria.Fragment)
|
||||||
|
hysteria := make(map[string]any, 20)
|
||||||
|
|
||||||
|
hysteria["name"] = name
|
||||||
|
hysteria["type"] = scheme
|
||||||
|
hysteria["server"] = urlHysteria.Hostname()
|
||||||
|
hysteria["port"] = urlHysteria.Port()
|
||||||
|
hysteria["sni"] = query.Get("peer")
|
||||||
|
hysteria["obfs"] = query.Get("obfs")
|
||||||
|
hysteria["alpn"] = query.Get("alpn")
|
||||||
|
hysteria["auth_str"] = query.Get("auth")
|
||||||
|
hysteria["protocol"] = query.Get("protocol")
|
||||||
|
up := query.Get("up")
|
||||||
|
down := query.Get("down")
|
||||||
|
if up == "" {
|
||||||
|
up = query.Get("upmbps")
|
||||||
|
}
|
||||||
|
if down == "" {
|
||||||
|
down = query.Get("downmbps")
|
||||||
|
}
|
||||||
|
hysteria["down"] = down
|
||||||
|
hysteria["up"] = up
|
||||||
|
hysteria["skip-cert-verify"], _ = strconv.ParseBool(query.Get("insecure"))
|
||||||
|
|
||||||
|
proxies = append(proxies, hysteria)
|
||||||
|
|
||||||
case "trojan":
|
case "trojan":
|
||||||
urlTrojan, err := url.Parse(line)
|
urlTrojan, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -85,25 +93,60 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
trojan["network"] = network
|
trojan["network"] = network
|
||||||
}
|
}
|
||||||
|
|
||||||
if network == "ws" {
|
switch network {
|
||||||
|
case "ws":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
|
|
||||||
headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["User-Agent"] = RandUserAgent()
|
||||||
|
|
||||||
wsOpts["path"] = query.Get("path")
|
wsOpts["path"] = query.Get("path")
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
trojan["ws-opts"] = wsOpts
|
trojan["ws-opts"] = wsOpts
|
||||||
|
|
||||||
|
case "grpc":
|
||||||
|
grpcOpts := make(map[string]any)
|
||||||
|
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||||
|
trojan["grpc-opts"] = grpcOpts
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, trojan)
|
proxies = append(proxies, trojan)
|
||||||
case "vmess":
|
|
||||||
dcBuf, err := enc.DecodeString(body)
|
case "vless":
|
||||||
|
urlVLess, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
query := urlVLess.Query()
|
||||||
|
vless := make(map[string]any, 20)
|
||||||
|
handleVShareLink(names, urlVLess, scheme, vless)
|
||||||
|
if flow := query.Get("flow"); flow != "" {
|
||||||
|
vless["flow"] = strings.ToLower(flow)
|
||||||
|
}
|
||||||
|
proxies = append(proxies, vless)
|
||||||
|
|
||||||
|
case "vmess":
|
||||||
|
// V2RayN-styled share link
|
||||||
|
// https://github.com/2dust/v2rayN/wiki/%E5%88%86%E4%BA%AB%E9%93%BE%E6%8E%A5%E6%A0%BC%E5%BC%8F%E8%AF%B4%E6%98%8E(ver-2)
|
||||||
|
dcBuf, err := tryDecodeBase64([]byte(body))
|
||||||
|
if err != nil {
|
||||||
|
// Xray VMessAEAD share link
|
||||||
|
urlVMess, err := url.Parse(line)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
query := urlVMess.Query()
|
||||||
|
vmess := make(map[string]any, 20)
|
||||||
|
handleVShareLink(names, urlVMess, scheme, vmess)
|
||||||
|
vmess["alterId"] = 0
|
||||||
|
vmess["cipher"] = "auto"
|
||||||
|
if encryption := query.Get("encryption"); encryption != "" {
|
||||||
|
vmess["cipher"] = encryption
|
||||||
|
}
|
||||||
|
proxies = append(proxies, vmess)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
jsonDc := json.NewDecoder(bytes.NewReader(dcBuf))
|
jsonDc := json.NewDecoder(bytes.NewReader(dcBuf))
|
||||||
values := make(map[string]any, 20)
|
values := make(map[string]any, 20)
|
||||||
@ -120,40 +163,85 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
vmess["server"] = values["add"]
|
vmess["server"] = values["add"]
|
||||||
vmess["port"] = values["port"]
|
vmess["port"] = values["port"]
|
||||||
vmess["uuid"] = values["id"]
|
vmess["uuid"] = values["id"]
|
||||||
vmess["alterId"] = values["aid"]
|
if alterId, ok := values["aid"]; ok {
|
||||||
vmess["cipher"] = "auto"
|
vmess["alterId"] = alterId
|
||||||
|
} else {
|
||||||
|
vmess["alterId"] = 0
|
||||||
|
}
|
||||||
vmess["udp"] = true
|
vmess["udp"] = true
|
||||||
|
vmess["tls"] = false
|
||||||
vmess["skip-cert-verify"] = false
|
vmess["skip-cert-verify"] = false
|
||||||
|
|
||||||
host := values["host"]
|
vmess["cipher"] = "auto"
|
||||||
network := strings.ToLower(values["net"].(string))
|
if cipher, ok := values["scy"]; ok && cipher != "" {
|
||||||
|
vmess["cipher"] = cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
if sni, ok := values["sni"]; ok && sni != "" {
|
||||||
|
vmess["servername"] = sni
|
||||||
|
}
|
||||||
|
|
||||||
|
network := strings.ToLower(values["net"].(string))
|
||||||
|
if values["type"] == "http" {
|
||||||
|
network = "http"
|
||||||
|
} else if network == "http" {
|
||||||
|
network = "h2"
|
||||||
|
}
|
||||||
vmess["network"] = network
|
vmess["network"] = network
|
||||||
|
|
||||||
tls := strings.ToLower(values["tls"].(string))
|
tls := strings.ToLower(values["tls"].(string))
|
||||||
if tls != "" && tls != "0" && tls != "null" {
|
if strings.HasSuffix(tls, "tls") {
|
||||||
if host != nil {
|
|
||||||
vmess["servername"] = host
|
|
||||||
}
|
|
||||||
vmess["tls"] = true
|
vmess["tls"] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
if network == "ws" {
|
switch network {
|
||||||
|
case "http":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
httpOpts := make(map[string]any)
|
||||||
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
|
headers["Host"] = []string{host.(string)}
|
||||||
|
}
|
||||||
|
httpOpts["path"] = []string{"/"}
|
||||||
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
|
httpOpts["path"] = []string{path.(string)}
|
||||||
|
}
|
||||||
|
httpOpts["headers"] = headers
|
||||||
|
|
||||||
|
vmess["http-opts"] = httpOpts
|
||||||
|
|
||||||
|
case "h2":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
h2Opts := make(map[string]any)
|
||||||
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
|
headers["Host"] = []string{host.(string)}
|
||||||
|
}
|
||||||
|
|
||||||
|
h2Opts["path"] = values["path"]
|
||||||
|
h2Opts["headers"] = headers
|
||||||
|
|
||||||
|
vmess["h2-opts"] = h2Opts
|
||||||
|
|
||||||
|
case "ws":
|
||||||
headers := make(map[string]any)
|
headers := make(map[string]any)
|
||||||
wsOpts := make(map[string]any)
|
wsOpts := make(map[string]any)
|
||||||
|
wsOpts["path"] = []string{"/"}
|
||||||
headers["Host"] = RandHost()
|
if host, ok := values["host"]; ok && host != "" {
|
||||||
headers["User-Agent"] = RandUserAgent()
|
headers["Host"] = host.(string)
|
||||||
|
}
|
||||||
if values["path"] != nil {
|
if path, ok := values["path"]; ok && path != "" {
|
||||||
wsOpts["path"] = values["path"]
|
wsOpts["path"] = path.(string)
|
||||||
}
|
}
|
||||||
wsOpts["headers"] = headers
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
vmess["ws-opts"] = wsOpts
|
vmess["ws-opts"] = wsOpts
|
||||||
|
|
||||||
|
case "grpc":
|
||||||
|
grpcOpts := make(map[string]any)
|
||||||
|
grpcOpts["grpc-service-name"] = values["path"]
|
||||||
|
vmess["grpc-opts"] = grpcOpts
|
||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, vmess)
|
proxies = append(proxies, vmess)
|
||||||
|
|
||||||
case "ss":
|
case "ss":
|
||||||
urlSS, err := url.Parse(line)
|
urlSS, err := url.Parse(line)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -164,7 +252,7 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
port := urlSS.Port()
|
port := urlSS.Port()
|
||||||
|
|
||||||
if port == "" {
|
if port == "" {
|
||||||
dcBuf, err := enc.DecodeString(urlSS.Host)
|
dcBuf, err := encRaw.DecodeString(urlSS.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -181,11 +269,10 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
)
|
)
|
||||||
|
|
||||||
if password, found = urlSS.User.Password(); !found {
|
if password, found = urlSS.User.Password(); !found {
|
||||||
dcBuf, err := enc.DecodeString(cipher)
|
dcBuf, _ := enc.DecodeString(cipher)
|
||||||
if err != nil {
|
if !strings.Contains(string(dcBuf), "2022-blake3") {
|
||||||
continue
|
dcBuf, _ = encRaw.DecodeString(cipher)
|
||||||
}
|
}
|
||||||
|
|
||||||
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
cipher, password, found = strings.Cut(string(dcBuf), ":")
|
||||||
if !found {
|
if !found {
|
||||||
continue
|
continue
|
||||||
@ -200,11 +287,19 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
ss["port"] = urlSS.Port()
|
ss["port"] = urlSS.Port()
|
||||||
ss["cipher"] = cipher
|
ss["cipher"] = cipher
|
||||||
ss["password"] = password
|
ss["password"] = password
|
||||||
|
query := urlSS.Query()
|
||||||
ss["udp"] = true
|
ss["udp"] = true
|
||||||
|
if strings.Contains(query.Get("plugin"), "obfs") {
|
||||||
|
obfsParams := strings.Split(query.Get("plugin"), ";")
|
||||||
|
ss["plugin"] = "obfs"
|
||||||
|
ss["plugin-opts"] = map[string]any{
|
||||||
|
"host": obfsParams[2][10:],
|
||||||
|
"mode": obfsParams[1][5:],
|
||||||
|
}
|
||||||
|
}
|
||||||
proxies = append(proxies, ss)
|
proxies = append(proxies, ss)
|
||||||
case "ssr":
|
case "ssr":
|
||||||
dcBuf, err := enc.DecodeString(body)
|
dcBuf, err := encRaw.DecodeString(body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -261,54 +356,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
proxies = append(proxies, ssr)
|
proxies = append(proxies, ssr)
|
||||||
case "vless":
|
|
||||||
urlVless, err := url.Parse(line)
|
|
||||||
if err != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
query := urlVless.Query()
|
|
||||||
|
|
||||||
name := uniqueName(names, urlVless.Fragment)
|
|
||||||
vless := make(map[string]any, 20)
|
|
||||||
|
|
||||||
vless["name"] = name
|
|
||||||
vless["type"] = scheme
|
|
||||||
vless["server"] = urlVless.Hostname()
|
|
||||||
vless["port"] = urlVless.Port()
|
|
||||||
vless["uuid"] = urlVless.User.Username()
|
|
||||||
vless["udp"] = true
|
|
||||||
vless["skip-cert-verify"] = false
|
|
||||||
|
|
||||||
sni := query.Get("sni")
|
|
||||||
if sni != "" {
|
|
||||||
vless["servername"] = sni
|
|
||||||
}
|
|
||||||
|
|
||||||
flow := strings.ToLower(query.Get("flow"))
|
|
||||||
if flow != "" {
|
|
||||||
vless["flow"] = flow
|
|
||||||
}
|
|
||||||
|
|
||||||
network := strings.ToLower(query.Get("type"))
|
|
||||||
if network != "" {
|
|
||||||
vless["network"] = network
|
|
||||||
}
|
|
||||||
|
|
||||||
if network == "ws" {
|
|
||||||
headers := make(map[string]any)
|
|
||||||
wsOpts := make(map[string]any)
|
|
||||||
|
|
||||||
headers["Host"] = RandHost()
|
|
||||||
headers["User-Agent"] = RandUserAgent()
|
|
||||||
|
|
||||||
wsOpts["path"] = query.Get("path")
|
|
||||||
wsOpts["headers"] = headers
|
|
||||||
|
|
||||||
vless["ws-opts"] = wsOpts
|
|
||||||
}
|
|
||||||
|
|
||||||
proxies = append(proxies, vless)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -319,18 +366,6 @@ func ConvertsV2Ray(buf []byte) ([]map[string]any, error) {
|
|||||||
return proxies, nil
|
return proxies, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func urlSafe(data string) string {
|
|
||||||
return strings.ReplaceAll(strings.ReplaceAll(data, "+", "-"), "/", "_")
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeUrlSafe(data string) string {
|
|
||||||
dcBuf, err := base64.URLEncoding.DecodeString(data)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return string(dcBuf)
|
|
||||||
}
|
|
||||||
|
|
||||||
func uniqueName(names map[string]int, name string) string {
|
func uniqueName(names map[string]int, name string) string {
|
||||||
if index, ok := names[name]; ok {
|
if index, ok := names[name]; ok {
|
||||||
index++
|
index++
|
||||||
|
@ -29,6 +29,7 @@ var hostsSuffix = []string{
|
|||||||
".alidns.com",
|
".alidns.com",
|
||||||
".cdngslb.com",
|
".cdngslb.com",
|
||||||
".mxhichina.com",
|
".mxhichina.com",
|
||||||
|
".alibabadns.com",
|
||||||
}
|
}
|
||||||
|
|
||||||
var userAgents = []string{
|
var userAgents = []string{
|
||||||
|
89
common/convert/v.go
Normal file
89
common/convert/v.go
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
package convert
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func handleVShareLink(names map[string]int, url *url.URL, scheme string, proxy map[string]any) {
|
||||||
|
// Xray VMessAEAD / VLESS share link standard
|
||||||
|
// https://github.com/XTLS/Xray-core/discussions/716
|
||||||
|
query := url.Query()
|
||||||
|
proxy["name"] = uniqueName(names, url.Fragment)
|
||||||
|
proxy["type"] = scheme
|
||||||
|
proxy["server"] = url.Hostname()
|
||||||
|
proxy["port"] = url.Port()
|
||||||
|
proxy["uuid"] = url.User.Username()
|
||||||
|
proxy["udp"] = true
|
||||||
|
proxy["skip-cert-verify"] = false
|
||||||
|
proxy["tls"] = false
|
||||||
|
tls := strings.ToLower(query.Get("security"))
|
||||||
|
if strings.HasSuffix(tls, "tls") {
|
||||||
|
proxy["tls"] = true
|
||||||
|
}
|
||||||
|
if sni := query.Get("sni"); sni != "" {
|
||||||
|
proxy["servername"] = sni
|
||||||
|
}
|
||||||
|
|
||||||
|
network := strings.ToLower(query.Get("type"))
|
||||||
|
if network == "" {
|
||||||
|
network = "tcp"
|
||||||
|
}
|
||||||
|
fakeType := strings.ToLower(query.Get("headerType"))
|
||||||
|
if fakeType == "http" {
|
||||||
|
network = "http"
|
||||||
|
} else if network == "http" {
|
||||||
|
network = "h2"
|
||||||
|
}
|
||||||
|
proxy["network"] = network
|
||||||
|
switch network {
|
||||||
|
case "tcp":
|
||||||
|
if fakeType != "none" {
|
||||||
|
headers := make(map[string]any)
|
||||||
|
httpOpts := make(map[string]any)
|
||||||
|
httpOpts["path"] = []string{"/"}
|
||||||
|
|
||||||
|
if host := query.Get("host"); host != "" {
|
||||||
|
headers["Host"] = []string{host}
|
||||||
|
}
|
||||||
|
|
||||||
|
if method := query.Get("method"); method != "" {
|
||||||
|
httpOpts["method"] = method
|
||||||
|
}
|
||||||
|
|
||||||
|
if path := query.Get("path"); path != "" {
|
||||||
|
httpOpts["path"] = []string{path}
|
||||||
|
}
|
||||||
|
httpOpts["headers"] = headers
|
||||||
|
proxy["http-opts"] = httpOpts
|
||||||
|
}
|
||||||
|
|
||||||
|
case "http":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
h2Opts := make(map[string]any)
|
||||||
|
h2Opts["path"] = []string{"/"}
|
||||||
|
if path := query.Get("path"); path != "" {
|
||||||
|
h2Opts["path"] = []string{path}
|
||||||
|
}
|
||||||
|
if host := query.Get("host"); host != "" {
|
||||||
|
h2Opts["host"] = []string{host}
|
||||||
|
}
|
||||||
|
h2Opts["headers"] = headers
|
||||||
|
proxy["h2-opts"] = h2Opts
|
||||||
|
|
||||||
|
case "ws":
|
||||||
|
headers := make(map[string]any)
|
||||||
|
wsOpts := make(map[string]any)
|
||||||
|
headers["User-Agent"] = RandUserAgent()
|
||||||
|
headers["Host"] = query.Get("host")
|
||||||
|
wsOpts["path"] = query.Get("path")
|
||||||
|
wsOpts["headers"] = headers
|
||||||
|
|
||||||
|
proxy["ws-opts"] = wsOpts
|
||||||
|
|
||||||
|
case "grpc":
|
||||||
|
grpcOpts := make(map[string]any)
|
||||||
|
grpcOpts["grpc-service-name"] = query.Get("serviceName")
|
||||||
|
proxy["grpc-opts"] = grpcOpts
|
||||||
|
}
|
||||||
|
}
|
@ -12,28 +12,19 @@ import (
|
|||||||
func Relay(leftConn, rightConn net.Conn) {
|
func Relay(leftConn, rightConn net.Conn) {
|
||||||
ch := make(chan error)
|
ch := make(chan error)
|
||||||
|
|
||||||
tcpKeepAlive(leftConn)
|
|
||||||
tcpKeepAlive(rightConn)
|
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
// Wrapping to avoid using *net.TCPConn.(ReadFrom)
|
||||||
// See also https://github.com/Dreamacro/clash/pull/1209
|
// See also https://github.com/Dreamacro/clash/pull/1209
|
||||||
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
_, err := io.CopyBuffer(WriteOnlyWriter{Writer: leftConn}, ReadOnlyReader{Reader: rightConn}, buf)
|
||||||
_ = pool.Put(buf)
|
pool.Put(buf)
|
||||||
_ = leftConn.SetReadDeadline(time.Now())
|
leftConn.SetReadDeadline(time.Now())
|
||||||
ch <- err
|
ch <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
buf := pool.Get(pool.RelayBufferSize)
|
buf := pool.Get(pool.RelayBufferSize)
|
||||||
_, _ = io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
io.CopyBuffer(WriteOnlyWriter{Writer: rightConn}, ReadOnlyReader{Reader: leftConn}, buf)
|
||||||
_ = pool.Put(buf)
|
pool.Put(buf)
|
||||||
_ = rightConn.SetReadDeadline(time.Now())
|
rightConn.SetReadDeadline(time.Now())
|
||||||
<-ch
|
<-ch
|
||||||
}
|
}
|
||||||
|
|
||||||
func tcpKeepAlive(c net.Conn) {
|
|
||||||
if tcp, ok := c.(*net.TCPConn); ok {
|
|
||||||
_ = tcp.SetKeepAlive(true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
46
common/net/tcpip.go
Normal file
46
common/net/tcpip.go
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
package net
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SplitNetworkType(s string) (string, string, error) {
|
||||||
|
var (
|
||||||
|
shecme string
|
||||||
|
hostPort string
|
||||||
|
)
|
||||||
|
result := strings.Split(s, "://")
|
||||||
|
if len(result) == 2 {
|
||||||
|
shecme = result[0]
|
||||||
|
hostPort = result[1]
|
||||||
|
} else if len(result) == 1 {
|
||||||
|
hostPort = result[0]
|
||||||
|
} else {
|
||||||
|
return "", "", fmt.Errorf("tcp/udp style error")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(shecme) == 0 {
|
||||||
|
shecme = "udp"
|
||||||
|
}
|
||||||
|
|
||||||
|
if shecme != "tcp" && shecme != "udp" {
|
||||||
|
return "", "", fmt.Errorf("scheme should be tcp:// or udp://")
|
||||||
|
} else {
|
||||||
|
return shecme, hostPort, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SplitHostPort(s string) (host, port string, hasPort bool, err error) {
|
||||||
|
temp := s
|
||||||
|
hasPort = true
|
||||||
|
|
||||||
|
if !strings.Contains(s, ":") && !strings.Contains(s, "]:") {
|
||||||
|
temp += ":0"
|
||||||
|
hasPort = false
|
||||||
|
}
|
||||||
|
|
||||||
|
host, port, err = net.SplitHostPort(temp)
|
||||||
|
return
|
||||||
|
}
|
@ -8,7 +8,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
var defaultAllocator = NewAllocator()
|
var DefaultAllocator = NewAllocator()
|
||||||
|
|
||||||
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
// Allocator for incoming frames, optimized to prevent overwriting after zeroing
|
||||||
type Allocator struct {
|
type Allocator struct {
|
||||||
|
@ -13,9 +13,9 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func Get(size int) []byte {
|
func Get(size int) []byte {
|
||||||
return defaultAllocator.Get(size)
|
return DefaultAllocator.Get(size)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Put(buf []byte) error {
|
func Put(buf []byte) error {
|
||||||
return defaultAllocator.Put(buf)
|
return DefaultAllocator.Put(buf)
|
||||||
}
|
}
|
||||||
|
@ -31,7 +31,7 @@ func NewDecoder(option Option) *Decoder {
|
|||||||
// Decode transform a map[string]any to a struct
|
// Decode transform a map[string]any to a struct
|
||||||
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
func (d *Decoder) Decode(src map[string]any, dst any) error {
|
||||||
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
if reflect.TypeOf(dst).Kind() != reflect.Ptr {
|
||||||
return fmt.Errorf("Decode must recive a ptr struct")
|
return fmt.Errorf("decode must recive a ptr struct")
|
||||||
}
|
}
|
||||||
t := reflect.TypeOf(dst).Elem()
|
t := reflect.TypeOf(dst).Elem()
|
||||||
v := reflect.ValueOf(dst).Elem()
|
v := reflect.ValueOf(dst).Elem()
|
||||||
@ -301,7 +301,7 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
|
|||||||
field reflect.StructField
|
field reflect.StructField
|
||||||
val reflect.Value
|
val reflect.Value
|
||||||
}
|
}
|
||||||
fields := []field{}
|
var fields []field
|
||||||
for len(structs) > 0 {
|
for len(structs) > 0 {
|
||||||
structVal := structs[0]
|
structVal := structs[0]
|
||||||
structs = structs[1:]
|
structs = structs[1:]
|
||||||
|
@ -137,45 +137,3 @@ func TestStructure_Nest(t *testing.T) {
|
|||||||
assert.Nil(t, err)
|
assert.Nil(t, err)
|
||||||
assert.Equal(t, s.BazOptional, goal)
|
assert.Equal(t, s.BazOptional, goal)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestStructure_SliceNilValue(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"foo": 1,
|
|
||||||
"bar": []any{"bar", nil},
|
|
||||||
}
|
|
||||||
|
|
||||||
goal := &BazSlice{
|
|
||||||
Foo: 1,
|
|
||||||
Bar: []string{"bar", ""},
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &BazSlice{}
|
|
||||||
err := weakTypeDecoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Equal(t, goal.Bar, s.Bar)
|
|
||||||
|
|
||||||
s = &BazSlice{}
|
|
||||||
err = decoder.Decode(rawMap, s)
|
|
||||||
assert.NotNil(t, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStructure_SliceNilValueComplex(t *testing.T) {
|
|
||||||
rawMap := map[string]any{
|
|
||||||
"bar": []any{map[string]any{"bar": "foo"}, nil},
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &struct {
|
|
||||||
Bar []map[string]any `test:"bar"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err := decoder.Decode(rawMap, s)
|
|
||||||
assert.Nil(t, err)
|
|
||||||
assert.Nil(t, s.Bar[1])
|
|
||||||
|
|
||||||
ss := &struct {
|
|
||||||
Bar []Baz `test:"bar"`
|
|
||||||
}{}
|
|
||||||
|
|
||||||
err = decoder.Decode(rawMap, ss)
|
|
||||||
assert.NotNil(t, err)
|
|
||||||
}
|
|
||||||
|
44
common/utils/range.go
Normal file
44
common/utils/range.go
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"golang.org/x/exp/constraints"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Range[T constraints.Ordered] struct {
|
||||||
|
start T
|
||||||
|
end T
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRange[T constraints.Ordered](start, end T) *Range[T] {
|
||||||
|
if start > end {
|
||||||
|
return &Range[T]{
|
||||||
|
start: end,
|
||||||
|
end: start,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Range[T]{
|
||||||
|
start: start,
|
||||||
|
end: end,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) Contains(t T) bool {
|
||||||
|
return t >= r.start && t <= r.end
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) LeftContains(t T) bool {
|
||||||
|
return t >= r.start && t < r.end
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) RightContains(t T) bool {
|
||||||
|
return t > r.start && t <= r.end
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) Start() T {
|
||||||
|
return r.start
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Range[T]) End() T {
|
||||||
|
return r.end
|
||||||
|
}
|
16
common/utils/uuid.go
Normal file
16
common/utils/uuid.go
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var uuidNamespace, _ = uuid.FromString("00000000-0000-0000-0000-000000000000")
|
||||||
|
|
||||||
|
// UUIDMap https://github.com/XTLS/Xray-core/issues/158#issue-783294090
|
||||||
|
func UUIDMap(str string) (uuid.UUID, error) {
|
||||||
|
u, err := uuid.FromString(str)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.NewV5(uuidNamespace, str), nil
|
||||||
|
}
|
||||||
|
return u, nil
|
||||||
|
}
|
74
common/utils/uuid_test.go
Normal file
74
common/utils/uuid_test.go
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/gofrs/uuid"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestUUIDMap(t *testing.T) {
|
||||||
|
type args struct {
|
||||||
|
str string
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
args args
|
||||||
|
want uuid.UUID
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "uuid-test-1",
|
||||||
|
args: args{
|
||||||
|
str: "82410302-039e-41b6-98b0-d964084b4170",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("82410302-039e-41b6-98b0-d964084b4170"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "uuid-test-2",
|
||||||
|
args: args{
|
||||||
|
str: "88c502e6-d7eb-4c8e-8259-94cb13d83c77",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("88c502e6-d7eb-4c8e-8259-94cb13d83c77"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "uuid-map-1",
|
||||||
|
args: args{
|
||||||
|
str: "123456",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("f8598425-92f2-5508-a071-4fc67f9040ac"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
// GENERATED BY 'xray uuid -i'
|
||||||
|
{
|
||||||
|
name: "uuid-map-2",
|
||||||
|
args: args{
|
||||||
|
str: "a9dk23bz0",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("c91481b6-fc0f-5d9e-b166-5ddf07b9c3c5"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "uuid-map-2",
|
||||||
|
args: args{
|
||||||
|
str: "中文123",
|
||||||
|
},
|
||||||
|
want: uuid.FromStringOrNil("145c544c-2229-59e5-8dbb-3f33b7610d26"),
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := UUIDMap(tt.args.str)
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Errorf("UUIDMap() error = %v, wantErr %v", err, tt.wantErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(got, tt.want) {
|
||||||
|
t.Errorf("UUIDMap() got = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -3,10 +3,23 @@ package dialer
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"github.com/Dreamacro/clash/component/resolver"
|
||||||
|
"go.uber.org/atomic"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/resolver"
|
var (
|
||||||
|
dialMux sync.Mutex
|
||||||
|
actualSingleDialContext = singleDialContext
|
||||||
|
actualDualStackDialContext = dualStackDialContext
|
||||||
|
tcpConcurrent = false
|
||||||
|
DisableIPv6 = false
|
||||||
|
ErrorInvalidedNetworkStack = errors.New("invalided network stack")
|
||||||
|
ErrorDisableIPv6 = errors.New("IPv6 is disabled, dialer cancel")
|
||||||
)
|
)
|
||||||
|
|
||||||
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
func DialContext(ctx context.Context, network, address string, options ...Option) (net.Conn, error) {
|
||||||
@ -23,37 +36,23 @@ func DialContext(ctx context.Context, network, address string, options ...Option
|
|||||||
o(opt)
|
o(opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if opt.network == 4 || opt.network == 6 {
|
||||||
|
if strings.Contains(network, "tcp") {
|
||||||
|
network = "tcp"
|
||||||
|
} else {
|
||||||
|
network = "udp"
|
||||||
|
}
|
||||||
|
|
||||||
|
network = fmt.Sprintf("%s%d", network, opt.network)
|
||||||
|
}
|
||||||
|
|
||||||
switch network {
|
switch network {
|
||||||
case "tcp4", "tcp6", "udp4", "udp6":
|
case "tcp4", "tcp6", "udp4", "udp6":
|
||||||
host, port, err := net.SplitHostPort(address)
|
return actualSingleDialContext(ctx, network, address, opt)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var ip netip.Addr
|
|
||||||
switch network {
|
|
||||||
case "tcp4", "udp4":
|
|
||||||
if !opt.direct {
|
|
||||||
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv4(host)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
if !opt.direct {
|
|
||||||
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
|
||||||
} else {
|
|
||||||
ip, err = resolver.ResolveIPv6(host)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return dialContext(ctx, network, ip, port, opt)
|
|
||||||
case "tcp", "udp":
|
case "tcp", "udp":
|
||||||
return dualStackDialContext(ctx, network, address, opt)
|
return actualDualStackDialContext(ctx, network, address, opt)
|
||||||
default:
|
default:
|
||||||
return nil, errors.New("network invalid")
|
return nil, ErrorInvalidedNetworkStack
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -89,6 +88,24 @@ func ListenPacket(ctx context.Context, network, address string, options ...Optio
|
|||||||
return lc.ListenPacket(ctx, network, address)
|
return lc.ListenPacket(ctx, network, address)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func SetDial(concurrent bool) {
|
||||||
|
dialMux.Lock()
|
||||||
|
tcpConcurrent = concurrent
|
||||||
|
if concurrent {
|
||||||
|
actualSingleDialContext = concurrentSingleDialContext
|
||||||
|
actualDualStackDialContext = concurrentDualStackDialContext
|
||||||
|
} else {
|
||||||
|
actualSingleDialContext = singleDialContext
|
||||||
|
actualDualStackDialContext = dualStackDialContext
|
||||||
|
}
|
||||||
|
|
||||||
|
dialMux.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetDial() bool {
|
||||||
|
return tcpConcurrent
|
||||||
|
}
|
||||||
|
|
||||||
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
func dialContext(ctx context.Context, network string, destination netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
dialer := &net.Dialer{}
|
dialer := &net.Dialer{}
|
||||||
if opt.interfaceName != "" {
|
if opt.interfaceName != "" {
|
||||||
@ -100,6 +117,10 @@ func dialContext(ctx context.Context, network string, destination netip.Addr, po
|
|||||||
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
bindMarkToDialer(opt.routingMark, dialer, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if DisableIPv6 && destination.Is6() {
|
||||||
|
return nil, ErrorDisableIPv6
|
||||||
|
}
|
||||||
|
|
||||||
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
return dialer.DialContext(ctx, network, net.JoinHostPort(destination.String(), port))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -159,27 +180,223 @@ func dualStackDialContext(ctx context.Context, network, address string, opt *opt
|
|||||||
go startRacer(ctx, network+"4", host, opt.direct, false)
|
go startRacer(ctx, network+"4", host, opt.direct, false)
|
||||||
go startRacer(ctx, network+"6", host, opt.direct, true)
|
go startRacer(ctx, network+"6", host, opt.direct, true)
|
||||||
|
|
||||||
for res := range results {
|
count := 2
|
||||||
if res.error == nil {
|
for i := 0; i < count; i++ {
|
||||||
return res.Conn, nil
|
select {
|
||||||
}
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
if !res.ipv6 {
|
return res.Conn, nil
|
||||||
primary = res
|
|
||||||
} else {
|
|
||||||
fallback = res
|
|
||||||
}
|
|
||||||
|
|
||||||
if primary.done && fallback.done {
|
|
||||||
if primary.resolved {
|
|
||||||
return nil, primary.error
|
|
||||||
} else if fallback.resolved {
|
|
||||||
return nil, fallback.error
|
|
||||||
} else {
|
|
||||||
return nil, primary.error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !res.ipv6 {
|
||||||
|
primary = res
|
||||||
|
} else {
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
|
||||||
|
if primary.done && fallback.done {
|
||||||
|
if primary.resolved {
|
||||||
|
return nil, primary.error
|
||||||
|
} else if fallback.resolved {
|
||||||
|
return nil, fallback.error
|
||||||
|
} else {
|
||||||
|
return nil, primary.error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errors.New("never touched")
|
return nil, errors.New("dual stack tcp shake hands failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDualStackDialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
if opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIP(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPProxyServerHost(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentDialContext(ctx context.Context, network string, ips []netip.Addr, port string, opt *option) (net.Conn, error) {
|
||||||
|
returned := make(chan struct{})
|
||||||
|
defer close(returned)
|
||||||
|
|
||||||
|
type dialResult struct {
|
||||||
|
ip netip.Addr
|
||||||
|
net.Conn
|
||||||
|
error
|
||||||
|
isPrimary bool
|
||||||
|
done bool
|
||||||
|
}
|
||||||
|
|
||||||
|
preferCount := atomic.NewInt32(0)
|
||||||
|
results := make(chan dialResult)
|
||||||
|
tcpRacer := func(ctx context.Context, ip netip.Addr) {
|
||||||
|
result := dialResult{ip: ip, done: true}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
select {
|
||||||
|
case results <- result:
|
||||||
|
case <-returned:
|
||||||
|
if result.Conn != nil {
|
||||||
|
_ = result.Conn.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if strings.Contains(network, "tcp") {
|
||||||
|
network = "tcp"
|
||||||
|
} else {
|
||||||
|
network = "udp"
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip.Is6() {
|
||||||
|
network += "6"
|
||||||
|
if opt.prefer != 4 {
|
||||||
|
result.isPrimary = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ip.Is4() {
|
||||||
|
network += "4"
|
||||||
|
if opt.prefer != 6 {
|
||||||
|
result.isPrimary = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if result.isPrimary {
|
||||||
|
preferCount.Add(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Conn, result.error = dialContext(ctx, network, ip, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, ip := range ips {
|
||||||
|
go tcpRacer(ctx, ip)
|
||||||
|
}
|
||||||
|
|
||||||
|
connCount := len(ips)
|
||||||
|
var fallback dialResult
|
||||||
|
for i := 0; i < connCount; i++ {
|
||||||
|
select {
|
||||||
|
case res := <-results:
|
||||||
|
if res.error == nil {
|
||||||
|
if res.isPrimary {
|
||||||
|
return res.Conn, nil
|
||||||
|
} else {
|
||||||
|
if !fallback.done || fallback.error != nil {
|
||||||
|
fallback = res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if res.isPrimary {
|
||||||
|
preferCount.Add(-1)
|
||||||
|
if preferCount.Load() == 0 && fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-ctx.Done():
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if fallback.done && fallback.error == nil {
|
||||||
|
return fallback.Conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("all ips %v tcp shake hands failed", ips)
|
||||||
|
}
|
||||||
|
|
||||||
|
func singleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ip netip.Addr
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv4ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv4(host)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if !opt.direct {
|
||||||
|
ip, err = resolver.ResolveIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ip, err = resolver.ResolveIPv6(host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return dialContext(ctx, network, ip, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentSingleDialContext(ctx context.Context, network string, address string, opt *option) (net.Conn, error) {
|
||||||
|
switch network {
|
||||||
|
case "tcp4", "udp4":
|
||||||
|
return concurrentIPv4DialContext(ctx, network, address, opt)
|
||||||
|
default:
|
||||||
|
return concurrentIPv6DialContext(ctx, network, address, opt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentIPv4DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
if !opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIPv4ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPv4(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func concurrentIPv6DialContext(ctx context.Context, network, address string, opt *option) (net.Conn, error) {
|
||||||
|
host, port, err := net.SplitHostPort(address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ips []netip.Addr
|
||||||
|
if !opt.direct {
|
||||||
|
ips, err = resolver.ResolveAllIPv6ProxyServerHost(host)
|
||||||
|
} else {
|
||||||
|
ips, err = resolver.ResolveAllIPv6(host)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return concurrentDialContext(ctx, network, ips, port, opt)
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import "go.uber.org/atomic"
|
import (
|
||||||
|
"go.uber.org/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
DefaultOptions []Option
|
DefaultOptions []Option
|
||||||
@ -13,6 +15,8 @@ type option struct {
|
|||||||
addrReuse bool
|
addrReuse bool
|
||||||
routingMark int
|
routingMark int
|
||||||
direct bool
|
direct bool
|
||||||
|
network int
|
||||||
|
prefer int
|
||||||
}
|
}
|
||||||
|
|
||||||
type Option func(opt *option)
|
type Option func(opt *option)
|
||||||
@ -40,3 +44,25 @@ func WithDirect() Option {
|
|||||||
opt.direct = true
|
opt.direct = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func WithPreferIPv4() Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.prefer = 4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithPreferIPv6() Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
opt.prefer = 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithOnlySingleStack(isIPv4 bool) Option {
|
||||||
|
return func(opt *option) {
|
||||||
|
if isIPv4 {
|
||||||
|
opt.network = 4
|
||||||
|
} else {
|
||||||
|
opt.network = 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
99
component/ebpf/bpf/bpf_endian.h
Normal file
99
component/ebpf/bpf/bpf_endian.h
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
|
||||||
|
#ifndef __BPF_ENDIAN__
|
||||||
|
#define __BPF_ENDIAN__
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Isolate byte #n and put it into byte #m, for __u##b type.
|
||||||
|
* E.g., moving byte #6 (nnnnnnnn) into byte #1 (mmmmmmmm) for __u64:
|
||||||
|
* 1) xxxxxxxx nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx
|
||||||
|
* 2) nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx 00000000
|
||||||
|
* 3) 00000000 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn
|
||||||
|
* 4) 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn 00000000
|
||||||
|
*/
|
||||||
|
#define ___bpf_mvb(x, b, n, m) ((__u##b)(x) << (b-(n+1)*8) >> (b-8) << (m*8))
|
||||||
|
|
||||||
|
#define ___bpf_swab16(x) ((__u16)( \
|
||||||
|
___bpf_mvb(x, 16, 0, 1) | \
|
||||||
|
___bpf_mvb(x, 16, 1, 0)))
|
||||||
|
|
||||||
|
#define ___bpf_swab32(x) ((__u32)( \
|
||||||
|
___bpf_mvb(x, 32, 0, 3) | \
|
||||||
|
___bpf_mvb(x, 32, 1, 2) | \
|
||||||
|
___bpf_mvb(x, 32, 2, 1) | \
|
||||||
|
___bpf_mvb(x, 32, 3, 0)))
|
||||||
|
|
||||||
|
#define ___bpf_swab64(x) ((__u64)( \
|
||||||
|
___bpf_mvb(x, 64, 0, 7) | \
|
||||||
|
___bpf_mvb(x, 64, 1, 6) | \
|
||||||
|
___bpf_mvb(x, 64, 2, 5) | \
|
||||||
|
___bpf_mvb(x, 64, 3, 4) | \
|
||||||
|
___bpf_mvb(x, 64, 4, 3) | \
|
||||||
|
___bpf_mvb(x, 64, 5, 2) | \
|
||||||
|
___bpf_mvb(x, 64, 6, 1) | \
|
||||||
|
___bpf_mvb(x, 64, 7, 0)))
|
||||||
|
|
||||||
|
/* LLVM's BPF target selects the endianness of the CPU
|
||||||
|
* it compiles on, or the user specifies (bpfel/bpfeb),
|
||||||
|
* respectively. The used __BYTE_ORDER__ is defined by
|
||||||
|
* the compiler, we cannot rely on __BYTE_ORDER from
|
||||||
|
* libc headers, since it doesn't reflect the actual
|
||||||
|
* requested byte order.
|
||||||
|
*
|
||||||
|
* Note, LLVM's BPF target has different __builtin_bswapX()
|
||||||
|
* semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE
|
||||||
|
* in bpfel and bpfeb case, which means below, that we map
|
||||||
|
* to cpu_to_be16(). We could use it unconditionally in BPF
|
||||||
|
* case, but better not rely on it, so that this header here
|
||||||
|
* can be used from application and BPF program side, which
|
||||||
|
* use different targets.
|
||||||
|
*/
|
||||||
|
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
|
||||||
|
# define __bpf_ntohs(x) __builtin_bswap16(x)
|
||||||
|
# define __bpf_htons(x) __builtin_bswap16(x)
|
||||||
|
# define __bpf_constant_ntohs(x) ___bpf_swab16(x)
|
||||||
|
# define __bpf_constant_htons(x) ___bpf_swab16(x)
|
||||||
|
# define __bpf_ntohl(x) __builtin_bswap32(x)
|
||||||
|
# define __bpf_htonl(x) __builtin_bswap32(x)
|
||||||
|
# define __bpf_constant_ntohl(x) ___bpf_swab32(x)
|
||||||
|
# define __bpf_constant_htonl(x) ___bpf_swab32(x)
|
||||||
|
# define __bpf_be64_to_cpu(x) __builtin_bswap64(x)
|
||||||
|
# define __bpf_cpu_to_be64(x) __builtin_bswap64(x)
|
||||||
|
# define __bpf_constant_be64_to_cpu(x) ___bpf_swab64(x)
|
||||||
|
# define __bpf_constant_cpu_to_be64(x) ___bpf_swab64(x)
|
||||||
|
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
|
||||||
|
# define __bpf_ntohs(x) (x)
|
||||||
|
# define __bpf_htons(x) (x)
|
||||||
|
# define __bpf_constant_ntohs(x) (x)
|
||||||
|
# define __bpf_constant_htons(x) (x)
|
||||||
|
# define __bpf_ntohl(x) (x)
|
||||||
|
# define __bpf_htonl(x) (x)
|
||||||
|
# define __bpf_constant_ntohl(x) (x)
|
||||||
|
# define __bpf_constant_htonl(x) (x)
|
||||||
|
# define __bpf_be64_to_cpu(x) (x)
|
||||||
|
# define __bpf_cpu_to_be64(x) (x)
|
||||||
|
# define __bpf_constant_be64_to_cpu(x) (x)
|
||||||
|
# define __bpf_constant_cpu_to_be64(x) (x)
|
||||||
|
#else
|
||||||
|
# error "Fix your compiler's __BYTE_ORDER__?!"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define bpf_htons(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_htons(x) : __bpf_htons(x))
|
||||||
|
#define bpf_ntohs(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_ntohs(x) : __bpf_ntohs(x))
|
||||||
|
#define bpf_htonl(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_htonl(x) : __bpf_htonl(x))
|
||||||
|
#define bpf_ntohl(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_ntohl(x) : __bpf_ntohl(x))
|
||||||
|
#define bpf_cpu_to_be64(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_cpu_to_be64(x) : __bpf_cpu_to_be64(x))
|
||||||
|
#define bpf_be64_to_cpu(x) \
|
||||||
|
(__builtin_constant_p(x) ? \
|
||||||
|
__bpf_constant_be64_to_cpu(x) : __bpf_be64_to_cpu(x))
|
||||||
|
|
||||||
|
#endif /* __BPF_ENDIAN__ */
|
4139
component/ebpf/bpf/bpf_helper_defs.h
Normal file
4139
component/ebpf/bpf/bpf_helper_defs.h
Normal file
File diff suppressed because it is too large
Load Diff
262
component/ebpf/bpf/bpf_helpers.h
Normal file
262
component/ebpf/bpf/bpf_helpers.h
Normal file
@ -0,0 +1,262 @@
|
|||||||
|
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
|
||||||
|
#ifndef __BPF_HELPERS__
|
||||||
|
#define __BPF_HELPERS__
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Note that bpf programs need to include either
|
||||||
|
* vmlinux.h (auto-generated from BTF) or linux/types.h
|
||||||
|
* in advance since bpf_helper_defs.h uses such types
|
||||||
|
* as __u64.
|
||||||
|
*/
|
||||||
|
#include "bpf_helper_defs.h"
|
||||||
|
|
||||||
|
#define __uint(name, val) int (*name)[val]
|
||||||
|
#define __type(name, val) typeof(val) *name
|
||||||
|
#define __array(name, val) typeof(val) *name[]
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper macro to place programs, maps, license in
|
||||||
|
* different sections in elf_bpf file. Section names
|
||||||
|
* are interpreted by libbpf depending on the context (BPF programs, BPF maps,
|
||||||
|
* extern variables, etc).
|
||||||
|
* To allow use of SEC() with externs (e.g., for extern .maps declarations),
|
||||||
|
* make sure __attribute__((unused)) doesn't trigger compilation warning.
|
||||||
|
*/
|
||||||
|
#define SEC(name) \
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wignored-attributes\"") \
|
||||||
|
__attribute__((section(name), used)) \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
|
||||||
|
/* Avoid 'linux/stddef.h' definition of '__always_inline'. */
|
||||||
|
#undef __always_inline
|
||||||
|
#define __always_inline inline __attribute__((always_inline))
|
||||||
|
|
||||||
|
#ifndef __noinline
|
||||||
|
#define __noinline __attribute__((noinline))
|
||||||
|
#endif
|
||||||
|
#ifndef __weak
|
||||||
|
#define __weak __attribute__((weak))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Use __hidden attribute to mark a non-static BPF subprogram effectively
|
||||||
|
* static for BPF verifier's verification algorithm purposes, allowing more
|
||||||
|
* extensive and permissive BPF verification process, taking into account
|
||||||
|
* subprogram's caller context.
|
||||||
|
*/
|
||||||
|
#define __hidden __attribute__((visibility("hidden")))
|
||||||
|
|
||||||
|
/* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include
|
||||||
|
* any system-level headers (such as stddef.h, linux/version.h, etc), and
|
||||||
|
* commonly-used macros like NULL and KERNEL_VERSION aren't available through
|
||||||
|
* vmlinux.h. This just adds unnecessary hurdles and forces users to re-define
|
||||||
|
* them on their own. So as a convenience, provide such definitions here.
|
||||||
|
*/
|
||||||
|
#ifndef NULL
|
||||||
|
#define NULL ((void *)0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef KERNEL_VERSION
|
||||||
|
#define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper macros to manipulate data structures
|
||||||
|
*/
|
||||||
|
#ifndef offsetof
|
||||||
|
#define offsetof(TYPE, MEMBER) ((unsigned long)&((TYPE *)0)->MEMBER)
|
||||||
|
#endif
|
||||||
|
#ifndef container_of
|
||||||
|
#define container_of(ptr, type, member) \
|
||||||
|
({ \
|
||||||
|
void *__mptr = (void *)(ptr); \
|
||||||
|
((type *)(__mptr - offsetof(type, member))); \
|
||||||
|
})
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper macro to throw a compilation error if __bpf_unreachable() gets
|
||||||
|
* built into the resulting code. This works given BPF back end does not
|
||||||
|
* implement __builtin_trap(). This is useful to assert that certain paths
|
||||||
|
* of the program code are never used and hence eliminated by the compiler.
|
||||||
|
*
|
||||||
|
* For example, consider a switch statement that covers known cases used by
|
||||||
|
* the program. __bpf_unreachable() can then reside in the default case. If
|
||||||
|
* the program gets extended such that a case is not covered in the switch
|
||||||
|
* statement, then it will throw a build error due to the default case not
|
||||||
|
* being compiled out.
|
||||||
|
*/
|
||||||
|
#ifndef __bpf_unreachable
|
||||||
|
# define __bpf_unreachable() __builtin_trap()
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper function to perform a tail call with a constant/immediate map slot.
|
||||||
|
*/
|
||||||
|
#if __clang_major__ >= 8 && defined(__bpf__)
|
||||||
|
static __always_inline void
|
||||||
|
bpf_tail_call_static(void *ctx, const void *map, const __u32 slot)
|
||||||
|
{
|
||||||
|
if (!__builtin_constant_p(slot))
|
||||||
|
__bpf_unreachable();
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Provide a hard guarantee that LLVM won't optimize setting r2 (map
|
||||||
|
* pointer) and r3 (constant map index) from _different paths_ ending
|
||||||
|
* up at the _same_ call insn as otherwise we won't be able to use the
|
||||||
|
* jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel
|
||||||
|
* given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key
|
||||||
|
* tracking for prog array pokes") for details on verifier tracking.
|
||||||
|
*
|
||||||
|
* Note on clobber list: we need to stay in-line with BPF calling
|
||||||
|
* convention, so even if we don't end up using r0, r4, r5, we need
|
||||||
|
* to mark them as clobber so that LLVM doesn't end up using them
|
||||||
|
* before / after the call.
|
||||||
|
*/
|
||||||
|
asm volatile("r1 = %[ctx]\n\t"
|
||||||
|
"r2 = %[map]\n\t"
|
||||||
|
"r3 = %[slot]\n\t"
|
||||||
|
"call 12"
|
||||||
|
:: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot)
|
||||||
|
: "r0", "r1", "r2", "r3", "r4", "r5");
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Helper structure used by eBPF C program
|
||||||
|
* to describe BPF map attributes to libbpf loader
|
||||||
|
*/
|
||||||
|
struct bpf_map_def {
|
||||||
|
unsigned int type;
|
||||||
|
unsigned int key_size;
|
||||||
|
unsigned int value_size;
|
||||||
|
unsigned int max_entries;
|
||||||
|
unsigned int map_flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum libbpf_pin_type {
|
||||||
|
LIBBPF_PIN_NONE,
|
||||||
|
/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
|
||||||
|
LIBBPF_PIN_BY_NAME,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum libbpf_tristate {
|
||||||
|
TRI_NO = 0,
|
||||||
|
TRI_YES = 1,
|
||||||
|
TRI_MODULE = 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
#define __kconfig __attribute__((section(".kconfig")))
|
||||||
|
#define __ksym __attribute__((section(".ksyms")))
|
||||||
|
|
||||||
|
#ifndef ___bpf_concat
|
||||||
|
#define ___bpf_concat(a, b) a ## b
|
||||||
|
#endif
|
||||||
|
#ifndef ___bpf_apply
|
||||||
|
#define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
|
||||||
|
#endif
|
||||||
|
#ifndef ___bpf_nth
|
||||||
|
#define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
|
||||||
|
#endif
|
||||||
|
#ifndef ___bpf_narg
|
||||||
|
#define ___bpf_narg(...) \
|
||||||
|
___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define ___bpf_fill0(arr, p, x) do {} while (0)
|
||||||
|
#define ___bpf_fill1(arr, p, x) arr[p] = x
|
||||||
|
#define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
|
||||||
|
#define ___bpf_fill(arr, args...) \
|
||||||
|
___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
|
||||||
|
|
||||||
|
/*
|
||||||
|
* BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
|
||||||
|
* in a structure.
|
||||||
|
*/
|
||||||
|
#define BPF_SEQ_PRINTF(seq, fmt, args...) \
|
||||||
|
({ \
|
||||||
|
static const char ___fmt[] = fmt; \
|
||||||
|
unsigned long long ___param[___bpf_narg(args)]; \
|
||||||
|
\
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
||||||
|
___bpf_fill(___param, args); \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
\
|
||||||
|
bpf_seq_printf(seq, ___fmt, sizeof(___fmt), \
|
||||||
|
___param, sizeof(___param)); \
|
||||||
|
})
|
||||||
|
|
||||||
|
/*
|
||||||
|
* BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
|
||||||
|
* an array of u64.
|
||||||
|
*/
|
||||||
|
#define BPF_SNPRINTF(out, out_size, fmt, args...) \
|
||||||
|
({ \
|
||||||
|
static const char ___fmt[] = fmt; \
|
||||||
|
unsigned long long ___param[___bpf_narg(args)]; \
|
||||||
|
\
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
||||||
|
___bpf_fill(___param, args); \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
\
|
||||||
|
bpf_snprintf(out, out_size, ___fmt, \
|
||||||
|
___param, sizeof(___param)); \
|
||||||
|
})
|
||||||
|
|
||||||
|
#ifdef BPF_NO_GLOBAL_DATA
|
||||||
|
#define BPF_PRINTK_FMT_MOD
|
||||||
|
#else
|
||||||
|
#define BPF_PRINTK_FMT_MOD static const
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define __bpf_printk(fmt, ...) \
|
||||||
|
({ \
|
||||||
|
BPF_PRINTK_FMT_MOD char ____fmt[] = fmt; \
|
||||||
|
bpf_trace_printk(____fmt, sizeof(____fmt), \
|
||||||
|
##__VA_ARGS__); \
|
||||||
|
})
|
||||||
|
|
||||||
|
/*
|
||||||
|
* __bpf_vprintk wraps the bpf_trace_vprintk helper with variadic arguments
|
||||||
|
* instead of an array of u64.
|
||||||
|
*/
|
||||||
|
#define __bpf_vprintk(fmt, args...) \
|
||||||
|
({ \
|
||||||
|
static const char ___fmt[] = fmt; \
|
||||||
|
unsigned long long ___param[___bpf_narg(args)]; \
|
||||||
|
\
|
||||||
|
_Pragma("GCC diagnostic push") \
|
||||||
|
_Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
|
||||||
|
___bpf_fill(___param, args); \
|
||||||
|
_Pragma("GCC diagnostic pop") \
|
||||||
|
\
|
||||||
|
bpf_trace_vprintk(___fmt, sizeof(___fmt), \
|
||||||
|
___param, sizeof(___param)); \
|
||||||
|
})
|
||||||
|
|
||||||
|
/* Use __bpf_printk when bpf_printk call has 3 or fewer fmt args
|
||||||
|
* Otherwise use __bpf_vprintk
|
||||||
|
*/
|
||||||
|
#define ___bpf_pick_printk(...) \
|
||||||
|
___bpf_nth(_, ##__VA_ARGS__, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
|
||||||
|
__bpf_vprintk, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
|
||||||
|
__bpf_vprintk, __bpf_vprintk, __bpf_printk /*3*/, __bpf_printk /*2*/,\
|
||||||
|
__bpf_printk /*1*/, __bpf_printk /*0*/)
|
||||||
|
|
||||||
|
/* Helper macro to print out debug messages */
|
||||||
|
#define bpf_printk(fmt, args...) ___bpf_pick_printk(args)(fmt, ##args)
|
||||||
|
|
||||||
|
#endif
|
342
component/ebpf/bpf/redir.c
Normal file
342
component/ebpf/bpf/redir.c
Normal file
@ -0,0 +1,342 @@
|
|||||||
|
#include <stdint.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
//#include <linux/types.h>
|
||||||
|
|
||||||
|
#include <linux/bpf.h>
|
||||||
|
#include <linux/if_ether.h>
|
||||||
|
//#include <linux/if_packet.h>
|
||||||
|
//#include <linux/if_vlan.h>
|
||||||
|
#include <linux/ip.h>
|
||||||
|
#include <linux/in.h>
|
||||||
|
#include <linux/tcp.h>
|
||||||
|
//#include <linux/udp.h>
|
||||||
|
|
||||||
|
#include <linux/pkt_cls.h>
|
||||||
|
|
||||||
|
#include "bpf_endian.h"
|
||||||
|
#include "bpf_helpers.h"
|
||||||
|
|
||||||
|
#define IP_CSUM_OFF (ETH_HLEN + offsetof(struct iphdr, check))
|
||||||
|
#define IP_DST_OFF (ETH_HLEN + offsetof(struct iphdr, daddr))
|
||||||
|
#define IP_SRC_OFF (ETH_HLEN + offsetof(struct iphdr, saddr))
|
||||||
|
#define IP_PROTO_OFF (ETH_HLEN + offsetof(struct iphdr, protocol))
|
||||||
|
#define TCP_CSUM_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, check))
|
||||||
|
#define TCP_SRC_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, source))
|
||||||
|
#define TCP_DST_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct tcphdr, dest))
|
||||||
|
//#define UDP_CSUM_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, check))
|
||||||
|
//#define UDP_SRC_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, source))
|
||||||
|
//#define UDP_DST_OFF (ETH_HLEN + sizeof(struct iphdr) + offsetof(struct udphdr, dest))
|
||||||
|
#define IS_PSEUDO 0x10
|
||||||
|
|
||||||
|
struct origin_info {
|
||||||
|
__be32 ip;
|
||||||
|
__be16 port;
|
||||||
|
__u16 pad;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct origin_info *origin_info_unused __attribute__((unused));
|
||||||
|
|
||||||
|
struct redir_info {
|
||||||
|
__be32 sip;
|
||||||
|
__be32 dip;
|
||||||
|
__be16 sport;
|
||||||
|
__be16 dport;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct redir_info *redir_info_unused __attribute__((unused));
|
||||||
|
|
||||||
|
struct {
|
||||||
|
__uint(type, BPF_MAP_TYPE_LRU_HASH);
|
||||||
|
__type(key, struct redir_info);
|
||||||
|
__type(value, struct origin_info);
|
||||||
|
__uint(max_entries, 65535);
|
||||||
|
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
||||||
|
} pair_original_dst_map SEC(".maps");
|
||||||
|
|
||||||
|
struct {
|
||||||
|
__uint(type, BPF_MAP_TYPE_ARRAY);
|
||||||
|
__type(key, __u32);
|
||||||
|
__type(value, __u32);
|
||||||
|
__uint(max_entries, 3);
|
||||||
|
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
||||||
|
} redir_params_map SEC(".maps");
|
||||||
|
|
||||||
|
static __always_inline int rewrite_ip(struct __sk_buff *skb, __be32 new_ip, bool is_dest) {
|
||||||
|
int ret, off = 0, flags = IS_PSEUDO;
|
||||||
|
__be32 old_ip;
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_load_bytes(skb, IP_DST_OFF, &old_ip, 4);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_load_bytes(skb, IP_SRC_OFF, &old_ip, 4);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
off = TCP_CSUM_OFF;
|
||||||
|
// __u8 proto;
|
||||||
|
//
|
||||||
|
// ret = bpf_skb_load_bytes(skb, IP_PROTO_OFF, &proto, 1);
|
||||||
|
// if (ret < 0) {
|
||||||
|
// return BPF_DROP;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// switch (proto) {
|
||||||
|
// case IPPROTO_TCP:
|
||||||
|
// off = TCP_CSUM_OFF;
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case IPPROTO_UDP:
|
||||||
|
// off = UDP_CSUM_OFF;
|
||||||
|
// flags |= BPF_F_MARK_MANGLED_0;
|
||||||
|
// break;
|
||||||
|
//
|
||||||
|
// case IPPROTO_ICMPV6:
|
||||||
|
// off = offsetof(struct icmp6hdr, icmp6_cksum);
|
||||||
|
// break;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// if (off) {
|
||||||
|
ret = bpf_l4_csum_replace(skb, off, old_ip, new_ip, flags | sizeof(new_ip));
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
// }
|
||||||
|
|
||||||
|
ret = bpf_l3_csum_replace(skb, IP_CSUM_OFF, old_ip, new_ip, sizeof(new_ip));
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_store_bytes(skb, IP_DST_OFF, &new_ip, sizeof(new_ip), 0);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_store_bytes(skb, IP_SRC_OFF, &new_ip, sizeof(new_ip), 0);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static __always_inline int rewrite_port(struct __sk_buff *skb, __be16 new_port, bool is_dest) {
|
||||||
|
int ret, off = 0;
|
||||||
|
__be16 old_port;
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_load_bytes(skb, TCP_DST_OFF, &old_port, 2);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_load_bytes(skb, TCP_SRC_OFF, &old_port, 2);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
off = TCP_CSUM_OFF;
|
||||||
|
|
||||||
|
ret = bpf_l4_csum_replace(skb, off, old_port, new_port, sizeof(new_port));
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (is_dest)
|
||||||
|
ret = bpf_skb_store_bytes(skb, TCP_DST_OFF, &new_port, sizeof(new_port), 0);
|
||||||
|
else
|
||||||
|
ret = bpf_skb_store_bytes(skb, TCP_SRC_OFF, &new_port, sizeof(new_port), 0);
|
||||||
|
|
||||||
|
if (ret < 0) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static __always_inline bool is_lan_ip(__be32 addr) {
|
||||||
|
if (addr == 0xffffffff)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 fist = (__u8)(addr & 0xff);
|
||||||
|
|
||||||
|
if (fist == 127 || fist == 10)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 second = (__u8)((addr >> 8) & 0xff);
|
||||||
|
|
||||||
|
if (fist == 172 && second >= 16 && second <= 31)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (fist == 192 && second == 168)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("tc_clash_auto_redir_ingress")
|
||||||
|
int tc_redir_ingress_func(struct __sk_buff *skb) {
|
||||||
|
void *data = (void *)(long)skb->data;
|
||||||
|
void *data_end = (void *)(long)skb->data_end;
|
||||||
|
struct ethhdr *eth = data;
|
||||||
|
|
||||||
|
if ((void *)(eth + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto != bpf_htons(ETH_P_IP))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
||||||
|
if ((void *)(iph + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__u32 key = 0, *route_index, *redir_ip, *redir_port;
|
||||||
|
|
||||||
|
route_index = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!route_index)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (iph->protocol == IPPROTO_ICMP && *route_index != 0)
|
||||||
|
return bpf_redirect(*route_index, 0);
|
||||||
|
|
||||||
|
if (iph->protocol != IPPROTO_TCP)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
||||||
|
if ((void *)(tcph + 1) > data_end)
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
|
||||||
|
key = 1;
|
||||||
|
redir_ip = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_ip)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
key = 2;
|
||||||
|
redir_port = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_port)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__be32 new_ip = bpf_htonl(*redir_ip);
|
||||||
|
__be16 new_port = bpf_htonl(*redir_port) >> 16;
|
||||||
|
__be32 old_ip = iph->daddr;
|
||||||
|
__be16 old_port = tcph->dest;
|
||||||
|
|
||||||
|
if (old_ip == new_ip || is_lan_ip(old_ip) || bpf_ntohs(old_port) == 53) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct redir_info p_key = {
|
||||||
|
.sip = iph->saddr,
|
||||||
|
.sport = tcph->source,
|
||||||
|
.dip = new_ip,
|
||||||
|
.dport = new_port,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (tcph->syn && !tcph->ack) {
|
||||||
|
struct origin_info origin = {
|
||||||
|
.ip = old_ip,
|
||||||
|
.port = old_port,
|
||||||
|
};
|
||||||
|
|
||||||
|
bpf_map_update_elem(&pair_original_dst_map, &p_key, &origin, BPF_NOEXIST);
|
||||||
|
|
||||||
|
if (rewrite_ip(skb, new_ip, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_port(skb, new_port, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
struct origin_info *origin = bpf_map_lookup_elem(&pair_original_dst_map, &p_key);
|
||||||
|
if (!origin) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_ip(skb, new_ip, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_port(skb, new_port, true) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("tc_clash_auto_redir_egress")
|
||||||
|
int tc_redir_egress_func(struct __sk_buff *skb) {
|
||||||
|
void *data = (void *)(long)skb->data;
|
||||||
|
void *data_end = (void *)(long)skb->data_end;
|
||||||
|
struct ethhdr *eth = data;
|
||||||
|
|
||||||
|
if ((void *)(eth + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto != bpf_htons(ETH_P_IP))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__u32 key = 0, *redir_ip, *redir_port; // *clash_mark
|
||||||
|
|
||||||
|
// clash_mark = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
// if (clash_mark && *clash_mark != 0 && *clash_mark == skb->mark)
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
||||||
|
if ((void *)(iph + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (iph->protocol != IPPROTO_TCP)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
||||||
|
if ((void *)(tcph + 1) > data_end)
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
|
||||||
|
key = 1;
|
||||||
|
redir_ip = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_ip)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
key = 2;
|
||||||
|
redir_port = bpf_map_lookup_elem(&redir_params_map, &key);
|
||||||
|
if (!redir_port)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__be32 new_ip = bpf_htonl(*redir_ip);
|
||||||
|
__be16 new_port = bpf_htonl(*redir_port) >> 16;
|
||||||
|
__be32 old_ip = iph->saddr;
|
||||||
|
__be16 old_port = tcph->source;
|
||||||
|
|
||||||
|
if (old_ip != new_ip || old_port != new_port) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct redir_info p_key = {
|
||||||
|
.sip = iph->daddr,
|
||||||
|
.sport = tcph->dest,
|
||||||
|
.dip = iph->saddr,
|
||||||
|
.dport = tcph->source,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct origin_info *origin = bpf_map_lookup_elem(&pair_original_dst_map, &p_key);
|
||||||
|
if (!origin) {
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tcph->fin && tcph->ack) {
|
||||||
|
bpf_map_delete_elem(&pair_original_dst_map, &p_key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_ip(skb, origin->ip, false) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rewrite_port(skb, origin->port, false) < 0) {
|
||||||
|
return TC_ACT_SHOT;
|
||||||
|
}
|
||||||
|
|
||||||
|
return TC_ACT_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
char _license[] SEC("license") = "GPL";
|
103
component/ebpf/bpf/tc.c
Normal file
103
component/ebpf/bpf/tc.c
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
#include <stdbool.h>
|
||||||
|
#include <linux/bpf.h>
|
||||||
|
#include <linux/if_ether.h>
|
||||||
|
#include <linux/ip.h>
|
||||||
|
#include <linux/in.h>
|
||||||
|
//#include <linux/tcp.h>
|
||||||
|
//#include <linux/udp.h>
|
||||||
|
#include <linux/pkt_cls.h>
|
||||||
|
|
||||||
|
#include "bpf_endian.h"
|
||||||
|
#include "bpf_helpers.h"
|
||||||
|
|
||||||
|
struct {
|
||||||
|
__uint(type, BPF_MAP_TYPE_ARRAY);
|
||||||
|
__type(key, __u32);
|
||||||
|
__type(value, __u32);
|
||||||
|
__uint(max_entries, 2);
|
||||||
|
__uint(pinning, LIBBPF_PIN_BY_NAME);
|
||||||
|
} tc_params_map SEC(".maps");
|
||||||
|
|
||||||
|
static __always_inline bool is_lan_ip(__be32 addr) {
|
||||||
|
if (addr == 0xffffffff)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 fist = (__u8)(addr & 0xff);
|
||||||
|
|
||||||
|
if (fist == 127 || fist == 10)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
__u8 second = (__u8)((addr >> 8) & 0xff);
|
||||||
|
|
||||||
|
if (fist == 172 && second >= 16 && second <= 31)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (fist == 192 && second == 168)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
SEC("tc_clash_redirect_to_tun")
|
||||||
|
int tc_tun_func(struct __sk_buff *skb) {
|
||||||
|
void *data = (void *)(long)skb->data;
|
||||||
|
void *data_end = (void *)(long)skb->data_end;
|
||||||
|
struct ethhdr *eth = data;
|
||||||
|
|
||||||
|
if ((void *)(eth + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto == bpf_htons(ETH_P_ARP))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__u32 key = 0, *clash_mark, *tun_ifindex;
|
||||||
|
|
||||||
|
clash_mark = bpf_map_lookup_elem(&tc_params_map, &key);
|
||||||
|
if (!clash_mark)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (skb->mark == *clash_mark)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (eth->h_proto == bpf_htons(ETH_P_IP)) {
|
||||||
|
struct iphdr *iph = (struct iphdr *)(eth + 1);
|
||||||
|
if ((void *)(iph + 1) > data_end)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
if (iph->protocol == IPPROTO_ICMP)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
__be32 daddr = iph->daddr;
|
||||||
|
|
||||||
|
if (is_lan_ip(daddr))
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
// if (iph->protocol == IPPROTO_TCP) {
|
||||||
|
// struct tcphdr *tcph = (struct tcphdr *)(iph + 1);
|
||||||
|
// if ((void *)(tcph + 1) > data_end)
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
//
|
||||||
|
// __u16 source = bpf_ntohs(tcph->source);
|
||||||
|
// if (source == 22 || source == 80 || source == 443 || source == 8080 || source == 8443 || source == 9090 || (source >= 7890 && source <= 7895))
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
// } else if (iph->protocol == IPPROTO_UDP) {
|
||||||
|
// struct udphdr *udph = (struct udphdr *)(iph + 1);
|
||||||
|
// if ((void *)(udph + 1) > data_end)
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
//
|
||||||
|
// __u16 source = bpf_ntohs(udph->source);
|
||||||
|
// if (source == 53 || (source >= 135 && source <= 139))
|
||||||
|
// return TC_ACT_OK;
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
key = 1;
|
||||||
|
tun_ifindex = bpf_map_lookup_elem(&tc_params_map, &key);
|
||||||
|
if (!tun_ifindex)
|
||||||
|
return TC_ACT_OK;
|
||||||
|
|
||||||
|
//return bpf_redirect(*tun_ifindex, BPF_F_INGRESS); // __bpf_rx_skb
|
||||||
|
return bpf_redirect(*tun_ifindex, 0); // __bpf_tx_skb / __dev_xmit_skb
|
||||||
|
}
|
||||||
|
|
||||||
|
char _license[] SEC("license") = "GPL";
|
13
component/ebpf/byteorder/byteorder.go
Normal file
13
component/ebpf/byteorder/byteorder.go
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
package byteorder
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NetIPv4ToHost32 converts an net.IP to a uint32 in host byte order. ip
|
||||||
|
// must be a IPv4 address, otherwise the function will panic.
|
||||||
|
func NetIPv4ToHost32(ip net.IP) uint32 {
|
||||||
|
ipv4 := ip.To4()
|
||||||
|
_ = ipv4[3] // Assert length of ipv4.
|
||||||
|
return Native.Uint32(ipv4)
|
||||||
|
}
|
12
component/ebpf/byteorder/byteorder_bigendian.go
Normal file
12
component/ebpf/byteorder/byteorder_bigendian.go
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
||||||
|
|
||||||
|
package byteorder
|
||||||
|
|
||||||
|
import "encoding/binary"
|
||||||
|
|
||||||
|
var Native binary.ByteOrder = binary.BigEndian
|
||||||
|
|
||||||
|
func HostToNetwork16(u uint16) uint16 { return u }
|
||||||
|
func HostToNetwork32(u uint32) uint32 { return u }
|
||||||
|
func NetworkToHost16(u uint16) uint16 { return u }
|
||||||
|
func NetworkToHost32(u uint32) uint32 { return u }
|
15
component/ebpf/byteorder/byteorder_littleendian.go
Normal file
15
component/ebpf/byteorder/byteorder_littleendian.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
||||||
|
|
||||||
|
package byteorder
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"math/bits"
|
||||||
|
)
|
||||||
|
|
||||||
|
var Native binary.ByteOrder = binary.LittleEndian
|
||||||
|
|
||||||
|
func HostToNetwork16(u uint16) uint16 { return bits.ReverseBytes16(u) }
|
||||||
|
func HostToNetwork32(u uint32) uint32 { return bits.ReverseBytes32(u) }
|
||||||
|
func NetworkToHost16(u uint16) uint16 { return bits.ReverseBytes16(u) }
|
||||||
|
func NetworkToHost32(u uint32) uint32 { return bits.ReverseBytes32(u) }
|
33
component/ebpf/ebpf.go
Normal file
33
component/ebpf/ebpf.go
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
package ebpf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TcEBpfProgram struct {
|
||||||
|
pros []C.EBpf
|
||||||
|
rawNICs []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TcEBpfProgram) RawNICs() []string {
|
||||||
|
return t.rawNICs
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TcEBpfProgram) Close() {
|
||||||
|
for _, p := range t.pros {
|
||||||
|
p.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *TcEBpfProgram) Lookup(srcAddrPort netip.AddrPort) (addr socks5.Addr, err error) {
|
||||||
|
for _, p := range t.pros {
|
||||||
|
addr, err = p.Lookup(srcAddrPort)
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
114
component/ebpf/ebpf_linux.go
Normal file
114
component/ebpf/ebpf_linux.go
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
//go:build !android
|
||||||
|
|
||||||
|
package ebpf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/common/cmd"
|
||||||
|
"github.com/Dreamacro/clash/component/dialer"
|
||||||
|
"github.com/Dreamacro/clash/component/ebpf/redir"
|
||||||
|
"github.com/Dreamacro/clash/component/ebpf/tc"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewTcEBpfProgram new redirect to tun ebpf program
|
||||||
|
func NewTcEBpfProgram(ifaceNames []string, tunName string) (*TcEBpfProgram, error) {
|
||||||
|
tunIface, err := netlink.LinkByName(tunName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", tunName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
tunIndex := uint32(tunIface.Attrs().Index)
|
||||||
|
|
||||||
|
dialer.DefaultRoutingMark.Store(C.ClashTrafficMark)
|
||||||
|
|
||||||
|
ifMark := uint32(dialer.DefaultRoutingMark.Load())
|
||||||
|
|
||||||
|
var pros []C.EBpf
|
||||||
|
for _, ifaceName := range ifaceNames {
|
||||||
|
iface, err := netlink.LinkByName(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", ifaceName, err)
|
||||||
|
}
|
||||||
|
if iface.Attrs().OperState != netlink.OperUp {
|
||||||
|
return nil, fmt.Errorf("network iface %q is down", ifaceName)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := iface.Attrs()
|
||||||
|
index := attrs.Index
|
||||||
|
|
||||||
|
tcPro := tc.NewEBpfTc(ifaceName, index, ifMark, tunIndex)
|
||||||
|
if err = tcPro.Start(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pros = append(pros, tcPro)
|
||||||
|
}
|
||||||
|
|
||||||
|
systemSetting(ifaceNames...)
|
||||||
|
|
||||||
|
return &TcEBpfProgram{pros: pros, rawNICs: ifaceNames}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRedirEBpfProgram new auto redirect ebpf program
|
||||||
|
func NewRedirEBpfProgram(ifaceNames []string, redirPort uint16, defaultRouteInterfaceName string) (*TcEBpfProgram, error) {
|
||||||
|
defaultRouteInterface, err := netlink.LinkByName(defaultRouteInterfaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", defaultRouteInterfaceName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultRouteIndex := uint32(defaultRouteInterface.Attrs().Index)
|
||||||
|
|
||||||
|
var pros []C.EBpf
|
||||||
|
for _, ifaceName := range ifaceNames {
|
||||||
|
iface, err := netlink.LinkByName(ifaceName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q: %w", ifaceName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := iface.Attrs()
|
||||||
|
index := attrs.Index
|
||||||
|
|
||||||
|
addrs, err := netlink.AddrList(iface, netlink.FAMILY_V4)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("lookup network iface %q address: %w", ifaceName, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(addrs) == 0 {
|
||||||
|
return nil, fmt.Errorf("network iface %q does not contain any ipv4 addresses", ifaceName)
|
||||||
|
}
|
||||||
|
|
||||||
|
address, _ := netip.AddrFromSlice(addrs[0].IP)
|
||||||
|
redirAddrPort := netip.AddrPortFrom(address, redirPort)
|
||||||
|
|
||||||
|
redirPro := redir.NewEBpfRedirect(ifaceName, index, 0, defaultRouteIndex, redirAddrPort)
|
||||||
|
if err = redirPro.Start(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
pros = append(pros, redirPro)
|
||||||
|
}
|
||||||
|
|
||||||
|
systemSetting(ifaceNames...)
|
||||||
|
|
||||||
|
return &TcEBpfProgram{pros: pros, rawNICs: ifaceNames}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func systemSetting(ifaceNames ...string) {
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.ip_forward=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.forwarding=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.accept_local=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.accept_redirects=1")
|
||||||
|
_, _ = cmd.ExecCmd("sysctl -w net.ipv4.conf.all.rp_filter=0")
|
||||||
|
|
||||||
|
for _, ifaceName := range ifaceNames {
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.forwarding=1", ifaceName))
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.accept_local=1", ifaceName))
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.accept_redirects=1", ifaceName))
|
||||||
|
_, _ = cmd.ExecCmd(fmt.Sprintf("sysctl -w net.ipv4.conf.%s.rp_filter=0", ifaceName))
|
||||||
|
}
|
||||||
|
}
|
17
component/ebpf/ebpf_others.go
Normal file
17
component/ebpf/ebpf_others.go
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
//go:build !linux || android
|
||||||
|
|
||||||
|
package ebpf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewTcEBpfProgram new ebpf tc program
|
||||||
|
func NewTcEBpfProgram(_ []string, _ string) (*TcEBpfProgram, error) {
|
||||||
|
return nil, fmt.Errorf("system not supported")
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRedirEBpfProgram new ebpf redirect program
|
||||||
|
func NewRedirEBpfProgram(_ []string, _ uint16, _ string) (*TcEBpfProgram, error) {
|
||||||
|
return nil, fmt.Errorf("system not supported")
|
||||||
|
}
|
216
component/ebpf/redir/auto_redirect.go
Normal file
216
component/ebpf/redir/auto_redirect.go
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
"github.com/cilium/ebpf/rlimit"
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
"github.com/Dreamacro/clash/component/ebpf/byteorder"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf ../bpf/redir.c
|
||||||
|
|
||||||
|
const (
|
||||||
|
mapKey1 uint32 = 0
|
||||||
|
mapKey2 uint32 = 1
|
||||||
|
mapKey3 uint32 = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
type EBpfRedirect struct {
|
||||||
|
objs io.Closer
|
||||||
|
originMap *ebpf.Map
|
||||||
|
qdisc netlink.Qdisc
|
||||||
|
filter netlink.Filter
|
||||||
|
filterEgress netlink.Filter
|
||||||
|
|
||||||
|
ifName string
|
||||||
|
ifIndex int
|
||||||
|
ifMark uint32
|
||||||
|
rtIndex uint32
|
||||||
|
redirIp uint32
|
||||||
|
redirPort uint16
|
||||||
|
|
||||||
|
bpfPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEBpfRedirect(ifName string, ifIndex int, ifMark uint32, routeIndex uint32, redirAddrPort netip.AddrPort) *EBpfRedirect {
|
||||||
|
return &EBpfRedirect{
|
||||||
|
ifName: ifName,
|
||||||
|
ifIndex: ifIndex,
|
||||||
|
ifMark: ifMark,
|
||||||
|
rtIndex: routeIndex,
|
||||||
|
redirIp: binary.BigEndian.Uint32(redirAddrPort.Addr().AsSlice()),
|
||||||
|
redirPort: redirAddrPort.Port(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfRedirect) Start() error {
|
||||||
|
if err := rlimit.RemoveMemlock(); err != nil {
|
||||||
|
return fmt.Errorf("remove memory lock: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.bpfPath = filepath.Join(C.BpfFSPath, e.ifName)
|
||||||
|
if err := os.MkdirAll(e.bpfPath, os.ModePerm); err != nil {
|
||||||
|
return fmt.Errorf("failed to create bpf fs subpath: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var objs bpfObjects
|
||||||
|
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
|
||||||
|
Maps: ebpf.MapOptions{
|
||||||
|
PinPath: e.bpfPath,
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("loading objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.objs = &objs
|
||||||
|
e.originMap = objs.bpfMaps.PairOriginalDstMap
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey1, e.rtIndex, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey2, e.redirIp, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.RedirParamsMap.Update(mapKey3, uint32(e.redirPort), ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := netlink.QdiscAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Handle: netlink.MakeHandle(0xffff, 0),
|
||||||
|
Parent: netlink.HANDLE_CLSACT,
|
||||||
|
}
|
||||||
|
|
||||||
|
qdisc := &netlink.GenericQdisc{
|
||||||
|
QdiscAttrs: attrs,
|
||||||
|
QdiscType: "clsact",
|
||||||
|
}
|
||||||
|
|
||||||
|
e.qdisc = qdisc
|
||||||
|
|
||||||
|
if err := netlink.QdiscAdd(qdisc); err != nil {
|
||||||
|
if os.IsExist(err) {
|
||||||
|
_ = netlink.QdiscDel(qdisc)
|
||||||
|
err = netlink.QdiscAdd(qdisc)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot add clsact qdisc: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
filterAttrs := netlink.FilterAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Parent: netlink.HANDLE_MIN_INGRESS,
|
||||||
|
Handle: netlink.MakeHandle(0, 1),
|
||||||
|
Protocol: unix.ETH_P_IP,
|
||||||
|
Priority: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
filter := &netlink.BpfFilter{
|
||||||
|
FilterAttrs: filterAttrs,
|
||||||
|
Fd: objs.bpfPrograms.TcRedirIngressFunc.FD(),
|
||||||
|
Name: "clash-redir-ingress-" + e.ifName,
|
||||||
|
DirectAction: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := netlink.FilterAdd(filter); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot attach ebpf object to filter ingress: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.filter = filter
|
||||||
|
|
||||||
|
filterAttrsEgress := netlink.FilterAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Parent: netlink.HANDLE_MIN_EGRESS,
|
||||||
|
Handle: netlink.MakeHandle(0, 1),
|
||||||
|
Protocol: unix.ETH_P_IP,
|
||||||
|
Priority: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
filterEgress := &netlink.BpfFilter{
|
||||||
|
FilterAttrs: filterAttrsEgress,
|
||||||
|
Fd: objs.bpfPrograms.TcRedirEgressFunc.FD(),
|
||||||
|
Name: "clash-redir-egress-" + e.ifName,
|
||||||
|
DirectAction: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := netlink.FilterAdd(filterEgress); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot attach ebpf object to filter egress: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.filterEgress = filterEgress
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfRedirect) Close() {
|
||||||
|
if e.filter != nil {
|
||||||
|
_ = netlink.FilterDel(e.filter)
|
||||||
|
}
|
||||||
|
if e.filterEgress != nil {
|
||||||
|
_ = netlink.FilterDel(e.filterEgress)
|
||||||
|
}
|
||||||
|
if e.qdisc != nil {
|
||||||
|
_ = netlink.QdiscDel(e.qdisc)
|
||||||
|
}
|
||||||
|
if e.objs != nil {
|
||||||
|
_ = e.objs.Close()
|
||||||
|
}
|
||||||
|
_ = os.Remove(filepath.Join(e.bpfPath, "redir_params_map"))
|
||||||
|
_ = os.Remove(filepath.Join(e.bpfPath, "pair_original_dst_map"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfRedirect) Lookup(srcAddrPort netip.AddrPort) (socks5.Addr, error) {
|
||||||
|
rAddr := srcAddrPort.Addr().Unmap()
|
||||||
|
if rAddr.Is6() {
|
||||||
|
return nil, fmt.Errorf("remote address is ipv6")
|
||||||
|
}
|
||||||
|
|
||||||
|
srcIp := binary.BigEndian.Uint32(rAddr.AsSlice())
|
||||||
|
scrPort := srcAddrPort.Port()
|
||||||
|
|
||||||
|
key := bpfRedirInfo{
|
||||||
|
Sip: byteorder.HostToNetwork32(srcIp),
|
||||||
|
Sport: byteorder.HostToNetwork16(scrPort),
|
||||||
|
Dip: byteorder.HostToNetwork32(e.redirIp),
|
||||||
|
Dport: byteorder.HostToNetwork16(e.redirPort),
|
||||||
|
}
|
||||||
|
|
||||||
|
origin := bpfOriginInfo{}
|
||||||
|
|
||||||
|
err := e.originMap.Lookup(key, &origin)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := make([]byte, net.IPv4len+3)
|
||||||
|
addr[0] = socks5.AtypIPv4
|
||||||
|
|
||||||
|
binary.BigEndian.PutUint32(addr[1:1+net.IPv4len], byteorder.NetworkToHost32(origin.Ip)) // big end
|
||||||
|
binary.BigEndian.PutUint16(addr[1+net.IPv4len:3+net.IPv4len], byteorder.NetworkToHost16(origin.Port)) // big end
|
||||||
|
return addr, nil
|
||||||
|
}
|
138
component/ebpf/redir/bpf_bpfeb.go
Normal file
138
component/ebpf/redir/bpf_bpfeb.go
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
||||||
|
// +build arm64be armbe mips mips64 mips64p32 ppc64 s390 s390x sparc sparc64
|
||||||
|
|
||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
type bpfOriginInfo struct {
|
||||||
|
Ip uint32
|
||||||
|
Port uint16
|
||||||
|
Pad uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
type bpfRedirInfo struct {
|
||||||
|
Sip uint32
|
||||||
|
Dip uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcRedirEgressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
PairOriginalDstMap *ebpf.MapSpec `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.MapSpec `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
PairOriginalDstMap *ebpf.Map `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.Map `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.PairOriginalDstMap,
|
||||||
|
m.RedirParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcRedirEgressFunc *ebpf.Program `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.Program `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcRedirEgressFunc,
|
||||||
|
p.TcRedirIngressFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfeb.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/redir/bpf_bpfeb.o
Normal file
BIN
component/ebpf/redir/bpf_bpfeb.o
Normal file
Binary file not shown.
138
component/ebpf/redir/bpf_bpfel.go
Normal file
138
component/ebpf/redir/bpf_bpfel.go
Normal file
@ -0,0 +1,138 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
||||||
|
// +build 386 amd64 amd64p32 arm arm64 mips64le mips64p32le mipsle ppc64le riscv64
|
||||||
|
|
||||||
|
package redir
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
type bpfOriginInfo struct {
|
||||||
|
Ip uint32
|
||||||
|
Port uint16
|
||||||
|
Pad uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
type bpfRedirInfo struct {
|
||||||
|
Sip uint32
|
||||||
|
Dip uint32
|
||||||
|
Sport uint16
|
||||||
|
Dport uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcRedirEgressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.ProgramSpec `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
PairOriginalDstMap *ebpf.MapSpec `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.MapSpec `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
PairOriginalDstMap *ebpf.Map `ebpf:"pair_original_dst_map"`
|
||||||
|
RedirParamsMap *ebpf.Map `ebpf:"redir_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.PairOriginalDstMap,
|
||||||
|
m.RedirParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcRedirEgressFunc *ebpf.Program `ebpf:"tc_redir_egress_func"`
|
||||||
|
TcRedirIngressFunc *ebpf.Program `ebpf:"tc_redir_ingress_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcRedirEgressFunc,
|
||||||
|
p.TcRedirIngressFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfel.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/redir/bpf_bpfel.o
Normal file
BIN
component/ebpf/redir/bpf_bpfel.o
Normal file
Binary file not shown.
119
component/ebpf/tc/bpf_bpfeb.go
Normal file
119
component/ebpf/tc/bpf_bpfeb.go
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
|
||||||
|
// +build arm64be armbe mips mips64 mips64p32 ppc64 s390 s390x sparc sparc64
|
||||||
|
|
||||||
|
package tc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcTunFunc *ebpf.ProgramSpec `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
TcParamsMap *ebpf.MapSpec `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
TcParamsMap *ebpf.Map `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.TcParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcTunFunc *ebpf.Program `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcTunFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfeb.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/tc/bpf_bpfeb.o
Normal file
BIN
component/ebpf/tc/bpf_bpfeb.o
Normal file
Binary file not shown.
119
component/ebpf/tc/bpf_bpfel.go
Normal file
119
component/ebpf/tc/bpf_bpfel.go
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
// Code generated by bpf2go; DO NOT EDIT.
|
||||||
|
//go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
|
||||||
|
// +build 386 amd64 amd64p32 arm arm64 mips64le mips64p32le mipsle ppc64le riscv64
|
||||||
|
|
||||||
|
package tc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// loadBpf returns the embedded CollectionSpec for bpf.
|
||||||
|
func loadBpf() (*ebpf.CollectionSpec, error) {
|
||||||
|
reader := bytes.NewReader(_BpfBytes)
|
||||||
|
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("can't load bpf: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadBpfObjects loads bpf and converts it into a struct.
|
||||||
|
//
|
||||||
|
// The following types are suitable as obj argument:
|
||||||
|
//
|
||||||
|
// *bpfObjects
|
||||||
|
// *bpfPrograms
|
||||||
|
// *bpfMaps
|
||||||
|
//
|
||||||
|
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
|
||||||
|
func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
|
||||||
|
spec, err := loadBpf()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.LoadAndAssign(obj, opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains maps and programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfSpecs struct {
|
||||||
|
bpfProgramSpecs
|
||||||
|
bpfMapSpecs
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfSpecs contains programs before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfProgramSpecs struct {
|
||||||
|
TcTunFunc *ebpf.ProgramSpec `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMapSpecs contains maps before they are loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed ebpf.CollectionSpec.Assign.
|
||||||
|
type bpfMapSpecs struct {
|
||||||
|
TcParamsMap *ebpf.MapSpec `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfObjects contains all objects after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfObjects struct {
|
||||||
|
bpfPrograms
|
||||||
|
bpfMaps
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *bpfObjects) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
&o.bpfPrograms,
|
||||||
|
&o.bpfMaps,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfMaps contains all maps after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfMaps struct {
|
||||||
|
TcParamsMap *ebpf.Map `ebpf:"tc_params_map"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *bpfMaps) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
m.TcParamsMap,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// bpfPrograms contains all programs after they have been loaded into the kernel.
|
||||||
|
//
|
||||||
|
// It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
|
||||||
|
type bpfPrograms struct {
|
||||||
|
TcTunFunc *ebpf.Program `ebpf:"tc_tun_func"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bpfPrograms) Close() error {
|
||||||
|
return _BpfClose(
|
||||||
|
p.TcTunFunc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _BpfClose(closers ...io.Closer) error {
|
||||||
|
for _, closer := range closers {
|
||||||
|
if err := closer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do not access this directly.
|
||||||
|
//go:embed bpf_bpfel.o
|
||||||
|
var _BpfBytes []byte
|
BIN
component/ebpf/tc/bpf_bpfel.o
Normal file
BIN
component/ebpf/tc/bpf_bpfel.o
Normal file
Binary file not shown.
147
component/ebpf/tc/redirect_to_tun.go
Normal file
147
component/ebpf/tc/redirect_to_tun.go
Normal file
@ -0,0 +1,147 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package tc
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/cilium/ebpf"
|
||||||
|
"github.com/cilium/ebpf/rlimit"
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/transport/socks5"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf ../bpf/tc.c
|
||||||
|
|
||||||
|
const (
|
||||||
|
mapKey1 uint32 = 0
|
||||||
|
mapKey2 uint32 = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
type EBpfTC struct {
|
||||||
|
objs io.Closer
|
||||||
|
qdisc netlink.Qdisc
|
||||||
|
filter netlink.Filter
|
||||||
|
|
||||||
|
ifName string
|
||||||
|
ifIndex int
|
||||||
|
ifMark uint32
|
||||||
|
tunIfIndex uint32
|
||||||
|
|
||||||
|
bpfPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEBpfTc(ifName string, ifIndex int, ifMark uint32, tunIfIndex uint32) *EBpfTC {
|
||||||
|
return &EBpfTC{
|
||||||
|
ifName: ifName,
|
||||||
|
ifIndex: ifIndex,
|
||||||
|
ifMark: ifMark,
|
||||||
|
tunIfIndex: tunIfIndex,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfTC) Start() error {
|
||||||
|
if err := rlimit.RemoveMemlock(); err != nil {
|
||||||
|
return fmt.Errorf("remove memory lock: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.bpfPath = filepath.Join(C.BpfFSPath, e.ifName)
|
||||||
|
if err := os.MkdirAll(e.bpfPath, os.ModePerm); err != nil {
|
||||||
|
return fmt.Errorf("failed to create bpf fs subpath: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var objs bpfObjects
|
||||||
|
if err := loadBpfObjects(&objs, &ebpf.CollectionOptions{
|
||||||
|
Maps: ebpf.MapOptions{
|
||||||
|
PinPath: e.bpfPath,
|
||||||
|
},
|
||||||
|
}); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("loading objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.objs = &objs
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.TcParamsMap.Update(mapKey1, e.ifMark, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := objs.bpfMaps.TcParamsMap.Update(mapKey2, e.tunIfIndex, ebpf.UpdateAny); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("storing objects: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs := netlink.QdiscAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Handle: netlink.MakeHandle(0xffff, 0),
|
||||||
|
Parent: netlink.HANDLE_CLSACT,
|
||||||
|
}
|
||||||
|
|
||||||
|
qdisc := &netlink.GenericQdisc{
|
||||||
|
QdiscAttrs: attrs,
|
||||||
|
QdiscType: "clsact",
|
||||||
|
}
|
||||||
|
|
||||||
|
e.qdisc = qdisc
|
||||||
|
|
||||||
|
if err := netlink.QdiscAdd(qdisc); err != nil {
|
||||||
|
if os.IsExist(err) {
|
||||||
|
_ = netlink.QdiscDel(qdisc)
|
||||||
|
err = netlink.QdiscAdd(qdisc)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot add clsact qdisc: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
filterAttrs := netlink.FilterAttrs{
|
||||||
|
LinkIndex: e.ifIndex,
|
||||||
|
Parent: netlink.HANDLE_MIN_EGRESS,
|
||||||
|
Handle: netlink.MakeHandle(0, 1),
|
||||||
|
Protocol: unix.ETH_P_ALL,
|
||||||
|
Priority: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
filter := &netlink.BpfFilter{
|
||||||
|
FilterAttrs: filterAttrs,
|
||||||
|
Fd: objs.bpfPrograms.TcTunFunc.FD(),
|
||||||
|
Name: "clash-tc-" + e.ifName,
|
||||||
|
DirectAction: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := netlink.FilterAdd(filter); err != nil {
|
||||||
|
e.Close()
|
||||||
|
return fmt.Errorf("cannot attach ebpf object to filter: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.filter = filter
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfTC) Close() {
|
||||||
|
if e.filter != nil {
|
||||||
|
_ = netlink.FilterDel(e.filter)
|
||||||
|
}
|
||||||
|
if e.qdisc != nil {
|
||||||
|
_ = netlink.QdiscDel(e.qdisc)
|
||||||
|
}
|
||||||
|
if e.objs != nil {
|
||||||
|
_ = e.objs.Close()
|
||||||
|
}
|
||||||
|
_ = os.Remove(filepath.Join(e.bpfPath, "tc_params_map"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *EBpfTC) Lookup(_ netip.AddrPort) (socks5.Addr, error) {
|
||||||
|
return nil, fmt.Errorf("not supported")
|
||||||
|
}
|
@ -3,6 +3,7 @@ package geodata
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
@ -14,7 +15,7 @@ type loader struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSite(list string) ([]*router.Domain, error) {
|
||||||
return l.LoadGeoSiteWithAttr("geosite.dat", list)
|
return l.LoadGeoSiteWithAttr(C.GeositeName, list)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*router.Domain, error) {
|
||||||
@ -29,7 +30,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
|||||||
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
return nil, fmt.Errorf("empty listname in rule: %s", siteWithAttr)
|
||||||
}
|
}
|
||||||
|
|
||||||
domains, err := l.LoadSite(file, list)
|
domains, err := l.LoadSiteByPath(file, list)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@ -58,7 +59,7 @@ func (l *loader) LoadGeoSiteWithAttr(file string, siteWithAttr string) ([]*route
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
func (l *loader) LoadGeoIP(country string) ([]*router.CIDR, error) {
|
||||||
return l.LoadIP("geoip.dat", country)
|
return l.LoadIPByPath(C.GeoipName, country)
|
||||||
}
|
}
|
||||||
|
|
||||||
var loaders map[string]func() LoaderImplementation
|
var loaders map[string]func() LoaderImplementation
|
||||||
|
@ -5,8 +5,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type LoaderImplementation interface {
|
type LoaderImplementation interface {
|
||||||
LoadSite(filename, list string) ([]*router.Domain, error)
|
LoadSiteByPath(filename, list string) ([]*router.Domain, error)
|
||||||
LoadIP(filename, country string) ([]*router.CIDR, error)
|
LoadSiteByBytes(geositeBytes []byte, list string) ([]*router.Domain, error)
|
||||||
|
LoadIPByPath(filename, country string) ([]*router.CIDR, error)
|
||||||
|
LoadIPByBytes(geoipBytes []byte, country string) ([]*router.CIDR, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Loader interface {
|
type Loader interface {
|
||||||
|
52
component/geodata/init.go
Normal file
52
component/geodata/init.go
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
package geodata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
C "github.com/Dreamacro/clash/constant"
|
||||||
|
"github.com/Dreamacro/clash/log"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
var initFlag bool
|
||||||
|
|
||||||
|
func InitGeoSite() error {
|
||||||
|
if _, err := os.Stat(C.Path.GeoSite()); os.IsNotExist(err) {
|
||||||
|
log.Infoln("Can't find GeoSite.dat, start download")
|
||||||
|
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
log.Infoln("Download GeoSite.dat finish")
|
||||||
|
}
|
||||||
|
if !initFlag {
|
||||||
|
if err := Verify(C.GeositeName); err != nil {
|
||||||
|
log.Warnln("GeoSite.dat invalid, remove and download: %s", err)
|
||||||
|
if err := os.Remove(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't remove invalid GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
if err := downloadGeoSite(C.Path.GeoSite()); err != nil {
|
||||||
|
return fmt.Errorf("can't download GeoSite.dat: %s", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
initFlag = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func downloadGeoSite(path string) (err error) {
|
||||||
|
resp, err := http.Get(C.GeoSiteUrl)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
_, err = io.Copy(f, resp.Body)
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
@ -8,7 +8,6 @@ import (
|
|||||||
"github.com/Dreamacro/clash/component/geodata/router"
|
"github.com/Dreamacro/clash/component/geodata/router"
|
||||||
C "github.com/Dreamacro/clash/constant"
|
C "github.com/Dreamacro/clash/constant"
|
||||||
"github.com/Dreamacro/clash/log"
|
"github.com/Dreamacro/clash/log"
|
||||||
|
|
||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -33,7 +32,7 @@ func (g GeoIPCache) Set(key string, value *router.GeoIP) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (g GeoIPCache) Unmarshal(filename, code string) (*router.GeoIP, error) {
|
func (g GeoIPCache) Unmarshal(filename, code string) (*router.GeoIP, error) {
|
||||||
asset := C.Path.Resolve(filename)
|
asset := C.Path.GetAssetLocation(filename)
|
||||||
idx := strings.ToLower(asset + ":" + code)
|
idx := strings.ToLower(asset + ":" + code)
|
||||||
if g.Has(idx) {
|
if g.Has(idx) {
|
||||||
return g.Get(idx), nil
|
return g.Get(idx), nil
|
||||||
@ -98,7 +97,7 @@ func (g GeoSiteCache) Set(key string, value *router.GeoSite) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error) {
|
func (g GeoSiteCache) Unmarshal(filename, code string) (*router.GeoSite, error) {
|
||||||
asset := C.Path.Resolve(filename)
|
asset := C.Path.GetAssetLocation(filename)
|
||||||
idx := strings.ToLower(asset + ":" + code)
|
idx := strings.ToLower(asset + ":" + code)
|
||||||
if g.Has(idx) {
|
if g.Has(idx) {
|
||||||
return g.Get(idx), nil
|
return g.Get(idx), nil
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user